elf_loader 0.17.0

A no_std-friendly ELF loader and runtime linker for Rust.
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
use super::*;
use std::sync::OnceLock;

#[cfg(target_pointer_width = "64")]
const E_SHOFF_OFFSET: usize = 0x28;
#[cfg(not(target_pointer_width = "64"))]
const E_SHOFF_OFFSET: usize = 0x20;
#[cfg(target_pointer_width = "64")]
const E_SHNUM_OFFSET: usize = 0x3c;
#[cfg(not(target_pointer_width = "64"))]
const E_SHNUM_OFFSET: usize = 0x30;
#[cfg(target_pointer_width = "64")]
const E_SHSTRNDX_OFFSET: usize = 0x3e;
#[cfg(not(target_pointer_width = "64"))]
const E_SHSTRNDX_OFFSET: usize = 0x32;

struct PlanningFixtures {
    basic: &'static [u8],
    missing_sections: Vec<u8>,
    invalid_sections: Vec<u8>,
    #[cfg(target_arch = "x86_64")]
    retained: &'static [u8],
}

fn fixtures() -> &'static PlanningFixtures {
    static FIXTURES: OnceLock<PlanningFixtures> = OnceLock::new();
    FIXTURES.get_or_init(|| {
        let real = crate::fixture::fixtures();
        PlanningFixtures {
            basic: &real.plain,
            missing_sections: strip_section_headers(real.plain.clone()),
            invalid_sections: break_section_name_table(real.plain.clone()),
            #[cfg(target_arch = "x86_64")]
            retained: &real.provider,
        }
    })
}

fn set_u16(bytes: &mut [u8], offset: usize, value: u16) {
    bytes[offset..offset + 2].copy_from_slice(&value.to_le_bytes());
}

#[cfg(target_pointer_width = "64")]
fn set_usize(bytes: &mut [u8], offset: usize, value: usize) {
    bytes[offset..offset + 8].copy_from_slice(&(value as u64).to_le_bytes());
}

#[cfg(not(target_pointer_width = "64"))]
fn set_usize(bytes: &mut [u8], offset: usize, value: usize) {
    bytes[offset..offset + 4].copy_from_slice(&(value as u32).to_le_bytes());
}

fn strip_section_headers(mut bytes: Vec<u8>) -> Vec<u8> {
    set_usize(&mut bytes, E_SHOFF_OFFSET, 0);
    set_u16(&mut bytes, E_SHNUM_OFFSET, 0);
    set_u16(&mut bytes, E_SHSTRNDX_OFFSET, 0);
    bytes
}

fn break_section_name_table(mut bytes: Vec<u8>) -> Vec<u8> {
    set_u16(&mut bytes, E_SHSTRNDX_OFFSET, u16::MAX);
    bytes
}

#[test]
#[cfg(target_arch = "x86_64")]
fn arena_materializes_section_bytes() {
    let bytes = fixtures().retained;

    let mut context = LinkContext::<()>::new(DomainId::PROCESS);
    let resolver = SingleBinaryResolver {
        key: "root",
        name: "arena_root.so",
        data: bytes,
    };
    let configure = |plan: &mut LinkPassPlan<'_, ReorderPass>| -> elf_loader::Result<()> {
        let root = plan.root().expect("root module should be visible");
        assert!(
            root.capability(plan) == ModuleCapability::SectionReorderable,
            "compiled dylib should expose retained relocation repair inputs",
        );

        let data_section = root
            .scanned(plan)
            .alloc_sections()
            .find(|section| section.name() == ".data")
            .expect("compiled dylib should contain a .data section")
            .id();
        let layout_section = root
            .section(plan, data_section)
            .expect("missing planned .data section");
        {
            layout_section
                .data_mut(plan)?
                .copy_from_slice(&[9, 8, 7, 6]);
            let arena = plan.create_arena(ArenaDescriptor::new(
                PageSize::Base,
                MemoryClass::WritableData,
                ArenaSharing::Private,
            ));
            assert!(
                layout_section.assign(plan, arena, 0),
                "failed to assign .data into arena",
            );
        }
        Ok(())
    };

    let loaded = Linker::new()
        .resolver(resolver)
        .run()
        .map_pipeline(|mut pipeline| {
            pipeline.push(TestPass(configure));
            pipeline
        })
        .load_scan_first(&mut context, "root")
        .expect("failed to execute arena-backed scan-first load");

    assert!(context.module_id("root").is_some());

    unsafe {
        let module = context.module(loaded.root()).unwrap();
        let ptr = module
            .get::<u8>("value")
            .expect("missing exported object symbol")
            .into_raw() as *const u8;
        assert!(
            module
                .memory()
                .host_ptr(VmAddr::new(ptr as usize))
                .is_some()
        );
        assert_eq!(std::slice::from_raw_parts(ptr, 4), &[9, 8, 7, 6]);
    }
}

#[test]
#[cfg(target_arch = "x86_64")]
fn arena_supports_assign_next() {
    let bytes = fixtures().retained;

    let mut context = LinkContext::<()>::new(DomainId::PROCESS);
    let resolver = SingleBinaryResolver {
        key: "root",
        name: "arena_assign_next_root.so",
        data: bytes,
    };
    let mut observed_offset = None;
    let mut observed_size = None;
    let configure = |plan: &mut LinkPassPlan<'_, ReorderPass>| -> elf_loader::Result<()> {
        let root = plan.root().expect("root module should be visible");
        assert!(
            root.capability(plan) == ModuleCapability::SectionReorderable,
            "compiled dylib should expose retained relocation repair inputs",
        );

        let data_section = root
            .scanned(plan)
            .alloc_sections()
            .find(|section| section.name() == ".data")
            .expect("compiled dylib should contain a .data section")
            .id();
        let layout_section = root
            .section(plan, data_section)
            .expect("missing planned .data section");
        layout_section.resize(plan, 8)?;
        assert_eq!(layout_section.metadata(plan).size(), 8);
        layout_section
            .data_mut(plan)?
            .copy_from_slice(&[4, 3, 2, 1, 8, 7, 6, 5]);

        let arena = plan.create_arena(ArenaDescriptor::new(
            PageSize::Base,
            MemoryClass::WritableData,
            ArenaSharing::Private,
        ));
        assert!(
            layout_section.assign_next(plan, arena),
            "failed to assign .data into arena at the next aligned offset",
        );
        observed_offset = layout_section
            .placement(plan)
            .map(|placement| placement.offset());
        observed_size = layout_section
            .placement(plan)
            .map(|placement| placement.size());
        Ok(())
    };

    let loaded = Linker::new()
        .resolver(resolver)
        .run()
        .map_pipeline(|mut pipeline| {
            pipeline.push(TestPass(configure));
            pipeline
        })
        .load_scan_first(&mut context, "root")
        .expect("failed to execute arena-backed scan-first load with assign_next");

    assert_eq!(observed_offset, Some(0));
    assert_eq!(observed_size, Some(8));
    assert!(context.module_id("root").is_some());

    unsafe {
        let module = context.module(loaded.root()).unwrap();
        let ptr = module
            .get::<u8>("value")
            .expect("missing exported object symbol")
            .into_raw() as *const u8;
        assert!(
            module
                .memory()
                .host_ptr(VmAddr::new(ptr as usize))
                .is_some()
        );
        assert_eq!(std::slice::from_raw_parts(ptr, 4), &[4, 3, 2, 1]);
    }
}

#[test]
#[cfg(target_arch = "x86_64")]
fn defaults_to_section_regions() {
    let bytes = fixtures().retained;

    let mut context = LinkContext::<()>::new(DomainId::PROCESS);
    let resolver = SingleBinaryResolver {
        key: "root",
        name: "default_section_regions_root.so",
        data: bytes,
    };
    let mut observed_capability = None;
    let configure = |plan: &mut LinkPassPlan<'_>| -> elf_loader::Result<()> {
        let root = plan.root().expect("root module should be visible");
        observed_capability = Some(root.capability(plan));
        Ok(())
    };

    let loaded = Linker::new()
        .resolver(resolver)
        .run()
        .map_pipeline(|mut pipeline| {
            pipeline.push(TestPass(configure));
            pipeline
        })
        .load_scan_first(&mut context, "root")
        .expect("failed to load section-reorderable dylib through the default section-region path");

    assert_eq!(
        observed_capability,
        Some(ModuleCapability::SectionReorderable),
    );
    unsafe {
        let module = context.module(loaded.root()).unwrap();
        let ptr = module
            .get::<u8>("value")
            .expect("missing exported object symbol")
            .into_raw() as *const u8;
        assert!(
            module
                .memory()
                .host_ptr(VmAddr::new(ptr as usize))
                .is_some()
        );
        assert_eq!(std::slice::from_raw_parts(ptr, 4), &[1, 2, 3, 4]);
    }
}

#[test]
fn missing_sections_become_opaque() {
    let bytes = fixtures().missing_sections.as_slice();

    let mut context = LinkContext::<()>::new(DomainId::PROCESS);
    let resolver = SingleBinaryResolver {
        key: "root",
        name: "opaque_root.so",
        data: bytes,
    };
    let mut observed_capability = None;
    let mut saw_missing_section_headers = false;
    let configure = |plan: &mut LinkPassPlan<'_>| -> elf_loader::Result<()> {
        let root = plan.root().expect("root module should be visible");
        observed_capability = Some(root.capability(plan));
        saw_missing_section_headers = root.scanned(plan).section_headers().is_none();
        root.set_materialization(plan, Materialization::WholeDsoRegion);
        Ok(())
    };

    let loaded = Linker::new()
        .resolver(resolver)
        .run()
        .map_pipeline(|mut pipeline| {
            pipeline.push(TestPass(configure));
            pipeline
        })
        .load_scan_first(&mut context, "root")
        .expect("failed to load opaque dylib through scan-first path");

    assert_eq!(observed_capability, Some(ModuleCapability::Opaque));
    assert!(
        saw_missing_section_headers,
        "opaque modules should not expose a usable section table",
    );

    assert!(context.module_id("root").is_some());

    unsafe {
        let module = context.module(loaded.root()).unwrap();
        let ptr = module
            .get::<u8>("value")
            .expect("missing exported object symbol")
            .into_raw() as *const u8;
        assert!(
            module
                .memory()
                .host_ptr(VmAddr::new(ptr as usize))
                .is_some()
        );
        assert_eq!(std::slice::from_raw_parts(ptr, 4), &[1, 2, 3, 4]);
    }
}

#[test]
fn invalid_sections_become_opaque() {
    let bytes = fixtures().invalid_sections.as_slice();

    let mut context = LinkContext::<()>::new(DomainId::PROCESS);
    let resolver = SingleBinaryResolver {
        key: "root",
        name: "broken_shstr_root.so",
        data: bytes,
    };
    let mut observed_capability = None;
    let configure = |plan: &mut LinkPassPlan<'_>| -> elf_loader::Result<()> {
        let root = plan.root().expect("root module should be visible");
        observed_capability = Some(root.capability(plan));
        Ok(())
    };

    let _loaded = Linker::new()
        .resolver(resolver)
        .run()
        .map_pipeline(|mut pipeline| {
            pipeline.push(TestPass(configure));
            pipeline
        })
        .load_scan_first(&mut context, "root")
        .expect("scan-first load should downgrade unusable section tables");

    assert_eq!(observed_capability, Some(ModuleCapability::Opaque));
}

#[test]
fn whole_dso_supports_section_overrides() {
    let bytes = fixtures().basic;

    let mut context = LinkContext::<()>::new(DomainId::PROCESS);
    let resolver = SingleBinaryResolver {
        key: "root",
        name: "whole_region_root.so",
        data: bytes,
    };
    let mut observed_capability = None;
    let mut observed_materialization = None;
    let configure = |plan: &mut LinkPassPlan<'_, DataPass>| -> elf_loader::Result<()> {
        let root = plan.root().expect("root module should be visible");
        observed_capability = Some(root.capability(plan));
        observed_materialization = root.materialization(plan);

        let data_section = root
            .scanned(plan)
            .alloc_sections()
            .find(|section| section.name() == ".data")
            .expect("compiled dylib should contain a .data section")
            .id();
        let layout_section = root
            .section(plan, data_section)
            .expect("missing planned .data section");
        layout_section
            .data_mut(plan)?
            .copy_from_slice(&[9, 8, 7, 6]);
        root.set_materialization(plan, Materialization::WholeDsoRegion);
        observed_materialization = root.materialization(plan);
        Ok(())
    };

    let loaded = Linker::new()
        .resolver(resolver)
        .run()
        .map_pipeline(|mut pipeline| {
            pipeline.push(TestPass(configure));
            pipeline
        })
        .load_scan_first(&mut context, "root")
        .expect("failed to execute whole-DSO scan-first load");

    assert_eq!(
        observed_capability,
        Some(ModuleCapability::SectionData),
        "no emit-relocs should classify as section-data only",
    );
    assert_eq!(
        observed_materialization,
        Some(Materialization::WholeDsoRegion),
    );

    unsafe {
        let module = context.module(loaded.root()).unwrap();
        let ptr = module
            .get::<u8>("value")
            .expect("missing exported object symbol")
            .into_raw() as *const u8;
        assert!(
            module
                .memory()
                .host_ptr(VmAddr::new(ptr as usize))
                .is_some()
        );
        assert_eq!(std::slice::from_raw_parts(ptr, 4), &[9, 8, 7, 6]);
    }
}

#[test]
fn section_data_rejects_section_regions() {
    let bytes = fixtures().basic;

    let mut context = LinkContext::<()>::new(DomainId::PROCESS);
    let resolver = SingleBinaryResolver {
        key: "root",
        name: "illegal_section_region_root.so",
        data: bytes,
    };
    let mut observed_capability = None;
    let mut observed_materialization = None;
    let configure = |plan: &mut LinkPassPlan<'_, DataPass>| -> elf_loader::Result<()> {
        let root = plan.root().expect("root module should be visible");
        observed_capability = Some(root.capability(plan));

        assert_eq!(
            root.set_materialization(plan, Materialization::SectionRegions),
            None,
        );
        observed_materialization = root.materialization(plan);
        Ok(())
    };

    let err = Linker::new()
        .resolver(resolver)
        .run()
        .map_pipeline(|mut pipeline| {
            pipeline.push(TestPass(configure));
            pipeline
        })
        .load_scan_first(&mut context, "root")
        .expect_err("section-data modules must reject section-region placement");
    assert_eq!(observed_capability, Some(ModuleCapability::SectionData));
    assert_eq!(
        observed_materialization,
        Some(Materialization::SectionRegions)
    );
    assert!(
        err.to_string().contains("cannot use section regions"),
        "unexpected error: {err}",
    );
}