Debian Codegraph @

libphobos/libdruntime/gcc/sections/elf.d

raw
1 // ELF-specific support for sections with shared libraries.
2 // Copyright (C) 2019-2025 Free Software Foundation, Inc.
3
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
7 // version.
8
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
12 // for more details.
13
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.
17
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/>.
22
23 module gcc.sections.elf;
24
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;
31
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 (OpenBSD) enum SharedELF = true;
37 else version (DragonFlyBSD) enum SharedELF = true;
38 else version (CRuntime_UClibc) enum SharedELF = true;
39 else version (Solaris) enum SharedELF = true;
40 else enum SharedELF = false;
41 static if (SharedELF):
42
43 import core.memory;
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;
48 version (linux)
49 {
50 import core.sys.linux.dlfcn;
51 import core.sys.linux.elf;
52 import core.sys.linux.link;
53 }
54 else version (FreeBSD)
55 {
56 import core.sys.freebsd.dlfcn;
57 import core.sys.freebsd.sys.elf;
58 import core.sys.freebsd.sys.link_elf;
59 }
60 else version (NetBSD)
61 {
62 import core.sys.netbsd.dlfcn;
63 import core.sys.netbsd.sys.elf;
64 import core.sys.netbsd.sys.link_elf;
65 }
66 else version (OpenBSD)
67 {
68 import core.sys.openbsd.dlfcn;
69 import core.sys.openbsd.sys.elf;
70 import core.sys.openbsd.sys.link_elf;
71 }
72 else version (DragonFlyBSD)
73 {
74 import core.sys.dragonflybsd.dlfcn;
75 import core.sys.dragonflybsd.sys.elf;
76 import core.sys.dragonflybsd.sys.link_elf;
77 }
78 else version (Solaris)
79 {
80 import core.sys.solaris.dlfcn;
81 import core.sys.solaris.link;
82 import core.sys.solaris.sys.elf;
83 import core.sys.solaris.sys.link;
84 }
85 else
86 {
87 static assert(0, "unimplemented");
88 }
89 import core.sys.posix.pthread;
90 import rt.deh;
91 import rt.dmain2;
92 import rt.minfo;
93 import core.internal.container.array;
94 import core.internal.container.hashtab;
95 import gcc.builtins;
96 import gcc.config;
97 import gcc.sections.common;
98
99 alias DSO SectionGroup;
100 struct DSO
101 {
102 static int opApply(scope int delegate(ref DSO) dg)
103 {
104 foreach (dso; _loadedDSOs)
105 {
106 if (auto res = dg(*dso))
107 return res;
108 }
109 return 0;
110 }
111
112 static int opApplyReverse(scope int delegate(ref DSO) dg)
113 {
114 foreach_reverse (dso; _loadedDSOs)
115 {
116 if (auto res = dg(*dso))
117 return res;
118 }
119 return 0;
120 }
121
122 @property immutable(ModuleInfo*)[] modules() const nothrow @nogc
123 {
124 return _moduleGroup.modules;
125 }
126
127 @property ref inout(ModuleGroup) moduleGroup() inout return nothrow @nogc
128 {
129 return _moduleGroup;
130 }
131
132 @property inout(void[])[] gcRanges() inout nothrow @nogc
133 {
134 return _gcRanges[];
135 }
136
137 private:
138
139 invariant()
140 {
141 safeAssert(_moduleGroup.modules.length > 0, "No modules for DSO.");
142 safeAssert(_tlsMod || !_tlsSize, "Inconsistent TLS fields for DSO.");
143 }
144
145 ModuleGroup _moduleGroup;
146 Array!(void[]) _gcRanges;
147 size_t _tlsMod;
148 size_t _tlsSize;
149
150 version (Shared)
151 {
152 Array!(void[]) _codeSegments; // array of code segments
153 Array!(DSO*) _deps; // D libraries needed by this DSO
154 void* _handle; // corresponding handle
155 }
156
157 // get the TLS range for the executing thread
158 void[] tlsRange() const nothrow @nogc
159 {
160 return getTLSRange(_tlsMod, _tlsSize);
161 }
162 }
163
164 /****
165 * Gets called on program startup just before GC is initialized.
166 */
167 void initSections() nothrow @nogc
168 {
169 }
170
171
172 /***
173 * Gets called on program shutdown just after GC is terminated.
174 */
175 void finiSections() nothrow @nogc
176 {
177 }
178
179 alias ScanDG = void delegate(void* pbeg, void* pend) nothrow;
180
181 version (Shared)
182 {
183 import gcc.sections : pinLoadedLibraries, unpinLoadedLibraries,
184 inheritLoadedLibraries, cleanupLoadedLibraries, sizeOfTLS;
185
186 /***
187 * Called once per thread; returns array of thread local storage ranges
188 */
189 Array!(ThreadDSO)* initTLSRanges() @nogc nothrow
190 {
191 return &_loadedDSOs();
192 }
193
194 void finiTLSRanges(Array!(ThreadDSO)* tdsos) @nogc nothrow
195 {
196 // Nothing to do here. tdsos used to point to the _loadedDSOs instance
197 // in the dying thread's TLS segment and as such is not valid anymore.
198 // The memory for the array contents was already reclaimed in
199 // cleanupLoadedLibraries().
200 }
201
202 void scanTLSRanges(Array!(ThreadDSO)* tdsos, scope ScanDG dg) nothrow
203 {
204 version (GNU_EMUTLS)
205 {
206 import gcc.emutls;
207 _d_emutls_scan(dg);
208 }
209 else
210 {
211 foreach (ref tdso; *tdsos)
212 dg(tdso._tlsRange.ptr, tdso._tlsRange.ptr + tdso._tlsRange.length);
213 }
214 }
215
216 pragma(mangle, gcc.sections.sizeOfTLS.mangleof)
217 size_t sizeOfTLS() nothrow @nogc
218 {
219 auto tdsos = initTLSRanges();
220 size_t sum;
221 foreach (ref tdso; *tdsos)
222 sum += tdso._tlsRange.length;
223 return sum;
224 }
225
226 // interface for core.thread to inherit loaded libraries
227 pragma(mangle, gcc.sections.pinLoadedLibraries.mangleof)
228 void* pinLoadedLibraries() nothrow @nogc
229 {
230 auto res = cast(Array!(ThreadDSO)*)calloc(1, Array!(ThreadDSO).sizeof);
231 res.length = _loadedDSOs.length;
232 foreach (i, ref tdso; _loadedDSOs)
233 {
234 (*res)[i] = tdso;
235 if (tdso._addCnt)
236 {
237 // Increment the dlopen ref for explicitly loaded libraries to pin them.
238 const success = .dlopen(linkMapForHandle(tdso._pdso._handle).l_name, RTLD_LAZY) !is null;
239 safeAssert(success, "Failed to increment dlopen ref.");
240 (*res)[i]._addCnt = 1; // new array takes over the additional ref count
241 }
242 }
243 return res;
244 }
245
246 pragma(mangle, gcc.sections.unpinLoadedLibraries.mangleof)
247 void unpinLoadedLibraries(void* p) nothrow @nogc
248 {
249 auto pary = cast(Array!(ThreadDSO)*)p;
250 // In case something failed we need to undo the pinning.
251 foreach (ref tdso; *pary)
252 {
253 if (tdso._addCnt)
254 {
255 auto handle = tdso._pdso._handle;
256 safeAssert(handle !is null, "Invalid library handle.");
257 .dlclose(handle);
258 }
259 }
260 pary.reset();
261 .free(pary);
262 }
263
264 // Called before TLS ctors are ran, copy over the loaded libraries
265 // of the parent thread.
266 pragma(mangle, gcc.sections.inheritLoadedLibraries.mangleof)
267 void inheritLoadedLibraries(void* p) nothrow @nogc
268 {
269 safeAssert(_loadedDSOs.empty, "DSOs have already been registered for this thread.");
270 _loadedDSOs.swap(*cast(Array!(ThreadDSO)*)p);
271 .free(p);
272 foreach (ref dso; _loadedDSOs)
273 {
274 // the copied _tlsRange corresponds to parent thread
275 dso.updateTLSRange();
276 }
277 }
278
279 // Called after all TLS dtors ran, decrements all remaining dlopen refs.
280 pragma(mangle, gcc.sections.cleanupLoadedLibraries.mangleof)
281 void cleanupLoadedLibraries() nothrow @nogc
282 {
283 foreach (ref tdso; _loadedDSOs)
284 {
285 if (tdso._addCnt == 0) continue;
286
287 auto handle = tdso._pdso._handle;
288 safeAssert(handle !is null, "Invalid DSO handle.");
289 for (; tdso._addCnt > 0; --tdso._addCnt)
290 .dlclose(handle);
291 }
292
293 // Free the memory for the array contents.
294 _loadedDSOs.reset();
295 }
296 }
297 else
298 {
299 import gcc.sections : sizeOfTLS;
300
301 /***
302 * Called once per thread; returns array of thread local storage ranges
303 */
304 Array!(void[])* initTLSRanges() nothrow @nogc
305 {
306 auto rngs = &_tlsRanges();
307 if (rngs.empty)
308 {
309 foreach (ref pdso; _loadedDSOs)
310 rngs.insertBack(pdso.tlsRange());
311 }
312 return rngs;
313 }
314
315 void finiTLSRanges(Array!(void[])* rngs) nothrow @nogc
316 {
317 rngs.reset();
318 }
319
320 void scanTLSRanges(Array!(void[])* rngs, scope ScanDG dg) nothrow
321 {
322 version (GNU_EMUTLS)
323 {
324 import gcc.emutls;
325 _d_emutls_scan(dg);
326 }
327 else
328 {
329 foreach (rng; *rngs)
330 dg(rng.ptr, rng.ptr + rng.length);
331 }
332 }
333
334 pragma(mangle, gcc.sections.sizeOfTLS.mangleof)
335 size_t sizeOfTLS() nothrow @nogc
336 {
337 auto rngs = initTLSRanges();
338 size_t sum;
339 foreach (rng; *rngs)
340 sum += rng.length;
341 return sum;
342 }
343 }
344
345 private:
346
347 version (Shared)
348 {
349 /*
350 * Array of thread local DSO metadata for all libraries loaded and
351 * initialized in this thread.
352 *
353 * Note:
354 * A newly spawned thread will inherit these libraries.
355 * Note:
356 * We use an array here to preserve the order of
357 * initialization. If that became a performance issue, we
358 * could use a hash table and enumerate the DSOs during
359 * loading so that the hash table values could be sorted when
360 * necessary.
361 */
362 struct ThreadDSO
363 {
364 DSO* _pdso;
365 static if (_pdso.sizeof == 8) uint _refCnt, _addCnt;
366 else static if (_pdso.sizeof == 4) ushort _refCnt, _addCnt;
367 else static assert(0, "unimplemented");
368 void[] _tlsRange;
369 alias _pdso this;
370 // update the _tlsRange for the executing thread
371 void updateTLSRange() nothrow @nogc
372 {
373 _tlsRange = _pdso.tlsRange();
374 }
375 }
376 @property ref Array!(ThreadDSO) _loadedDSOs() @nogc nothrow { static Array!(ThreadDSO) x; return x; }
377
378 /*
379 * Set to true during rt_loadLibrary/rt_unloadLibrary calls.
380 */
381 bool _rtLoading;
382
383 /*
384 * Hash table to map link_map* to corresponding DSO*.
385 * The hash table is protected by a Mutex.
386 */
387 __gshared pthread_mutex_t _handleToDSOMutex;
388 @property ref HashTab!(void*, DSO*) _handleToDSO() @nogc nothrow { __gshared HashTab!(void*, DSO*) x; return x; }
389 }
390 else
391 {
392 /*
393 * Static DSOs loaded by the runtime linker. This includes the
394 * executable. These can't be unloaded.
395 */
396 @property ref Array!(DSO*) _loadedDSOs() @nogc nothrow { __gshared Array!(DSO*) x; return x; }
397
398 /*
399 * Thread local array that contains TLS memory ranges for each
400 * library initialized in this thread.
401 */
402 @property ref Array!(void[]) _tlsRanges() @nogc nothrow { static Array!(void[]) x; return x; }
403
404 enum _rtLoading = false;
405 }
406
407 ///////////////////////////////////////////////////////////////////////////////
408 // Compiler to runtime interface.
409 ///////////////////////////////////////////////////////////////////////////////
410
411 /*
412 * This data structure is generated by the compiler, and then passed to
413 * _d_dso_registry().
414 */
415 struct CompilerDSOData
416 {
417 size_t _version; // currently 1
418 void** _slot; // can be used to store runtime data
419 immutable(object.ModuleInfo*)* _minfo_beg, _minfo_end; // array of modules in this object file
420 }
421
422 T[] toRange(T)(T* beg, T* end) { return beg[0 .. end - beg]; }
423
424 /* For each shared library and executable, the compiler generates code that
425 * sets up CompilerDSOData and calls _d_dso_registry().
426 * A pointer to that code is inserted into both the .ctors and .dtors
427 * segment so it gets called by the loader on startup and shutdown.
428 */
429 extern(C) void _d_dso_registry(CompilerDSOData* data)
430 {
431 // only one supported currently
432 safeAssert(data._version >= 1, "Incompatible compiler-generated DSO data version.");
433
434 // no backlink => register
435 if (*data._slot is null)
436 {
437 immutable firstDSO = _loadedDSOs.empty;
438 if (firstDSO) initLocks();
439
440 DSO* pdso = cast(DSO*).calloc(1, DSO.sizeof);
441 assert(typeid(DSO).initializer().ptr is null);
442 *data._slot = pdso; // store backlink in library record
443
444 pdso._moduleGroup = ModuleGroup(toRange(data._minfo_beg, data._minfo_end));
445
446 dl_phdr_info info = void;
447 const headerFound = findDSOInfoForAddr(data._slot, &info);
448 safeAssert(headerFound, "Failed to find image header.");
449
450 scanSegments(info, pdso);
451
452 version (Shared)
453 {
454 auto handle = handleForAddr(data._slot);
455
456 getDependencies(info, pdso._deps);
457 pdso._handle = handle;
458 setDSOForHandle(pdso, pdso._handle);
459
460 if (!_rtLoading)
461 {
462 /* This DSO was not loaded by rt_loadLibrary which
463 * happens for all dependencies of an executable or
464 * the first dlopen call from a C program.
465 * In this case we add the DSO to the _loadedDSOs of this
466 * thread with a refCnt of 1 and call the TlsCtors.
467 */
468 immutable ushort refCnt = 1, addCnt = 0;
469 _loadedDSOs.insertBack(ThreadDSO(pdso, refCnt, addCnt, pdso.tlsRange()));
470 }
471 }
472 else
473 {
474 foreach (p; _loadedDSOs)
475 safeAssert(p !is pdso, "DSO already registered.");
476 _loadedDSOs.insertBack(pdso);
477 _tlsRanges.insertBack(pdso.tlsRange());
478 }
479
480 // don't initialize modules before rt_init was called (see Bugzilla 11378)
481 if (isRuntimeInitialized())
482 {
483 registerGCRanges(pdso);
484 // rt_loadLibrary will run tls ctors, so do this only for dlopen
485 immutable runTlsCtors = !_rtLoading;
486 runModuleConstructors(pdso, runTlsCtors);
487 }
488 }
489 // has backlink => unregister
490 else
491 {
492 DSO* pdso = cast(DSO*)*data._slot;
493 *data._slot = null;
494
495 // don't finalizes modules after rt_term was called (see Bugzilla 11378)
496 if (isRuntimeInitialized())
497 {
498 // rt_unloadLibrary already ran tls dtors, so do this only for dlclose
499 immutable runTlsDtors = !_rtLoading;
500 runModuleDestructors(pdso, runTlsDtors);
501 unregisterGCRanges(pdso);
502 // run finalizers after module dtors (same order as in rt_term)
503 version (Shared) runFinalizers(pdso);
504 }
505
506 version (Shared)
507 {
508 if (!_rtLoading)
509 {
510 /* This DSO was not unloaded by rt_unloadLibrary so we
511 * have to remove it from _loadedDSOs here.
512 */
513 foreach (i, ref tdso; _loadedDSOs)
514 {
515 if (tdso._pdso == pdso)
516 {
517 _loadedDSOs.remove(i);
518 break;
519 }
520 }
521 }
522
523 unsetDSOForHandle(pdso, pdso._handle);
524 }
525 else
526 {
527 // static DSOs are unloaded in reverse order
528 safeAssert(pdso == _loadedDSOs.back, "DSO being unregistered isn't current last one.");
529 _loadedDSOs.popBack();
530 }
531
532 freeDSO(pdso);
533
534 // last DSO being unloaded => shutdown registry
535 if (_loadedDSOs.empty)
536 {
537 version (Shared)
538 {
539 safeAssert(_handleToDSO.empty, "_handleToDSO not in sync with _loadedDSOs.");
540 _handleToDSO.reset();
541 }
542 finiLocks();
543 version (GNU_EMUTLS)
544 {
545 import gcc.emutls;
546 _d_emutls_destroy();
547 }
548 }
549 }
550 }
551
552 ///////////////////////////////////////////////////////////////////////////////
553 // Dynamic loading
554 ///////////////////////////////////////////////////////////////////////////////
555
556 // Shared D libraries are only supported when linking against a shared druntime library.
557
558 version (Shared)
559 {
560 ThreadDSO* findThreadDSO(DSO* pdso) nothrow @nogc
561 {
562 foreach (ref tdata; _loadedDSOs)
563 if (tdata._pdso == pdso) return &tdata;
564 return null;
565 }
566
567 void incThreadRef(DSO* pdso, bool incAdd)
568 {
569 if (auto tdata = findThreadDSO(pdso)) // already initialized
570 {
571 if (incAdd && ++tdata._addCnt > 1) return;
572 ++tdata._refCnt;
573 }
574 else
575 {
576 foreach (dep; pdso._deps)
577 incThreadRef(dep, false);
578 immutable ushort refCnt = 1, addCnt = incAdd ? 1 : 0;
579 _loadedDSOs.insertBack(ThreadDSO(pdso, refCnt, addCnt, pdso.tlsRange()));
580 pdso._moduleGroup.runTlsCtors();
581 }
582 }
583
584 void decThreadRef(DSO* pdso, bool decAdd)
585 {
586 auto tdata = findThreadDSO(pdso);
587 safeAssert(tdata !is null, "Failed to find thread DSO.");
588 safeAssert(!decAdd || tdata._addCnt > 0, "Mismatching rt_unloadLibrary call.");
589
590 if (decAdd && --tdata._addCnt > 0) return;
591 if (--tdata._refCnt > 0) return;
592
593 pdso._moduleGroup.runTlsDtors();
594 foreach (i, ref td; _loadedDSOs)
595 if (td._pdso == pdso) _loadedDSOs.remove(i);
596 foreach (dep; pdso._deps)
597 decThreadRef(dep, false);
598 }
599
600 extern(C) void* rt_loadLibrary(const char* name)
601 {
602 immutable save = _rtLoading;
603 _rtLoading = true;
604 scope (exit) _rtLoading = save;
605
606 auto handle = .dlopen(name, RTLD_LAZY);
607 if (handle is null) return null;
608
609 // if it's a D library
610 if (auto pdso = dsoForHandle(handle))
611 incThreadRef(pdso, true);
612 return handle;
613 }
614
615 extern(C) int rt_unloadLibrary(void* handle)
616 {
617 if (handle is null) return false;
618
619 immutable save = _rtLoading;
620 _rtLoading = true;
621 scope (exit) _rtLoading = save;
622
623 // if it's a D library
624 if (auto pdso = dsoForHandle(handle))
625 decThreadRef(pdso, true);
626 return .dlclose(handle) == 0;
627 }
628 }
629
630 ///////////////////////////////////////////////////////////////////////////////
631 // Helper functions
632 ///////////////////////////////////////////////////////////////////////////////
633
634 void initLocks() nothrow @nogc
635 {
636 version (Shared)
637 !pthread_mutex_init(&_handleToDSOMutex, null) || assert(0);
638 }
639
640 void finiLocks() nothrow @nogc
641 {
642 version (Shared)
643 !pthread_mutex_destroy(&_handleToDSOMutex) || assert(0);
644 }
645
646 void runModuleConstructors(DSO* pdso, bool runTlsCtors)
647 {
648 pdso._moduleGroup.sortCtors();
649 pdso._moduleGroup.runCtors();
650 if (runTlsCtors) pdso._moduleGroup.runTlsCtors();
651 }
652
653 void runModuleDestructors(DSO* pdso, bool runTlsDtors)
654 {
655 if (runTlsDtors) pdso._moduleGroup.runTlsDtors();
656 pdso._moduleGroup.runDtors();
657 }
658
659 void registerGCRanges(DSO* pdso) nothrow @nogc
660 {
661 foreach (rng; pdso._gcRanges)
662 GC.addRange(rng.ptr, rng.length);
663 }
664
665 void unregisterGCRanges(DSO* pdso) nothrow @nogc
666 {
667 foreach (rng; pdso._gcRanges)
668 GC.removeRange(rng.ptr);
669 }
670
671 version (Shared) void runFinalizers(DSO* pdso)
672 {
673 foreach (seg; pdso._codeSegments)
674 GC.runFinalizers(seg);
675 }
676
677 void freeDSO(DSO* pdso) nothrow @nogc
678 {
679 pdso._gcRanges.reset();
680 version (Shared)
681 {
682 pdso._codeSegments.reset();
683 pdso._deps.reset();
684 pdso._handle = null;
685 }
686 .free(pdso);
687 }
688
689 version (Shared)
690 {
691 @nogc nothrow:
692 link_map* linkMapForHandle(void* handle)
693 {
694 static if (__traits(compiles, RTLD_DI_LINKMAP))
695 {
696 link_map* map;
697 const success = dlinfo(handle, RTLD_DI_LINKMAP, &map) == 0;
698 safeAssert(success, "Failed to get DSO info.");
699 return map;
700 }
701 else version (OpenBSD)
702 {
703 safeAssert(handle !is null, "Failed to get DSO info.");
704 return cast(link_map*)handle;
705 }
706 else
707 static assert(0, "unimplemented");
708 }
709
710 DSO* dsoForHandle(void* handle)
711 {
712 DSO* pdso;
713 !pthread_mutex_lock(&_handleToDSOMutex) || assert(0);
714 if (auto ppdso = handle in _handleToDSO)
715 pdso = *ppdso;
716 !pthread_mutex_unlock(&_handleToDSOMutex) || assert(0);
717 return pdso;
718 }
719
720 void setDSOForHandle(DSO* pdso, void* handle)
721 {
722 !pthread_mutex_lock(&_handleToDSOMutex) || assert(0);
723 safeAssert(handle !in _handleToDSO, "DSO already registered.");
724 _handleToDSO[handle] = pdso;
725 !pthread_mutex_unlock(&_handleToDSOMutex) || assert(0);
726 }
727
728 void unsetDSOForHandle(DSO* pdso, void* handle)
729 {
730 !pthread_mutex_lock(&_handleToDSOMutex) || assert(0);
731 safeAssert(_handleToDSO[handle] == pdso, "Handle doesn't match registered DSO.");
732 _handleToDSO.remove(handle);
733 !pthread_mutex_unlock(&_handleToDSOMutex) || assert(0);
734 }
735
736 void getDependencies(const ref dl_phdr_info info, ref Array!(DSO*) deps)
737 {
738 // get the entries of the .dynamic section
739 ElfW!"Dyn"[] dyns;
740 foreach (ref phdr; info.dlpi_phdr[0 .. info.dlpi_phnum])
741 {
742 if (phdr.p_type == PT_DYNAMIC)
743 {
744 auto p = cast(ElfW!"Dyn"*)(info.dlpi_addr + (phdr.p_vaddr & ~(size_t.sizeof - 1)));
745 dyns = p[0 .. phdr.p_memsz / ElfW!"Dyn".sizeof];
746 break;
747 }
748 }
749 // find the string table which contains the sonames
750 const(char)* strtab;
751 foreach (dyn; dyns)
752 {
753 if (dyn.d_tag == DT_STRTAB)
754 {
755 version (CRuntime_Musl)
756 strtab = cast(const(char)*)(info.dlpi_addr + dyn.d_un.d_ptr); // relocate
757 else version (linux)
758 {
759 // This might change in future glibc releases (after 2.29) as dynamic sections
760 // are not required to be read-only on RISC-V. This was copy & pasted from MIPS
761 // while upstreaming RISC-V support. Otherwise MIPS is the only arch which sets
762 // in glibc: #define DL_RO_DYN_SECTION 1
763 version (RISCV_Any)
764 strtab = cast(const(char)*)(info.dlpi_addr + dyn.d_un.d_ptr); // relocate
765 else version (MIPS_Any)
766 strtab = cast(const(char)*)(info.dlpi_addr + dyn.d_un.d_ptr); // relocate
767 else
768 strtab = cast(const(char)*)dyn.d_un.d_ptr;
769 }
770 else version (FreeBSD)
771 strtab = cast(const(char)*)(info.dlpi_addr + dyn.d_un.d_ptr); // relocate
772 else version (NetBSD)
773 strtab = cast(const(char)*)(info.dlpi_addr + dyn.d_un.d_ptr); // relocate
774 else version (OpenBSD)
775 strtab = cast(const(char)*)(info.dlpi_addr + dyn.d_un.d_ptr); // relocate
776 else version (DragonFlyBSD)
777 strtab = cast(const(char)*)(info.dlpi_addr + dyn.d_un.d_ptr); // relocate
778 else version (Solaris)
779 strtab = cast(const(char)*)(info.dlpi_addr + dyn.d_un.d_ptr); // relocate
780 else
781 static assert(0, "unimplemented");
782 break;
783 }
784 }
785 foreach (dyn; dyns)
786 {
787 immutable tag = dyn.d_tag;
788 if (!(tag == DT_NEEDED || tag == DT_AUXILIARY || tag == DT_FILTER))
789 continue;
790
791 // soname of the dependency
792 auto name = strtab + dyn.d_un.d_val;
793 // get handle without loading the library
794 auto handle = handleForName(name);
795 // the runtime linker has already loaded all dependencies
796 safeAssert(handle !is null, "Failed to get library handle.");
797 // if it's a D library
798 if (auto pdso = dsoForHandle(handle))
799 deps.insertBack(pdso); // append it to the dependencies
800 }
801 }
802
803 void* handleForName(const char* name)
804 {
805 version (Solaris) enum refCounted = false;
806 else version (OpenBSD) enum refCounted = false;
807 else enum refCounted = true;
808
809 static if (__traits(compiles, RTLD_NOLOAD))
810 enum flags = (RTLD_NOLOAD | RTLD_LAZY);
811 else
812 enum flags = RTLD_LAZY;
813
814 auto handle = .dlopen(name, flags);
815 static if (refCounted)
816 {
817 if (handle !is null)
818 .dlclose(handle); // drop reference count
819 }
820 return handle;
821 }
822 }
823
824 ///////////////////////////////////////////////////////////////////////////////
825 // Elf program header iteration
826 ///////////////////////////////////////////////////////////////////////////////
827
828 /************
829 * Scan segments in Linux dl_phdr_info struct and store
830 * the TLS and writeable data segments in *pdso.
831 */
832 void scanSegments(const ref dl_phdr_info info, DSO* pdso) nothrow @nogc
833 {
834 foreach (ref phdr; info.dlpi_phdr[0 .. info.dlpi_phnum])
835 {
836 switch (phdr.p_type)
837 {
838 case PT_LOAD:
839 if (phdr.p_flags & PF_W) // writeable data segment
840 {
841 auto beg = cast(void*)(info.dlpi_addr + (phdr.p_vaddr & ~(size_t.sizeof - 1)));
842 pdso._gcRanges.insertBack(beg[0 .. phdr.p_memsz]);
843 }
844 version (Shared) if (phdr.p_flags & PF_X) // code segment
845 {
846 auto beg = cast(void*)(info.dlpi_addr + (phdr.p_vaddr & ~(size_t.sizeof - 1)));
847 pdso._codeSegments.insertBack(beg[0 .. phdr.p_memsz]);
848 }
849 break;
850
851 case PT_TLS: // TLS segment
852 version (GNU_EMUTLS)
853 {
854 }
855 else
856 {
857 safeAssert(!pdso._tlsSize, "Multiple TLS segments in image header.");
858 static if (OS_Have_Dlpi_Tls_Modid)
859 {
860 pdso._tlsMod = info.dlpi_tls_modid;
861 pdso._tlsSize = phdr.p_memsz;
862 }
863 else version (Solaris)
864 {
865 struct Rt_map
866 {
867 Link_map rt_public;
868 const char* rt_pathname;
869 c_ulong rt_padstart;
870 c_ulong rt_padimlen;
871 c_ulong rt_msize;
872 uint rt_flags;
873 uint rt_flags1;
874 c_ulong rt_tlsmodid;
875 }
876
877 Rt_map* map;
878 version (Shared)
879 dlinfo(handleForName(info.dlpi_name), RTLD_DI_LINKMAP, &map);
880 else
881 dlinfo(RTLD_SELF, RTLD_DI_LINKMAP, &map);
882 // Until Solaris 11.4, tlsmodid for the executable is 0.
883 // Let it start at 1 as the rest of the code expects.
884 pdso._tlsMod = map.rt_tlsmodid + 1;
885 pdso._tlsSize = phdr.p_memsz;
886 }
887 else
888 {
889 pdso._tlsMod = 0;
890 pdso._tlsSize = 0;
891 }
892 }
893 break;
894
895 default:
896 break;
897 }
898 }
899 }
900
901 /**************************
902 * Input:
903 * result where the output is to be written; dl_phdr_info is an OS struct
904 * Returns:
905 * true if found, and *result is filled in
906 * References:
907 * http://linux.die.net/man/3/dl_iterate_phdr
908 */
909 bool findDSOInfoForAddr(in void* addr, dl_phdr_info* result=null) nothrow @nogc
910 {
911 version (linux) enum IterateManually = true;
912 else version (NetBSD) enum IterateManually = true;
913 else version (OpenBSD) enum IterateManually = true;
914 else version (Solaris) enum IterateManually = true;
915 else enum IterateManually = false;
916
917 static if (IterateManually)
918 {
919 static struct DG { const(void)* addr; dl_phdr_info* result; }
920
921 extern(C) int callback(dl_phdr_info* info, size_t sz, void* arg) nothrow @nogc
922 {
923 auto p = cast(DG*)arg;
924 if (findSegmentForAddr(*info, p.addr))
925 {
926 if (p.result !is null) *p.result = *info;
927 return 1; // break;
928 }
929 return 0; // continue iteration
930 }
931
932 auto dg = DG(addr, result);
933
934 /* OS function that walks through the list of an application's shared objects and
935 * calls 'callback' once for each object, until either all shared objects
936 * have been processed or 'callback' returns a nonzero value.
937 */
938 return dl_iterate_phdr(&callback, &dg) != 0;
939 }
940 else version (FreeBSD)
941 {
942 return !!_rtld_addr_phdr(addr, result);
943 }
944 else version (DragonFlyBSD)
945 {
946 return !!_rtld_addr_phdr(addr, result);
947 }
948 else
949 static assert(0, "unimplemented");
950 }
951
952 /*********************************
953 * Determine if 'addr' lies within shared object 'info'.
954 * If so, return true and fill in 'result' with the corresponding ELF program header.
955 */
956 bool findSegmentForAddr(const ref dl_phdr_info info, in void* addr, ElfW!"Phdr"* result=null) nothrow @nogc
957 {
958 if (addr < cast(void*)info.dlpi_addr) // less than base address of object means quick reject
959 return false;
960
961 foreach (ref phdr; info.dlpi_phdr[0 .. info.dlpi_phnum])
962 {
963 auto beg = cast(void*)(info.dlpi_addr + phdr.p_vaddr);
964 if (cast(size_t)(addr - beg) < phdr.p_memsz)
965 {
966 if (result !is null) *result = phdr;
967 return true;
968 }
969 }
970 return false;
971 }
972
973 /**************************
974 * Input:
975 * addr an internal address of a DSO
976 * Returns:
977 * the dlopen handle for that DSO or null if addr is not within a loaded DSO
978 */
979 version (Shared) void* handleForAddr(void* addr) nothrow @nogc
980 {
981 Dl_info info = void;
982 if (dladdr(addr, &info) != 0)
983 return handleForName(info.dli_fname);
984 return null;
985 }
986
987 ///////////////////////////////////////////////////////////////////////////////
988 // TLS module helper
989 ///////////////////////////////////////////////////////////////////////////////
990
991
992 /*
993 * Returns: the TLS memory range for a given module and the calling
994 * thread or null if that module has no TLS.
995 *
996 * Note: This will cause the TLS memory to be eagerly allocated.
997 */
998 struct tls_index
999 {
1000 version (CRuntime_Glibc)
1001 {
1002 // For x86_64, fields are of type uint64_t, this is important for x32
1003 // where tls_index would otherwise have the wrong size.
1004 // See https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/x86_64/dl-tls.h
1005 version (X86_64)
1006 {
1007 ulong ti_module;
1008 ulong ti_offset;
1009 }
1010 else
1011 {
1012 c_ulong ti_module;
1013 c_ulong ti_offset;
1014 }
1015 }
1016 else
1017 {
1018 size_t ti_module;
1019 size_t ti_offset;
1020 }
1021 }
1022
1023 extern(C) void* __tls_get_addr(tls_index* ti) nothrow @nogc;
1024 extern(C) void* __ibmz_get_tls_offset(tls_index *ti) nothrow @nogc;
1025
1026 /* The dynamic thread vector (DTV) pointers may point 0x8000 past the start of
1027 * each TLS block. This is at least true for PowerPC and Mips platforms.
1028 * See: https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/powerpc/dl-tls.h;h=f7cf6f96ebfb505abfd2f02be0ad0e833107c0cd;hb=HEAD#l34
1029 * https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/mips/dl-tls.h;h=93a6dc050cb144b9f68b96fb3199c60f5b1fcd18;hb=HEAD#l32
1030 * https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/riscv/dl-tls.h;h=ab2d860314de94c18812bc894ff6b3f55368f20f;hb=HEAD#l32
1031 */
1032 version (X86)
1033 enum TLS_DTV_OFFSET = 0x0;
1034 else version (X86_64)
1035 enum TLS_DTV_OFFSET = 0x0;
1036 else version (ARM)
1037 enum TLS_DTV_OFFSET = 0x0;
1038 else version (AArch64)
1039 enum TLS_DTV_OFFSET = 0x0;
1040 else version (RISCV32)
1041 enum TLS_DTV_OFFSET = 0x800;
1042 else version (RISCV64)
1043 enum TLS_DTV_OFFSET = 0x800;
1044 else version (HPPA)
1045 enum TLS_DTV_OFFSET = 0x0;
1046 else version (SPARC)
1047 enum TLS_DTV_OFFSET = 0x0;
1048 else version (SPARC64)
1049 enum TLS_DTV_OFFSET = 0x0;
1050 else version (PPC)
1051 enum TLS_DTV_OFFSET = 0x8000;
1052 else version (PPC64)
1053 enum TLS_DTV_OFFSET = 0x8000;
1054 else version (MIPS32)
1055 enum TLS_DTV_OFFSET = 0x8000;
1056 else version (MIPS64)
1057 enum TLS_DTV_OFFSET = 0x8000;
1058 else version (IBMZ_Any)
1059 enum TLS_DTV_OFFSET = 0x0;
1060 else version (LoongArch64)
1061 enum TLS_DTV_OFFSET = 0x0;
1062 else
1063 static assert( false, "Platform not supported." );
1064
1065 void[] getTLSRange(size_t mod, size_t sz) nothrow @nogc
1066 {
1067 if (mod == 0)
1068 return null;
1069
1070 version (GNU_EMUTLS)
1071 return null; // Handled in scanTLSRanges().
1072 else
1073 {
1074 version (Solaris)
1075 {
1076 static if (!OS_Have_Dlpi_Tls_Modid)
1077 mod -= 1;
1078 }
1079
1080 // base offset
1081 auto ti = tls_index(mod, 0);
1082 version (CRuntime_Musl)
1083 return (__tls_get_addr(&ti)-TLS_DTV_OFFSET)[0 .. sz];
1084 else version (IBMZ_Any)
1085 {
1086 // IBM Z only provides __tls_get_offset instead of __tls_get_addr
1087 // which returns an offset relative to the thread pointer.
1088 auto addr = __ibmz_get_tls_offset(&ti);
1089 addr = addr + cast(c_ulong)__builtin_thread_pointer();
1090 return addr[0 .. sz];
1091 }
1092 else
1093 return (__tls_get_addr(&ti)-TLS_DTV_OFFSET)[0 .. sz];
1094 }
1095 }