Debian Codegraph @

libphobos/libdruntime/gcc/sections/pecoff.d

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