elf_loader 0.12.0

A pure-rust library for loading all ELF format files from both memory and files.
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
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
pub(crate) mod dylib;
pub(crate) mod exec;

use crate::{
    ELFRelro, ElfRelocation, Loader, Result,
    arch::{Dyn, ElfPhdr, ElfRelType},
    dynamic::ElfDynamic,
    loader::{Builder, FnArray},
    mmap::Mmap,
    object::{ElfObject, ElfObjectAsync},
    relocation::{LazyScope, UnknownHandler},
    segment::ElfSegments,
    symbol::SymbolTable,
};
use alloc::{boxed::Box, ffi::CString, vec::Vec};
use core::{
    any::Any,
    cell::Cell,
    ffi::CStr,
    fmt::Debug,
    marker::PhantomData,
    ops::{Deref, DerefMut},
    ptr::{NonNull, null},
    sync::atomic::{AtomicBool, Ordering},
};
use delegate::delegate;
use dylib::{ElfDylib, RelocatedDylib};
use elf::abi::PT_LOAD;
use exec::{ElfExec, RelocatedExec};

#[cfg(not(feature = "portable-atomic"))]
use alloc::sync::{Arc, Weak};
#[cfg(feature = "portable-atomic")]
use portable_atomic_util::{Arc, Weak};

struct DataItem {
    key: u8,
    value: Option<Box<dyn Any>>,
}

/// User-defined data associated with the loaded ELF file
pub struct UserData {
    data: Vec<DataItem>,
}

impl UserData {
    #[inline]
    pub const fn empty() -> Self {
        Self { data: Vec::new() }
    }

    #[inline]
    pub fn insert(&mut self, key: u8, value: Box<dyn Any>) -> Option<Box<dyn Any>> {
        for item in &mut self.data {
            if item.key == key {
                let old = core::mem::take(&mut item.value);
                item.value = Some(value);
                return old;
            }
        }
        self.data.push(DataItem {
            key,
            value: Some(value),
        });
        None
    }

    #[inline]
    pub fn get(&self, key: u8) -> Option<&Box<dyn Any>> {
        self.data.iter().find_map(|item| {
            if item.key == key {
                return item.value.as_ref();
            }
            None
        })
    }
}

impl Deref for Relocated<'_> {
    type Target = CoreComponent;

    fn deref(&self) -> &Self::Target {
        &self.core
    }
}

/// An unrelocated elf file
#[derive(Debug)]
pub enum Elf {
    Dylib(ElfDylib),
    Exec(ElfExec),
}

/// A elf file that has been relocated
#[derive(Debug, Clone)]
pub enum RelocatedElf<'scope> {
    Dylib(RelocatedDylib<'scope>),
    Exec(RelocatedExec<'scope>),
}

impl<'scope> RelocatedElf<'scope> {
    #[inline]
    pub fn into_dylib(self) -> Option<RelocatedDylib<'scope>> {
        match self {
            RelocatedElf::Dylib(dylib) => Some(dylib),
            RelocatedElf::Exec(_) => None,
        }
    }

    #[inline]
    pub fn into_exec(self) -> Option<RelocatedExec<'scope>> {
        match self {
            RelocatedElf::Dylib(_) => None,
            RelocatedElf::Exec(exec) => Some(exec),
        }
    }

    #[inline]
    pub fn as_dylib(&self) -> Option<&RelocatedDylib<'scope>> {
        match self {
            RelocatedElf::Dylib(dylib) => Some(dylib),
            RelocatedElf::Exec(_) => None,
        }
    }
}

impl Deref for Elf {
    type Target = ElfCommonPart;

    fn deref(&self) -> &Self::Target {
        match self {
            Elf::Dylib(elf_dylib) => elf_dylib,
            Elf::Exec(elf_exec) => elf_exec,
        }
    }
}

// 使用CoreComponentRef是防止出现循环引用
pub(crate) fn create_lazy_scope<F>(libs: Vec<CoreComponentRef>, pre_find: &F) -> LazyScope
where
    F: Fn(&str) -> Option<*const ()>,
{
    #[cfg(not(feature = "portable-atomic"))]
    type Ptr<T> = Arc<T>;
    #[cfg(feature = "portable-atomic")]
    type Ptr<T> = Box<T>;
    // workaround unstable CoerceUnsized by create Box<dyn _> then convert using Arc::from
    // https://github.com/rust-lang/rust/issues/18598
    let closure: Ptr<dyn for<'a> Fn(&'a str) -> Option<*const ()>> = Ptr::new(move |name| {
        libs.iter().find_map(|lib| {
            pre_find(name).or_else(|| unsafe {
                RelocatedDylib::from_core_component(lib.upgrade().unwrap())
                    .get::<()>(name)
                    .map(|sym| sym.into_raw())
            })
        })
    });
    closure.into()
}

impl Elf {
    /// Relocate the elf file with the given dynamic libraries and function closure.
    /// # Note
    /// During relocation, the symbol is first searched in the function closure `pre_find`.
    pub fn easy_relocate<'iter, 'scope, 'find, 'lib, F>(
        self,
        scope: impl IntoIterator<Item = &'iter RelocatedDylib<'scope>>,
        pre_find: &'find F,
    ) -> Result<RelocatedElf<'lib>>
    where
        F: Fn(&str) -> Option<*const ()>,
        'scope: 'iter,
        'iter: 'lib,
        'find: 'lib,
    {
        match self {
            Elf::Dylib(elf_dylib) => Ok(RelocatedElf::Dylib(
                elf_dylib.easy_relocate(scope, pre_find)?,
            )),
            Elf::Exec(elf_exec) => Ok(RelocatedElf::Exec(elf_exec.easy_relocate(scope, pre_find)?)),
        }
    }

    /// Relocate the elf file with the given dynamic libraries and function closure.
    /// # Note
    /// * During relocation, the symbol is first searched in the function closure `pre_find`.
    /// * The `deal_unknown` function is used to handle relocation types not implemented by efl_loader or failed relocations
    /// * relocation will be done in the exact order in which the dynamic libraries appear in `scope`.
    /// * When lazy binding, the symbol is first looked for in the global scope and then in the local lazy scope
    pub fn relocate<'iter, 'scope, 'find, 'lib, F>(
        self,
        scope: impl AsRef<[&'iter RelocatedDylib<'scope>]>,
        pre_find: &'find F,
        deal_unknown: &mut UnknownHandler,
        local_lazy_scope: Option<LazyScope<'lib>>,
    ) -> Result<RelocatedElf<'lib>>
    where
        F: Fn(&str) -> Option<*const ()>,
        'scope: 'iter,
        'iter: 'lib,
        'find: 'lib,
    {
        let relocated_elf = match self {
            Elf::Dylib(elf_dylib) => RelocatedElf::Dylib(elf_dylib.relocate(
                scope,
                pre_find,
                deal_unknown,
                local_lazy_scope,
            )?),
            Elf::Exec(elf_exec) => RelocatedElf::Exec(elf_exec.relocate(
                scope,
                pre_find,
                deal_unknown,
                local_lazy_scope,
            )?),
        };
        Ok(relocated_elf)
    }
}

#[derive(Clone)]
pub(crate) struct Relocated<'scope> {
    pub(crate) core: CoreComponent,
    pub(crate) _marker: PhantomData<&'scope ()>,
}

pub(crate) struct CoreComponentInner {
    /// is initialized
    is_init: AtomicBool,
    /// file name
    name: CString,
    /// elf symbols
    pub(crate) symbols: Option<SymbolTable>,
    /// dynamic
    dynamic: Option<NonNull<Dyn>>,
    /// rela.plt
    #[allow(unused)]
    pub(crate) pltrel: Option<NonNull<ElfRelType>>,
    /// phdrs
    phdrs: ElfPhdrs,
    /// .fini and .fini_array
    fini: Box<dyn Fn()>,
    /// needed libs' name
    needed_libs: Box<[&'static str]>,
    /// user data
    user_data: UserData,
    /// lazy binding scope
    pub(crate) lazy_scope: Option<LazyScope<'static>>,
    /// semgents
    pub(crate) segments: ElfSegments,
}

impl Drop for CoreComponentInner {
    fn drop(&mut self) {
        if self.is_init.load(Ordering::Relaxed) {
            (self.fini)();
        }
    }
}

/// `CoreComponentRef` is a version of `CoreComponent` that holds a non-owning reference to the managed allocation.
pub struct CoreComponentRef {
    inner: Weak<CoreComponentInner>,
}

impl CoreComponentRef {
    /// Attempts to upgrade the Weak pointer to an Arc
    pub fn upgrade(&self) -> Option<CoreComponent> {
        self.inner.upgrade().map(|inner| CoreComponent { inner })
    }
}

/// The core part of an elf object
#[derive(Clone)]
pub struct CoreComponent {
    pub(crate) inner: Arc<CoreComponentInner>,
}

unsafe impl Sync for CoreComponentInner {}
unsafe impl Send for CoreComponentInner {}

impl CoreComponent {
    #[inline]
    pub(crate) fn set_lazy_scope(&self, lazy_scope: LazyScope) {
        // 因为在完成重定位前,只有unsafe的方法可以拿到CoreComponent的引用,所以这里认为是安全的
        unsafe {
            let ptr = &mut *(Arc::as_ptr(&self.inner) as *mut CoreComponentInner);
            // 在relocate接口处保证了lazy_scope的声明周期,因此这里直接转换
            ptr.lazy_scope = Some(core::mem::transmute::<LazyScope<'_>, LazyScope<'static>>(
                lazy_scope,
            ));
        };
    }

    #[inline]
    pub(crate) fn set_init(&self) {
        self.inner.is_init.store(true, Ordering::Relaxed);
    }

    #[inline]
    /// Creates a new Weak pointer to this allocation.
    pub fn downgrade(&self) -> CoreComponentRef {
        CoreComponentRef {
            inner: Arc::downgrade(&self.inner),
        }
    }

    /// Gets user data from the elf object.
    #[inline]
    pub fn user_data(&self) -> &UserData {
        &self.inner.user_data
    }

    /// Gets the number of strong references to the elf object.
    #[inline]
    pub fn strong_count(&self) -> usize {
        Arc::strong_count(&self.inner)
    }

    /// Gets the number of weak references to the elf object.
    #[inline]
    pub fn weak_count(&self) -> usize {
        Arc::weak_count(&self.inner)
    }

    /// Gets the name of the elf object.
    #[inline]
    pub fn name(&self) -> &str {
        self.inner.name.to_str().unwrap()
    }

    /// Gets the C-style name of the elf object.
    #[inline]
    pub fn cname(&self) -> &CStr {
        &self.inner.name
    }

    /// Gets the short name of the elf object.
    #[inline]
    pub fn shortname(&self) -> &str {
        self.name().split('/').next_back().unwrap()
    }

    /// Gets the base address of the elf object.
    #[inline]
    pub fn base(&self) -> usize {
        self.inner.segments.base()
    }

    /// Gets the memory length of the elf object map.
    #[inline]
    pub fn map_len(&self) -> usize {
        self.inner.segments.len()
    }

    /// Gets the program headers of the elf object.
    #[inline]
    pub fn phdrs(&self) -> &[ElfPhdr] {
        match &self.inner.phdrs {
            ElfPhdrs::Mmap(phdrs) => &phdrs,
            ElfPhdrs::Vec(phdrs) => &phdrs,
        }
    }

    /// Gets the address of the dynamic section.
    #[inline]
    pub fn dynamic(&self) -> Option<NonNull<Dyn>> {
        self.inner.dynamic
    }

    /// Gets the needed libs' name of the elf object.
    #[inline]
    pub fn needed_libs(&self) -> &[&str] {
        &self.inner.needed_libs
    }

    /// Gets the symbol table.
    #[inline]
    pub fn symtab(&self) -> Option<&SymbolTable> {
        self.inner.symbols.as_ref()
    }

    #[inline]
    pub(crate) fn segments(&self) -> &ElfSegments {
        &self.inner.segments
    }

    fn from_raw(
        name: CString,
        base: usize,
        dynamic: ElfDynamic,
        phdrs: &'static [ElfPhdr],
        mut segments: ElfSegments,
        user_data: UserData,
    ) -> Self {
        segments.offset = (segments.memory.as_ptr() as usize).wrapping_sub(base);
        Self {
            inner: Arc::new(CoreComponentInner {
                name,
                is_init: AtomicBool::new(true),
                symbols: Some(SymbolTable::new(&dynamic)),
                pltrel: None,
                dynamic: NonNull::new(dynamic.dyn_ptr as _),
                phdrs: ElfPhdrs::Mmap(phdrs),
                segments,
                fini: Box::new(|| {}),
                needed_libs: Box::new([]),
                user_data,
                lazy_scope: None,
            }),
        }
    }
}

impl Debug for CoreComponent {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Dylib")
            .field("name", &self.inner.name)
            .finish()
    }
}

struct ElfExtraData {
    /// lazy binding
    lazy: bool,
    /// .got.plt
    got: Option<NonNull<usize>>,
    /// rela.dyn and rela.plt
    relocation: ElfRelocation,
    /// GNU_RELRO segment
    relro: Option<ELFRelro>,
    /// init
    init: Box<dyn Fn()>,
    /// DT_RPATH
    rpath: Option<&'static str>,
    /// DT_RUNPATH
    runpath: Option<&'static str>,
}

struct LazyData {
    /// core component
    core: CoreComponent,
    /// extra data
    extra: ElfExtraData,
}

enum State {
    Empty,
    Uninit {
        is_dylib: bool,
        phdrs: ElfPhdrs,
        init_fn: FnArray,
        fini_fn: FnArray,
        name: CString,
        dynamic_ptr: Option<NonNull<Dyn>>,
        segments: ElfSegments,
        relro: Option<ELFRelro>,
        user_data: UserData,
        lazy_bind: Option<bool>,
    },
    Init(LazyData),
}

impl State {
    fn init(self) -> Self {
        let lazy_data = match self {
            State::Uninit {
                name,
                dynamic_ptr,
                segments,
                relro,
                user_data,
                lazy_bind,
                init_fn,
                fini_fn,
                phdrs,
                is_dylib,
            } => {
                if let Some(dynamic_ptr) = dynamic_ptr {
                    let dynamic = ElfDynamic::new(dynamic_ptr.as_ptr(), &segments).unwrap();
                    let relocation = ElfRelocation::new(
                        dynamic.pltrel,
                        dynamic.dynrel,
                        dynamic.relr,
                        dynamic.rel_count,
                    );
                    let symbols = SymbolTable::new(&dynamic);
                    let needed_libs: Vec<&'static str> = dynamic
                        .needed_libs
                        .iter()
                        .map(|needed_lib| symbols.strtab().get_str(needed_lib.get()))
                        .collect();
                    LazyData {
                        extra: ElfExtraData {
                            lazy: lazy_bind.unwrap_or(!dynamic.bind_now),
                            relro,
                            relocation,
                            init: Box::new(move || init_fn(dynamic.init_fn, dynamic.init_array_fn)),
                            got: dynamic.got,
                            rpath: dynamic
                                .rpath_off
                                .map(|rpath_off| symbols.strtab().get_str(rpath_off.get())),
                            runpath: dynamic
                                .runpath_off
                                .map(|runpath_off| symbols.strtab().get_str(runpath_off.get())),
                        },
                        core: CoreComponent {
                            inner: Arc::new(CoreComponentInner {
                                is_init: AtomicBool::new(false),
                                name,
                                symbols: Some(symbols),
                                dynamic: NonNull::new(dynamic.dyn_ptr as _),
                                pltrel: NonNull::new(
                                    dynamic.pltrel.map_or(null(), |plt| plt.as_ptr()) as _,
                                ),
                                phdrs,
                                fini: Box::new(move || {
                                    fini_fn(dynamic.fini_fn, dynamic.fini_array_fn)
                                }),
                                segments,
                                needed_libs: needed_libs.into_boxed_slice(),
                                user_data,
                                lazy_scope: None,
                            }),
                        },
                    }
                } else {
                    assert!(!is_dylib, "dylib does not have dynamic");
                    let relocation = ElfRelocation::new(None, None, None, None);
                    LazyData {
                        core: CoreComponent {
                            inner: Arc::new(CoreComponentInner {
                                is_init: AtomicBool::new(false),
                                name,
                                symbols: None,
                                dynamic: None,
                                pltrel: None,
                                phdrs: ElfPhdrs::Mmap(&[]),
                                fini: Box::new(|| {}),
                                segments,
                                needed_libs: Box::new([]),
                                user_data,
                                lazy_scope: None,
                            }),
                        },
                        extra: ElfExtraData {
                            lazy: lazy_bind.unwrap_or(false),
                            relro,
                            relocation,
                            init: Box::new(|| {}),
                            got: None,
                            rpath: None,
                            runpath: None,
                        },
                    }
                }
            }
            State::Empty | State::Init(_) => unreachable!(),
        };
        State::Init(lazy_data)
    }
}

struct LazyParse {
    state: Cell<State>,
}

impl LazyParse {
    fn force(&self) -> &LazyData {
        // 快路径加速
        if let State::Init(lazy_data) = unsafe { &*self.state.as_ptr() } {
            return lazy_data;
        }
        self.state.set(self.state.replace(State::Empty).init());
        match unsafe { &*self.state.as_ptr() } {
            State::Empty | State::Uninit { .. } => unreachable!(),
            State::Init(lazy_data) => lazy_data,
        }
    }

    fn force_mut(&mut self) -> &mut LazyData {
        // 快路径加速
        if let State::Init(lazy_data) = self.state.get_mut() {
            return unsafe { core::mem::transmute(lazy_data) };
        }
        self.state.set(self.state.replace(State::Empty).init());
        match unsafe { &mut *self.state.as_ptr() } {
            State::Empty | State::Uninit { .. } => unreachable!(),
            State::Init(lazy_data) => lazy_data,
        }
    }
}

impl Deref for LazyParse {
    type Target = LazyData;

    #[inline]
    fn deref(&self) -> &LazyData {
        self.force()
    }
}

impl DerefMut for LazyParse {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.force_mut()
    }
}

#[derive(Clone)]
enum ElfPhdrs {
    Mmap(&'static [ElfPhdr]),
    Vec(Vec<ElfPhdr>),
}

/// A common part of elf object
pub struct ElfCommonPart {
    /// entry
    entry: usize,
    /// PT_INTERP
    interp: Option<&'static str>,
    /// file name
    name: &'static CStr,
    /// phdrs
    phdrs: ElfPhdrs,
    /// data parse lazy
    data: LazyParse,
}

impl ElfCommonPart {
    /// Gets the entry point of the elf object.
    #[inline]
    pub fn entry(&self) -> usize {
        self.entry
    }

    /// Gets the core component reference of the elf object
    #[inline]
    pub fn core_component_ref(&self) -> &CoreComponent {
        &self.data.core
    }

    /// Gets the core component of the elf object
    #[inline]
    pub fn core_component(&self) -> CoreComponent {
        self.data.core.clone()
    }

    #[inline]
    /// Gets the core component of the elf object
    pub fn into_core_component(self) -> CoreComponent {
        self.data.force();
        match self.data.state.into_inner() {
            State::Empty | State::Uninit { .. } => unreachable!(),
            State::Init(lazy_data) => lazy_data.core,
        }
    }

    /// Whether lazy binding is enabled for the current elf object.
    #[inline]
    pub fn is_lazy(&self) -> bool {
        self.data.extra.lazy
    }

    /// Gets the DT_RPATH value.
    #[inline]
    pub fn rpath(&self) -> Option<&str> {
        self.data.extra.rpath
    }

    /// Gets the DT_RUNPATH value.
    #[inline]
    pub fn runpath(&self) -> Option<&str> {
        self.data.extra.runpath
    }

    /// Gets the PT_INTERP value.
    #[inline]
    pub fn interp(&self) -> Option<&str> {
        self.interp
    }

    /// Gets the name of the elf object.
    #[inline]
    pub fn name(&self) -> &str {
        self.name.to_str().unwrap()
    }

    /// Gets the C-style name of the elf object.
    #[inline]
    pub fn cname(&self) -> &CStr {
        self.name
    }

    /// Gets the short name of the elf object.
    #[inline]
    pub fn shortname(&self) -> &str {
        self.name().split('/').next_back().unwrap()
    }

    /// Gets the program headers of the elf object.
    pub fn phdrs(&self) -> &[ElfPhdr] {
        match &self.phdrs {
            ElfPhdrs::Mmap(phdrs) => &phdrs,
            ElfPhdrs::Vec(phdrs) => &phdrs,
        }
    }

    #[inline]
    pub(crate) fn got(&self) -> Option<NonNull<usize>> {
        self.data.extra.got
    }

    #[inline]
    pub(crate) fn relocation(&self) -> &ElfRelocation {
        &self.data.extra.relocation
    }

    #[inline]
    pub(crate) fn finish(&self) {
        self.data.core.set_init();
        (self.data.extra.init)();
    }

    #[inline]
    pub(crate) fn relro(&self) -> Option<&ELFRelro> {
        self.data.extra.relro.as_ref()
    }

    #[inline]
    pub(crate) fn user_data_mut(&mut self) -> Option<&mut UserData> {
        // 因为从LazyCell中获取可变引用是unstable feature,所以这里使用unsafe方法
        // 获取可变引用,然后通过forget释放掉Arc,避免Arc的计数器减1,导致Arc被释放。
        Arc::get_mut(&mut self.data.core.inner).map(|inner| &mut inner.user_data)
    }

    delegate! {
        to self.data.core{
            pub(crate) fn symtab(&self) -> Option<&SymbolTable>;
            /// Gets the base address of the elf object.
            pub fn base(&self) -> usize;
            /// Gets the needed libs' name of the elf object.
            pub fn needed_libs(&self) -> &[&str];
            /// Gets the address of the dynamic section.
            pub fn dynamic(&self) -> Option<NonNull<Dyn>>;
            /// Gets the memory length of the elf object map.
            pub fn map_len(&self) -> usize;
            /// Gets user data from the elf object.
            pub fn user_data(&self) -> &UserData;
        }
    }
}

impl Builder {
    pub(crate) fn create_inner(self, phdrs: &[ElfPhdr], is_dylib: bool) -> ElfCommonPart {
        let (phdr_start, phdr_end) = self.ehdr.phdr_range();
        // 获取映射到内存中的Phdr
        let phdrs = self
            .phdr_mmap
            .or_else(|| {
                phdrs
                    .iter()
                    .filter(|phdr| phdr.p_type == PT_LOAD)
                    .find_map(|phdr| {
                        let cur_range =
                            phdr.p_offset as usize..(phdr.p_offset + phdr.p_filesz) as usize;
                        if cur_range.contains(&phdr_start) && cur_range.contains(&phdr_end) {
                            return Some(self.segments.get_slice::<ElfPhdr>(
                                phdr.p_vaddr as usize + phdr_start - cur_range.start,
                                self.ehdr.e_phnum() * size_of::<ElfPhdr>(),
                            ));
                        }
                        None
                    })
            })
            .map(|phdrs| ElfPhdrs::Mmap(phdrs))
            .unwrap_or_else(|| ElfPhdrs::Vec(Vec::from(phdrs)));
        ElfCommonPart {
            entry: self.ehdr.e_entry as usize + if is_dylib { self.segments.base() } else { 0 },
            interp: self.interp,
            name: unsafe { core::mem::transmute::<&CStr, &CStr>(self.name.as_c_str()) },
            phdrs: phdrs.clone(),
            data: LazyParse {
                state: Cell::new(State::Uninit {
                    is_dylib,
                    phdrs,
                    init_fn: self.init_fn,
                    fini_fn: self.fini_fn,
                    name: self.name,
                    dynamic_ptr: self.dynamic_ptr,
                    segments: self.segments,
                    relro: self.relro,
                    user_data: self.user_data,
                    lazy_bind: self.lazy_bind,
                }),
            },
        }
    }

    pub(crate) fn create_elf(self, phdrs: &[ElfPhdr], is_dylib: bool) -> Elf {
        if is_dylib {
            Elf::Dylib(self.create_dylib(phdrs))
        } else {
            Elf::Exec(self.create_exec(phdrs))
        }
    }
}

impl<M: Mmap> Loader<M> {
    /// Load a elf file into memory
    pub fn easy_load(&mut self, object: impl ElfObject) -> Result<Elf> {
        self.load(object, None)
    }

    /// Load a elf file into memory
    /// # Note
    /// * When `lazy_bind` is not set, lazy binding is enabled using the dynamic library's DT_FLAGS flag.
    pub fn load(&mut self, mut object: impl ElfObject, lazy_bind: Option<bool>) -> Result<Elf> {
        let ehdr = self.buf.prepare_ehdr(&mut object)?;
        let is_dylib = ehdr.is_dylib();
        let (builder, phdrs) = self.load_impl(ehdr, object, lazy_bind)?;
        Ok(builder.create_elf(phdrs, is_dylib))
    }

    /// Load a elf file into memory
    /// # Note
    /// * When `lazy_bind` is not set, lazy binding is enabled using the dynamic library's DT_FLAGS flag.
    pub async fn load_async(
        &mut self,
        mut object: impl ElfObjectAsync,
        lazy_bind: Option<bool>,
    ) -> Result<Elf> {
        let ehdr = self.buf.prepare_ehdr(&mut object)?;
        let is_dylib = ehdr.is_dylib();
        let (builder, phdrs) = self.load_async_impl(ehdr, object, lazy_bind).await?;
        Ok(builder.create_elf(phdrs, is_dylib))
    }
}