nsh-cli 0.8.1

The nsh command line tool: build, package and run apps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
//! Splitting the web runtime into a main module and side modules.
//!
//! [`split`] makes the main module from what the first screen needs and a
//! side module for what the gates loaded later need, which the page loads
//! (`nsh.js`'s `loadSides`) before the code that uses them runs.
//!
//! A runtime whose crates call JS through wasm-bindgen is split before
//! wasm-bindgen runs, which then runs on the main module alone
//! (`web::link`): what wasm-bindgen reads or rewrites stays in the main
//! module, so the side modules hold none of it.

use std::{collections::BTreeMap, ops::Range};

use anyhow::{Context as _, bail, ensure};
use wasmparser::{
    ExternalKind, Operator, Parser, Payload, RelocationEntry, RelocationType, TypeRef, ValType,
};

use super::{
    Module, check, dropped_custom, put_limits, put_sleb, put_uleb, put_uleb5, read_u32, read_uleb5,
};

/// The main module and the side modules [`split`] made.
pub(crate) struct Split {
    /// The main module.
    pub(crate) main: Vec<u8>,
    /// The side modules: the gates' (in the order the gates were given),
    /// then the shared ones.
    pub(crate) sides: Vec<Side>,
}

/// A side module.
pub(crate) struct Side {
    /// Its name: its gate's, or `nsh_shared_<digest of its gates>`; the
    /// module name the modules importing from it use.
    pub(crate) name: String,
    /// The gate it exports, for a gate's module.
    pub(crate) gate: Option<String>,
    /// The lazy gates whose code it holds: its gate, or the gates sharing
    /// it, in the given order.
    pub(crate) gates: Vec<String>,
    /// The side modules it imports from: loaded before it.
    pub(crate) needs: Vec<String>,
    /// The module.
    pub(crate) bytes: Vec<u8>,
}

/// Who has a function or a byte: no module ([`NONE`]), the main module
/// ([`MAIN`]), or the side module of the set of lazy gates whose bits are
/// set.
type Owner = u128;
const NONE: Owner = 0;
const MAIN: Owner = 1 << 127;
/// The main module's export of its function table, which side modules
/// import: NSH's own name, as its globals' and functions' (`__nsh_g<i>`,
/// `__nsh_f<i>`), as wasm-bindgen removes the linker's
/// (`__indirect_function_table`).
pub(crate) const TABLE: &str = "__nsh_table";
/// Lazy gates past this many are kept in the main module.
const MAX_LAZY: usize = 127;
/// The fewest bytes of code and data a module of what several gates share
/// has: less goes to the main module (a request of its own, with a copy of
/// the types, costs more than the bytes).
const MIN_SHARED: usize = 32 * 1024;

/// Splits a runtime linked with `--emit-relocs` into a main module that
/// keeps `main_exports` (what [`prune`](super::prune) keeps) and side
/// modules for `lazy_gates` ([module docs](self)). With `bindgen`,
/// wasm-bindgen runs on the main module afterwards
/// ([`Module::bindgen_callers`]).
///
/// A lazy gate the main module reaches anyway stays an export of the main
/// module and gets no side module.
pub(crate) fn split(
    wasm: &[u8],
    main_exports: &[&str],
    lazy_gates: &[&str],
    bindgen: bool,
) -> anyhow::Result<Split> {
    let module = Module::parse(wasm)?;
    let extra = Extra::parse(wasm)?;
    let export = |name: &str| -> anyhow::Result<u32> {
        module
            .exports
            .iter()
            .find(|e| e.name == name && e.kind == ExternalKind::Func)
            .map(|e| e.index)
            .with_context(|| format!("the web runtime exports no `{name}`"))
    };
    let mut roots = Vec::new();
    for name in main_exports {
        if let Ok(func) = export(name) {
            roots.push(func);
        } else {
            ensure!(
                module.exports.iter().any(|e| e.name == *name),
                "the web runtime exports no `{name}`"
            );
        }
    }
    let mut kept_main: Vec<&str> = Vec::new();
    let mut lazy: Vec<&str> = Vec::new();
    for gate in lazy_gates {
        if lazy.len() < MAX_LAZY {
            lazy.push(gate);
        } else {
            roots.push(export(gate)?);
            kept_main.push(gate);
        }
    }
    let gates: Vec<u32> = lazy.iter().map(|g| export(g)).collect::<Result<_, _>>()?;
    let body_relocs = module.body_relocs()?;
    if bindgen {
        roots.extend(module.bindgen_callers(&body_relocs)?);
    }

    // Who reaches what: the main module first, then each gate. What a set
    // of several gates shares that is too small to be worth a request of
    // its own goes to the main module, with what it reaches.
    let base = module.data_low();
    let marks: Vec<super::Live> = gates
        .iter()
        .map(|&gate| module.mark_from(vec![gate], Vec::new()))
        .collect::<Result<_, _>>()?;
    let mut data_roots = Vec::new();
    let (funcs, bytes) = loop {
        let main = module.mark_from(roots.clone(), data_roots.clone())?;
        let (funcs, bytes) = owners(&module, &main, &marks);
        let mut size: BTreeMap<Owner, usize> = BTreeMap::new();
        for (func, owner) in funcs.iter().enumerate() {
            if owner.count_ones() > 1 && *owner != MAIN {
                let defined = func - module.imported_funcs as usize;
                *size.entry(*owner).or_default() += module.bodies[defined].len();
            }
        }
        for owner in &bytes {
            if owner.count_ones() > 1 && *owner != MAIN {
                *size.entry(*owner).or_default() += 1;
            }
        }
        // Only a small set whose code and data call nothing outside it and
        // the main module: the main module then grows by it alone.
        let mut leaf: BTreeMap<Owner, bool> = size.keys().map(|o| (*o, true)).collect();
        let mut call = |owner: Owner, entry: &RelocationEntry| -> anyhow::Result<()> {
            if matches!(
                entry.ty,
                RelocationType::FunctionIndexLeb | RelocationType::FunctionIndexI32
            ) {
                let callee = funcs[module.func_of(entry)? as usize];
                if callee != owner && callee != MAIN && callee != NONE {
                    leaf.insert(owner, false);
                }
            }
            Ok(())
        };
        for (func, owner) in funcs.iter().enumerate() {
            if size.contains_key(owner) {
                let defined = func - module.imported_funcs as usize;
                for entry in &module.code_relocs[body_relocs[defined].clone()] {
                    call(*owner, entry)?;
                }
            }
        }
        for reloc in &module.data_relocs {
            let owner = bytes[(reloc.address - base) as usize];
            if size.contains_key(&owner) {
                call(owner, &reloc.entry)?;
            }
        }
        let small = |owner: Owner| {
            size.get(&owner).is_some_and(|s| *s < MIN_SHARED) && leaf.get(&owner) == Some(&true)
        };
        let mut grew = false;
        for (func, owner) in funcs.iter().enumerate() {
            if small(*owner) {
                roots.push(func as u32);
                grew = true;
            }
        }
        for mark in &marks {
            for &range @ (_, start, end, _) in &mark.data {
                if (start..end).any(|at| small(bytes[(at - base) as usize])) {
                    data_roots.push(range);
                    grew = true;
                }
            }
        }
        if !grew {
            break (funcs, bytes);
        }
    };

    // The main module's function indices: imports keep theirs.
    let mut remap = vec![u32::MAX; module.func_count()];
    let mut next = 0;
    for (func, slot) in remap.iter_mut().enumerate() {
        if func < module.imported_funcs as usize || funcs[func] == MAIN {
            *slot = next;
            next += 1;
        }
    }

    // The side modules: every set of gates something belongs to.
    let mut owners: Vec<Owner> = funcs
        .iter()
        .chain(&bytes)
        .copied()
        .filter(|o| *o != NONE && *o != MAIN)
        .collect();
    owners.sort_unstable();
    owners.dedup();
    let name_of = |owner: Owner| -> String {
        if owner.count_ones() == 1 {
            return lazy[owner.trailing_zeros() as usize].to_owned();
        }
        // Named by its gates, so a module's name (and file) stays while
        // they do.
        let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
        for (k, gate) in lazy.iter().enumerate() {
            if owner & (1 << k) != 0 {
                for byte in gate.bytes().chain([0]) {
                    hash = (hash ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3);
                }
            }
        }
        format!("nsh_shared_{hash:016x}")
    };
    let mut exported = vec![false; module.func_count()];
    let mut plans = Vec::new();
    for &owner in &owners {
        plans.push(Plan::new(
            &module,
            &body_relocs,
            &funcs,
            &bytes,
            owner,
            &mut exported,
        )?);
    }
    let mut sides = Vec::new();
    for plan in &plans {
        let gate = (plan.owner.count_ones() == 1).then(|| {
            let k = plan.owner.trailing_zeros() as usize;
            (gates[k], lazy[k])
        });
        let name = name_of(plan.owner);
        let out = plan.write(
            &module,
            &extra,
            &body_relocs,
            &bytes,
            &exported,
            gate,
            &name_of,
        )?;
        wasmparser::Validator::new()
            .validate_all(&out)
            .with_context(|| format!("the side module `{name}` is not valid"))?;
        let mut needs: Vec<String> = plan.from.iter().map(|o| name_of(*o)).collect();
        needs.sort();
        let users = (0..lazy.len())
            .filter(|&k| plan.owner & (1 << k) != 0)
            .map(|k| lazy[k].to_owned())
            .collect();
        sides.push(Side {
            name,
            gate: gate.map(|(_, g)| g.to_owned()),
            gates: users,
            needs,
            bytes: out,
        });
    }
    // Gates' modules first, in the given order; then the shared ones.
    sides.sort_by_key(|side| match &side.gate {
        Some(gate) => (
            0,
            lazy.iter().position(|g| g == gate).unwrap_or(0),
            String::new(),
        ),
        None => (1, 0, side.name.clone()),
    });

    let kept: Vec<&str> = module
        .exports
        .iter()
        .filter(|e| {
            e.kind != ExternalKind::Func
                || main_exports.contains(&e.name)
                || kept_main.contains(&e.name)
                || (lazy_gates.contains(&e.name) && funcs[e.index as usize] == MAIN)
        })
        .map(|e| e.name)
        .collect();
    let out = write_main(
        &module,
        &extra,
        &body_relocs,
        &funcs,
        &bytes,
        &remap,
        &exported,
        &kept,
        bindgen,
    )?;
    wasmparser::Validator::new()
        .validate_all(&out)
        .context("the main module is not valid")?;
    Ok(Split { main: out, sides })
}

/// Checks that `processed`, what wasm-bindgen made of `main` (a main module
/// [`split`] for it), still has what the side modules import from it, as
/// they import it: the memory and the function table, at least as large,
/// the table's slots `main` fills and no other (the side modules fill the
/// others), each with a function of the same type (side modules call them
/// by it) unless wasm-bindgen put an import of its glue there, and the `__nsh_g*` globals and `__nsh_f*` functions, of the
/// same types, the globals with the same initial values (the stack
/// pointer's among them). Its data stays where `main`'s was: the side
/// modules' data is at fixed addresses next to it.
pub(crate) fn check_processed(main: &[u8], processed: &[u8]) -> anyhow::Result<()> {
    let before = SharedExports::read(main)?;
    let after = SharedExports::read(processed)?;
    for (name, item) in &before.exports {
        let Some(found) = after.exports.get(name) else {
            bail!("wasm-bindgen left out the main module's `{name}`, which side modules import");
        };
        let kept = match (item, found) {
            (Shared::Memory(was), Shared::Memory(is)) | (Shared::Table(was), Shared::Table(is)) => {
                is >= was
            }
            _ => item == found,
        };
        ensure!(
            kept,
            "wasm-bindgen changed the main module's `{name}`, which side modules import"
        );
    }
    ensure!(
        before.slots.keys().eq(after.slots.keys()),
        "wasm-bindgen changed which slots of the main module's function table it fills"
    );
    // wasm-bindgen replaces the functions describing a closure or a cast
    // with imports of the JS it makes for them, of other types, in their
    // slots too: it does so without the split, and only its glue calls
    // them, so the side modules do not.
    if let Some(slot) = before
        .slots
        .iter()
        .find(|&(slot, ty)| after.slots[slot] != *ty && !after.glue.contains(slot))
        .map(|(slot, _)| slot)
    {
        bail!(
            "wasm-bindgen changed the type of the function in slot {slot} of the main module's function table"
        );
    }
    let data = merged(before.data);
    if let Some((start, end)) = after
        .data
        .into_iter()
        .find(|&(start, end)| !data.iter().any(|&(s, e)| s <= start && end <= e))
    {
        bail!(
            "wasm-bindgen put data at {start}..{end} in the main module's memory, outside its data, where side modules' data may be"
        );
    }
    Ok(())
}

/// `ranges` sorted and with the adjacent and overlapping ones joined.
fn merged(mut ranges: Vec<(u64, u64)>) -> Vec<(u64, u64)> {
    ranges.sort_unstable();
    let mut out: Vec<(u64, u64)> = Vec::new();
    for (start, end) in ranges {
        match out.last_mut() {
            Some(last) if start <= last.1 => last.1 = last.1.max(end),
            _ => out.push((start, end)),
        }
    }
    out
}

/// What side modules import from a main module ([`check_processed`]).
#[derive(PartialEq)]
enum Shared {
    Memory(u64),
    Table(u64),
    Global(wasmparser::GlobalType, Option<i32>),
    Func(wasmparser::FuncType),
}

struct SharedExports {
    exports: BTreeMap<String, Shared>,
    /// The slots of the exported function table its element segments fill,
    /// with the type of the function in each, when it names one.
    slots: BTreeMap<u32, Option<wasmparser::FuncType>>,
    /// The slots of the exported function table filled with an imported
    /// function.
    glue: std::collections::BTreeSet<u32>,
    /// Where its active data segments are in memory 0: start, end.
    data: Vec<(u64, u64)>,
}

impl SharedExports {
    fn read(wasm: &[u8]) -> anyhow::Result<Self> {
        let mut types = Vec::new();
        let mut funcs = Vec::new();
        let mut globals = Vec::new();
        let mut memories = Vec::new();
        let mut tables = Vec::new();
        let mut exports = Vec::new();
        let mut segments = Vec::new();
        let mut imported = 0;
        let mut data = Vec::new();
        for payload in Parser::new(0).parse_all(wasm) {
            match payload? {
                Payload::TypeSection(reader) => {
                    for ty in reader.into_iter_err_on_gc_types() {
                        types.push(ty?);
                    }
                }
                Payload::ImportSection(reader) => {
                    for import in reader.into_imports() {
                        match import?.ty {
                            TypeRef::Func(ty) | TypeRef::FuncExact(ty) => {
                                funcs.push(ty);
                                imported += 1;
                            }
                            TypeRef::Memory(memory) => memories.push(memory.initial),
                            TypeRef::Table(table) => tables.push(table.initial),
                            TypeRef::Global(_) => bail!("the main module imports globals"),
                            TypeRef::Tag(_) => {}
                        }
                    }
                }
                Payload::FunctionSection(reader) => {
                    for ty in reader {
                        funcs.push(ty?);
                    }
                }
                Payload::TableSection(reader) => {
                    for table in reader {
                        tables.push(table?.ty.initial);
                    }
                }
                Payload::MemorySection(reader) => {
                    for memory in reader {
                        memories.push(memory?.initial);
                    }
                }
                Payload::GlobalSection(reader) => {
                    for global in reader {
                        let global = global?;
                        let value = match global.init_expr.get_operators_reader().read()? {
                            Operator::I32Const { value } => Some(value),
                            _ => None,
                        };
                        globals.push((global.ty, value));
                    }
                }
                Payload::ExportSection(reader) => {
                    for export in reader {
                        let export = export?;
                        exports.push((export.name.to_owned(), export.kind, export.index));
                    }
                }
                Payload::ElementSection(reader) => {
                    for element in reader {
                        let element = element?;
                        let wasmparser::ElementKind::Active {
                            table_index,
                            offset_expr,
                        } = element.kind
                        else {
                            continue;
                        };
                        // Each item: `None` for an empty slot, else the type
                        // of its function, when it names one.
                        let type_of = |func: u32| {
                            let ty = funcs
                                .get(func as usize)
                                .and_then(|&ty| types.get(ty as usize));
                            ty.cloned()
                                .context("a function of the main module has no type")
                        };
                        let mut glue = Vec::new();
                        let filled: Vec<Option<Option<wasmparser::FuncType>>> = match element.items
                        {
                            wasmparser::ElementItems::Functions(items) => items
                                .into_iter()
                                .enumerate()
                                .map(|(at, f)| {
                                    let f = f?;
                                    if f < imported {
                                        glue.push(at as u32);
                                    }
                                    anyhow::Ok(Some(Some(type_of(f)?)))
                                })
                                .collect::<Result<_, _>>()?,
                            wasmparser::ElementItems::Expressions(_, items) => items
                                .into_iter()
                                .enumerate()
                                .map(|(at, item)| {
                                    Ok(match item?.get_operators_reader().read()? {
                                        Operator::RefNull { .. } => None,
                                        Operator::RefFunc { function_index } => {
                                            if function_index < imported {
                                                glue.push(at as u32);
                                            }
                                            Some(Some(type_of(function_index)?))
                                        }
                                        _ => Some(None),
                                    })
                                })
                                .collect::<anyhow::Result<_>>()?,
                        };
                        let offset = super::i32_const(&offset_expr)? as u32;
                        segments.push((table_index.unwrap_or(0), offset, filled, glue));
                    }
                }
                Payload::DataSection(reader) => {
                    for segment in reader {
                        let segment = segment?;
                        if let wasmparser::DataKind::Active {
                            memory_index: 0,
                            offset_expr,
                        } = segment.kind
                        {
                            let start = u64::from(super::i32_const(&offset_expr)? as u32);
                            data.push((start, start + segment.data.len() as u64));
                        }
                    }
                }
                _ => {}
            }
        }
        let mut shared = SharedExports {
            exports: BTreeMap::new(),
            slots: BTreeMap::new(),
            glue: Default::default(),
            data,
        };
        for (name, kind, index) in exports {
            let index = index as usize;
            let item = match kind {
                ExternalKind::Memory if name == "memory" => Shared::Memory(memories[index]),
                ExternalKind::Table if name == TABLE => {
                    for (table, offset, filled, glue) in &segments {
                        if *table as usize == index {
                            shared.glue.extend(glue.iter().map(|at| offset + at));
                            shared.slots.extend(filled.iter().zip(*offset..).filter_map(
                                |(item, slot)| item.as_ref().map(|ty| (slot, ty.clone())),
                            ));
                        }
                    }
                    Shared::Table(tables[index])
                }
                ExternalKind::Global if name.starts_with("__nsh_g") => {
                    let (ty, value) = globals[index];
                    Shared::Global(ty, value)
                }
                ExternalKind::Func if name.starts_with("__nsh_f") => {
                    let ty = types
                        .get(funcs[index] as usize)
                        .context("a function of the main module has no type")?;
                    Shared::Func(ty.clone())
                }
                _ => continue,
            };
            shared.exports.insert(name, item);
        }
        Ok(shared)
    }
}

/// What [`Module`] does not keep: the types of the imported functions and
/// of the globals, and the table's export.
#[derive(Default)]
struct Extra {
    import_types: Vec<u32>,
    /// Each global's value type (its byte) and whether it is mutable.
    globals: Vec<(u8, bool)>,
}

impl Extra {
    fn parse(wasm: &[u8]) -> anyhow::Result<Self> {
        let mut extra = Extra::default();
        for payload in Parser::new(0).parse_all(wasm) {
            match payload? {
                Payload::ImportSection(reader) => {
                    for import in reader.into_imports() {
                        if let TypeRef::Func(ty) | TypeRef::FuncExact(ty) = import?.ty {
                            extra.import_types.push(ty);
                        }
                    }
                }
                Payload::GlobalSection(reader) => {
                    for global in reader {
                        let ty = global?.ty;
                        let byte = match ty.content_type {
                            ValType::I32 => 0x7f,
                            ValType::I64 => 0x7e,
                            ValType::F32 => 0x7d,
                            ValType::F64 => 0x7c,
                            ValType::V128 => 0x7b,
                            ValType::Ref(_) => {
                                bail!("the web runtime has a global of a reference type")
                            }
                        };
                        extra.globals.push((byte, ty.mutable));
                    }
                }
                _ => {}
            }
        }
        Ok(extra)
    }
}

impl Module<'_> {
    /// The lowest address of the data.
    fn data_low(&self) -> u32 {
        self.segments.first().map_or(0, |s| s.address)
    }

    /// The end of the data.
    fn data_high(&self) -> u32 {
        self.segments
            .last()
            .map_or(0, |s| s.address + s.bytes.len() as u32)
    }

    /// The type of function `func`.
    fn type_of(&self, extra: &Extra, func: u32) -> u32 {
        match func.checked_sub(self.imported_funcs) {
            Some(defined) => self.func_types[defined as usize],
            None => extra.import_types[func as usize],
        }
    }

    /// The table slot the linker gave each function (`u32::MAX`: none).
    fn slots(&self) -> Vec<u32> {
        let mut slots = vec![u32::MAX; self.func_count()];
        if let Some((base, funcs)) = &self.elements {
            for (index, &func) in funcs.iter().enumerate() {
                slots[func as usize] = *base as u32 + index as u32;
            }
        }
        slots
    }

    /// The functions whose code calls, or takes the table slot of, a
    /// function wasm-bindgen replaces in the module it reads: one of its
    /// imports ([`super::BINDGEN_IMPORTS`]), or the shim of a generic import
    /// (a function that calls [`super::DESCRIBE_GENERIC_IMPORT`]), whose calls it
    /// points at an import of its own. wasm-bindgen rewrites these functions
    /// and runs the descriptors they reach, so they and what they reach are
    /// roots of the main module, the one it runs on: a side module calls
    /// none of what it replaces.
    fn bindgen_callers(&self, body_relocs: &[Range<usize>]) -> anyhow::Result<Vec<u32>> {
        let refers = |defined: usize, to: &dyn Fn(u32) -> bool| -> anyhow::Result<bool> {
            for entry in &self.code_relocs[body_relocs[defined].clone()] {
                if matches!(
                    entry.ty,
                    RelocationType::FunctionIndexLeb
                        | RelocationType::FunctionIndexI32
                        | RelocationType::TableIndexSleb
                        | RelocationType::TableIndexI32
                ) && to(self.func_of(entry)?)
                {
                    return Ok(true);
                }
            }
            Ok(false)
        };
        let mut replaced = vec![false; self.func_count()];
        for &func in &self.bindgen_imports {
            replaced[func as usize] = true;
        }
        if let Some(describe) = self.describe_generic {
            for defined in 0..self.bodies.len() {
                if refers(defined, &|func| func == describe)? {
                    replaced[self.imported_funcs as usize + defined] = true;
                }
            }
        }
        let mut callers = Vec::new();
        for defined in 0..self.bodies.len() {
            if refers(defined, &|func| replaced[func as usize])? {
                callers.push(self.imported_funcs + defined as u32);
            }
        }
        Ok(callers)
    }
}

/// The runs of bytes `owner` has, as (address, bytes) with their data
/// relocations patched by `patch`.
fn runs(
    module: &Module<'_>,
    bytes: &[Owner],
    owner: Owner,
    patch: &dyn Fn(&mut [u8], &RelocationEntry) -> anyhow::Result<()>,
) -> anyhow::Result<Vec<(u32, Vec<u8>)>> {
    let base = module.data_low();
    let mut out: Vec<(u32, Vec<u8>)> = Vec::new();
    for segment in &module.segments {
        let len = segment.bytes.len() as u32;
        let mut at = 0;
        while at < len {
            let address = segment.address + at;
            if bytes[(address - base) as usize] != owner {
                at += 1;
                continue;
            }
            let start = at;
            while at < len && bytes[(segment.address + at - base) as usize] == owner {
                at += 1;
            }
            let from = segment.bytes.start + start as usize;
            let mut run = module.wasm[from..from + (at - start) as usize].to_vec();
            let (lo_addr, hi_addr) = (segment.address + start, segment.address + at);
            let lo = module.data_relocs.partition_point(|r| r.address < lo_addr);
            let hi = module.data_relocs.partition_point(|r| r.address < hi_addr);
            for reloc in &module.data_relocs[lo..hi] {
                let offset = (reloc.address - lo_addr) as usize;
                let extent = reloc.entry.ty.extent();
                ensure!(
                    offset + extent <= run.len(),
                    "a data relocation across modules"
                );
                patch(&mut run[offset..offset + extent], &reloc.entry)?;
            }
            // Memory starts zeroed: zeros need no bytes.
            if run.iter().any(|b| *b != 0) {
                out.push((lo_addr, run));
            }
        }
    }
    Ok(out)
}

/// Rewrites a function index a relocation names with `index`; table slots,
/// addresses, types and globals stay as they are.
fn patch_funcs(
    module: &Module<'_>,
    bytes: &mut [u8],
    entry: &RelocationEntry,
    index: &dyn Fn(u32) -> anyhow::Result<u32>,
) -> anyhow::Result<()> {
    match entry.ty {
        RelocationType::FunctionIndexLeb => {
            let func = module.func_of(entry)?;
            check(read_uleb5(bytes) == func, entry)?;
            put_uleb5(bytes, index(func)?);
        }
        RelocationType::FunctionIndexI32 => {
            let func = module.func_of(entry)?;
            check(read_u32(bytes) == func, entry)?;
            bytes[..4].copy_from_slice(&index(func)?.to_le_bytes());
        }
        // Addresses (`__heap_base` too: nothing moves), table slots, types
        // and globals stay.
        _ => {}
    }
    Ok(())
}

/// A function's body with its function indices patched.
fn body(
    module: &Module<'_>,
    body_relocs: &[std::ops::Range<usize>],
    defined: usize,
    index: &dyn Fn(u32) -> anyhow::Result<u32>,
) -> anyhow::Result<Vec<u8>> {
    let range = &module.bodies[defined];
    let mut bytes = module.wasm[range.clone()].to_vec();
    for entry in &module.code_relocs[body_relocs[defined].clone()] {
        let at = module.code_start + entry.offset as usize - range.start;
        let extent = entry.ty.extent();
        ensure!(
            at + extent <= bytes.len(),
            "a relocation past its function's end"
        );
        patch_funcs(module, &mut bytes[at..at + extent], entry, index)?;
    }
    Ok(bytes)
}

/// An element section of one active segment per run of consecutive slots.
fn elements(entries: &[(u32, u32)]) -> Vec<u8> {
    let mut runs: Vec<(u32, Vec<u32>)> = Vec::new();
    for &(slot, func) in entries {
        match runs.last_mut() {
            Some((start, funcs)) if *start + funcs.len() as u32 == slot => funcs.push(func),
            _ => runs.push((slot, vec![func])),
        }
    }
    let mut section = Vec::new();
    put_uleb(&mut section, runs.len() as u64);
    for (start, funcs) in runs {
        section.extend_from_slice(&[0, 0x41]);
        put_sleb(&mut section, i64::from(start as i32));
        section.push(0x0b);
        put_uleb(&mut section, funcs.len() as u64);
        for func in funcs {
            put_uleb(&mut section, func.into());
        }
    }
    section
}

fn data_section(segments: &[(u32, Vec<u8>)]) -> Vec<u8> {
    let mut section = Vec::new();
    put_uleb(&mut section, segments.len() as u64);
    for (address, bytes) in segments {
        section.extend_from_slice(&[0, 0x41]);
        put_sleb(&mut section, i64::from(*address as i32));
        section.push(0x0b);
        put_uleb(&mut section, bytes.len() as u64);
        section.extend_from_slice(bytes);
    }
    section
}

/// The `name` custom section `section` (its contents) with only its
/// globals' names (subsection 7), which the main module keeps as they are.
fn global_names(section: &[u8]) -> anyhow::Result<Vec<u8>> {
    let mut reader = wasmparser::BinaryReader::new(section, 0);
    let mut out = Vec::new();
    let name = reader.read_string()?;
    put_name(&mut out, name);
    while !reader.eof() {
        let id = reader.read_u8()?;
        let size = reader.read_var_u32()? as usize;
        let contents = reader.read_bytes(size)?;
        if id == 7 {
            out.push(id);
            put_uleb(&mut out, size as u64);
            out.extend_from_slice(contents);
        }
    }
    Ok(out)
}

fn put_name(out: &mut Vec<u8>, name: &str) {
    put_uleb(out, name.len() as u64);
    out.extend_from_slice(name.as_bytes());
}

fn put_section(out: &mut Vec<u8>, id: u8, section: &[u8]) {
    out.push(id);
    put_uleb(out, section.len() as u64);
    out.extend_from_slice(section);
}

#[allow(clippy::too_many_arguments)]
fn write_main(
    module: &Module<'_>,
    extra: &Extra,
    body_relocs: &[std::ops::Range<usize>],
    funcs: &[Owner],
    bytes: &[Owner],
    remap: &[u32],
    exported: &[bool],
    kept: &[&str],
    bindgen: bool,
) -> anyhow::Result<Vec<u8>> {
    let index = |func: u32| -> anyhow::Result<u32> {
        let new = remap[func as usize];
        ensure!(
            new != u32::MAX,
            "the main module calls function {func}, which it does not have"
        );
        Ok(new)
    };
    let slots = module.slots();
    let mut table: Vec<(u32, u32)> = (0..module.func_count())
        // Every main function the linker gave a slot: side modules take
        // their addresses too.
        .filter(|&f| funcs[f] == MAIN && slots[f] != u32::MAX)
        .map(|f| (slots[f], remap[f]))
        .collect();
    table.sort_unstable();
    let segments = runs(module, bytes, MAIN, &|b, e| {
        patch_funcs(module, b, e, &index)
    })?;

    let mut out = Vec::with_capacity(module.wasm.len() / 2);
    out.extend_from_slice(&module.wasm[..8]);
    for (id, range, name) in &module.sections {
        let mut section = Vec::new();
        match id {
            // What wasm-bindgen reads: the features the module was built
            // with (it uses externrefs when it has reference types), and
            // the globals' names (it finds the stack pointer by its name).
            // The functions' names no longer match their indices.
            0 if bindgen && *name == "target_features" => {
                section.extend_from_slice(&module.wasm[range.clone()]);
            }
            0 if bindgen && *name == "name" => {
                section = global_names(&module.wasm[range.clone()])?;
            }
            0 if dropped_custom(name) => continue,
            3 => {
                let types: Vec<u32> = (0..module.bodies.len())
                    .filter(|&d| funcs[module.imported_funcs as usize + d] == MAIN)
                    .map(|d| module.func_types[d])
                    .collect();
                put_uleb(&mut section, types.len() as u64);
                for ty in types {
                    put_uleb(&mut section, ty.into());
                }
            }
            7 => {
                let mut entries: Vec<(String, u8, u32)> = Vec::new();
                for export in &module.exports {
                    if !kept.contains(&export.name) {
                        continue;
                    }
                    let (kind, index) = match export.kind {
                        ExternalKind::Func => (0, remap[export.index as usize]),
                        ExternalKind::Table => (1, export.index),
                        ExternalKind::Memory => (2, export.index),
                        ExternalKind::Global => (3, export.index),
                        ExternalKind::Tag => (4, export.index),
                        ExternalKind::FuncExact => bail!("an exact function export"),
                    };
                    entries.push((export.name.to_owned(), kind, index));
                }
                entries.push((TABLE.into(), 1, 0));
                for g in 0..extra.globals.len() {
                    entries.push((format!("__nsh_g{g}"), 3, g as u32));
                }
                for (func, exported) in exported.iter().enumerate() {
                    if *exported && (func < module.imported_funcs as usize || funcs[func] == MAIN) {
                        entries.push((format!("__nsh_f{func}"), 0, remap[func]));
                    }
                }
                put_uleb(&mut section, entries.len() as u64);
                for (name, kind, index) in entries {
                    put_name(&mut section, &name);
                    section.push(kind);
                    put_uleb(&mut section, index.into());
                }
            }
            8 => put_uleb(&mut section, index(module.start.unwrap_or(0))?.into()),
            9 => {
                if table.is_empty() {
                    continue;
                }
                section = elements(&table);
            }
            10 => {
                let kept: Vec<usize> = (0..module.bodies.len())
                    .filter(|&d| funcs[module.imported_funcs as usize + d] == MAIN)
                    .collect();
                put_uleb(&mut section, kept.len() as u64);
                for d in kept {
                    let bytes = body(module, body_relocs, d, &index)?;
                    put_uleb(&mut section, bytes.len() as u64);
                    section.extend_from_slice(&bytes);
                }
            }
            12 => put_uleb(&mut section, segments.len() as u64),
            11 => section = data_section(&segments),
            _ => section.extend_from_slice(&module.wasm[range.clone()]),
        }
        put_section(&mut out, *id, &section);
    }
    Ok(out)
}

/// One side module's functions: those it imports, then its own.
struct Plan {
    owner: Owner,
    /// What it imports, by the module that has it ([`MAIN`] for the main
    /// module and its imports).
    imports: Vec<(Owner, u32)>,
    /// The side modules it imports from.
    from: Vec<Owner>,
    own: Vec<u32>,
    index: Vec<u32>,
}

impl Plan {
    fn new(
        module: &Module<'_>,
        body_relocs: &[std::ops::Range<usize>],
        funcs: &[Owner],
        bytes: &[Owner],
        owner: Owner,
        exported: &mut [bool],
    ) -> anyhow::Result<Plan> {
        let own: Vec<u32> = (0..module.func_count() as u32)
            .filter(|&f| funcs[f as usize] == owner)
            .collect();
        let mut wanted = vec![false; module.func_count()];
        let mut note = |entry: &RelocationEntry| -> anyhow::Result<()> {
            if matches!(
                entry.ty,
                RelocationType::FunctionIndexLeb | RelocationType::FunctionIndexI32
            ) {
                let func = module.func_of(entry)?;
                if funcs[func as usize] != owner {
                    wanted[func as usize] = true;
                }
            }
            Ok(())
        };
        for &func in &own {
            let defined = (func - module.imported_funcs) as usize;
            for entry in &module.code_relocs[body_relocs[defined].clone()] {
                note(entry)?;
            }
        }
        let base = module.data_low();
        for reloc in &module.data_relocs {
            if bytes[(reloc.address - base) as usize] == owner {
                note(&reloc.entry)?;
            }
        }
        let mut imports = Vec::new();
        let mut from = Vec::new();
        for func in (0..module.func_count() as u32).filter(|&f| wanted[f as usize]) {
            let has = if func < module.imported_funcs {
                MAIN
            } else {
                funcs[func as usize]
            };
            // What a module reaches, its callees reach with at least the
            // same gates: never a module it is itself imported by.
            ensure!(
                has == MAIN || (has & owner == owner && has != owner),
                "a side module calls function {func}, which no module it may import from has"
            );
            exported[func as usize] = true;
            if has != MAIN && !from.contains(&has) {
                from.push(has);
            }
            imports.push((has, func));
        }
        // Grouped by module, as they are imported.
        imports.sort_by_key(|&(has, func)| (has, func));
        let mut index = vec![u32::MAX; module.func_count()];
        for (i, func) in imports
            .iter()
            .map(|(_, f)| *f)
            .chain(own.iter().copied())
            .enumerate()
        {
            index[func as usize] = i as u32;
        }
        Ok(Plan {
            owner,
            imports,
            from,
            own,
            index,
        })
    }

    #[allow(clippy::too_many_arguments)]
    fn write(
        &self,
        module: &Module<'_>,
        extra: &Extra,
        body_relocs: &[std::ops::Range<usize>],
        bytes: &[Owner],
        exported: &[bool],
        gate: Option<(u32, &str)>,
        name_of: &dyn Fn(Owner) -> String,
    ) -> anyhow::Result<Vec<u8>> {
        let lookup = |func: u32| -> anyhow::Result<u32> {
            let i = self.index[func as usize];
            ensure!(
                i != u32::MAX,
                "a side module calls function {func}, which it does not import"
            );
            Ok(i)
        };
        let mut out = module.wasm[..8].to_vec();
        // Types: the main module's, as they are.
        let types = module
            .sections
            .iter()
            .find(|(id, ..)| *id == 1)
            .context("the web runtime has no types")?;
        put_section(&mut out, 1, &module.wasm[types.1.clone()]);

        let mut section = Vec::new();
        let count = 2 + extra.globals.len() + self.imports.len();
        put_uleb(&mut section, count as u64);
        put_name(&mut section, "main");
        put_name(&mut section, "memory");
        section.push(2);
        let memory = module
            .memory
            .as_ref()
            .context("the web runtime has no memory")?;
        put_limits(&mut section, memory.initial, None);
        put_name(&mut section, "main");
        put_name(&mut section, TABLE);
        section.push(1);
        section.push(0x70);
        let table = module
            .table
            .as_ref()
            .context("the web runtime has no table")?;
        put_limits(&mut section, table.initial, None);
        for (g, (ty, mutable)) in extra.globals.iter().enumerate() {
            put_name(&mut section, "main");
            put_name(&mut section, &format!("__nsh_g{g}"));
            section.extend_from_slice(&[3, *ty, u8::from(*mutable)]);
        }
        for &(has, func) in &self.imports {
            let from = if has == MAIN {
                "main".to_owned()
            } else {
                name_of(has)
            };
            put_name(&mut section, &from);
            put_name(&mut section, &format!("__nsh_f{func}"));
            section.push(0);
            put_uleb(&mut section, module.type_of(extra, func).into());
        }
        put_section(&mut out, 2, &section);

        let mut section = Vec::new();
        put_uleb(&mut section, self.own.len() as u64);
        for &func in &self.own {
            put_uleb(&mut section, module.type_of(extra, func).into());
        }
        put_section(&mut out, 3, &section);

        let mut entries: Vec<(String, u32)> = Vec::new();
        if let Some((func, name)) = gate {
            entries.push((name.to_owned(), lookup(func)?));
        }
        for &func in &self.own {
            if exported[func as usize] {
                entries.push((format!("__nsh_f{func}"), lookup(func)?));
            }
        }
        let mut section = Vec::new();
        put_uleb(&mut section, entries.len() as u64);
        for (name, index) in entries {
            put_name(&mut section, &name);
            section.push(0);
            put_uleb(&mut section, index.into());
        }
        put_section(&mut out, 7, &section);

        // Every own function the linker gave a slot: other modules take
        // their addresses too.
        let slots = module.slots();
        let mut table: Vec<(u32, u32)> = self
            .own
            .iter()
            .filter(|&&f| slots[f as usize] != u32::MAX)
            .map(|&f| (slots[f as usize], self.index[f as usize]))
            .collect();
        table.sort_unstable();
        if !table.is_empty() {
            put_section(&mut out, 9, &elements(&table));
        }
        let segments = runs(module, bytes, self.owner, &|b, e| {
            patch_funcs(module, b, e, &lookup)
        })?;
        let mut section = Vec::new();
        put_uleb(&mut section, segments.len() as u64);
        put_section(&mut out, 12, &section);

        let mut section = Vec::new();
        put_uleb(&mut section, self.own.len() as u64);
        for &func in &self.own {
            let bytes = body(
                module,
                body_relocs,
                (func - module.imported_funcs) as usize,
                &lookup,
            )?;
            put_uleb(&mut section, bytes.len() as u64);
            section.extend_from_slice(&bytes);
        }
        put_section(&mut out, 10, &section);
        put_section(&mut out, 11, &data_section(&segments));
        Ok(out)
    }
}

/// Who has each function and each byte: the main module what `main`
/// reaches, the set of gates of `marks` that reach it otherwise.
fn owners(
    module: &Module<'_>,
    main: &super::Live,
    marks: &[super::Live],
) -> (Vec<Owner>, Vec<Owner>) {
    let base = module.data_low();
    let mut funcs = vec![NONE; module.func_count()];
    let mut bytes = vec![NONE; (module.data_high() - base) as usize];
    let mut claim = |live: &super::Live, owner: Owner| {
        for (func, live) in live.funcs.iter().enumerate() {
            if *live && func >= module.imported_funcs as usize && funcs[func] != MAIN {
                funcs[func] |= owner;
            }
        }
        for &(_, start, end, _) in &live.data {
            for at in start..end {
                let byte = &mut bytes[(at - base) as usize];
                if *byte != MAIN {
                    *byte |= owner;
                }
            }
        }
    };
    claim(main, MAIN);
    for (k, mark) in marks.iter().enumerate() {
        claim(mark, 1 << k);
    }
    (funcs, bytes)
}

#[cfg(test)]
mod tests {
    /// Splits the checkout's linkable runtime (built by `nsh package`) and
    /// prints the sizes: `cargo test -p nsh-cli split_the_runtime -- --ignored --nocapture`.
    #[test]
    #[ignore = "needs target/wasm32-unknown-unknown/web/nsh-browser.wasm"]
    fn split_the_runtime() {
        let path = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../target/wasm32-unknown-unknown/web/nsh-browser.wasm"
        );
        let wasm = std::fs::read(path).expect("the linkable runtime");
        let exports = super::super::exports(&wasm).unwrap();
        let lazy = [
            "nsh_feature_shader",
            "nsh_part_rich_editor",
            "nsh_part_text_view",
            "nsh_part_editor",
            "nsh_part_diff",
            "nsh_part_plot",
            "nsh_std_zlib",
            "nsh_part_data_table",
            "nsh_part_dock",
        ];
        let main: Vec<&str> = exports
            .iter()
            .map(String::as_str)
            .filter(|n| !lazy.contains(n))
            .collect();
        let split = super::split(&wasm, &main, &lazy, false).unwrap();
        let gz = |b: &[u8]| {
            use std::io::Write as _;
            let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best());
            e.write_all(b).unwrap();
            e.finish().unwrap().len()
        };
        println!("main {} gz {}", split.main.len(), gz(&split.main));
        for side in &split.sides {
            println!(
                "{} {} gz {} needs {:?}",
                side.name,
                side.bytes.len(),
                gz(&side.bytes),
                side.needs
            );
        }
    }
}