wasm_split_cli_support 0.2.3

Split a WASM module into lazily loadable chunks
Documentation
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
use std::{
    cell::OnceCell,
    collections::{HashMap, HashSet},
    ops::Range,
};

use eyre::{anyhow, bail, ensure, Result};
use tracing::trace;
use wasmparser::{
    CustomSectionReader, Data, DefinedDataSymbol, ElementItems, ElementKind, Export, ExternalKind,
    KnownCustom, Linking, Payload, RelocAddendKind, RelocationEntry, RelocationType, Segment,
    SymbolFlags, SymbolInfo,
};

use crate::{
    magic_constants,
    read::{GlobalId, InputFuncId, InputModule, InputOffset, SectionId, TableId, TagId},
    util::{find_subrange, shift_range, wasm_reloc_range},
};

// An offset (index) into the bytes of the input module
pub type SectionIndex = SectionId;
pub type SymbolIndex = usize;

#[derive(Default)]
pub struct RelocInfoParser<'a> {
    info: RelocInfo<'a>,
    has_linking_section: bool,
    // We NEED this to be present to identify the table to fix-up
    indirect_function_table: Option<TableId>,
}

impl<'a> RelocInfoParser<'a> {
    fn visit_linking(&mut self, subsection: Linking<'a>) -> Result<()> {
        match subsection {
            Linking::SegmentInfo(segments) => {
                ensure!(self.info.segments.is_empty(), "duplicate segments info");
                self.info.segments = segments.into_iter().collect::<Result<_, _>>()?;
                return Ok(());
            }
            Linking::SymbolTable(map) => {
                ensure!(self.info.symbols.is_empty(), "duplicate symbol table");
                self.info.symbols = map.into_iter().collect::<Result<Vec<_>, _>>()?;
                for sym in &self.info.symbols {
                    #[allow(clippy::single_match)] // other special cases might follow
                    match *sym {
                        SymbolInfo::Table {
                            name: Some("__indirect_function_table"),
                            index,
                            ..
                        } => {
                            self.indirect_function_table = Some(index as TableId);
                        }
                        _ => {}
                    }
                }
            }
            _ => {}
        }
        Ok(())
    }
    fn visit_custom(&mut self, custom: &CustomSectionReader<'a>) -> Result<bool> {
        match custom.as_known() {
            KnownCustom::Linking(reader) => {
                self.has_linking_section = true;
                for subsection in reader.subsections() {
                    let () = self.visit_linking(subsection?)?;
                }
                Ok(true)
            }
            KnownCustom::Reloc(reader) => {
                let mut reloc_entries = reader
                    .entries()
                    .into_iter()
                    .collect::<Result<Vec<_>, _>>()?;
                // We need to slices of entries when we search for a specific offset
                // We *might* be fine with assuming that the entries are already sorted, but a single pass to correct this
                // doesn't cost a lot of performance.
                reloc_entries.sort_unstable_by_key(|entry| entry.offset);
                self.info
                    .relocs
                    .insert(reader.section_index() as SectionIndex, reloc_entries);
                Ok(true)
            }
            _ => Ok(false),
        }
    }
    pub fn visit_payload(&mut self, payload: &Payload<'a>) -> Result<bool> {
        let section_index = self.info.relocatable_ranges.len();
        if let Some((_, mut section_range)) = payload.as_section() {
            if let Payload::CustomSection(custom) = payload {
                // Not sure where this is specified, and it might even be wrong.
                // https://github.com/WebAssembly/tool-conventions/blob/main/Linking.md#relocation-sections says:
                // > offset: relative to the relevant section's contents: offset zero is immediately after the id and size of the section
                // well, the data offset comes after the name of the custom section, not "immediately after the id and size".
                // alas, llvm seems to generate relocations relative to data offset though.
                section_range.start = custom.data_offset();
            }
            self.info.relocatable_ranges.push(section_range);
        }
        match payload {
            Payload::DataSection(_) => {
                self.info.data_section_index = section_index;
                Ok(true)
            }
            Payload::CodeSectionStart { .. } => {
                self.info.code_section_index = section_index;
                Ok(true)
            }
            Payload::CustomSection(reader) => {
                self.info.custom_sections.insert(section_index);
                self.visit_custom(reader)
            }
            _ => Ok(false),
        }
    }
    pub fn finish(self, module: &InputModule<'a>) -> Result<RelocInfo<'a>> {
        let mut info = self.info;
        info.data_symbols = get_data_symbols(&module.data_segments, &info.symbols)?;
        if !self.has_linking_section {
            bail!("No linking section found. Make sure that your program is compiled with `-Clink-args=--emit-relocs`.");
        }
        let Some(indirect_function_table) = self.indirect_function_table else {
            bail!("No indirect function table found in the reloc data");
        };
        info.indirect_table = indirect_function_table;
        get_indirect_functions(&mut info, indirect_function_table, module)?;
        reconstruct_global_symbols(&mut info, module)?;
        Ok(info)
    }
}

fn get_indirect_functions(
    this: &mut RelocInfo<'_>,
    iftable: TableId,
    module: &InputModule,
) -> Result<()> {
    let mut input_indirect_funcs = HashSet::new();
    for elems in &module.elements {
        let ElementKind::Active {
            table_index,
            offset_expr: _,
        } = elems.kind
        else {
            continue;
        };
        if table_index.unwrap_or(0) as usize != iftable {
            continue;
        }
        let ElementItems::Functions(funcs) = &elems.items else {
            bail!("expected immediate function ids in the indirect function table");
        };
        let funcs: Vec<u32> = funcs.clone().into_iter().collect::<Result<Vec<_>, _>>()?;
        input_indirect_funcs.extend(funcs.into_iter().map(|f| f as usize));
    }

    let mut visible_functions = HashSet::new();
    for symbol in &this.symbols {
        let SymbolInfo::Func { index, flags, .. } = *symbol else {
            continue;
        };
        if !input_indirect_funcs.contains(&(index as usize)) {
            continue;
        }
        let mut keep = flags.contains(SymbolFlags::NO_STRIP);
        keep |= flags.contains(SymbolFlags::EXPORTED | SymbolFlags::BINDING_WEAK);
        if !keep {
            continue;
        }
        visible_functions.insert(index as InputFuncId);
    }

    let mut referenced_indirects = visible_functions.clone();
    for relocation in this.relocs.values().flat_map(|relocs| relocs.iter()) {
        use RelocationType::*;
        if !matches!(
            relocation.ty,
            TableIndexI32
                | TableIndexI64
                | TableIndexSleb
                | TableIndexSleb64
                | TableIndexRelSleb
                | TableIndexRelSleb64
        ) {
            continue;
        }
        let symbol = &this.symbols[relocation.index as usize];
        let SymbolInfo::Func { index, .. } = *symbol else {
            bail!("invalid TABLE_INDEX relocation expected");
        };
        referenced_indirects.insert(index as InputFuncId);
    }

    this.visible_indirects = visible_functions;
    this.referenced_indirects = referenced_indirects;
    Ok(())
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct DataSymbol {
    pub symbol_index: SymbolIndex,
    // Range relative to the start of the WebAssembly file.
    pub range: Range<InputOffset>,
}

fn get_data_symbols(data_segments: &[Data], symbols: &[SymbolInfo]) -> Result<Vec<DataSymbol>> {
    let mut data_symbols = Vec::new();
    for (symbol_index, info) in symbols.iter().enumerate() {
        let SymbolInfo::Data {
            symbol: Some(symbol),
            ..
        } = info
        else {
            continue;
        };
        if symbol.size == 0 {
            // Ignore zero-size symbols since they cannot be the target of a relocation.
            continue;
        }
        let data_segment = data_segments
            .get(symbol.index as usize)
            .ok_or_else(|| anyhow!("Invalid data segment index in symbol: {:?}", symbol))?;
        let symbol_range = shift_range(0..u64::from(symbol.size), u64::from(symbol.offset));
        let data_start = data_segment.range.end - data_segment.data.len() as u64;
        if symbol_range.end > data_segment.range.end - data_start {
            bail!(
                "Invalid symbol {symbol:?} for data segment of size {:?}",
                data_segment.data.len()
            );
        }
        data_symbols.push(DataSymbol {
            symbol_index,
            range: shift_range(symbol_range, data_start),
        });
    }
    // We assume that these are sorted by range start later on
    data_symbols.sort_unstable_by_key(|symbol| symbol.range.start);
    Ok(data_symbols)
}

fn reconstruct_global_symbols(reloc_info: &mut RelocInfo<'_>, module: &InputModule) -> Result<()> {
    let symbol_as_global = &mut reloc_info.symbol_as_global;
    debug_assert!(
        symbol_as_global.is_empty(),
        "should not yet contain reconstructed data"
    );
    for &export in &module.exports {
        let Export {
            kind: ExternalKind::Global,
            index: global_index,
            name: global_name,
        } = export
        else {
            continue;
        };
        // You would think that there is reloc data available that tells us which symbols are exported
        // but there is not. The flags also do not tell us this information (which might be a bug in the
        // way symbol information is emitted). In any case, we reconstruct this information.
        let Some((symbol_index, symbol)) =
            reloc_info
                .symbols
                .iter()
                .enumerate()
                .find(|(_, &symbol_info)| {
                    let SymbolInfo::Data {
                        flags: _,
                        name: symbol_name,
                        symbol: _,
                    } = symbol_info
                    else {
                        return false;
                    };
                    symbol_name == global_name
                })
        else {
            continue;
        };
        let global_index: GlobalId = global_index.try_into().unwrap();
        if global_name.starts_with(magic_constants::GLOBAL_WASM_SPLIT_MARKER) {
            // let's try to be conservative and double check that the marker symbol is zero-sized data
            match *symbol {
                SymbolInfo::Data {
                    symbol: Some(symbol),
                    ..
                } if symbol.size == 0 => {
                    reloc_info.split_marker_globals.insert(global_index);
                    continue;
                }
                SymbolInfo::Data { .. } => tracing::warn!("expected zero sized marker export"),
                _ => tracing::warn!("expected wasm split marker export to export a data symbol"),
            }
        }
        tracing::trace!(
            "Recovered global symbol {global_index} mapping to {symbol_index} [{symbol:?}]"
        );
        #[cfg(debug_assertions)]
        {
            use eyre::ensure;
            use eyre::Context;
            use wasmparser::{Operator, ValType};

            let global = &module.globals[global_index];
            ensure!(
                matches!(global.ty.content_type, ValType::I32 | ValType::I64),
                "expected be a memory address"
            );
            ensure!(
                !global.ty.mutable && !global.ty.shared,
                "a memory address should be immutable and not shared"
            );
            let _addr: usize = match global.init_expr.get_operators_reader().read() {
                Ok(Operator::I32Const { value }) => {
                    usize::try_from(value).context("a valid address should fit into a usize")?
                }
                Ok(Operator::I64Const { value }) => {
                    usize::try_from(value).context("a valid address should fit into a usize")?
                }
                _ => {
                    bail!("expected a constant initializer expression for an exported data symbol");
                }
            };
            // could decode the symbol's address from the data-segment base address here too. Trust that this is correct
        }
        symbol_as_global.insert(global_index, symbol_index);
    }
    Ok(())
}

#[derive(Default)]
pub struct RelocInfo<'a> {
    // The relocatable range within each section. The start offset is the base from which
    // the relocation entry is offset from.
    pub relocatable_ranges: Vec<Range<InputOffset>>,
    pub segments: Vec<Segment<'a>>,
    pub custom_sections: HashSet<SectionId>,
    invalid_reloc_warn: OnceCell<()>,

    pub code_section_index: SectionIndex,
    pub data_section_index: SectionIndex,
    pub data_symbols: Vec<DataSymbol>,
    pub symbols: Vec<SymbolInfo<'a>>,
    pub relocs: HashMap<usize, Vec<RelocationEntry>>,

    pub indirect_table: TableId,
    pub stack_pointer: GlobalId,
    pub visible_indirects: HashSet<InputFuncId>,
    pub referenced_indirects: HashSet<InputFuncId>,
    // `#i -> #s` if Global #i contains the address of symbol #s
    pub symbol_as_global: HashMap<GlobalId, SymbolIndex>,
    pub split_marker_globals: HashSet<GlobalId>,
}

impl RelocInfo<'_> {
    pub fn print_relocs(&self) {
        use wasmparser::RelocAddendKind;
        if !tracing::event_enabled!(tracing::Level::TRACE) {
            return;
        }

        trace!("Symbols >>>>>>>>>>>>>>>>>>>>>>>>");
        for symbol in &self.symbols {
            trace!("{symbol:?}");
        }
        trace!("Symbols <<<<<<<<<<<<<<<<<<<<<<<<");
        for (section, relocs) in &self.relocs {
            trace!(%section, "Reloc section >>>>>>>>>>>>>>>>>>>>>>>>");
            for reloc in relocs {
                struct InvalidRelocIndex; // TODO: replace with std::fmt::from_fn
                impl std::fmt::Debug for InvalidRelocIndex {
                    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                        write!(f, "<invalid reloc index>")
                    }
                }
                let symbol = self
                    .symbols
                    .get(reloc.index as usize)
                    .map(|r| r as &dyn std::fmt::Debug)
                    .unwrap_or(&InvalidRelocIndex);
                let mut symbol_info = format!("  [{}] = {:?}({symbol:?})", reloc.offset, reloc.ty);
                if matches!(
                    reloc.ty.addend_kind(),
                    RelocAddendKind::Addend64 | RelocAddendKind::Addend32
                ) {
                    symbol_info += &format!(" {:+}", reloc.addend);
                }
                trace!(%symbol_info);
            }
            trace!(%section, "Reloc section <<<<<<<<<<<<<<<<<<<<<<<<");
        }
    }
    pub fn reloc_base(&self, section: SectionIndex) -> InputOffset {
        self.relocatable_ranges[section].start
    }
    pub fn data_section_reloc_base(&self) -> InputOffset {
        self.reloc_base(self.data_section_index)
    }
    pub fn code_section_reloc_base(&self) -> InputOffset {
        self.reloc_base(self.code_section_index)
    }
    pub fn iter_section_relocs(&self, section: SectionIndex) -> &'_ [RelocationEntry] {
        self.relocs
            .get(&section)
            .map(|relocs| &relocs[..])
            .unwrap_or_default()
    }
    pub fn iter_data_relocs(&self) -> impl Iterator<Item = &'_ RelocationEntry> {
        self.iter_section_relocs(self.data_section_index).iter()
    }
    pub fn iter_code_relocs(&self) -> impl Iterator<Item = &'_ RelocationEntry> {
        self.iter_section_relocs(self.code_section_index).iter()
    }
    pub fn get_relocations_for_range(
        &self,
        range: &Range<InputOffset>,
    ) -> (
        InputOffset,
        impl Iterator<Item = &RelocationEntry> + use<'_>,
    ) {
        let target_sections = find_subrange(
            &self.relocatable_ranges,
            |section_range| section_range.end >= range.end,
            |section_range| section_range.start < range.end,
        );
        let section = target_sections.start;
        let section_range = &self.relocatable_ranges[section];
        let reloc_base = section_range.start;
        assert!(
            section_range.start <= range.start && range.end <= section_range.end,
            "range to rellocate should be fully contained in one section"
        );
        let section_subrange = (range.start - reloc_base)..(range.end - reloc_base);

        let section_relocs = self.iter_section_relocs(section);
        let reloc_range = find_subrange(
            section_relocs,
            |reloc| u64::from(reloc.offset) >= section_subrange.start,
            |reloc| u64::from(reloc.offset) < section_subrange.end,
        );

        (reloc_base, section_relocs[reloc_range].iter())
    }

    pub fn get_relocated_data(
        module: &InputModule,
        range: Range<InputOffset>,
        target: &impl RelocTarget,
    ) -> Result<Vec<u8>> {
        let this = &module.reloc_info;
        let mut data = Vec::from(&module.raw[range.start as usize..range.end as usize]);
        let (reloc_base, relocs) = this.get_relocations_for_range(&range);
        let reloc_base_to_data_off = range.start - reloc_base;
        for relocation in relocs {
            this.apply_relocation(target, &mut data, reloc_base_to_data_off, relocation)?;
        }
        Ok(data)
    }

    pub fn expand_relocation(&self, relocation: &RelocationEntry) -> Result<RelocDetails<'_>> {
        use wasmparser::RelocationType::*;
        let symbol_index = relocation.index as usize;
        if symbol_index > self.symbols.len() {
            bail!("Found {relocation:?} with invalid symbol index?");
        }
        let symbol = &self.symbols[symbol_index];
        let ty = relocation.ty;
        match ty {
            MemoryAddrLeb | MemoryAddrSleb | MemoryAddrI32 | MemoryAddrLeb64 | MemoryAddrSleb64
            | MemoryAddrI64 | MemoryAddrTlsSleb | MemoryAddrLocrelI32 | MemoryAddrTlsSleb64
            | MemoryAddrRelSleb | MemoryAddrRelSleb64 => {
                let wasmparser::SymbolInfo::Data {
                    flags,
                    name,
                    symbol: ref symbol_def,
                } = *symbol
                else {
                    bail!("Expected a data symbol as target of a MEMORY_ADDR relocation, got {symbol:?}");
                };
                Ok(RelocDetails::MemoryAddr(DataDetails {
                    symbol_index,
                    _flags: flags,
                    _name: name,
                    definition: symbol_def.as_ref(),
                }))
            }
            TableIndexSleb | TableIndexSleb64 | TableIndexI32 | TableIndexI64 => {
                let wasmparser::SymbolInfo::Func { flags, index, name } = *symbol else {
                    bail!("Expected a func symbol as target of a TABLE_INDEX relocation, got {symbol:?}");
                };
                Ok(RelocDetails::TableIndex(SymbolDetails {
                    _symbol_index: symbol_index,
                    _flags: flags,
                    index: index as InputFuncId,
                    _name: name,
                }))
            }
            TableIndexRelSleb | TableIndexRelSleb64 => {
                let wasmparser::SymbolInfo::Func { flags, index, name } = *symbol else {
                    bail!("Expected a func symbol as target of a TABLE_INDEX relocation, got {symbol:?}");
                };
                Ok(RelocDetails::RelTableIndex(SymbolDetails {
                    _symbol_index: symbol_index,
                    _flags: flags,
                    index: index as InputFuncId,
                    _name: name,
                }))
            }
            wasmparser::RelocationType::FunctionIndexLeb
            | wasmparser::RelocationType::FunctionIndexI32 => {
                let wasmparser::SymbolInfo::Func { flags, index, name } = *symbol else {
                    bail!("Expected a func symbol as target of a FUNCTION_INDEX relocation, got {symbol:?}");
                };
                Ok(RelocDetails::FunctionIndex(SymbolDetails {
                    _symbol_index: symbol_index,
                    _flags: flags,
                    index: index as InputFuncId,
                    _name: name,
                }))
            }
            wasmparser::RelocationType::TableNumberLeb => {
                let wasmparser::SymbolInfo::Table { flags, index, name } = *symbol else {
                    bail!("Expected a table symbol as target of a TABLE_NUMBER relocation, got {symbol:?}");
                };
                Ok(RelocDetails::TableNumber(SymbolDetails {
                    _symbol_index: symbol_index,
                    _flags: flags,
                    index: index as TableId,
                    _name: name,
                }))
            }
            wasmparser::RelocationType::GlobalIndexI32
            | wasmparser::RelocationType::GlobalIndexLeb => {
                let wasmparser::SymbolInfo::Global { flags, index, name } = *symbol else {
                    bail!("Expected a global symbol as target of a GLOBAL_INDEX relocation, got {symbol:?}");
                };
                Ok(RelocDetails::GlobalIndex(SymbolDetails {
                    _symbol_index: symbol_index,
                    _flags: flags,
                    index: index as GlobalId,
                    _name: name,
                }))
            }
            wasmparser::RelocationType::EventIndexLeb => {
                let wasmparser::SymbolInfo::Event { flags, index, name } = *symbol else {
                    bail!("Expected a global symbol as target of a EVENT_INDEX relocation, got {symbol:?}");
                };
                Ok(RelocDetails::TagIndex(SymbolDetails {
                    _symbol_index: symbol_index,
                    _flags: flags,
                    index: index as TagId,
                    _name: name,
                }))
            }
            wasmparser::RelocationType::TypeIndexLeb => Ok(RelocDetails::TypeIndex {
                _symbol_idx: symbol_index,
                _symbol: *symbol,
            }),
            wasmparser::RelocationType::FunctionOffsetI32
            | wasmparser::RelocationType::FunctionOffsetI64 => {
                let wasmparser::SymbolInfo::Func { flags, index, name } = *symbol else {
                    bail!("Expected a func symbol as target of a FUNCTION_OFFSET relocation, got {symbol:?}");
                };
                Ok(RelocDetails::FunctionOffset(SymbolDetails {
                    _symbol_index: symbol_index,
                    _flags: flags,
                    index: index as InputFuncId,
                    _name: name,
                }))
            }
            wasmparser::RelocationType::SectionOffsetI32 => {
                let wasmparser::SymbolInfo::Section { flags, section } = *symbol else {
                    bail!("Expected a section symbol as target of a SECTION_OFFSET relocation, got {symbol:?}");
                };
                let section = section as SectionId;
                // If the reloc points to a section with semantic context (such as data/code), we expect to relocate against a symbol,
                // not by offset. It is used e.g. to point to DIE in debug_info sections. Why this happens via offset and not by some
                // kind of "symbol" "inside" that custom section with an associated range similar to data symbols is a question I can
                // not answer.
                // NOTE: it seems newer compiler versions do not bother to emit this in any case.
                ensure!(
                    self.custom_sections.contains(&section),
                    "Expect a SECTION_OFFSET relocation to point into a custom section"
                );
                Ok(RelocDetails::SectionOffset(SymbolDetails {
                    _symbol_index: symbol_index,
                    index: section,
                    _flags: flags,
                    _name: None,
                }))
            } // [relocate data segments]
              // TODO: there is no relocation for data segment indices. As such, we'd have to parse the opcodes to find
              // references to passive and declarative data segments. The solution: only handling active segments
              // and don't change the index of passive ones.
        }
    }

    fn apply_relocation<T: RelocTarget>(
        &self,
        reloc_target: &T,
        data: &mut [u8],
        reloc_base_to_data_off: u64,
        relocation: &RelocationEntry,
    ) -> Result<()> {
        // TODO(MSRV): -1i32.cast_unsigned() since rust 1.87
        let relocated = if relocation.index == (-1i32 as u32) {
            // We have found a relocation against a symbol that isn't in the symbol table.
            // This most likely means that we will miss out on correct relocations.
            // We must handle this though, as some compilers will emit relocations in the debug section
            // against non-public symbols and use index -1 for those.
            let fixup = reloc_target.fixup_reloc_entry(relocation)?;
            if fixup.is_none_or(|addr| addr == SENTINEL_UNDEF) {
                self.invalid_reloc_warn.get_or_init(|| {
                    tracing::warn!(
                        "Skipping relocation {relocation:?} with tombstone symbol (others omitted)"
                    );
                });
            }
            fixup
        } else {
            let details = self.expand_relocation(relocation)?;
            reloc_target.reloc_value(details)?
        };
        let relocation_range = wasm_reloc_range(relocation);
        let target = &mut data[(relocation_range.start - reloc_base_to_data_off) as usize
            ..(relocation_range.end - reloc_base_to_data_off) as usize];
        let ty = relocation.ty;
        let Some(value) = relocated else {
            return Ok(());
        };
        debug_assert!(
            relocation.addend == 0 || ty.addend_kind() != RelocAddendKind::None,
            "relocation {relocation:?} without addend should have addend == 0, not {}",
            relocation.addend,
        );
        let () = encode_for_ty(ty, value, relocation.addend, target, T::SENTINEL_UNDEF)?;
        Ok(())
    }
}

#[derive(Debug)]
pub struct SymbolDetails<'a, Idx> {
    pub _symbol_index: usize,
    pub index: Idx,
    pub _flags: SymbolFlags,
    pub _name: Option<&'a str>,
}

#[derive(Debug)]
pub struct DataDetails<'a> {
    pub symbol_index: usize,
    pub _flags: SymbolFlags,
    pub _name: &'a str,
    pub definition: Option<&'a DefinedDataSymbol>,
}

#[derive(Debug)]
pub enum RelocDetails<'a> {
    TypeIndex {
        _symbol_idx: usize,
        _symbol: SymbolInfo<'a>,
    },
    MemoryAddr(DataDetails<'a>),
    TableIndex(SymbolDetails<'a, InputFuncId>),
    RelTableIndex(SymbolDetails<'a, InputFuncId>),
    FunctionIndex(SymbolDetails<'a, InputFuncId>),
    TableNumber(SymbolDetails<'a, TableId>),
    GlobalIndex(SymbolDetails<'a, GlobalId>),
    TagIndex(SymbolDetails<'a, TagId>),
    FunctionOffset(SymbolDetails<'a, InputFuncId>),
    SectionOffset(SymbolDetails<'a, SectionId>),
}

pub const SENTINEL_UNDEF: u64 = u64::MAX;
pub trait RelocTarget {
    const SENTINEL_UNDEF: bool = false;
    /// Fixup a relocation entry with an invalid symbol. If this fixup fails,
    /// we warn and relocate to a tombstone address or error if tombstones
    /// are not enabled for this relocation context.
    fn fixup_reloc_entry(&self, entry: &RelocationEntry) -> Result<Option<u64>> {
        // assert: entry.index == (-1i32 as u32)
        ensure!(
            Self::SENTINEL_UNDEF,
            "Invalid relocation {entry:?} with tombstone symbol couldn't be fixed"
        );
        Ok(Some(SENTINEL_UNDEF))
    }
    fn reloc_value(&self, reloc: RelocDetails<'_>) -> Result<Option<u64>>;
}

fn encode_leb128_u32_5byte(mut value: u32, buf: &mut [u8; 5]) {
    for b in &mut buf[0..5] {
        *b = (value as u8) & 0x7f;
        value >>= 7;
    }
    for b in &mut buf[0..4] {
        *b |= 0x80;
    }
}

fn encode_leb128_i32_5byte(mut value: i32, buf: &mut [u8; 5]) {
    for b in &mut buf[0..5] {
        *b = (value as u8) & 0x7f;
        value >>= 7;
    }
    for b in &mut buf[0..4] {
        *b |= 0x80;
    }
}

fn encode_leb128_u64_10byte(mut value: u64, buf: &mut [u8; 10]) {
    for b in &mut buf[0..10] {
        *b = (value as u8) & 0x7f;
        value >>= 7;
    }
    for b in &mut buf[0..9] {
        *b |= 0x80;
    }
}

fn encode_leb128_i64_10byte(mut value: i64, buf: &mut [u8; 10]) {
    for b in &mut buf[0..10] {
        *b = (value as u8) & 0x7f;
        value >>= 7;
    }
    for b in &mut buf[0..9] {
        *b |= 0x80;
    }
}

fn encode_u32(value: u32, buf: &mut [u8; 4]) {
    *buf = value.to_le_bytes();
}

fn encode_u64(value: u64, buf: &mut [u8; 8]) {
    *buf = value.to_le_bytes();
}

fn encode_for_ty(
    ty: RelocationType,
    value: u64,
    addend: i64,
    target: &mut [u8],
    allow_undef: bool,
) -> Result<()> {
    use RelocationType::*;
    let resolved = if allow_undef && value == SENTINEL_UNDEF {
        Some(SENTINEL_UNDEF)
    } else {
        value.checked_add_signed(addend)
    };
    let Some(resolved) = resolved else {
        bail!("reloc {ty:?} <{value:x}{addend:+}> overflows");
    };
    macro_rules! try_into_value {
        ($resolved:ident as $t:ty, $msg:literal) => {
            match $resolved {
                SENTINEL_UNDEF if allow_undef => -1isize as $t,
                #[allow(irrefutable_let_patterns)]
                resolved if let Ok(resolved) = resolved.try_into() => resolved,
                resolved => {
                    bail!("{}: {resolved:x}", $msg);
                }
            }
        };
    }
    match ty {
        TableIndexI32 | MemoryAddrI32 | FunctionOffsetI32 | SectionOffsetI32 | GlobalIndexI32
        | FunctionIndexI32 | MemoryAddrLocrelI32 => {
            let resolved = try_into_value!(resolved as u32, "invalid value for I32 relocation");
            encode_u32(resolved, target.try_into().unwrap());
            Ok(())
        }
        FunctionIndexLeb | MemoryAddrLeb | TypeIndexLeb | GlobalIndexLeb | EventIndexLeb
        | TableNumberLeb => {
            let resolved = try_into_value!(resolved as u32, "invalid value for leb relocation");
            encode_leb128_u32_5byte(resolved, target.try_into().unwrap());
            Ok(())
        }
        TableIndexSleb | MemoryAddrSleb | MemoryAddrRelSleb | TableIndexRelSleb
        | MemoryAddrTlsSleb => {
            let resolved = try_into_value!(resolved as i32, "invalid value for sleb relocation");
            encode_leb128_i32_5byte(resolved, target.try_into().unwrap());
            Ok(())
        }
        FunctionOffsetI64 | MemoryAddrI64 | TableIndexI64 => {
            let resolved = try_into_value!(resolved as u64, "invalid value for I64 relocation");
            encode_u64(resolved, target.try_into().unwrap());
            Ok(())
        }
        MemoryAddrLeb64 => {
            let resolved = try_into_value!(resolved as u64, "invalid value for leb64 relocation");
            encode_leb128_u64_10byte(resolved, target.try_into().unwrap());
            Ok(())
        }
        MemoryAddrRelSleb64 | TableIndexSleb64 | TableIndexRelSleb64 | MemoryAddrTlsSleb64
        | MemoryAddrSleb64 => {
            let resolved = try_into_value!(resolved as i64, "invalid value for sleb64 relocation");
            encode_leb128_i64_10byte(resolved, target.try_into().unwrap());
            Ok(())
        }
    }
}