-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader.rs
More file actions
1554 lines (1391 loc) · 57.2 KB
/
Copy pathloader.rs
File metadata and controls
1554 lines (1391 loc) · 57.2 KB
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
//! # Program Loading
//!
//! Types and functions used to dynamically load (and link) programs.
use {
crate::{
InitFileSystem,
memory::{AddressSpace, KernelMapping},
},
alloc::{
boxed::Box,
collections::{btree_map::BTreeMap, btree_set::BTreeSet},
string::{String, ToString as _},
sync::{Arc, Weak},
vec::Vec,
},
boot_info::BootInfo,
core::{
ops::Range,
sync::atomic::{AtomicUsize, Ordering},
},
elf::{
ElfFile, ObjectFileType, SHF_ALLOC, SHF_EXECINSTR, SHF_TLS, SHF_WRITE, SectionData,
SectionHeaderType, SymbolBinding, SymbolType,
},
fs::FileSystem,
hashbrown::{HashMap, HashSet},
log::{debug, error, info, trace},
memory_types::{Address, Page, PageRange, PageTableFlags, USER_HEAP_L4_INDEX},
spin_mutex::Mutex,
};
const AUTO_MAP_DEPENDENCIES: bool = false;
const FUNDAMENTAL_SYMBOLS: &[&str] = &[
"fmaxf",
"fminf",
"memcmp",
"memcpy",
"memmove",
"memset",
"strlen",
"__addsf3",
"__divsf3",
"__divdf3",
"__eqsf2",
"__extendhfsf2",
"__fixsfsi",
"__fixunssfdi",
"__floatdidf",
"__floatdisf",
"__floatsisf",
"__floatundisf",
"__gedf2",
"__gesf2",
"__gtsf2",
"__ltdf2",
"__muldf3",
"__mulsf3",
"__nedf2",
"__nesf2",
"__subsf3",
"__truncsfhf2",
"__udivti3",
"__umodti3",
"__unordsf2",
];
static LOADER: Loader = Loader::new();
static mut PROVIDER: Option<GlobalObjectProvider> = None;
/// Initialize the [global loader](global_loader).
pub fn init(boot_info: &'static BootInfo) {
unsafe {
PROVIDER = Some(GlobalObjectProvider {
fs: Mutex::new(Box::new(InitFileSystem {
root_object_map: &boot_info.root_object_map,
})),
});
}
init_fundamental_symbols();
// HACK: Need to add support for aliasing sections based on symbol table to
// avoid having to do this.
let math_object = global_loader()
.load_object(
"math",
&AddressSpace::new("load_math", None),
// The actual value of this address doesn't matter.
Address::from_table_indices(USER_HEAP_L4_INDEX, 0, 0, 0).page(),
)
.unwrap();
for name in ["__ltsf2", "__lesf2"] {
let lock = math_object.lock();
let Some(section) = lock
.sections
.values()
.find(|section| &*section.name == name)
else {
panic!("Couldn't find section for fundamental math symbol `{name}`");
};
global_loader().add_alias_to_section(name, Arc::downgrade(section));
}
global_loader()
.load_object(
"time",
&AddressSpace::new("load_time", None),
// The actual value of this address doesn't matter.
Address::from_table_indices(USER_HEAP_L4_INDEX, 0, 0, 0).page(),
)
.unwrap();
global_loader()
.load_object(
"framebuffer",
&AddressSpace::new("load_framebuffer", None),
// The actual value of this address doesn't matter.
Address::from_table_indices(USER_HEAP_L4_INDEX, 0, 0, 0).page(),
)
.unwrap();
global_loader()
.load_object(
"heap",
&AddressSpace::new("load_heap", None),
// The actual value of this address doesn't matter.
Address::from_table_indices(USER_HEAP_L4_INDEX, 0, 0, 0).page(),
)
.unwrap();
with_symbol_value(
"hardware::TSC_FREQUENCY_KHZ",
|tsc_frequency: &mut u64| unsafe {
assert_eq!(*tsc_frequency, 0);
*tsc_frequency = hardware::TSC_FREQUENCY_KHZ;
},
);
with_symbol_value("hardware::TSC_PERIOD_FS", |tsc_period: &mut u64| unsafe {
assert_eq!(*tsc_period, 0);
*tsc_period = hardware::TSC_PERIOD_FS;
});
with_symbol_value(
"framebuffer::FRAMEBUFFER_ADDR",
|fb_addr: &mut AtomicUsize| {
assert_eq!(fb_addr.load(Ordering::SeqCst), 0);
fb_addr.store(
boot_info.display_info.framebuffer_addr as usize,
Ordering::SeqCst,
);
},
);
with_symbol_value(
"framebuffer::FRAMEBUFFER_SIZE",
|fb_size: &mut AtomicUsize| {
assert_eq!(fb_size.load(Ordering::SeqCst), 0);
fb_size.store(boot_info.display_info.framebuffer_size, Ordering::SeqCst);
},
);
with_symbol_value(
"framebuffer::FRAMEBUFFER_WIDTH",
|fb_width: &mut AtomicUsize| {
assert_eq!(fb_width.load(Ordering::SeqCst), 0);
fb_width.store(boot_info.display_info.stride as usize, Ordering::SeqCst);
},
);
with_symbol_value(
"framebuffer::FRAMEBUFFER_HEIGHT",
|fb_height: &mut AtomicUsize| {
assert_eq!(fb_height.load(Ordering::SeqCst), 0);
fb_height.store(boot_info.display_info.height as usize, Ordering::SeqCst);
},
);
// global_loader().dump_info();
}
fn with_symbol_value<T, F>(name: &str, op: F)
where
T: Sized,
F: FnOnce(&mut T),
{
let sym = global_loader().get_section(name).unwrap();
let value = sym.upgrade().unwrap();
let mut mapping = value.mapping.lock();
op(unsafe { mapping.as_mut::<T>(value.mapping_offset) });
}
fn init_fundamental_symbols() {
global_loader()
.load_object(
"hardware",
&AddressSpace::new("load_hardware", None),
// The actual value of this address doesn't matter.
Address::from_table_indices(USER_HEAP_L4_INDEX, 0, 0, 0).page(),
)
.unwrap();
global_loader()
.load_object(
"panic",
&AddressSpace::new("load_panic", None),
// The actual value of this address doesn't matter.
Address::from_table_indices(USER_HEAP_L4_INDEX, 0, 0, 0).page(),
)
.unwrap();
let object = global_loader()
.load_object(
"lang",
&AddressSpace::new("load_fundamental", None),
// The actual value of this address doesn't matter.
Address::from_table_indices(USER_HEAP_L4_INDEX, 0, 0, 0).page(),
)
.unwrap();
let object_lock = object.lock();
for name in FUNDAMENTAL_SYMBOLS {
// Some of the fundamental symbols are not global, so we need to search through
// the loaded object's sections because the global section map won't have
// non-global sections.
let Some(section) = object_lock
.sections
.values()
.find(|section| &*section.name == *name)
else {
panic!("Couldn't find section for fundamental symbol `{name}`");
};
global_loader().add_alias_to_section(name, Arc::downgrade(section));
}
}
/// Get a reference to the global object loader.
pub fn global_loader<'a>() -> &'a Loader {
&LOADER
}
/// Get a reference to the [`GlobalObjectProvider`].
pub fn global_object_provider<'a>() -> &'a GlobalObjectProvider {
unsafe {
PROVIDER
.as_ref()
.expect("global object provider should be initialized")
}
}
/// The global object provider.
///
/// Internally, this is just a [`FileSystem`] trait object wrapped in a
/// [`Mutex`].
pub struct GlobalObjectProvider {
fs: Mutex<Box<dyn FileSystem>>,
}
impl<'a> ObjectProvider for &'a GlobalObjectProvider {
fn read_object(&self, name: &str) -> Result<Vec<u8>, &'static str> {
if !name.starts_with("/") {
let path = self
.fs
.lock()
.list(&format!("/{name}"))?
.into_iter()
.find(|object_name| object_name == &format!("/{name}.o"))
.ok_or("no object found")?;
self.fs.lock().read(&path)
} else {
self.fs.lock().read(name)
}
}
}
/// A set of loaded [objects](LoadedObject) and [sections](LoadedSection).
#[derive(Debug)]
pub struct Loader {
objects: Mutex<HashMap<Arc<str>, Arc<Mutex<LoadedObject>>, rustc_hash::FxBuildHasher>>,
sections: Mutex<HashMap<Arc<str>, Weak<LoadedSection>, rustc_hash::FxBuildHasher>>,
sections_by_addr: Mutex<BTreeMap<(Address, usize), Weak<LoadedSection>>>,
}
/// An object that has been loaded into memory.
#[derive(Debug)]
pub struct LoadedObject {
/// The demangled name of this object.
pub name: Arc<str>,
/// The sections that have been loaded into memory for this object.
pub sections: HashMap<usize, Arc<LoadedSection>, rustc_hash::FxBuildHasher>,
/// A set of section indices representing the global sections of this
/// object. They can be used as keys for [`self.sections`](Self::sections).
pub global_sections: BTreeSet<usize>,
/// A set of section indices representing the data sections of this object.
/// They can be used as keys for [`self.sections`](Self::sections).
pub data_sections: BTreeSet<usize>,
/// A set of section indices representing the thread-local storage (TLS)
/// sections of this object. They can be used as keys for
/// [`self.sections`](Self::sections).
pub tls_sections: BTreeSet<usize>,
/// Sections this object depends on.
pub dependencies: HashSet<Dependency, rustc_hash::FxBuildHasher>,
pub executable_mapping: Option<Arc<Mutex<KernelMapping>>>,
pub read_only_mapping: Option<Arc<Mutex<KernelMapping>>>,
pub read_write_mapping: Option<Arc<Mutex<KernelMapping>>>,
}
#[derive(Debug)]
pub struct Dependency {
pub target_section: Arc<LoadedSection>,
pub source_section: Arc<LoadedSection>,
}
impl PartialEq for Dependency {
fn eq(&self, other: &Self) -> bool {
self.source_section.name == other.source_section.name
}
}
impl Eq for Dependency {}
impl core::hash::Hash for Dependency {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.source_section.name.hash(state);
}
}
/// An object section that has been loaded into memory.
#[derive(Debug)]
pub struct LoadedSection {
/// The demangled name of this section.
pub name: Arc<str>,
/// The type of this section (`.text`, `.data`, etc.).
pub kind: SectionKind,
/// Whether this section is global (public).
pub global: bool,
/// The size of this section in bytes.
pub size: usize,
/// The memory address of this section.
pub addr: Address,
/// A reference to the mapping that contains this section's data.
pub mapping: Arc<Mutex<KernelMapping>>,
/// The offset into [`self.mapping`](Self::mapping) at which this section's
/// data starts.
pub mapping_offset: usize,
/// The object that contains this section.
pub owner: Weak<Mutex<LoadedObject>>,
}
/// The type of a [`LoadedSection`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SectionKind {
/// Executable code.
Text,
/// Immutable program data.
Rodata,
/// Mutable program data.
Data,
/// Uninitialized program data.
Bss,
/// Thread-local data.
TlsData,
TlsBss,
GccExceptTable,
/// Exception handling (unwind) information.
EhFrame,
}
impl SectionKind {
pub fn name(&self) -> &'static str {
match self {
SectionKind::Text => ".text",
SectionKind::Rodata => ".rodata",
SectionKind::Data => ".data",
SectionKind::Bss => ".bss",
SectionKind::TlsData => ".tdata",
SectionKind::TlsBss => ".tbss",
SectionKind::GccExceptTable => ".gcc_except_table",
SectionKind::EhFrame => ".eh_frame",
}
}
}
/// Something capable of reading object data.
pub trait ObjectProvider {
/// Read the bytes of the object with the given name.
fn read_object(&self, name: &str) -> Result<Vec<u8>, &'static str>;
}
impl Loader {
/// Create an empty `Loader` without any loaded [objects](LoadedObject) or
/// [sections](LoadedSection).
pub const fn new() -> Self {
Self {
objects: Mutex::new(HashMap::with_hasher(rustc_hash::FxBuildHasher)),
sections: Mutex::new(HashMap::with_hasher(rustc_hash::FxBuildHasher)),
sections_by_addr: Mutex::new(BTreeMap::new()),
}
}
/// Dump debug information to the logger.
#[allow(unused)]
pub fn dump_info(&self) {
let objects = self.objects.lock();
// let sections = self.sections.lock();
debug!(
"--- OBJECTS ---\n{}",
objects
.iter()
.map(|(name, object)| {
let object = object.lock();
let section_count = object.sections.len();
format!(
" {name}:{}\n deps:{}\n",
if section_count > 20 {
format!("\n {section_count} sections")
} else {
object
.sections
.iter()
.map(|(index, section)| {
format!(
"\n {index:>4} | {:#x} | {:>10} | {}",
section.addr,
section.kind.name(),
§ion.name[..section.name.len().min(50)],
)
})
.collect::<String>()
},
object
.dependencies
.iter()
.map(|dep| {
let source_owner = dep.source_section.owner.upgrade().unwrap();
format!(
"\n {} @ {}.{}",
dep.target_section.name,
source_owner.lock().name,
dep.source_section.name,
)
})
.collect::<String>(),
)
})
.collect::<String>(),
);
// debug!(
// "--- SECTIONS ---\n{}",
// sections
// .iter()
// .filter(|(name, _section)| !name.starts_with("<")
// && !name.contains("core[")
// && !name.contains("compiler_builtins[")
// && !name.contains("alloc[")
// && !name.starts_with("anon."))
// .map(|(name, section)| format!(
// " {}: {} ref(s)\n",
// &name[..name.len().min(60)],
// section.weak_count(),
// ))
// .collect::<String>(),
// );
}
}
// Section manipulation.
impl Loader {
/// Get the [object](LoadedObject) with the given name.
pub fn get_object(&self, name: &str) -> Option<Weak<Mutex<LoadedObject>>> {
self.objects.lock().get(name).map(Arc::downgrade)
}
/// Get the first [section](LoadedSection) that starts with the given prefix
/// and ends with the given suffix.
pub fn get_section(&self, name: &str) -> Option<Weak<LoadedSection>> {
self.sections
.lock()
.iter()
.find(|(section_name, _section)| &***section_name == name)
.map(|(_section_name, section)| section.clone())
}
/// Get the first text [section](LoadedSection) that starts with the given
/// prefix and ends with the given suffix.
pub fn get_text_section(&self, prefix: &str, suffix: &str) -> Option<Weak<LoadedSection>> {
self.sections
.lock()
.iter()
.find(|(name, section)| {
section
.upgrade()
.is_some_and(|section| matches!(section.kind, SectionKind::Text))
&& name.starts_with(prefix)
&& name.ends_with(suffix)
})
.map(|(_name, section)| section.clone())
}
/// Get the first [section](LoadedSection) that contains the given address.
pub fn get_section_for_addr(&self, addr: Address) -> Option<Weak<LoadedSection>> {
self.sections_by_addr
.lock()
.iter()
.find(|((section_addr, section_size), _section)| {
&addr >= section_addr && addr < *section_addr + *section_size
})
.map(|(_range, section)| section.clone())
}
fn get_or_load_section(
&self,
name: &str,
for_object: &LoadedObject,
address_space: &AddressSpace,
start_page: &mut Page,
) -> Result<Weak<LoadedSection>, &'static str> {
if let Some(section) = self.sections.lock().get(name) {
return Ok(section.clone());
}
// HACK: For some reason, the `<usize as core::fmt:Display>::fmt` symbol fails
// to load. I think it's some weird edge case with object section loading.
if name == "<usize as core::fmt::Display>::fmt" {
let ref_name = "<u64 as core::fmt::Display>::fmt";
trace!("Adding alias `{name}` to `{ref_name}`");
let Some(section) = self.sections.lock().get(&*ref_name).cloned() else {
unreachable!();
};
self.add_alias_to_section(&name, section.clone());
return Ok(section);
} else if name == "<u64 as core::fmt::LowerHex>::fmt" {
let ref_name = "<usize as core::fmt::LowerHex>::fmt";
trace!("Adding alias `{name}` to `{ref_name}`");
let Some(section) = self.sections.lock().get(&*ref_name).cloned() else {
unreachable!();
};
self.add_alias_to_section(&name, section.clone());
return Ok(section);
} else if name == "<u64 as core::fmt::UpperHex>::fmt" {
let ref_name = "<usize as core::fmt::UpperHex>::fmt";
trace!("Adding alias `{name}` to `{ref_name}`");
let Some(section) = self.sections.lock().get(&*ref_name).cloned() else {
unreachable!();
};
self.add_alias_to_section(&name, section.clone());
return Ok(section);
}
for object_name in crate_names_in_symbol(name) {
// Skip already loaded objects.
if self.get_object(&object_name).is_some() {
continue;
}
trace!(
"Loading object `{object_name}` as a dependency of `{}` for symbol `{name}`",
for_object.name,
);
self.load_object_impl(
&object_name,
&global_object_provider().read_object(&object_name)?,
address_space,
start_page,
)?;
if let Some(section) = self.sections.lock().get(name) {
return Ok(section.clone());
}
}
// error!("Failed to load `{name}` for `{}`", for_object.name);
Err("section not found")
}
fn add_alias_to_section(&self, name: &str, section: Weak<LoadedSection>) {
self.sections.lock().insert(name.into(), section);
}
fn add_sections<'a, I>(&self, sections: I) -> usize
where
I: IntoIterator<Item = &'a Arc<LoadedSection>>,
{
let mut map = self.sections.lock();
let mut range_map = self.sections_by_addr.lock();
let mut added_count = 0;
for new_section in sections.into_iter() {
range_map.insert(
(new_section.addr, new_section.size),
Arc::downgrade(new_section),
);
if new_section.global {
if let Some(_old_section) =
map.insert(new_section.name.clone(), Arc::downgrade(new_section))
{
// let old_section = old_section.upgrade().unwrap();
// debug!(
// "Moved `{}` from {:x} to {:x}",
// old_section.name, old_section.addr, new_section.addr,
// );
} else {
added_count += 1;
}
}
}
added_count
}
}
// Loading implementation.
impl Loader {
/// Load an object into memory.
///
/// Internally, this method uses the [`GlobalObjectProvider`] to read
/// object data.
///
/// ## Arguments
///
/// - `object_name`, the name of the object to be loaded.
/// - `address_space`, the [`AddressSpace`] to load the object into.
/// - `start_page`, the starting page within `address_space` at which the object (and
/// its dependencies) will be loaded.
pub fn load_object(
&self,
object_name: &str,
address_space: &AddressSpace,
mut start_page: Page,
) -> Result<Arc<Mutex<LoadedObject>>, &'static str> {
info!("Loading `{object_name}`...");
let object_bytes = global_object_provider().read_object(object_name)?;
self.load_object_impl(object_name, &object_bytes, address_space, &mut start_page)
}
fn load_object_impl(
&self,
object_name: &str,
object_bytes: &[u8],
address_space: &AddressSpace,
start_page: &mut Page,
) -> Result<Arc<Mutex<LoadedObject>>, &'static str> {
let mut mappings = BTreeSet::new();
let (object, elf_file) = self.load_object_sections(
object_name,
object_bytes,
address_space,
start_page,
&mut mappings,
)?;
self.add_sections(object.lock().sections.values());
self.objects
.lock()
.insert(object_name.into(), Arc::clone(&object));
self.relocate_object_sections(
&elf_file,
&object,
address_space,
start_page,
&mut mappings,
)?;
Ok(object)
}
fn load_object_sections<'obj>(
&self,
object_name: &'obj str,
object_bytes: &'obj [u8],
address_space: &AddressSpace,
start_page: &mut Page,
mappings: &mut BTreeSet<Address>,
) -> Result<(Arc<Mutex<LoadedObject>>, ElfFile<'obj>), &'static str> {
let elf_file = ElfFile::new(object_bytes)?;
if elf_file.header.get_type() != ObjectFileType::Relocatable {
return Err("not a relocatable ELF file");
}
let SectionMappings {
executable: executable_mapping,
read_only: read_only_mapping,
read_write: read_write_mapping,
} = allocate_section_mappings(object_name, &elf_file)?;
// Map loaded sections into the object's address space.
if let Some(mapping) = &executable_mapping {
let pages = PageRange::from_start_len(*start_page, mapping.pages.len());
mappings.insert(mapping.addr());
mapping
.map_into(
address_space,
pages,
PageTableFlags::PRESENT | PageTableFlags::USER_ACCESSIBLE,
)
.unwrap();
*start_page = pages.end;
}
if let Some(mapping) = &read_only_mapping {
let pages = PageRange::from_start_len(*start_page, mapping.pages.len());
mappings.insert(mapping.addr());
mapping
.map_into(
address_space,
pages,
PageTableFlags::PRESENT | PageTableFlags::USER_ACCESSIBLE,
)
.unwrap();
*start_page = pages.end;
}
if let Some(mapping) = &read_write_mapping {
let pages = PageRange::from_start_len(*start_page, mapping.pages.len());
mappings.insert(mapping.addr());
mapping
.map_into(
address_space,
pages,
PageTableFlags::PRESENT | PageTableFlags::USER_ACCESSIBLE,
)
.unwrap();
*start_page = pages.end;
}
let executable_mapping = executable_mapping.map(|mapping| Arc::new(Mutex::new(mapping)));
let read_only_mapping = read_only_mapping.map(|mapping| Arc::new(Mutex::new(mapping)));
let read_write_mapping = read_write_mapping.map(|mapping| Arc::new(Mutex::new(mapping)));
// The `.text` sections always come at the beginning, so we can get the byte
// range without needing to know the offset.
if let Some(executable_mapping) = &executable_mapping {
let mut executable_map_lock = executable_mapping.lock();
let text_size = executable_map_lock.size();
let slice = elf_file.input.get(..text_size).ok_or_else(|| {
error!("End of last `.text` section ({text_size}) was miscalculated to be beyond ELF file bounds ({})", elf_file.input.len());
"end of last `.text` section was miscalculated to be beyond ELF file bounds"
})?;
executable_map_lock
.as_slice_mut(0, text_size)
.copy_from_slice(slice);
}
let object = Arc::new(Mutex::new(LoadedObject {
name: rustc_demangle::demangle(object_name).to_string().into(),
sections: HashMap::with_hasher(rustc_hash::FxBuildHasher),
global_sections: BTreeSet::new(),
data_sections: BTreeSet::new(),
tls_sections: BTreeSet::new(),
dependencies: HashSet::with_hasher(rustc_hash::FxBuildHasher),
executable_mapping: executable_mapping.clone(),
read_only_mapping: read_only_mapping.clone(),
read_write_mapping: read_write_mapping.clone(),
}));
let mut loaded_sections: HashMap<usize, Arc<LoadedSection>, rustc_hash::FxBuildHasher> =
HashMap::with_hasher(rustc_hash::FxBuildHasher);
let mut data_sections: BTreeSet<usize> = BTreeSet::new();
let mut tls_sections: BTreeSet<usize> = BTreeSet::new();
let global_sections: BTreeSet<usize> = {
let symbol_table = elf_file.get_symbol_table()?;
let mut globals: BTreeSet<usize> = BTreeSet::new();
for entry in symbol_table.iter() {
if entry.get_binding() == Ok(SymbolBinding::Global) {
match entry.get_type() {
Ok(SymbolType::Func | SymbolType::Object | SymbolType::Tls) => {
globals.insert(entry.shndx() as usize);
}
_ => continue,
}
}
}
globals
};
let mut rodata_offset: usize = 0;
let mut data_offset: usize = 0;
for (section_index, section) in elf_file.section_iter().enumerate() {
let section_flags = section.flags();
// Skip non-allocated sections.
if section_flags & SHF_ALLOC == 0 {
continue;
}
// If the current section is zero-sized, it's a reference to the next section.
// So, we just use the next section's information (size, align, etc.) with the
// current section's name.
let section_name = section.get_name(&elf_file)?;
let section = if section.size() == 0 {
// If the next section has the same offset as the current one, use it instead of
// the current one.
match elf_file.get_section_header((section_index + 1) as u16) {
Ok(next_section) => {
if next_section.offset() == section.offset() {
next_section
} else {
section
}
}
_ => {
return Err("couldn't get the section following a zero-sized section");
}
}
} else {
section
};
let section_size = section.size() as usize;
let section_align = section.align() as usize;
let is_write = section_flags & SHF_WRITE == SHF_WRITE;
let is_exec = section_flags & SHF_EXECINSTR == SHF_EXECINSTR;
let is_tls = section_flags & SHF_TLS == SHF_TLS;
macro_rules! symbol_name_after_prefix {
($sec_name:ident, $prefix:literal) => {
if let Some(name) = $sec_name.get($prefix.len()..) {
name
} else {
// Ignore placeholder sections.
match $sec_name {
".text" | ".rodata" | ".data" | ".bss" => continue,
_ => {
return Err(concat!(
"failed to get the ",
$prefix,
" section's name after '",
$prefix,
"'"
));
}
}
}
};
}
// .text
if is_exec && !is_write {
let Some(executable_mapping) = &executable_mapping else {
continue;
};
let is_global = global_sections.contains(§ion_index);
let mut name = symbol_name_after_prefix!(section_name, ".text.");
if name.starts_with(".") {
name = name.strip_prefix(".").unwrap();
}
let name = if is_global && name.starts_with("unlikely.") {
name.get("unlikely.".len()..)
.ok_or("failed to get `.text.unlikely.` section's name")?
} else {
name
};
// We already copied the content of all `.text` sections above, so here we just
// record the metadata into a new `LoadedSection` object.
let text_offset = section.offset() as usize;
let section_addr = executable_mapping.lock().addr() + text_offset;
loaded_sections.insert(
section_index,
Arc::new(LoadedSection {
name: format!("{:#}", rustc_demangle::demangle(name)).into(),
kind: SectionKind::Text,
size: section_size,
addr: section_addr,
global: is_global,
mapping: Arc::clone(&executable_mapping),
mapping_offset: text_offset,
owner: Arc::downgrade(&object),
}),
);
}
// .tdata/.tbss
else if is_tls {
let Some(read_only_mapping) = &read_only_mapping else {
continue;
};
let mut read_only_map_lock = read_only_mapping.lock();
// check if this TLS section is .bss or .data
let is_bss = section.get_type() == Ok(SectionHeaderType::NoBits);
let name = if is_bss {
symbol_name_after_prefix!(section_name, ".tbss.")
} else {
symbol_name_after_prefix!(section_name, ".tdata.")
};
rodata_offset = rodata_offset.next_multiple_of(section_align);
let (mapping_offset, kind) = if is_bss {
// Offset is irrelevant here.
(usize::MAX, SectionKind::TlsBss)
} else {
let slice = read_only_map_lock.as_slice_mut(rodata_offset, section_size);
match section.get_data(&elf_file) {
Ok(SectionData::Undefined(sec_data)) => slice.copy_from_slice(sec_data),
_ => {
return Err("couldn't get data for `.tdata` section");
}
};
(rodata_offset, SectionKind::TlsData)
};
let tls_section = Arc::new(LoadedSection {
name: format!("{:#}", rustc_demangle::demangle(name)).into(),
kind,
size: section_size,
addr: Address::new(0), // See below.
global: global_sections.contains(§ion_index),
mapping: Arc::clone(&read_only_mapping),
mapping_offset,
owner: Arc::downgrade(&object),
});
// This should initialize a TLS area and set the section's address.
if true {
return Err("TODO: TLS section initialization");
}
loaded_sections.insert(section_index, tls_section);
tls_sections.insert(section_index);
rodata_offset += section_size;
}
// .data/.bss
else if is_write {
let Some(read_write_mapping) = &read_write_mapping else {
continue;
};
let mut read_write_map_lock = read_write_mapping.lock();
let is_bss = section.get_type() == Ok(SectionHeaderType::NoBits);
let mut name = if is_bss {
symbol_name_after_prefix!(section_name, ".bss.")
} else {
symbol_name_after_prefix!(section_name, ".data.")
};
if name.starts_with(".") {
name = name.strip_prefix(".").unwrap();
}
data_offset = data_offset.next_multiple_of(section_align);
assert!(data_offset < read_write_map_lock.size());
let section_addr = read_write_map_lock.addr() + data_offset;
let slice = read_write_map_lock.as_slice_mut(data_offset, section_size);
match section.get_data(&elf_file) {
Ok(SectionData::Undefined(sec_data)) => slice.copy_from_slice(sec_data),
Ok(SectionData::Empty) => slice.fill(0),
_ => {
return Err("couldn't get data for `.data` section");
}
}
loaded_sections.insert(
section_index,
Arc::new(LoadedSection {
name: format!("{:#}", rustc_demangle::demangle(name)).into(),
kind: if is_bss {
SectionKind::Bss
} else {
SectionKind::Data
},
size: section_size,
addr: section_addr,
global: global_sections.contains(§ion_index),
mapping: Arc::clone(&read_write_mapping),
mapping_offset: data_offset,
owner: Arc::downgrade(&object),
}),
);
data_sections.insert(section_index);
data_offset += section_size;
}
// .rodata
else if section_name.starts_with(".rodata") {
let Some(read_only_mapping) = &read_only_mapping else {
continue;
};
let mut read_only_map_lock = read_only_mapping.lock();
let name = symbol_name_after_prefix!(section_name, ".rodata.");
rodata_offset = rodata_offset.next_multiple_of(section_align);
assert!(rodata_offset < read_only_map_lock.size());
let section_addr = read_only_map_lock.addr() + rodata_offset;
let slice = read_only_map_lock.as_slice_mut(rodata_offset, section_size);
match section.get_data(&elf_file) {
Ok(SectionData::Undefined(sec_data)) => slice.copy_from_slice(sec_data),
Ok(SectionData::Empty) => slice.fill(0),
_ => {
return Err("couldn't get data for `.rodata` section");