Debian Codegraph @

libphobos/libdruntime/gcc/sections/macho.d

raw
1 // MACHO-specific support for sections.
2 // Copyright (C) 2021-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.macho;
24
25 version (OSX):
26
27 import core.memory;
28 import core.stdc.stdlib;
29 import core.sys.darwin.dlfcn;
30 import core.sys.darwin.mach.dyld;
31 import core.sys.darwin.mach.getsect;
32 import core.sys.posix.pthread;
33 import rt.dmain2;
34 import rt.minfo;
35 import core.internal.container.array;
36 import core.internal.container.hashtab;
37 import gcc.sections.common;
38
39 version (GNU_EMUTLS)
40 import gcc.emutls;
41
42 alias DSO SectionGroup;
43 struct DSO
44 {
45 static int opApply(scope int delegate(ref DSO) dg)
46 {
47 foreach (dso; _loadedDSOs)
48 {
49 if (auto res = dg(*dso))
50 return res;
51 }
52 return 0;
53 }
54
55 static int opApplyReverse(scope int delegate(ref DSO) dg)
56 {
57 foreach_reverse (dso; _loadedDSOs)
58 {
59 if (auto res = dg(*dso))
60 return res;
61 }
62 return 0;
63 }
64
65 @property immutable(ModuleInfo*)[] modules() const nothrow @nogc
66 {
67 return _moduleGroup.modules;
68 }
69
70 @property ref inout(ModuleGroup) moduleGroup() inout return nothrow @nogc
71 {
72 return _moduleGroup;
73 }
74
75 @property inout(void[])[] gcRanges() inout nothrow @nogc
76 {
77 return _gcRanges[];
78 }
79
80 private:
81
82 invariant()
83 {
84 safeAssert(_moduleGroup.modules.length > 0, "No modules for DSO.");
85 }
86
87 void** _slot;
88 ModuleGroup _moduleGroup;
89 Array!(void[]) _gcRanges;
90
91 version (Shared)
92 {
93 Array!(void[]) _codeSegments; // array of code segments
94 Array!(DSO*) _deps; // D libraries needed by this DSO
95 void* _handle; // corresponding handle
96 }
97 }
98
99 /****
100 * Gets called on program startup just before GC is initialized.
101 */
102 void initSections() nothrow @nogc
103 {
104 }
105
106 /***
107 * Gets called on program shutdown just after GC is terminated.
108 */
109 void finiSections() nothrow @nogc
110 {
111 }
112
113 alias ScanDG = void delegate(void* pbeg, void* pend) nothrow;
114
115 version (Shared)
116 {
117 import gcc.sections : pinLoadedLibraries, unpinLoadedLibraries,
118 inheritLoadedLibraries, cleanupLoadedLibraries;
119
120 /***
121 * Called once per thread; returns array of thread local storage ranges
122 */
123 Array!(ThreadDSO)* initTLSRanges() @nogc nothrow
124 {
125 return &_loadedDSOs();
126 }
127
128 void finiTLSRanges(Array!(ThreadDSO)* tdsos) @nogc nothrow
129 {
130 // Nothing to do here. tdsos used to point to the _loadedDSOs instance
131 // in the dying thread's TLS segment and as such is not valid anymore.
132 // The memory for the array contents was already reclaimed in
133 // cleanupLoadedLibraries().
134 }
135
136 void scanTLSRanges(Array!(ThreadDSO)* tdsos, scope ScanDG dg) nothrow
137 {
138 version (GNU_EMUTLS)
139 _d_emutls_scan(dg);
140 else
141 static assert(0, "Native TLS unimplemented");
142 }
143
144 // interface for core.thread to inherit loaded libraries
145 pragma(mangle, gcc.sections.pinLoadedLibraries.mangleof)
146 void* pinLoadedLibraries() nothrow @nogc
147 {
148 auto res = cast(Array!(ThreadDSO)*)calloc(1, Array!(ThreadDSO).sizeof);
149 res.length = _loadedDSOs.length;
150 foreach (i, ref tdso; _loadedDSOs)
151 {
152 (*res)[i] = tdso;
153 if (tdso._addCnt)
154 {
155 // Increment the dlopen ref for explicitly loaded libraries to pin them.
156 const success = .dlopen(nameForDSO(tdso._pdso), RTLD_LAZY) !is null;
157 safeAssert(success, "Failed to increment dlopen ref.");
158 (*res)[i]._addCnt = 1; // new array takes over the additional ref count
159 }
160 }
161 return res;
162 }
163
164 pragma(mangle, gcc.sections.unpinLoadedLibraries.mangleof)
165 void unpinLoadedLibraries(void* p) nothrow @nogc
166 {
167 auto pary = cast(Array!(ThreadDSO)*)p;
168 // In case something failed we need to undo the pinning.
169 foreach (ref tdso; *pary)
170 {
171 if (tdso._addCnt)
172 {
173 auto handle = tdso._pdso._handle;
174 safeAssert(handle !is null, "Invalid library handle.");
175 .dlclose(handle);
176 }
177 }
178 pary.reset();
179 .free(pary);
180 }
181
182 // Called before TLS ctors are ran, copy over the loaded libraries
183 // of the parent thread.
184 pragma(mangle, gcc.sections.inheritLoadedLibraries.mangleof)
185 void inheritLoadedLibraries(void* p) nothrow @nogc
186 {
187 safeAssert(_loadedDSOs.empty, "DSOs have already been registered for this thread.");
188 _loadedDSOs.swap(*cast(Array!(ThreadDSO)*)p);
189 .free(p);
190 }
191
192 // Called after all TLS dtors ran, decrements all remaining dlopen refs.
193 pragma(mangle, gcc.sections.cleanupLoadedLibraries.mangleof)
194 void cleanupLoadedLibraries() nothrow @nogc
195 {
196 foreach (ref tdso; _loadedDSOs)
197 {
198 if (tdso._addCnt == 0) continue;
199
200 auto handle = tdso._pdso._handle;
201 safeAssert(handle !is null, "Invalid DSO handle.");
202 for (; tdso._addCnt > 0; --tdso._addCnt)
203 .dlclose(handle);
204 }
205
206 // Free the memory for the array contents.
207 _loadedDSOs.reset();
208 }
209 }
210 else
211 {
212 /***
213 * Called once per thread; returns array of thread local storage ranges
214 */
215 Array!(void[])* initTLSRanges() nothrow @nogc
216 {
217 return null;
218 }
219
220 void finiTLSRanges(Array!(void[])* rngs) nothrow @nogc
221 {
222 }
223
224 void scanTLSRanges(Array!(void[])* rngs, scope ScanDG dg) nothrow
225 {
226 version (GNU_EMUTLS)
227 _d_emutls_scan(dg);
228 else
229 static assert(0, "Native TLS unimplemented");
230 }
231 }
232
233 private:
234
235 version (Shared)
236 {
237 /*
238 * Array of thread local DSO metadata for all libraries loaded and
239 * initialized in this thread.
240 *
241 * Note:
242 * A newly spawned thread will inherit these libraries.
243 * Note:
244 * We use an array here to preserve the order of
245 * initialization. If that became a performance issue, we
246 * could use a hash table and enumerate the DSOs during
247 * loading so that the hash table values could be sorted when
248 * necessary.
249 */
250 struct ThreadDSO
251 {
252 DSO* _pdso;
253 static if (_pdso.sizeof == 8) uint _refCnt, _addCnt;
254 else static if (_pdso.sizeof == 4) ushort _refCnt, _addCnt;
255 else static assert(0, "unimplemented");
256 alias _pdso this;
257 }
258
259 @property ref Array!(ThreadDSO) _loadedDSOs() @nogc nothrow
260 {
261 static Array!(ThreadDSO) x;
262 return x;
263 }
264
265 /*
266 * Set to true during rt_loadLibrary/rt_unloadLibrary calls.
267 */
268 bool _rtLoading;
269
270 /*
271 * Hash table to map the native handle (as returned by dlopen)
272 * to the corresponding DSO*, protected by a mutex.
273 */
274 __gshared pthread_mutex_t _handleToDSOMutex;
275 @property ref HashTab!(void*, DSO*) _handleToDSO() @nogc nothrow
276 {
277 __gshared HashTab!(void*, DSO*) x;
278 return x;
279 }
280 }
281 else
282 {
283 /*
284 * Static DSOs loaded by the runtime linker. This includes the
285 * executable. These can't be unloaded.
286 */
287 @property ref Array!(DSO*) _loadedDSOs() @nogc nothrow
288 {
289 __gshared Array!(DSO*) x;
290 return x;
291 }
292
293 enum _rtLoading = false;
294 }
295
296 ///////////////////////////////////////////////////////////////////////////////
297 // Compiler to runtime interface.
298 ///////////////////////////////////////////////////////////////////////////////
299
300 struct MachHeader
301 {
302 const(mach_header)* header; // the mach header of the image
303 intptr_t slide; // virtural memory address slide amount
304 }
305
306 /****
307 * This data structure is generated by the compiler, and then passed to
308 * _d_dso_registry().
309 */
310 struct CompilerDSOData
311 {
312 size_t _version; // currently 1
313 void** _slot; // can be used to store runtime data
314 immutable(object.ModuleInfo*)* _minfo_beg, _minfo_end; // array of modules in this object file
315 }
316
317 T[] toRange(T)(T* beg, T* end) { return beg[0 .. end - beg]; }
318
319 /* For each shared library and executable, the compiler generates code that
320 * sets up CompilerDSOData and calls _d_dso_registry().
321 * A pointer to that code is inserted into both the .ctors and .dtors
322 * segment so it gets called by the loader on startup and shutdown.
323 */
324 extern(C) void _d_dso_registry(CompilerDSOData* data)
325 {
326 // only one supported currently
327 safeAssert(data._version >= 1, "Incompatible compiler-generated DSO data version.");
328
329 // no backlink => register
330 if (*data._slot is null)
331 {
332 immutable firstDSO = _loadedDSOs.empty;
333 if (firstDSO) initLocks();
334
335 DSO* pdso = cast(DSO*).calloc(1, DSO.sizeof);
336 assert(typeid(DSO).initializer().ptr is null);
337 pdso._slot = data._slot;
338 *data._slot = pdso; // store backlink in library record
339
340 pdso._moduleGroup = ModuleGroup(toRange(data._minfo_beg, data._minfo_end));
341
342 MachHeader header = void;
343 const headerFound = findImageHeaderForAddr(data._slot, header);
344 safeAssert(headerFound, "Failed to find image header.");
345
346 scanSegments(header, pdso);
347
348 version (Shared)
349 {
350 auto handle = handleForAddr(data._slot);
351
352 getDependencies(header, pdso._deps);
353 pdso._handle = handle;
354 setDSOForHandle(pdso, pdso._handle);
355
356 if (!_rtLoading)
357 {
358 /* This DSO was not loaded by rt_loadLibrary which
359 * happens for all dependencies of an executable or
360 * the first dlopen call from a C program.
361 * In this case we add the DSO to the _loadedDSOs of this
362 * thread with a refCnt of 1 and call the TlsCtors.
363 */
364 immutable ushort refCnt = 1, addCnt = 0;
365 _loadedDSOs.insertBack(ThreadDSO(pdso, refCnt, addCnt));
366 }
367 }
368 else
369 {
370 foreach (p; _loadedDSOs)
371 safeAssert(p !is pdso, "DSO already registered.");
372 _loadedDSOs.insertBack(pdso);
373 }
374
375 // don't initialize modules before rt_init was called
376 if (isRuntimeInitialized())
377 {
378 registerGCRanges(pdso);
379 // rt_loadLibrary will run tls ctors, so do this only for dlopen
380 immutable runTlsCtors = !_rtLoading;
381 runModuleConstructors(pdso, runTlsCtors);
382 }
383 }
384 // has backlink => unregister
385 else
386 {
387 DSO* pdso = cast(DSO*)*data._slot;
388 *data._slot = null;
389
390 // don't finalizes modules after rt_term was called (see Bugzilla 11378)
391 if (isRuntimeInitialized())
392 {
393 // rt_unloadLibrary already ran tls dtors, so do this only for dlclose
394 immutable runTlsDtors = !_rtLoading;
395 runModuleDestructors(pdso, runTlsDtors);
396 unregisterGCRanges(pdso);
397 // run finalizers after module dtors (same order as in rt_term)
398 version (Shared) runFinalizers(pdso);
399 }
400
401 version (Shared)
402 {
403 if (!_rtLoading)
404 {
405 /* This DSO was not unloaded by rt_unloadLibrary so we
406 * have to remove it from _loadedDSOs here.
407 */
408 foreach (i, ref tdso; _loadedDSOs)
409 {
410 if (tdso._pdso == pdso)
411 {
412 _loadedDSOs.remove(i);
413 break;
414 }
415 }
416 }
417
418 unsetDSOForHandle(pdso, pdso._handle);
419 }
420 else
421 {
422 // static DSOs are unloaded in reverse order
423 safeAssert(pdso == _loadedDSOs.back, "DSO being unregistered isn't current last one.");
424 _loadedDSOs.popBack();
425 }
426
427 freeDSO(pdso);
428
429 // last DSO being unloaded => shutdown registry
430 if (_loadedDSOs.empty)
431 {
432 version (GNU_EMUTLS)
433 _d_emutls_destroy();
434 version (Shared)
435 {
436 safeAssert(_handleToDSO.empty, "_handleToDSO not in sync with _loadedDSOs.");
437 _handleToDSO.reset();
438 }
439 finiLocks();
440 }
441 }
442 }
443
444 ///////////////////////////////////////////////////////////////////////////////
445 // dynamic loading
446 ///////////////////////////////////////////////////////////////////////////////
447
448 // Shared D libraries are only supported when linking against a shared druntime library.
449
450 version (Shared)
451 {
452 ThreadDSO* findThreadDSO(DSO* pdso) nothrow @nogc
453 {
454 foreach (ref tdata; _loadedDSOs)
455 if (tdata._pdso == pdso) return &tdata;
456 return null;
457 }
458
459 void incThreadRef(DSO* pdso, bool incAdd)
460 {
461 if (auto tdata = findThreadDSO(pdso)) // already initialized
462 {
463 if (incAdd && ++tdata._addCnt > 1) return;
464 ++tdata._refCnt;
465 }
466 else
467 {
468 foreach (dep; pdso._deps)
469 incThreadRef(dep, false);
470 immutable ushort refCnt = 1, addCnt = incAdd ? 1 : 0;
471 _loadedDSOs.insertBack(ThreadDSO(pdso, refCnt, addCnt));
472 pdso._moduleGroup.runTlsCtors();
473 }
474 }
475
476 void decThreadRef(DSO* pdso, bool decAdd)
477 {
478 auto tdata = findThreadDSO(pdso);
479 safeAssert(tdata !is null, "Failed to find thread DSO.");
480 safeAssert(!decAdd || tdata._addCnt > 0, "Mismatching rt_unloadLibrary call.");
481
482 if (decAdd && --tdata._addCnt > 0) return;
483 if (--tdata._refCnt > 0) return;
484
485 pdso._moduleGroup.runTlsDtors();
486 foreach (i, ref td; _loadedDSOs)
487 if (td._pdso == pdso) _loadedDSOs.remove(i);
488 foreach (dep; pdso._deps)
489 decThreadRef(dep, false);
490 }
491
492 extern(C) void* rt_loadLibrary(const char* name)
493 {
494 immutable save = _rtLoading;
495 _rtLoading = true;
496 scope (exit) _rtLoading = save;
497
498 auto handle = .dlopen(name, RTLD_LAZY);
499 if (handle is null) return null;
500
501 // if it's a D library
502 if (auto pdso = dsoForHandle(handle))
503 incThreadRef(pdso, true);
504 return handle;
505 }
506
507 extern(C) int rt_unloadLibrary(void* handle)
508 {
509 if (handle is null) return false;
510
511 immutable save = _rtLoading;
512 _rtLoading = true;
513 scope (exit) _rtLoading = save;
514
515 // if it's a D library
516 if (auto pdso = dsoForHandle(handle))
517 decThreadRef(pdso, true);
518 return .dlclose(handle) == 0;
519 }
520 }
521
522 ///////////////////////////////////////////////////////////////////////////////
523 // helper functions
524 ///////////////////////////////////////////////////////////////////////////////
525
526 void initLocks() nothrow @nogc
527 {
528 version (Shared)
529 !pthread_mutex_init(&_handleToDSOMutex, null) || assert(0);
530 }
531
532 void finiLocks() nothrow @nogc
533 {
534 version (Shared)
535 !pthread_mutex_destroy(&_handleToDSOMutex) || assert(0);
536 }
537
538 void runModuleConstructors(DSO* pdso, bool runTlsCtors)
539 {
540 pdso._moduleGroup.sortCtors();
541 pdso._moduleGroup.runCtors();
542 if (runTlsCtors) pdso._moduleGroup.runTlsCtors();
543 }
544
545 void runModuleDestructors(DSO* pdso, bool runTlsDtors)
546 {
547 if (runTlsDtors) pdso._moduleGroup.runTlsDtors();
548 pdso._moduleGroup.runDtors();
549 }
550
551 void registerGCRanges(DSO* pdso) nothrow @nogc
552 {
553 foreach (rng; pdso._gcRanges)
554 GC.addRange(rng.ptr, rng.length);
555 }
556
557 void unregisterGCRanges(DSO* pdso) nothrow @nogc
558 {
559 foreach (rng; pdso._gcRanges)
560 GC.removeRange(rng.ptr);
561 }
562
563 version (Shared) void runFinalizers(DSO* pdso)
564 {
565 foreach (seg; pdso._codeSegments)
566 GC.runFinalizers(seg);
567 }
568
569 void freeDSO(DSO* pdso) nothrow @nogc
570 {
571 pdso._gcRanges.reset();
572 version (Shared)
573 {
574 pdso._codeSegments.reset();
575 pdso._deps.reset();
576 pdso._handle = null;
577 }
578 .free(pdso);
579 }
580
581 version (Shared)
582 {
583 @nogc nothrow:
584 const(char)* nameForDSO(in DSO* pdso)
585 {
586 Dl_info info = void;
587 const success = dladdr(pdso._slot, &info) != 0;
588 safeAssert(success, "Failed to get DSO info.");
589 return info.dli_fname;
590 }
591
592 DSO* dsoForHandle(void* handle)
593 {
594 DSO* pdso;
595 !pthread_mutex_lock(&_handleToDSOMutex) || assert(0);
596 if (auto ppdso = handle in _handleToDSO)
597 pdso = *ppdso;
598 !pthread_mutex_unlock(&_handleToDSOMutex) || assert(0);
599 return pdso;
600 }
601
602 void setDSOForHandle(DSO* pdso, void* handle)
603 {
604 !pthread_mutex_lock(&_handleToDSOMutex) || assert(0);
605 safeAssert(handle !in _handleToDSO, "DSO already registered.");
606 _handleToDSO[handle] = pdso;
607 !pthread_mutex_unlock(&_handleToDSOMutex) || assert(0);
608 }
609
610 void unsetDSOForHandle(DSO* pdso, void* handle)
611 {
612 !pthread_mutex_lock(&_handleToDSOMutex) || assert(0);
613 safeAssert(_handleToDSO[handle] == pdso, "Handle doesn't match registered DSO.");
614 _handleToDSO.remove(handle);
615 !pthread_mutex_unlock(&_handleToDSOMutex) || assert(0);
616 }
617
618 void getDependencies(in MachHeader info, ref Array!(DSO*) deps)
619 {
620 // FIXME: Not implemented yet.
621 }
622
623 void* handleForName(const char* name)
624 {
625 auto handle = .dlopen(name, RTLD_NOLOAD | RTLD_LAZY);
626 if (handle !is null) .dlclose(handle); // drop reference count
627 return handle;
628 }
629 }
630
631 ///////////////////////////////////////////////////////////////////////////////
632 // Mach-O program header iteration
633 ///////////////////////////////////////////////////////////////////////////////
634
635 /************
636 * Scan segments in the image header and store
637 * the writeable data segments in *pdso.
638 */
639
640 void scanSegments(in MachHeader info, DSO* pdso)
641 {
642 foreach (e; dataSegs)
643 {
644 auto sect = getSection(info.header, info.slide, e.seg.ptr, e.sect.ptr);
645 if (sect != null)
646 pdso._gcRanges.insertBack((cast(void*)sect.ptr)[0 .. sect.length]);
647 }
648
649 version (Shared)
650 {
651 void[] text = getSection(info.header, info.slide, "__TEXT", "__text");
652 if (!text)
653 assert(0, "Failed to get text section.");
654 pdso._codeSegments.insertBack(text);
655 }
656 }
657
658 /**************************
659 * Input:
660 * result where the output is to be written
661 * Returns:
662 * true if found, and *result is filled in
663 */
664
665 bool findImageHeaderForAddr(in void* addr, out MachHeader result)
666 {
667 Dl_info info;
668 if (dladdr(addr, &info) == 0)
669 return false;
670
671 foreach (i; 0 .. _dyld_image_count())
672 {
673 if (info.dli_fbase == _dyld_get_image_header(i))
674 {
675 result.header = cast(const(mach_header)*)info.dli_fbase;
676 result.slide = _dyld_get_image_vmaddr_slide(i);
677 return true;
678 }
679 }
680 return false;
681 }
682
683 /**************************
684 * Input:
685 * addr an internal address of a DSO
686 * Returns:
687 * the dlopen handle for that DSO or null if addr is not within a loaded DSO
688 */
689 version (Shared) void* handleForAddr(void* addr) nothrow @nogc
690 {
691 Dl_info info = void;
692 if (dladdr(addr, &info) != 0)
693 return handleForName(info.dli_fname);
694 return null;
695 }
696
697 struct SegRef
698 {
699 string seg;
700 string sect;
701 }
702
703 static immutable SegRef[] dataSegs = [{SEG_DATA, SECT_DATA},
704 {SEG_DATA, SECT_BSS},
705 {SEG_DATA, SECT_COMMON}];
706
707 /**
708 * Returns the section for the named section in the named segment
709 * for the mach_header pointer passed, or null if not found.
710 */
711 ubyte[] getSection(in mach_header* header, intptr_t slide,
712 in char* segmentName, in char* sectionName)
713 {
714 version (D_LP64)
715 {
716 assert(header.magic == MH_MAGIC_64);
717 auto sect = getsectbynamefromheader_64(cast(mach_header_64*)header,
718 segmentName,
719 sectionName);
720 }
721 else
722 {
723 assert(header.magic == MH_MAGIC);
724 auto sect = getsectbynamefromheader(header,
725 segmentName,
726 sectionName);
727 }
728
729 if (sect !is null && sect.size > 0)
730 return (cast(ubyte*)sect.addr + slide)[0 .. cast(size_t)sect.size];
731 return null;
732 }