1 // ELF-specific support for sections with shared libraries.
2 // Copyright (C) 2019-2021 Free Software Foundation, Inc.
4 // GCC is free software; you can redistribute it and/or modify it under
5 // the terms of the GNU General Public License as published by the Free
6 // Software Foundation; either version 3, or (at your option) any later
9 // GCC is distributed in the hope that it will be useful, but WITHOUT ANY
10 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 // Under Section 7 of GPL version 3, you are granted additional
15 // permissions described in the GCC Runtime Library Exception, version
16 // 3.1, as published by the Free Software Foundation.
18 // You should have received a copy of the GNU General Public License and
19 // a copy of the GCC Runtime Library Exception along with this program;
20 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
21 // <http://www.gnu.org/licenses/>.
23 module gcc.sections.elf_shared;
25 version (MIPS32) version = MIPS_Any;
26 version (MIPS64) version = MIPS_Any;
27 version (RISCV32) version = RISCV_Any;
28 version (RISCV64) version = RISCV_Any;
29 version (S390) version = IBMZ_Any;
30 version (SystemZ) version = IBMZ_Any;
32 version (CRuntime_Glibc) enum SharedELF = true;
33 else version (CRuntime_Musl) enum SharedELF = true;
34 else version (FreeBSD) enum SharedELF = true;
35 else version (NetBSD) enum SharedELF = true;
36 else version (DragonFlyBSD) enum SharedELF = true;
37 else version (CRuntime_UClibc) enum SharedELF = true;
38 else version (Solaris) enum SharedELF = true;
39 else enum SharedELF = false;
40 static if (SharedELF):
44 import core.stdc.config;
45 import core.stdc.stdio;
46 import core.stdc.stdlib : calloc, exit, free, malloc, EXIT_FAILURE;
47 import core.stdc.string : strlen;
50 import core.sys.linux.dlfcn;
51 import core.sys.linux.elf;
52 import core.sys.linux.link;
54 else version (FreeBSD)
56 import core.sys.freebsd.dlfcn;
57 import core.sys.freebsd.sys.elf;
58 import core.sys.freebsd.sys.link_elf;
62 import core.sys.netbsd.dlfcn;
63 import core.sys.netbsd.sys.elf;
64 import core.sys.netbsd.sys.link_elf;
66 else version (DragonFlyBSD)
68 import core.sys.dragonflybsd.dlfcn;
69 import core.sys.dragonflybsd.sys.elf;
70 import core.sys.dragonflybsd.sys.link_elf;
72 else version (Solaris)
74 import core.sys.solaris.dlfcn;
75 import core.sys.solaris.link;
76 import core.sys.solaris.sys.elf;
77 import core.sys.solaris.sys.link;
81 static assert(0, "unimplemented");
83 import core.sys.posix.pthread;
89 import rt.util.container.array;
90 import rt.util.container.hashtab;
93 * Asserts the specified condition, independent from -release, by abort()ing.
94 * Regular assertions throw an AssertError and thus require an initialized
95 * GC, which isn't the case (yet or anymore) for the startup/shutdown code in
96 * this module (called by CRT ctors/dtors etc.).
98 private void safeAssert(bool condition, scope string msg, size_t line = __LINE__) @nogc nothrow @safe
100 import core.internal.abort;
101 condition || abort(msg, __FILE__, line);
104 alias DSO SectionGroup;
107 static int opApply(scope int delegate(ref DSO) dg)
109 foreach (dso; _loadedDSOs)
111 if (auto res = dg(*dso))
117 static int opApplyReverse(scope int delegate(ref DSO) dg)
119 foreach_reverse (dso; _loadedDSOs)
121 if (auto res = dg(*dso))
127 @property immutable(ModuleInfo*)[] modules() const nothrow @nogc
129 return _moduleGroup.modules;
132 @property ref inout(ModuleGroup) moduleGroup() inout nothrow @nogc
137 @property immutable(FuncTable)[] ehTables() const nothrow @nogc
142 @property inout(void[])[] gcRanges() inout nothrow @nogc
151 safeAssert(_moduleGroup.modules.length > 0, "No modules for DSO.");
152 safeAssert(_tlsMod || !_tlsSize, "Inconsistent TLS fields for DSO.");
155 ModuleGroup _moduleGroup;
156 Array!(void[]) _gcRanges;
162 Array!(void[]) _codeSegments; // array of code segments
163 Array!(DSO*) _deps; // D libraries needed by this DSO
164 void* _handle; // corresponding handle
167 // get the TLS range for the executing thread
168 void[] tlsRange() const nothrow @nogc
170 return getTLSRange(_tlsMod, _tlsSize);
175 * Boolean flag set to true while the runtime is initialized.
177 __gshared bool _isRuntimeInitialized;
180 version (FreeBSD) private __gshared void* dummy_ref;
181 version (DragonFlyBSD) private __gshared void* dummy_ref;
182 version (NetBSD) private __gshared void* dummy_ref;
183 version (Solaris) private __gshared void* dummy_ref;
186 * Gets called on program startup just before GC is initialized.
188 void initSections() nothrow @nogc
190 _isRuntimeInitialized = true;
191 // reference symbol to support weak linkage
192 version (FreeBSD) dummy_ref = &_d_dso_registry;
193 version (DragonFlyBSD) dummy_ref = &_d_dso_registry;
194 version (NetBSD) dummy_ref = &_d_dso_registry;
195 version (Solaris) dummy_ref = &_d_dso_registry;
200 * Gets called on program shutdown just after GC is terminated.
202 void finiSections() nothrow @nogc
204 _isRuntimeInitialized = false;
207 alias ScanDG = void delegate(void* pbeg, void* pend) nothrow;
212 * Called once per thread; returns array of thread local storage ranges
214 Array!(ThreadDSO)* initTLSRanges() @nogc nothrow
216 return &_loadedDSOs();
219 void finiTLSRanges(Array!(ThreadDSO)* tdsos) @nogc nothrow
221 // Nothing to do here. tdsos used to point to the _loadedDSOs instance
222 // in the dying thread's TLS segment and as such is not valid anymore.
223 // The memory for the array contents was already reclaimed in
224 // cleanupLoadedLibraries().
227 void scanTLSRanges(Array!(ThreadDSO)* tdsos, scope ScanDG dg) nothrow
236 foreach (ref tdso; *tdsos)
237 dg(tdso._tlsRange.ptr, tdso._tlsRange.ptr + tdso._tlsRange.length);
241 // interface for core.thread to inherit loaded libraries
242 void* pinLoadedLibraries() nothrow @nogc
244 auto res = cast(Array!(ThreadDSO)*)calloc(1, Array!(ThreadDSO).sizeof);
245 res.length = _loadedDSOs.length;
246 foreach (i, ref tdso; _loadedDSOs)
251 // Increment the dlopen ref for explicitly loaded libraries to pin them.
252 const success = .dlopen(linkMapForHandle(tdso._pdso._handle).l_name, RTLD_LAZY) !is null;
253 safeAssert(success, "Failed to increment dlopen ref.");
254 (*res)[i]._addCnt = 1; // new array takes over the additional ref count
260 void unpinLoadedLibraries(void* p) nothrow @nogc
262 auto pary = cast(Array!(ThreadDSO)*)p;
263 // In case something failed we need to undo the pinning.
264 foreach (ref tdso; *pary)
268 auto handle = tdso._pdso._handle;
269 safeAssert(handle !is null, "Invalid library handle.");
277 // Called before TLS ctors are ran, copy over the loaded libraries
278 // of the parent thread.
279 void inheritLoadedLibraries(void* p) nothrow @nogc
281 safeAssert(_loadedDSOs.empty, "DSOs have already been registered for this thread.");
282 _loadedDSOs.swap(*cast(Array!(ThreadDSO)*)p);
284 foreach (ref dso; _loadedDSOs)
286 // the copied _tlsRange corresponds to parent thread
287 dso.updateTLSRange();
291 // Called after all TLS dtors ran, decrements all remaining dlopen refs.
292 void cleanupLoadedLibraries() nothrow @nogc
294 foreach (ref tdso; _loadedDSOs)
296 if (tdso._addCnt == 0) continue;
298 auto handle = tdso._pdso._handle;
299 safeAssert(handle !is null, "Invalid DSO handle.");
300 for (; tdso._addCnt > 0; --tdso._addCnt)
304 // Free the memory for the array contents.
311 * Called once per thread; returns array of thread local storage ranges
313 Array!(void[])* initTLSRanges() nothrow @nogc
315 auto rngs = &_tlsRanges();
318 foreach (ref pdso; _loadedDSOs)
319 rngs.insertBack(pdso.tlsRange());
324 void finiTLSRanges(Array!(void[])* rngs) nothrow @nogc
329 void scanTLSRanges(Array!(void[])* rngs, scope ScanDG dg) nothrow
339 dg(rng.ptr, rng.ptr + rng.length);
349 * Array of thread local DSO metadata for all libraries loaded and
350 * initialized in this thread.
353 * A newly spawned thread will inherit these libraries.
355 * We use an array here to preserve the order of
356 * initialization. If that became a performance issue, we
357 * could use a hash table and enumerate the DSOs during
358 * loading so that the hash table values could be sorted when
364 static if (_pdso.sizeof == 8) uint _refCnt, _addCnt;
365 else static if (_pdso.sizeof == 4) ushort _refCnt, _addCnt;
366 else static assert(0, "unimplemented");
369 // update the _tlsRange for the executing thread
370 void updateTLSRange() nothrow @nogc
372 _tlsRange = _pdso.tlsRange();
375 @property ref Array!(ThreadDSO) _loadedDSOs() @nogc nothrow { static Array!(ThreadDSO) x; return x; }
378 * Set to true during rt_loadLibrary/rt_unloadLibrary calls.
383 * Hash table to map link_map* to corresponding DSO*.
384 * The hash table is protected by a Mutex.
386 __gshared pthread_mutex_t _handleToDSOMutex;
387 @property ref HashTab!(void*, DSO*) _handleToDSO() @nogc nothrow { __gshared HashTab!(void*, DSO*) x; return x; }
390 * Section in executable that contains copy relocations.
391 * Might be null when druntime is dynamically loaded by a C host.
393 __gshared const(void)[] _copyRelocSection;
398 * Static DSOs loaded by the runtime linker. This includes the
399 * executable. These can't be unloaded.
401 @property ref Array!(DSO*) _loadedDSOs() @nogc nothrow { __gshared Array!(DSO*) x; return x; }
404 * Thread local array that contains TLS memory ranges for each
405 * library initialized in this thread.
407 @property ref Array!(void[]) _tlsRanges() @nogc nothrow { static Array!(void[]) x; return x; }
409 enum _rtLoading = false;
412 ///////////////////////////////////////////////////////////////////////////////
413 // Compiler to runtime interface.
414 ///////////////////////////////////////////////////////////////////////////////
417 * This data structure is generated by the compiler, and then passed to
420 struct CompilerDSOData
422 size_t _version; // currently 1
423 void** _slot; // can be used to store runtime data
424 immutable(object.ModuleInfo*)* _minfo_beg, _minfo_end; // array of modules in this object file
427 T[] toRange(T)(T* beg, T* end) { return beg[0 .. end - beg]; }
429 /* For each shared library and executable, the compiler generates code that
430 * sets up CompilerDSOData and calls _d_dso_registry().
431 * A pointer to that code is inserted into both the .ctors and .dtors
432 * segment so it gets called by the loader on startup and shutdown.
434 extern(C) void _d_dso_registry(CompilerDSOData* data)
436 // only one supported currently
437 safeAssert(data._version >= 1, "Incompatible compiler-generated DSO data version.");
439 // no backlink => register
440 if (*data._slot is null)
442 immutable firstDSO = _loadedDSOs.empty;
443 if (firstDSO) initLocks();
445 DSO* pdso = cast(DSO*).calloc(1, DSO.sizeof);
446 assert(typeid(DSO).initializer().ptr is null);
447 *data._slot = pdso; // store backlink in library record
449 pdso._moduleGroup = ModuleGroup(toRange(data._minfo_beg, data._minfo_end));
451 dl_phdr_info info = void;
452 const headerFound = findDSOInfoForAddr(data._slot, &info);
453 safeAssert(headerFound, "Failed to find image header.");
455 scanSegments(info, pdso);
459 auto handle = handleForAddr(data._slot);
461 getDependencies(info, pdso._deps);
462 pdso._handle = handle;
463 setDSOForHandle(pdso, pdso._handle);
467 /* This DSO was not loaded by rt_loadLibrary which
468 * happens for all dependencies of an executable or
469 * the first dlopen call from a C program.
470 * In this case we add the DSO to the _loadedDSOs of this
471 * thread with a refCnt of 1 and call the TlsCtors.
473 immutable ushort refCnt = 1, addCnt = 0;
474 _loadedDSOs.insertBack(ThreadDSO(pdso, refCnt, addCnt, pdso.tlsRange()));
479 foreach (p; _loadedDSOs)
480 safeAssert(p !is pdso, "DSO already registered.");
481 _loadedDSOs.insertBack(pdso);
482 _tlsRanges.insertBack(pdso.tlsRange());
485 // don't initialize modules before rt_init was called (see Bugzilla 11378)
486 if (_isRuntimeInitialized)
488 registerGCRanges(pdso);
489 // rt_loadLibrary will run tls ctors, so do this only for dlopen
490 immutable runTlsCtors = !_rtLoading;
491 runModuleConstructors(pdso, runTlsCtors);
494 // has backlink => unregister
497 DSO* pdso = cast(DSO*)*data._slot;
500 // don't finalizes modules after rt_term was called (see Bugzilla 11378)
501 if (_isRuntimeInitialized)
503 // rt_unloadLibrary already ran tls dtors, so do this only for dlclose
504 immutable runTlsDtors = !_rtLoading;
505 runModuleDestructors(pdso, runTlsDtors);
506 unregisterGCRanges(pdso);
507 // run finalizers after module dtors (same order as in rt_term)
508 version (Shared) runFinalizers(pdso);
515 /* This DSO was not unloaded by rt_unloadLibrary so we
516 * have to remove it from _loadedDSOs here.
518 foreach (i, ref tdso; _loadedDSOs)
520 if (tdso._pdso == pdso)
522 _loadedDSOs.remove(i);
528 unsetDSOForHandle(pdso, pdso._handle);
532 // static DSOs are unloaded in reverse order
533 safeAssert(pdso == _loadedDSOs.back, "DSO being unregistered isn't current last one.");
534 _loadedDSOs.popBack();
539 // last DSO being unloaded => shutdown registry
540 if (_loadedDSOs.empty)
544 safeAssert(_handleToDSO.empty, "_handleToDSO not in sync with _loadedDSOs.");
545 _handleToDSO.reset();
557 ///////////////////////////////////////////////////////////////////////////////
559 ///////////////////////////////////////////////////////////////////////////////
561 // Shared D libraries are only supported when linking against a shared druntime library.
565 ThreadDSO* findThreadDSO(DSO* pdso) nothrow @nogc
567 foreach (ref tdata; _loadedDSOs)
568 if (tdata._pdso == pdso) return &tdata;
572 void incThreadRef(DSO* pdso, bool incAdd)
574 if (auto tdata = findThreadDSO(pdso)) // already initialized
576 if (incAdd && ++tdata._addCnt > 1) return;
581 foreach (dep; pdso._deps)
582 incThreadRef(dep, false);
583 immutable ushort refCnt = 1, addCnt = incAdd ? 1 : 0;
584 _loadedDSOs.insertBack(ThreadDSO(pdso, refCnt, addCnt, pdso.tlsRange()));
585 pdso._moduleGroup.runTlsCtors();
589 void decThreadRef(DSO* pdso, bool decAdd)
591 auto tdata = findThreadDSO(pdso);
592 safeAssert(tdata !is null, "Failed to find thread DSO.");
593 safeAssert(!decAdd || tdata._addCnt > 0, "Mismatching rt_unloadLibrary call.");
595 if (decAdd && --tdata._addCnt > 0) return;
596 if (--tdata._refCnt > 0) return;
598 pdso._moduleGroup.runTlsDtors();
599 foreach (i, ref td; _loadedDSOs)
600 if (td._pdso == pdso) _loadedDSOs.remove(i);
601 foreach (dep; pdso._deps)
602 decThreadRef(dep, false);
605 extern(C) void* rt_loadLibrary(const char* name)
607 immutable save = _rtLoading;
609 scope (exit) _rtLoading = save;
611 auto handle = .dlopen(name, RTLD_LAZY);
612 if (handle is null) return null;
614 // if it's a D library
615 if (auto pdso = dsoForHandle(handle))
616 incThreadRef(pdso, true);
620 extern(C) int rt_unloadLibrary(void* handle)
622 if (handle is null) return false;
624 immutable save = _rtLoading;
626 scope (exit) _rtLoading = save;
628 // if it's a D library
629 if (auto pdso = dsoForHandle(handle))
630 decThreadRef(pdso, true);
631 return .dlclose(handle) == 0;
635 ///////////////////////////////////////////////////////////////////////////////
637 ///////////////////////////////////////////////////////////////////////////////
639 void initLocks() nothrow @nogc
642 !pthread_mutex_init(&_handleToDSOMutex, null) || assert(0);
645 void finiLocks() nothrow @nogc
648 !pthread_mutex_destroy(&_handleToDSOMutex) || assert(0);
651 void runModuleConstructors(DSO* pdso, bool runTlsCtors)
653 pdso._moduleGroup.sortCtors();
654 pdso._moduleGroup.runCtors();
655 if (runTlsCtors) pdso._moduleGroup.runTlsCtors();
658 void runModuleDestructors(DSO* pdso, bool runTlsDtors)
660 if (runTlsDtors) pdso._moduleGroup.runTlsDtors();
661 pdso._moduleGroup.runDtors();
664 void registerGCRanges(DSO* pdso) nothrow @nogc
666 foreach (rng; pdso._gcRanges)
667 GC.addRange(rng.ptr, rng.length);
670 void unregisterGCRanges(DSO* pdso) nothrow @nogc
672 foreach (rng; pdso._gcRanges)
673 GC.removeRange(rng.ptr);
676 version (Shared) void runFinalizers(DSO* pdso)
678 foreach (seg; pdso._codeSegments)
679 GC.runFinalizers(seg);
682 void freeDSO(DSO* pdso) nothrow @nogc
684 pdso._gcRanges.reset();
687 pdso._codeSegments.reset();
697 link_map* linkMapForHandle(void* handle)
700 const success = dlinfo(handle, RTLD_DI_LINKMAP, &map) == 0;
701 safeAssert(success, "Failed to get DSO info.");
705 link_map* exeLinkMap(link_map* map)
707 safeAssert(map !is null, "Invalid link_map.");
708 while (map.l_prev !is null)
713 DSO* dsoForHandle(void* handle)
716 !pthread_mutex_lock(&_handleToDSOMutex) || assert(0);
717 if (auto ppdso = handle in _handleToDSO)
719 !pthread_mutex_unlock(&_handleToDSOMutex) || assert(0);
723 void setDSOForHandle(DSO* pdso, void* handle)
725 !pthread_mutex_lock(&_handleToDSOMutex) || assert(0);
726 safeAssert(handle !in _handleToDSO, "DSO already registered.");
727 _handleToDSO[handle] = pdso;
728 !pthread_mutex_unlock(&_handleToDSOMutex) || assert(0);
731 void unsetDSOForHandle(DSO* pdso, void* handle)
733 !pthread_mutex_lock(&_handleToDSOMutex) || assert(0);
734 safeAssert(_handleToDSO[handle] == pdso, "Handle doesn't match registered DSO.");
735 _handleToDSO.remove(handle);
736 !pthread_mutex_unlock(&_handleToDSOMutex) || assert(0);
739 void getDependencies(in ref dl_phdr_info info, ref Array!(DSO*) deps)
741 // get the entries of the .dynamic section
743 foreach (ref phdr; info.dlpi_phdr[0 .. info.dlpi_phnum])
745 if (phdr.p_type == PT_DYNAMIC)
747 auto p = cast(ElfW!"Dyn"*)(info.dlpi_addr + (phdr.p_vaddr & ~(size_t.sizeof - 1)));
748 dyns = p[0 .. phdr.p_memsz / ElfW!"Dyn".sizeof];
752 // find the string table which contains the sonames
756 if (dyn.d_tag == DT_STRTAB)
758 version (CRuntime_Musl)
759 strtab = cast(const(char)*)(info.dlpi_addr + dyn.d_un.d_ptr); // relocate
762 // This might change in future glibc releases (after 2.29) as dynamic sections
763 // are not required to be read-only on RISC-V. This was copy & pasted from MIPS
764 // while upstreaming RISC-V support. Otherwise MIPS is the only arch which sets
765 // in glibc: #define DL_RO_DYN_SECTION 1
767 strtab = cast(const(char)*)(info.dlpi_addr + dyn.d_un.d_ptr); // relocate
768 else version (MIPS_Any)
769 strtab = cast(const(char)*)(info.dlpi_addr + dyn.d_un.d_ptr); // relocate
771 strtab = cast(const(char)*)dyn.d_un.d_ptr;
773 else version (FreeBSD)
774 strtab = cast(const(char)*)(info.dlpi_addr + dyn.d_un.d_ptr); // relocate
775 else version (NetBSD)
776 strtab = cast(const(char)*)(info.dlpi_addr + dyn.d_un.d_ptr); // relocate
777 else version (DragonFlyBSD)
778 strtab = cast(const(char)*)(info.dlpi_addr + dyn.d_un.d_ptr); // relocate
779 else version (Solaris)
780 strtab = cast(const(char)*)(info.dlpi_addr + dyn.d_un.d_ptr); // relocate
782 static assert(0, "unimplemented");
788 immutable tag = dyn.d_tag;
789 if (!(tag == DT_NEEDED || tag == DT_AUXILIARY || tag == DT_FILTER))
792 // soname of the dependency
793 auto name = strtab + dyn.d_un.d_val;
794 // get handle without loading the library
795 auto handle = handleForName(name);
796 // the runtime linker has already loaded all dependencies
797 safeAssert(handle !is null, "Failed to get library handle.");
798 // if it's a D library
799 if (auto pdso = dsoForHandle(handle))
800 deps.insertBack(pdso); // append it to the dependencies
804 void* handleForName(const char* name)
806 auto handle = .dlopen(name, RTLD_NOLOAD | RTLD_LAZY);
807 version (Solaris) { }
808 else if (handle !is null) .dlclose(handle); // drop reference count
813 ///////////////////////////////////////////////////////////////////////////////
814 // Elf program header iteration
815 ///////////////////////////////////////////////////////////////////////////////
818 * Scan segments in Linux dl_phdr_info struct and store
819 * the TLS and writeable data segments in *pdso.
821 void scanSegments(in ref dl_phdr_info info, DSO* pdso) nothrow @nogc
823 foreach (ref phdr; info.dlpi_phdr[0 .. info.dlpi_phnum])
828 if (phdr.p_flags & PF_W) // writeable data segment
830 auto beg = cast(void*)(info.dlpi_addr + (phdr.p_vaddr & ~(size_t.sizeof - 1)));
831 pdso._gcRanges.insertBack(beg[0 .. phdr.p_memsz]);
833 version (Shared) if (phdr.p_flags & PF_X) // code segment
835 auto beg = cast(void*)(info.dlpi_addr + (phdr.p_vaddr & ~(size_t.sizeof - 1)));
836 pdso._codeSegments.insertBack(beg[0 .. phdr.p_memsz]);
840 case PT_TLS: // TLS segment
846 safeAssert(!pdso._tlsSize, "Multiple TLS segments in image header.");
847 static if (OS_Have_Dlpi_Tls_Modid)
849 pdso._tlsMod = info.dlpi_tls_modid;
850 pdso._tlsSize = phdr.p_memsz;
852 else version (Solaris)
857 const char* rt_pathname;
868 dlinfo(handleForName(info.dlpi_name), RTLD_DI_LINKMAP, &map);
870 dlinfo(RTLD_SELF, RTLD_DI_LINKMAP, &map);
871 // Until Solaris 11.4, tlsmodid for the executable is 0.
872 // Let it start at 1 as the rest of the code expects.
873 pdso._tlsMod = map.rt_tlsmodid + 1;
874 pdso._tlsSize = phdr.p_memsz;
890 /**************************
892 * result where the output is to be written; dl_phdr_info is an OS struct
894 * true if found, and *result is filled in
896 * http://linux.die.net/man/3/dl_iterate_phdr
898 bool findDSOInfoForAddr(in void* addr, dl_phdr_info* result=null) nothrow @nogc
900 version (linux) enum IterateManually = true;
901 else version (NetBSD) enum IterateManually = true;
902 else version (Solaris) enum IterateManually = true;
903 else enum IterateManually = false;
905 static if (IterateManually)
907 static struct DG { const(void)* addr; dl_phdr_info* result; }
909 extern(C) int callback(dl_phdr_info* info, size_t sz, void* arg) nothrow @nogc
911 auto p = cast(DG*)arg;
912 if (findSegmentForAddr(*info, p.addr))
914 if (p.result !is null) *p.result = *info;
917 return 0; // continue iteration
920 auto dg = DG(addr, result);
922 /* OS function that walks through the list of an application's shared objects and
923 * calls 'callback' once for each object, until either all shared objects
924 * have been processed or 'callback' returns a nonzero value.
926 return dl_iterate_phdr(&callback, &dg) != 0;
928 else version (FreeBSD)
930 return !!_rtld_addr_phdr(addr, result);
932 else version (DragonFlyBSD)
934 return !!_rtld_addr_phdr(addr, result);
937 static assert(0, "unimplemented");
940 /*********************************
941 * Determine if 'addr' lies within shared object 'info'.
942 * If so, return true and fill in 'result' with the corresponding ELF program header.
944 bool findSegmentForAddr(in ref dl_phdr_info info, in void* addr, ElfW!"Phdr"* result=null) nothrow @nogc
946 if (addr < cast(void*)info.dlpi_addr) // less than base address of object means quick reject
949 foreach (ref phdr; info.dlpi_phdr[0 .. info.dlpi_phnum])
951 auto beg = cast(void*)(info.dlpi_addr + phdr.p_vaddr);
952 if (cast(size_t)(addr - beg) < phdr.p_memsz)
954 if (result !is null) *result = phdr;
961 version (linux) import core.sys.linux.errno : program_invocation_name;
962 // should be in core.sys.freebsd.stdlib
963 version (FreeBSD) extern(C) const(char)* getprogname() nothrow @nogc;
964 version (DragonFlyBSD) extern(C) const(char)* getprogname() nothrow @nogc;
965 version (NetBSD) extern(C) const(char)* getprogname() nothrow @nogc;
966 version (Solaris) extern(C) const(char)* getprogname() nothrow @nogc;
968 @property const(char)* progname() nothrow @nogc
970 version (linux) return program_invocation_name;
971 version (FreeBSD) return getprogname();
972 version (DragonFlyBSD) return getprogname();
973 version (NetBSD) return getprogname();
974 version (Solaris) return getprogname();
977 const(char)[] dsoName(const char* dlpi_name) nothrow @nogc
979 // the main executable doesn't have a name in its dlpi_name field
980 const char* p = dlpi_name[0] != 0 ? dlpi_name : progname;
981 return p[0 .. strlen(p)];
984 /**************************
986 * addr an internal address of a DSO
988 * the dlopen handle for that DSO or null if addr is not within a loaded DSO
990 version (Shared) void* handleForAddr(void* addr) nothrow @nogc
993 if (dladdr(addr, &info) != 0)
994 return handleForName(info.dli_fname);
998 ///////////////////////////////////////////////////////////////////////////////
1000 ///////////////////////////////////////////////////////////////////////////////
1004 * Returns: the TLS memory range for a given module and the calling
1005 * thread or null if that module has no TLS.
1007 * Note: This will cause the TLS memory to be eagerly allocated.
1011 version (CRuntime_Glibc)
1013 // For x86_64, fields are of type uint64_t, this is important for x32
1014 // where tls_index would otherwise have the wrong size.
1015 // See https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/x86_64/dl-tls.h
1034 extern(C) void* __tls_get_addr(tls_index* ti) nothrow @nogc;
1035 extern(C) void* __ibmz_get_tls_offset(tls_index *ti) nothrow @nogc;
1037 /* The dynamic thread vector (DTV) pointers may point 0x8000 past the start of
1038 * each TLS block. This is at least true for PowerPC and Mips platforms.
1039 * See: https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/powerpc/dl-tls.h;h=f7cf6f96ebfb505abfd2f02be0ad0e833107c0cd;hb=HEAD#l34
1040 * https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/mips/dl-tls.h;h=93a6dc050cb144b9f68b96fb3199c60f5b1fcd18;hb=HEAD#l32
1041 * https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/riscv/dl-tls.h;h=ab2d860314de94c18812bc894ff6b3f55368f20f;hb=HEAD#l32
1044 enum TLS_DTV_OFFSET = 0x0;
1045 else version (X86_64)
1046 enum TLS_DTV_OFFSET = 0x0;
1048 enum TLS_DTV_OFFSET = 0x0;
1049 else version (AArch64)
1050 enum TLS_DTV_OFFSET = 0x0;
1051 else version (RISCV32)
1052 enum TLS_DTV_OFFSET = 0x800;
1053 else version (RISCV64)
1054 enum TLS_DTV_OFFSET = 0x800;
1056 enum TLS_DTV_OFFSET = 0x0;
1057 else version (SPARC)
1058 enum TLS_DTV_OFFSET = 0x0;
1059 else version (SPARC64)
1060 enum TLS_DTV_OFFSET = 0x0;
1062 enum TLS_DTV_OFFSET = 0x8000;
1063 else version (PPC64)
1064 enum TLS_DTV_OFFSET = 0x8000;
1065 else version (MIPS32)
1066 enum TLS_DTV_OFFSET = 0x8000;
1067 else version (MIPS64)
1068 enum TLS_DTV_OFFSET = 0x8000;
1069 else version (IBMZ_Any)
1070 enum TLS_DTV_OFFSET = 0x0;
1072 static assert( false, "Platform not supported." );
1074 void[] getTLSRange(size_t mod, size_t sz) nothrow @nogc
1079 version (GNU_EMUTLS)
1080 return null; // Handled in scanTLSRanges().
1085 static if (!OS_Have_Dlpi_Tls_Modid)
1090 auto ti = tls_index(mod, 0);
1091 version (CRuntime_Musl)
1092 return (__tls_get_addr(&ti)-TLS_DTV_OFFSET)[0 .. sz];
1093 else version (IBMZ_Any)
1095 // IBM Z only provides __tls_get_offset instead of __tls_get_addr
1096 // which returns an offset relative to the thread pointer.
1097 auto addr = __ibmz_get_tls_offset(&ti);
1098 addr = addr + cast(c_ulong)__builtin_thread_pointer();
1099 return addr[0 .. sz];
1102 return (__tls_get_addr(&ti)-TLS_DTV_OFFSET)[0 .. sz];