1 // PE/COFF-specific support for sections.
2 // Copyright (C) 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.pecoff;
28 import core.stdc.stdlib;
29 import core.sys.windows.winbase;
30 import core.sys.windows.windef;
31 import core.sys.windows.winnt;
33 import core.internal.container.array;
34 import core.internal.container.hashtab;
35 import gcc.sections.common;
40 alias DSO SectionGroup;
43 static int opApply(scope int delegate(ref DSO) dg)
45 foreach (dso; _loadedDSOs)
47 if (auto res = dg(*dso))
53 static int opApplyReverse(scope int delegate(ref DSO) dg)
55 foreach_reverse (dso; _loadedDSOs)
57 if (auto res = dg(*dso))
63 @property immutable(ModuleInfo*)[] modules() const nothrow @nogc
65 return _moduleGroup.modules;
68 @property ref inout(ModuleGroup) moduleGroup() inout return nothrow @nogc
73 @property inout(void[])[] gcRanges() inout nothrow @nogc
82 safeAssert(_moduleGroup.modules.length > 0, "No modules for DSO.");
86 ModuleGroup _moduleGroup;
87 Array!(void[]) _gcRanges;
91 Array!(void[]) _codeSegments; // array of code segments
92 Array!(DSO*) _deps; // D libraries needed by this DSO
93 void* _handle; // corresponding handle
98 * Boolean flag set to true while the runtime is initialized.
100 __gshared bool _isRuntimeInitialized;
103 * Gets called on program startup just before GC is initialized.
105 void initSections() nothrow @nogc
107 _isRuntimeInitialized = true;
111 * Gets called on program shutdown just after GC is terminated.
113 void finiSections() nothrow @nogc
115 _isRuntimeInitialized = false;
118 alias ScanDG = void delegate(void* pbeg, void* pend) nothrow;
122 import gcc.sections : pinLoadedLibraries, unpinLoadedLibraries,
123 inheritLoadedLibraries, cleanupLoadedLibraries;
126 * Called once per thread; returns array of thread local storage ranges
128 Array!(ThreadDSO)* initTLSRanges() @nogc nothrow
130 return &_loadedDSOs();
133 void finiTLSRanges(Array!(ThreadDSO)* tdsos) @nogc nothrow
135 // Nothing to do here. tdsos used to point to the _loadedDSOs instance
136 // in the dying thread's TLS segment and as such is not valid anymore.
137 // The memory for the array contents was already reclaimed in
138 // cleanupLoadedLibraries().
141 void scanTLSRanges(Array!(ThreadDSO)* tdsos, scope ScanDG dg) nothrow
146 static assert(0, "Native TLS unimplemented");
149 // interface for core.thread to inherit loaded libraries
150 pragma(mangle, gcc.sections.pinLoadedLibraries.mangleof)
151 void* pinLoadedLibraries() nothrow @nogc
153 auto res = cast(Array!(ThreadDSO)*)calloc(1, Array!(ThreadDSO).sizeof);
154 res.length = _loadedDSOs.length;
155 foreach (i, ref tdso; _loadedDSOs)
160 // Increment the DLL ref for explicitly loaded libraries to pin them.
162 char[] buffer = buf[];
163 const success = .LoadLibraryA(nameForDSO(tdso._pdso, buffer)) !is null;
164 safeAssert(success, "Failed to increment DLL ref.");
165 (*res)[i]._addCnt = 1; // new array takes over the additional ref count
171 pragma(mangle, gcc.sections.unpinLoadedLibraries.mangleof)
172 void unpinLoadedLibraries(void* p) nothrow @nogc
174 auto pary = cast(Array!(ThreadDSO)*)p;
175 // In case something failed we need to undo the pinning.
176 foreach (ref tdso; *pary)
180 auto handle = tdso._pdso._handle;
181 safeAssert(handle !is null, "Invalid library handle.");
182 .FreeLibrary(handle);
189 // Called before TLS ctors are ran, copy over the loaded libraries
190 // of the parent thread.
191 pragma(mangle, gcc.sections.inheritLoadedLibraries.mangleof)
192 void inheritLoadedLibraries(void* p) nothrow @nogc
194 safeAssert(_loadedDSOs.empty, "DSOs have already been registered for this thread.");
195 _loadedDSOs.swap(*cast(Array!(ThreadDSO)*)p);
199 // Called after all TLS dtors ran, decrements all remaining DLL refs.
200 pragma(mangle, gcc.sections.cleanupLoadedLibraries.mangleof)
201 void cleanupLoadedLibraries() nothrow @nogc
203 foreach (ref tdso; _loadedDSOs)
205 if (tdso._addCnt == 0) continue;
207 auto handle = tdso._pdso._handle;
208 safeAssert(handle !is null, "Invalid DSO handle.");
209 for (; tdso._addCnt > 0; --tdso._addCnt)
210 .FreeLibrary(handle);
213 // Free the memory for the array contents.
220 * Called once per thread; returns array of thread local storage ranges
222 Array!(void[])* initTLSRanges() nothrow @nogc
227 void finiTLSRanges(Array!(void[])* rngs) nothrow @nogc
231 void scanTLSRanges(Array!(void[])* rngs, scope ScanDG dg) nothrow
236 static assert(0, "Native TLS unimplemented");
245 * Array of thread local DSO metadata for all libraries loaded and
246 * initialized in this thread.
249 * A newly spawned thread will inherit these libraries.
251 * We use an array here to preserve the order of
252 * initialization. If that became a performance issue, we
253 * could use a hash table and enumerate the DSOs during
254 * loading so that the hash table values could be sorted when
260 static if (_pdso.sizeof == 8) uint _refCnt, _addCnt;
261 else static if (_pdso.sizeof == 4) ushort _refCnt, _addCnt;
262 else static assert(0, "unimplemented");
266 @property ref Array!(ThreadDSO) _loadedDSOs() @nogc nothrow
268 static Array!(ThreadDSO) x;
273 * Set to true during rt_loadLibrary/rt_unloadLibrary calls.
278 * Hash table to map the native handle (as returned by dlopen)
279 * to the corresponding DSO*, protected by a mutex.
281 __gshared CRITICAL_SECTION _handleToDSOMutex;
282 @property ref HashTab!(void*, DSO*) _handleToDSO() @nogc nothrow
284 __gshared HashTab!(void*, DSO*) x;
291 * Static DSOs loaded by the runtime linker. This includes the
292 * executable. These can't be unloaded.
294 @property ref Array!(DSO*) _loadedDSOs() @nogc nothrow
296 __gshared Array!(DSO*) x;
300 enum _rtLoading = false;
303 ///////////////////////////////////////////////////////////////////////////////
304 // Compiler to runtime interface.
305 ///////////////////////////////////////////////////////////////////////////////
308 * This data structure is generated by the compiler, and then passed to
311 struct CompilerDSOData
313 size_t _version; // currently 1
314 void** _slot; // can be used to store runtime data
315 immutable(object.ModuleInfo*)* _minfo_beg, _minfo_end; // array of modules in this object file
318 T[] toRange(T)(T* beg, T* end) { return beg[0 .. end - beg]; }
320 /* For each shared library and executable, the compiler generates code that
321 * sets up CompilerDSOData and calls _d_dso_registry().
322 * A pointer to that code is inserted into both the .ctors and .dtors
323 * segment so it gets called by the loader on startup and shutdown.
325 extern(C) void _d_dso_registry(CompilerDSOData* data)
327 // only one supported currently
328 safeAssert(data._version >= 1, "Incompatible compiler-generated DSO data version.");
330 // no backlink => register
331 if (*data._slot is null)
333 immutable firstDSO = _loadedDSOs.empty;
334 if (firstDSO) initLocks();
336 DSO* pdso = cast(DSO*).calloc(1, DSO.sizeof);
337 assert(typeid(DSO).initializer().ptr is null);
338 pdso._slot = data._slot;
339 *data._slot = pdso; // store backlink in library record
341 pdso._moduleGroup = ModuleGroup(toRange(data._minfo_beg, data._minfo_end));
343 HMODULE handle = void;
344 const moduleFound = findModuleHandleForAddr(data._slot, handle);
345 safeAssert(moduleFound, "Failed to find image header.");
347 scanSegments(handle, pdso);
351 getDependencies(handle, pdso._deps);
352 pdso._handle = handle;
353 setDSOForHandle(pdso, pdso._handle);
357 /* This DSO was not loaded by rt_loadLibrary which
358 * happens for all dependencies of an executable or
359 * the first dlopen call from a C program.
360 * In this case we add the DSO to the _loadedDSOs of this
361 * thread with a refCnt of 1 and call the TlsCtors.
363 immutable ushort refCnt = 1, addCnt = 0;
364 _loadedDSOs.insertBack(ThreadDSO(pdso, refCnt, addCnt));
369 foreach (p; _loadedDSOs)
370 safeAssert(p !is pdso, "DSO already registered.");
371 _loadedDSOs.insertBack(pdso);
374 // don't initialize modules before rt_init was called
375 if (_isRuntimeInitialized)
377 registerGCRanges(pdso);
378 // rt_loadLibrary will run tls ctors, so do this only for dlopen
379 immutable runTlsCtors = !_rtLoading;
380 runModuleConstructors(pdso, runTlsCtors);
383 // has backlink => unregister
386 DSO* pdso = cast(DSO*)*data._slot;
389 // don't finalizes modules after rt_term was called (see Bugzilla 11378)
390 if (_isRuntimeInitialized)
392 // rt_unloadLibrary already ran tls dtors, so do this only for dlclose
393 immutable runTlsDtors = !_rtLoading;
394 runModuleDestructors(pdso, runTlsDtors);
395 unregisterGCRanges(pdso);
396 // run finalizers after module dtors (same order as in rt_term)
397 version (Shared) runFinalizers(pdso);
404 /* This DSO was not unloaded by rt_unloadLibrary so we
405 * have to remove it from _loadedDSOs here.
407 foreach (i, ref tdso; _loadedDSOs)
409 if (tdso._pdso == pdso)
411 _loadedDSOs.remove(i);
417 unsetDSOForHandle(pdso, pdso._handle);
421 // static DSOs are unloaded in reverse order
422 safeAssert(pdso == _loadedDSOs.back, "DSO being unregistered isn't current last one.");
423 _loadedDSOs.popBack();
428 // last DSO being unloaded => shutdown registry
429 if (_loadedDSOs.empty)
435 safeAssert(_handleToDSO.empty, "_handleToDSO not in sync with _loadedDSOs.");
436 _handleToDSO.reset();
443 ///////////////////////////////////////////////////////////////////////////////
445 ///////////////////////////////////////////////////////////////////////////////
447 // Shared D libraries are only supported when linking against a shared druntime library.
451 ThreadDSO* findThreadDSO(DSO* pdso) nothrow @nogc
453 foreach (ref tdata; _loadedDSOs)
454 if (tdata._pdso == pdso) return &tdata;
458 void incThreadRef(DSO* pdso, bool incAdd)
460 if (auto tdata = findThreadDSO(pdso)) // already initialized
462 if (incAdd && ++tdata._addCnt > 1) return;
467 foreach (dep; pdso._deps)
468 incThreadRef(dep, false);
469 immutable ushort refCnt = 1, addCnt = incAdd ? 1 : 0;
470 _loadedDSOs.insertBack(ThreadDSO(pdso, refCnt, addCnt));
471 pdso._moduleGroup.runTlsCtors();
475 void decThreadRef(DSO* pdso, bool decAdd)
477 auto tdata = findThreadDSO(pdso);
478 safeAssert(tdata !is null, "Failed to find thread DSO.");
479 safeAssert(!decAdd || tdata._addCnt > 0, "Mismatching rt_unloadLibrary call.");
481 if (decAdd && --tdata._addCnt > 0) return;
482 if (--tdata._refCnt > 0) return;
484 pdso._moduleGroup.runTlsDtors();
485 foreach (i, ref td; _loadedDSOs)
486 if (td._pdso == pdso) _loadedDSOs.remove(i);
487 foreach (dep; pdso._deps)
488 decThreadRef(dep, false);
492 /***********************************
493 * These are a temporary means of providing a GC hook for DLL use. They may be
494 * replaced with some other similar functionality later.
499 void gc_setProxy(void* p);
502 alias void function(void*) gcSetFn;
503 alias void function() gcClrFn;
506 /*******************************************
507 * Loads a DLL written in D with the name 'name'.
509 * opaque handle to the DLL if successfully loaded
512 extern(C) void* rt_loadLibrary(const char* name)
516 immutable save = _rtLoading;
518 scope (exit) _rtLoading = save;
520 return initLibrary(.LoadLibraryA(name));
523 extern (C) void* rt_loadLibraryW(const wchar_t* name)
527 immutable save = _rtLoading;
529 scope (exit) _rtLoading = save;
531 return initLibrary(.LoadLibraryW(name));
534 void* initLibrary(void* handle)
541 // if it's a D library
542 if (auto pdso = dsoForHandle(handle))
543 incThreadRef(pdso, true);
545 gcSetFn gcSet = cast(gcSetFn) GetProcAddress(handle, "gc_setProxy");
548 // BUG: Set proxy, but too late
549 gcSet(gc_getProxy());
554 /*************************************
555 * Unloads DLL that was previously loaded by rt_loadLibrary().
557 * handle the handle returned by rt_loadLibrary()
560 * 0 some failure happened
562 extern(C) int rt_unloadLibrary(void* handle)
569 immutable save = _rtLoading;
571 scope (exit) _rtLoading = save;
573 // if it's a D library
574 if (auto pdso = dsoForHandle(handle))
575 decThreadRef(pdso, true);
577 gcClrFn gcClr = cast(gcClrFn) GetProcAddress(handle, "gc_clrProxy");
580 return .FreeLibrary(handle) != 0;
583 ///////////////////////////////////////////////////////////////////////////////
585 ///////////////////////////////////////////////////////////////////////////////
587 void initLocks() nothrow @nogc
590 InitializeCriticalSection(&_handleToDSOMutex);
593 void finiLocks() nothrow @nogc
596 DeleteCriticalSection(&_handleToDSOMutex);
599 void runModuleConstructors(DSO* pdso, bool runTlsCtors)
601 pdso._moduleGroup.sortCtors();
602 pdso._moduleGroup.runCtors();
603 if (runTlsCtors) pdso._moduleGroup.runTlsCtors();
606 void runModuleDestructors(DSO* pdso, bool runTlsDtors)
608 if (runTlsDtors) pdso._moduleGroup.runTlsDtors();
609 pdso._moduleGroup.runDtors();
612 void registerGCRanges(DSO* pdso) nothrow @nogc
614 foreach (rng; pdso._gcRanges)
615 GC.addRange(rng.ptr, rng.length);
618 void unregisterGCRanges(DSO* pdso) nothrow @nogc
620 foreach (rng; pdso._gcRanges)
621 GC.removeRange(rng.ptr);
624 version (Shared) void runFinalizers(DSO* pdso)
626 foreach (seg; pdso._codeSegments)
627 GC.runFinalizers(seg);
630 void freeDSO(DSO* pdso) nothrow @nogc
632 pdso._gcRanges.reset();
635 pdso._codeSegments.reset();
645 const(char)* nameForDSO(DSO* pdso, ref char[] buffer)
647 const success = GetModuleFileNameA(pdso._handle, buffer.ptr, cast(DWORD)buffer.length) != 0;
648 safeAssert(success, "Failed to get DLL name.");
652 DSO* dsoForHandle(in void* handle)
655 .EnterCriticalSection(&_handleToDSOMutex);
656 if (auto ppdso = handle in _handleToDSO)
658 .LeaveCriticalSection(&_handleToDSOMutex);
662 void setDSOForHandle(DSO* pdso, void* handle)
664 .EnterCriticalSection(&_handleToDSOMutex);
665 safeAssert(handle !in _handleToDSO, "DSO already registered.");
666 _handleToDSO[handle] = pdso;
667 .LeaveCriticalSection(&_handleToDSOMutex);
670 void unsetDSOForHandle(DSO* pdso, void* handle)
672 .EnterCriticalSection(&_handleToDSOMutex);
673 safeAssert(_handleToDSO[handle] == pdso, "Handle doesn't match registered DSO.");
674 _handleToDSO.remove(handle);
675 .LeaveCriticalSection(&_handleToDSOMutex);
678 void getDependencies(in HMODULE handle, ref Array!(DSO*) deps)
680 auto nthdr = getNTHeader(handle);
681 auto import_entry = nthdr.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
682 auto addr = import_entry.VirtualAddress;
683 auto datasize = import_entry.Size;
685 if (addr == 0 && datasize == 0)
687 // Maybe the optional header isn't there, look for the section.
688 foreach (section; getSectionHeader(handle))
690 if (!compareSectionName(section, ".idata"))
692 addr = section.VirtualAddress;
693 datasize = section.Misc.VirtualSize;
701 bool foundSection = false;
702 foreach (section; getSectionHeader(handle))
704 if (!compareSectionName(section, ".idata"))
706 // Section containing import table has no contents.
707 if (section.Misc.VirtualSize == 0)
712 // There is an import table, but the section containing it could not be found
717 // Get the names of each DLL
718 for (uint i = 0; i + IMAGE_IMPORT_DESCRIPTOR.sizeof <= datasize;
719 i += IMAGE_IMPORT_DESCRIPTOR.sizeof)
721 const data = cast(PIMAGE_IMPORT_DESCRIPTOR)(handle + addr + i);
725 // dll name of dependency
726 auto name = cast(char*)(handle + data.Name);
727 // get handle without loading the library
728 auto libhandle = handleForName(name);
729 // the runtime linker has already loaded all dependencies
730 safeAssert(handle !is null, "Failed to get library handle.");
731 // if it's a D library
732 if (auto pdso = dsoForHandle(handle))
733 deps.insertBack(pdso); // append it to the dependencies
737 void* handleForName(const char* name)
739 return GetModuleHandleA(name);
743 ///////////////////////////////////////////////////////////////////////////////
744 // PE/COFF program header iteration
745 ///////////////////////////////////////////////////////////////////////////////
747 bool compareSectionName(ref IMAGE_SECTION_HEADER section, string name) nothrow @nogc
749 if (name[] != cast(char[])section.Name[0 .. name.length])
751 return name.length == 8 || section.Name[name.length] == 0;
755 * Scan segments in the image header and store
756 * the writeable data segments in *pdso.
759 void scanSegments(in HMODULE handle, DSO* pdso) nothrow @nogc
761 foreach (section; getSectionHeader(handle))
763 // the ".data" image section includes both object file sections ".data" and ".bss"
764 if (compareSectionName(section, ".data"))
766 auto data = cast(void*)handle + section.VirtualAddress;
767 pdso._gcRanges.insertBack(data[0 .. section.Misc.VirtualSize]);
773 if (compareSectionName(section, ".text"))
775 auto text = cast(void*)handle + section.VirtualAddress;
776 pdso._codeSegments.insertBack(text[0 .. section.Misc.VirtualSize]);
783 /**************************
785 * handle where the output is to be written
787 * true if found, and *handle is filled in
790 bool findModuleHandleForAddr(in void* addr, out HMODULE handle) nothrow @nogc
792 if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
793 cast(const(wchar)*) addr, &handle))
800 * Returns the image NT header for the HMODULE handle passed,
801 * or null if not found.
803 PIMAGE_NT_HEADERS getNTHeader(in HMODULE handle) nothrow @nogc
805 auto doshdr = cast(PIMAGE_DOS_HEADER)handle;
806 if (doshdr.e_magic != IMAGE_DOS_SIGNATURE)
809 return cast(typeof(return))(cast(void*)doshdr + doshdr.e_lfanew);
813 * Returns the image section header for the HMODULE handle passed,
814 * or null if not found.
816 IMAGE_SECTION_HEADER[] getSectionHeader(in HMODULE handle) nothrow @nogc
818 if (auto nthdr = getNTHeader(handle))
820 const void* opthdr = &nthdr.OptionalHeader;
821 const offset = nthdr.FileHeader.SizeOfOptionalHeader;
822 const length = nthdr.FileHeader.NumberOfSections;
823 return (cast(PIMAGE_SECTION_HEADER)(opthdr + offset))[0 .. length];