Coverage Report

Created: 2026-11-23 07:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wasmtime/crates/cranelift/src/obj.rs
Line
Count
Source
1
//! Object file builder.
2
//!
3
//! Creates ELF image based on `Compilation` information. The ELF contains
4
//! functions and trampolines in the ".text" section. It also contains all
5
//! relocation records for the linking stage. If DWARF sections exist, their
6
//! content will be written as well.
7
//!
8
//! The object file has symbols for each function and trampoline, as well as
9
//! symbols that refer to libcalls.
10
//!
11
//! The function symbol names have format "_wasm_function_N", where N is
12
//! `FuncIndex`. The defined wasm function symbols refer to a JIT compiled
13
//! function body, the imported wasm function do not. The trampolines symbol
14
//! names have format "_trampoline_N", where N is `SignatureIndex`.
15
16
use crate::{CompiledFunction, Compiler};
17
use cranelift_codegen::TextSectionBuilder;
18
use cranelift_codegen::isa::unwind::{UnwindInfo, systemv};
19
use cranelift_control::ControlPlane;
20
use gimli::RunTimeEndian;
21
use gimli::write::{Address, EhFrame, EndianVec, FrameTable, Writer};
22
use object::write::{Object, SectionId, StandardSegment, Symbol, SymbolId, SymbolSection};
23
use object::{Architecture, SectionFlags, SectionKind, SymbolFlags, SymbolKind, SymbolScope};
24
use std::ops::Range;
25
use wasmtime_environ::error::Result;
26
use wasmtime_environ::{Compiler as _, FuncKey, TripleExt, obj};
27
28
const TEXT_SECTION_NAME: &[u8] = b".text";
29
30
384k
fn text_align(compiler: &Compiler) -> u64 {
31
    // text pages will not be made executable with pulley, so the section
32
    // doesn't need to be padded out to page alignment boundaries.
33
384k
    if compiler.triple().is_pulley() {
34
55.5k
        0x1
35
    } else {
36
328k
        compiler.page_size_align()
37
    }
38
384k
}
39
40
/// A helper structure used to assemble the final text section of an executable,
41
/// plus unwinding information and other related details.
42
///
43
/// This builder relies on Cranelift-specific internals but assembles into a
44
/// generic `Object` which will get further appended to in a compiler-agnostic
45
/// fashion later.
46
pub struct ModuleTextBuilder<'a> {
47
    /// The target that we're compiling for, used to query target-specific
48
    /// information as necessary.
49
    compiler: &'a Compiler,
50
51
    /// The object file that we're generating code into.
52
    obj: &'a mut Object<'static>,
53
54
    /// The WebAssembly module we're generating code for.
55
    text_section: SectionId,
56
57
    unwind_info: UnwindInfoBuilder<'a>,
58
59
    /// In-progress text section that we're using cranelift's `MachBuffer` to
60
    /// build to resolve relocations (calls) between functions.
61
    text: Box<dyn TextSectionBuilder>,
62
63
    ctrl_plane: ControlPlane,
64
}
65
66
impl<'a> ModuleTextBuilder<'a> {
67
    /// Creates a new builder for the text section of an executable.
68
    ///
69
    /// The `.text` section will be appended to the specified `obj` along with
70
    /// any unwinding or such information as necessary. The `num_funcs`
71
    /// parameter indicates the number of times the `append_func` function will
72
    /// be called. The `finish` function will panic if this contract is not met.
73
192k
    pub fn new(
74
192k
        obj: &'a mut Object<'static>,
75
192k
        compiler: &'a Compiler,
76
192k
        text: Box<dyn TextSectionBuilder>,
77
192k
    ) -> Self {
78
        // Entire code (functions and trampolines) will be placed
79
        // in the ".text" section.
80
192k
        let text_section = obj.add_section(
81
192k
            obj.segment_name(StandardSegment::Text).to_vec(),
82
192k
            TEXT_SECTION_NAME.to_vec(),
83
192k
            SectionKind::Text,
84
        );
85
86
        // If this target is Pulley then flag the text section as not needing the
87
        // executable bit in virtual memory which means that the runtime won't
88
        // try to call `Mmap::make_executable`, which makes Pulley more
89
        // portable.
90
192k
        if compiler.triple().is_pulley() {
91
27.7k
            let SectionFlags::Elf { sh_flags, .. } = obj.section_flags_mut(text_section) else {
92
0
                unreachable!();
93
            };
94
27.7k
            *sh_flags = obj::SH_WASMTIME_NOT_EXECUTED;
95
164k
        }
96
97
192k
        Self {
98
192k
            compiler,
99
192k
            obj,
100
192k
            text_section,
101
192k
            unwind_info: Default::default(),
102
192k
            text,
103
192k
            ctrl_plane: ControlPlane::default(),
104
192k
        }
105
192k
    }
106
107
    /// Appends the `func` specified named `name` to this object.
108
    ///
109
    /// The `resolve_reloc_target` closure is used to resolve a relocation
110
    /// target to an adjacent function which has already been added or will be
111
    /// added to this object. The argument is the relocation target specified
112
    /// within `CompiledFunction` and the return value must be an index where
113
    /// the target will be defined by the `n`th call to `append_func`.
114
    ///
115
    /// Returns the symbol associated with the function as well as the range
116
    /// that the function resides within the text section.
117
3.44M
    pub fn append_func(
118
3.44M
        &mut self,
119
3.44M
        name: &str,
120
3.44M
        compiled_func: &'a CompiledFunction,
121
3.44M
        resolve_reloc_target: impl Fn(wasmtime_environ::FuncKey) -> usize,
122
3.44M
    ) -> (Option<SymbolId>, Range<u64>) {
123
3.44M
        let body = compiled_func.buffer.data();
124
3.44M
        let alignment = compiled_func.alignment;
125
3.44M
        let body_len = body.len() as u64;
126
3.44M
        let off = self
127
3.44M
            .text
128
3.44M
            .append(true, &body, alignment, &mut self.ctrl_plane);
129
130
3.44M
        let symbol_id = if self.compiler.tunables().debug_symbols {
131
2.03M
            Some(self.obj.add_symbol(Symbol {
132
2.03M
                name: name.as_bytes().to_vec(),
133
2.03M
                value: off,
134
2.03M
                size: body_len,
135
2.03M
                kind: SymbolKind::Text,
136
2.03M
                scope: SymbolScope::Compilation,
137
2.03M
                weak: false,
138
2.03M
                section: SymbolSection::Section(self.text_section),
139
2.03M
                flags: SymbolFlags::None,
140
2.03M
            }))
141
        } else {
142
1.41M
            None
143
        };
144
145
3.44M
        if let Some(info) = compiled_func.unwind_info() {
146
1.67M
            self.unwind_info.push(off, body_len, info);
147
1.77M
        }
148
149
12.2M
        for r in compiled_func.relocations() {
150
12.2M
            let reloc_offset = off + u64::from(r.offset);
151
152
            // This relocation is used to fill in which hostcall id is
153
            // desired within the `call_indirect_host` opcode of Pulley
154
            // itself. The relocation target is the start of the instruction
155
            // and the goal is to insert the static signature number, `n`,
156
            // into the instruction.
157
            //
158
            // At this time the instruction looks like:
159
            //
160
            //      +------+------+------+------+
161
            //      | OP   | OP_EXTENDED |  N   |
162
            //      +------+------+------+------+
163
            //
164
            // This 4-byte encoding has `OP` indicating this is an "extended
165
            // opcode" where `OP_EXTENDED` is a 16-bit extended opcode.
166
            // The `N` byte is the index of the signature being called and
167
            // is what's b eing filled in.
168
            //
169
            // See the `test_call_indirect_host_width` in
170
            // `pulley/tests/all.rs` for this guarantee as well.
171
12.2M
            if let FuncKey::PulleyHostCall(host_call) = r.reloc_target {
172
                #[cfg(feature = "pulley")]
173
                {
174
                    use pulley_interpreter::encode::Encode;
175
365k
                    assert_eq!(pulley_interpreter::CallIndirectHost::WIDTH, 4);
176
                }
177
365k
                let n = host_call.index();
178
365k
                let byte = u8::try_from(n).unwrap();
179
365k
                self.text.write(reloc_offset + 3, &[byte]);
180
365k
                continue;
181
11.9M
            }
182
183
11.9M
            let target = resolve_reloc_target(r.reloc_target);
184
11.9M
            if self
185
11.9M
                .text
186
11.9M
                .resolve_reloc(reloc_offset, r.reloc, r.addend, target)
187
            {
188
11.9M
                continue;
189
0
            }
190
191
0
            panic!("failed to resolve relocation: {r:?} -> {target}");
192
        }
193
194
3.44M
        (symbol_id, off..off + body_len)
195
3.44M
    }
196
197
    /// Forces "veneers" to be used for inter-function calls in the text
198
    /// section which means that in-bounds optimized addresses are never used.
199
    ///
200
    /// This is only useful for debugging cranelift itself and typically this
201
    /// option is disabled.
202
75.4k
    pub fn force_veneers(&mut self) {
203
75.4k
        self.text.force_veneers();
204
75.4k
    }
205
206
    /// Appends the specified amount of bytes of padding into the text section.
207
    ///
208
    /// This is only useful when fuzzing and/or debugging cranelift itself and
209
    /// for production scenarios `padding` is 0 and this function does nothing.
210
3.44M
    pub fn append_padding(&mut self, padding: usize) {
211
3.44M
        if padding == 0 {
212
1.70M
            return;
213
1.74M
        }
214
1.74M
        self.text
215
1.74M
            .append(false, &vec![0; padding], 1, &mut self.ctrl_plane);
216
3.44M
    }
217
218
    /// Indicates that the text section has been written completely and this
219
    /// will finish appending it to the original object.
220
    ///
221
    /// Note that this will also write out the unwind information sections if
222
    /// necessary.
223
192k
    pub fn finish(mut self, postprocess_text: impl FnOnce(&mut [u8])) {
224
        // Finish up the text section now that we're done adding functions.
225
192k
        let mut text = self.text.finish(&mut self.ctrl_plane);
226
227
192k
        postprocess_text(&mut text[..]);
228
229
192k
        self.obj
230
192k
            .section_mut(self.text_section)
231
192k
            .set_data(text, text_align(self.compiler));
232
233
        // Append the unwind information for all our functions, if necessary.
234
192k
        self.unwind_info
235
192k
            .append_section(self.compiler, self.obj, self.text_section);
236
192k
    }
237
}
238
239
/// Builder used to create unwind information for a set of functions added to a
240
/// text section.
241
#[derive(Default)]
242
struct UnwindInfoBuilder<'a> {
243
    windows_xdata: Vec<u8>,
244
    windows_pdata: Vec<RUNTIME_FUNCTION>,
245
    systemv_unwind_info: Vec<(u64, &'a systemv::UnwindInfo)>,
246
}
247
248
// This is a mirror of `RUNTIME_FUNCTION` in the Windows API, but defined here
249
// to ensure everything is always `u32` and to have it available on all
250
// platforms. Note that all of these specifiers here are relative to a "base
251
// address" which we define as the base of where the text section is eventually
252
// loaded.
253
#[expect(non_camel_case_types, reason = "matching Windows style, not Rust")]
254
struct RUNTIME_FUNCTION {
255
    begin: u32,
256
    end: u32,
257
    unwind_address: u32,
258
}
259
260
impl<'a> UnwindInfoBuilder<'a> {
261
    /// Pushes the unwind information for a function into this builder.
262
    ///
263
    /// The function being described must be located at `function_offset` within
264
    /// the text section itself, and the function's size is specified by
265
    /// `function_len`.
266
    ///
267
    /// The `info` should come from Cranelift. and is handled here depending on
268
    /// its flavor.
269
1.67M
    fn push(&mut self, function_offset: u64, function_len: u64, info: &'a UnwindInfo) {
270
1.67M
        match info {
271
            // Windows unwind information is stored in two locations:
272
            //
273
            // * First is the actual unwinding information which is stored
274
            //   in the `.xdata` section. This is where `info`'s emitted
275
            //   information will go into.
276
            // * Second are pointers to connect all this unwind information,
277
            //   stored in the `.pdata` section. The `.pdata` section is an
278
            //   array of `RUNTIME_FUNCTION` structures.
279
            //
280
            // Due to how these will be loaded at runtime the `.pdata` isn't
281
            // actually assembled byte-wise here. Instead that's deferred to
282
            // happen later during `write_windows_unwind_info` which will apply
283
            // a further offset to `unwind_address`.
284
            //
285
            // FIXME: in theory we could "intern" the `unwind_info` value
286
            // here within the `.xdata` section. Most of our unwind
287
            // information for functions is probably pretty similar in which
288
            // case the `.xdata` could be quite small and `.pdata` could
289
            // have multiple functions point to the same unwinding
290
            // information.
291
0
            UnwindInfo::WindowsX64(info) => {
292
0
                let unwind_size = info.emit_size();
293
0
                let mut unwind_info = vec![0; unwind_size];
294
0
                info.emit(&mut unwind_info);
295
296
                // `.xdata` entries are always 4-byte aligned
297
0
                while self.windows_xdata.len() % 4 != 0 {
298
0
                    self.windows_xdata.push(0x00);
299
0
                }
300
0
                let unwind_address = self.windows_xdata.len();
301
0
                self.windows_xdata.extend_from_slice(&unwind_info);
302
303
                // Record a `RUNTIME_FUNCTION` which this will point to.
304
0
                self.windows_pdata.push(RUNTIME_FUNCTION {
305
0
                    begin: u32::try_from(function_offset).unwrap(),
306
0
                    end: u32::try_from(function_offset + function_len).unwrap(),
307
0
                    unwind_address: u32::try_from(unwind_address).unwrap(),
308
0
                });
309
            }
310
311
            // See https://learn.microsoft.com/en-us/cpp/build/arm64-exception-handling
312
0
            UnwindInfo::WindowsArm64(info) => {
313
0
                let code_words = info.code_words();
314
0
                let mut unwind_codes = vec![0; (code_words * 4) as usize];
315
0
                info.emit(&mut unwind_codes);
316
317
                // `.xdata` entries are always 4-byte aligned
318
0
                while self.windows_xdata.len() % 4 != 0 {
319
0
                    self.windows_xdata.push(0x00);
320
0
                }
321
322
                // First word:
323
                // 0-17:    Function Length
324
                // 18-19:   Version (must be 0)
325
                // 20:      X bit (is exception data present?)
326
                // 21:      E bit (has single packed epilogue?)
327
                // 22-26:   Epilogue count
328
                // 27-31:   Code words count
329
0
                let requires_extended_counts = code_words > (1 << 5);
330
0
                let encoded_function_len = function_len / 4;
331
0
                assert!(encoded_function_len < (1 << 18), "function too large");
332
0
                let mut word1 = u32::try_from(encoded_function_len).unwrap();
333
0
                if !requires_extended_counts {
334
0
                    word1 |= u32::from(code_words) << 27;
335
0
                }
336
0
                let unwind_address = self.windows_xdata.len();
337
0
                self.windows_xdata.extend_from_slice(&word1.to_le_bytes());
338
339
0
                if requires_extended_counts {
340
0
                    // Extended counts word:
341
0
                    // 0-15:    Epilogue count
342
0
                    // 16-23:   Code words count
343
0
                    let extended_counts_word = (code_words as u32) << 16;
344
0
                    self.windows_xdata
345
0
                        .extend_from_slice(&extended_counts_word.to_le_bytes());
346
0
                }
347
348
                // Skip epilogue information: Per comment on [`UnwindInst`], we
349
                // do not emit information about epilogues.
350
351
                // Emit the unwind codes.
352
0
                self.windows_xdata.extend_from_slice(&unwind_codes);
353
354
                // Record a `RUNTIME_FUNCTION` which this will point to.
355
                // NOTE: `end` is not used, so leave it as 0.
356
0
                self.windows_pdata.push(RUNTIME_FUNCTION {
357
0
                    begin: u32::try_from(function_offset).unwrap(),
358
0
                    end: 0,
359
0
                    unwind_address: u32::try_from(unwind_address).unwrap(),
360
0
                });
361
            }
362
363
            // System-V is different enough that we just record the unwinding
364
            // information to get processed at a later time.
365
1.67M
            UnwindInfo::SystemV(info) => {
366
1.67M
                self.systemv_unwind_info.push((function_offset, info));
367
1.67M
            }
368
369
0
            _ => panic!("some unwind info isn't handled here"),
370
        }
371
1.67M
    }
372
373
    /// Appends the unwind information section, if any, to the `obj` specified.
374
    ///
375
    /// This function must be called immediately after the text section was
376
    /// added to a builder. The unwind information section must trail the text
377
    /// section immediately.
378
    ///
379
    /// The `text_section`'s section identifier is passed into this function.
380
192k
    fn append_section(&self, compiler: &Compiler, obj: &mut Object<'_>, text_section: SectionId) {
381
        // This write will align the text section to a page boundary and then
382
        // return the offset at that point. This gives us the full size of the
383
        // text section at that point, after alignment.
384
192k
        let text_section_size = obj.append_section_data(text_section, &[], text_align(compiler));
385
386
192k
        if self.windows_xdata.len() > 0 {
387
0
            assert!(self.systemv_unwind_info.len() == 0);
388
            // The `.xdata` section must come first to be just-after the `.text`
389
            // section for the reasons documented in `write_windows_unwind_info`
390
            // below.
391
0
            let segment = obj.segment_name(StandardSegment::Data).to_vec();
392
0
            let xdata_id = obj.add_section(segment, b".xdata".to_vec(), SectionKind::ReadOnlyData);
393
0
            let segment = obj.segment_name(StandardSegment::Data).to_vec();
394
0
            let pdata_id = obj.add_section(segment, b".pdata".to_vec(), SectionKind::ReadOnlyData);
395
0
            self.write_windows_unwind_info(obj, xdata_id, pdata_id, text_section_size);
396
192k
        }
397
398
192k
        if self.systemv_unwind_info.len() > 0 {
399
72.9k
            let segment = obj.segment_name(StandardSegment::Data).to_vec();
400
72.9k
            let section_id =
401
72.9k
                obj.add_section(segment, b".eh_frame".to_vec(), SectionKind::ReadOnlyData);
402
72.9k
            self.write_systemv_unwind_info(compiler, obj, section_id, text_section_size)
403
119k
        }
404
192k
    }
405
406
    /// This function appends a nonstandard section to the object which is only
407
    /// used during `CodeMemory::publish`.
408
    ///
409
    /// This custom section effectively stores a `[RUNTIME_FUNCTION; N]` into
410
    /// the object file itself. This way registration of unwind info can simply
411
    /// pass this slice to the OS itself and there's no need to recalculate
412
    /// anything on the other end of loading a module from a precompiled object.
413
    ///
414
    /// Support for reading this is in `crates/jit/src/unwind/winx64.rs`.
415
0
    fn write_windows_unwind_info(
416
0
        &self,
417
0
        obj: &mut Object<'_>,
418
0
        xdata_id: SectionId,
419
0
        pdata_id: SectionId,
420
0
        text_section_size: u64,
421
0
    ) {
422
        // Append the `.xdata` section, or the actual unwinding information
423
        // codes and such which were built as we found unwind information for
424
        // functions.
425
0
        obj.append_section_data(xdata_id, &self.windows_xdata, 4);
426
427
        // Next append the `.pdata` section, or the array of `RUNTIME_FUNCTION`
428
        // structures stored in the binary.
429
        //
430
        // This memory will be passed at runtime to `RtlAddFunctionTable` which
431
        // takes a "base address" and the entries within `RUNTIME_FUNCTION` are
432
        // all relative to this base address. The base address we pass is the
433
        // address of the text section itself so all the pointers here must be
434
        // text-section-relative. The `begin` and `end` fields for the function
435
        // it describes are already text-section-relative, but the
436
        // `unwind_address` field needs to be updated here since the value
437
        // stored right now is `xdata`-section-relative. We know that the
438
        // `xdata` section follows the `.text` section so the
439
        // `text_section_size` is added in to calculate the final
440
        // `.text`-section-relative address of the unwind information.
441
0
        let xdata_rva = |address| {
442
0
            let address = u64::from(address);
443
0
            let address = address + text_section_size;
444
0
            u32::try_from(address).unwrap()
445
0
        };
446
0
        let pdata = match obj.architecture() {
447
            Architecture::X86_64 => {
448
0
                let mut pdata = Vec::with_capacity(self.windows_pdata.len() * 3 * 4);
449
0
                for info in self.windows_pdata.iter() {
450
0
                    pdata.extend_from_slice(&info.begin.to_le_bytes());
451
0
                    pdata.extend_from_slice(&info.end.to_le_bytes());
452
0
                    pdata.extend_from_slice(&xdata_rva(info.unwind_address).to_le_bytes());
453
0
                }
454
0
                pdata
455
            }
456
457
            Architecture::Aarch64 => {
458
                // Windows Arm64 .pdata also supports packed unwind data, but
459
                // we're not currently using that.
460
0
                let mut pdata = Vec::with_capacity(self.windows_pdata.len() * 2 * 4);
461
0
                for info in self.windows_pdata.iter() {
462
0
                    pdata.extend_from_slice(&info.begin.to_le_bytes());
463
0
                    pdata.extend_from_slice(&xdata_rva(info.unwind_address).to_le_bytes());
464
0
                }
465
0
                pdata
466
            }
467
468
0
            _ => unimplemented!("unsupported architecture for windows unwind info"),
469
        };
470
0
        obj.append_section_data(pdata_id, &pdata, 4);
471
0
    }
472
473
    /// This function appends a nonstandard section to the object which is only
474
    /// used during `CodeMemory::publish`.
475
    ///
476
    /// This will generate a `.eh_frame` section, but not one that can be
477
    /// naively loaded. The goal of this section is that we can create the
478
    /// section once here and never again does it need to change. To describe
479
    /// dynamically loaded functions though each individual FDE needs to talk
480
    /// about the function's absolute address that it's referencing. Naturally
481
    /// we don't actually know the function's absolute address when we're
482
    /// creating an object here.
483
    ///
484
    /// To solve this problem the FDE address encoding mode is set to
485
    /// `DW_EH_PE_pcrel`. This means that the actual effective address that the
486
    /// FDE describes is a relative to the address of the FDE itself. By
487
    /// leveraging this relative-ness we can assume that the relative distance
488
    /// between the FDE and the function it describes is constant, which should
489
    /// allow us to generate an FDE ahead-of-time here.
490
    ///
491
    /// For now this assumes that all the code of functions will start at a
492
    /// page-aligned address when loaded into memory. The eh_frame encoded here
493
    /// then assumes that the text section is itself page aligned to its size
494
    /// and the eh_frame will follow just after the text section. This means
495
    /// that the relative offsets we're using here is the FDE going backwards
496
    /// into the text section itself.
497
    ///
498
    /// Note that the library we're using to create the FDEs, `gimli`, doesn't
499
    /// actually encode addresses relative to the FDE itself. Instead the
500
    /// addresses are encoded relative to the start of the `.eh_frame` section.
501
    /// This makes it much easier for us where we provide the relative offset
502
    /// from the start of `.eh_frame` to the function in the text section, which
503
    /// given our layout basically means the offset of the function in the text
504
    /// section from the end of the text section.
505
    ///
506
    /// A final note is that the reason we page-align the text section's size is
507
    /// so the .eh_frame lives on a separate page from the text section itself.
508
    /// This allows `.eh_frame` to have different virtual memory permissions,
509
    /// such as being purely read-only instead of read/execute like the code
510
    /// bits.
511
72.9k
    fn write_systemv_unwind_info(
512
72.9k
        &self,
513
72.9k
        compiler: &Compiler,
514
72.9k
        obj: &mut Object<'_>,
515
72.9k
        section_id: SectionId,
516
72.9k
        text_section_size: u64,
517
72.9k
    ) {
518
72.9k
        let mut cie = match compiler.create_systemv_cie() {
519
72.9k
            Some(cie) => cie,
520
0
            None => return,
521
        };
522
72.9k
        let mut table = FrameTable::default();
523
72.9k
        cie.fde_address_encoding = gimli::constants::DW_EH_PE_pcrel;
524
72.9k
        let cie_id = table.add_cie(cie);
525
526
1.67M
        for (text_section_off, unwind_info) in self.systemv_unwind_info.iter() {
527
1.67M
            let backwards_off = text_section_size - text_section_off;
528
1.67M
            let actual_offset = -i64::try_from(backwards_off).unwrap();
529
1.67M
            // Note that gimli wants an unsigned 64-bit integer here, but
530
1.67M
            // unwinders just use this constant for a relative addition with the
531
1.67M
            // address of the FDE, which means that the sign doesn't actually
532
1.67M
            // matter.
533
1.67M
            let fde = unwind_info.to_fde(Address::Constant(actual_offset.cast_unsigned()));
534
1.67M
            table.add_fde(cie_id, fde);
535
1.67M
        }
536
72.9k
        let endian = match compiler.triple().endianness().unwrap() {
537
72.9k
            target_lexicon::Endianness::Little => RunTimeEndian::Little,
538
0
            target_lexicon::Endianness::Big => RunTimeEndian::Big,
539
        };
540
72.9k
        let mut eh_frame = EhFrame(MyVec(EndianVec::new(endian)));
541
72.9k
        table.write_eh_frame(&mut eh_frame).unwrap();
542
543
        // Some unwinding implementations expect a terminating "empty" length so
544
        // a 0 is written at the end of the table for those implementations.
545
72.9k
        let mut endian_vec = (eh_frame.0).0;
546
72.9k
        endian_vec.write_u32(0).unwrap();
547
72.9k
        obj.append_section_data(section_id, endian_vec.slice(), 1);
548
549
        use gimli::constants;
550
        use gimli::write::Error;
551
552
        struct MyVec(EndianVec<RunTimeEndian>);
553
554
        impl Writer for MyVec {
555
            type Endian = RunTimeEndian;
556
557
8.59M
            fn endian(&self) -> RunTimeEndian {
558
8.59M
                self.0.endian()
559
8.59M
            }
560
561
15.6M
            fn len(&self) -> usize {
562
15.6M
                self.0.len()
563
15.6M
            }
564
565
41.9M
            fn write(&mut self, buf: &[u8]) -> Result<(), Error> {
566
41.9M
                self.0.write(buf)
567
41.9M
            }
568
569
3.49M
            fn write_at(&mut self, pos: usize, buf: &[u8]) -> Result<(), Error> {
570
3.49M
                self.0.write_at(pos, buf)
571
3.49M
            }
572
573
            // FIXME(gimli-rs/gimli#576) this is the definition we want for
574
            // `write_eh_pointer` but the default implementation, at the time
575
            // of this writing, uses `offset - val` instead of `val - offset`.
576
            // A PR has been merged to fix this but until that's published we
577
            // can't use it.
578
1.67M
            fn write_eh_pointer(
579
1.67M
                &mut self,
580
1.67M
                address: Address,
581
1.67M
                eh_pe: constants::DwEhPe,
582
1.67M
                size: u8,
583
1.67M
            ) -> Result<(), Error> {
584
1.67M
                let val = match address {
585
1.67M
                    Address::Constant(val) => val,
586
0
                    Address::Symbol { .. } => unreachable!(),
587
                };
588
1.67M
                assert_eq!(eh_pe.application(), constants::DW_EH_PE_pcrel);
589
1.67M
                let offset = self.len() as u64;
590
1.67M
                let val = val.wrapping_sub(offset);
591
1.67M
                self.write_eh_pointer_data(val, eh_pe.format(), size)
592
1.67M
            }
593
        }
594
72.9k
    }
595
}