Debian Codegraph @

libphobos/libdruntime/core/runtime.d

raw
1 /**
2 * The runtime module exposes information specific to the D runtime code.
3 *
4 * Copyright: Copyright Sean Kelly 2005 - 2009.
5 * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
6 * Authors: Sean Kelly
7 * Source: $(DRUNTIMESRC core/_runtime.d)
8 * Documentation: https://dlang.org/phobos/core_runtime.html
9 */
10
11 /* NOTE: This file has been patched from the original DMD distribution to
12 * work with the GDC compiler.
13 */
14 module core.runtime;
15
16 version (OSX)
17 version = Darwin;
18 else version (iOS)
19 version = Darwin;
20 else version (TVOS)
21 version = Darwin;
22 else version (WatchOS)
23 version = Darwin;
24
25 version (GNU)
26 {
27 import gcc.backtrace;
28 // This shouldn't be necessary but ensure that code doesn't get mixed
29 // It does however prevent the unittest SEGV handler to be installed,
30 // which is desireable as it uses backtrace directly.
31 private enum hasExecinfo = false;
32 version = LibBacktrace_TraceHandler;
33 }
34 else version (DRuntime_Use_Libunwind)
35 {
36 version = DefineBacktrace_using_UnwindBacktrace;
37
38 // This shouldn't be necessary but ensure that code doesn't get mixed
39 // It does however prevent the unittest SEGV handler to be installed,
40 // which is desireable as it uses backtrace directly.
41 private enum hasExecinfo = false;
42 }
43 else
44 import core.internal.execinfo;
45
46 /// C interface for Runtime.loadLibrary
47 extern (C) void* rt_loadLibrary(const char* name);
48 /// ditto
49 version (Windows) extern (C) void* rt_loadLibraryW(const wchar* name);
50
51 /// C interface for Runtime.unloadLibrary, returns 1/0 instead of bool
52 extern (C) int rt_unloadLibrary(void* ptr);
53
54 /// C interface for Runtime.initialize, returns 1/0 instead of bool
55 extern(C) int rt_init();
56 /// C interface for Runtime.terminate, returns 1/0 instead of bool
57 extern(C) int rt_term();
58
59 /**
60 * This type is returned by the module unit test handler to indicate testing
61 * results.
62 */
63 struct UnitTestResult
64 {
65 /**
66 * Number of modules which were tested
67 */
68 size_t executed;
69
70 /**
71 * Number of modules passed the unittests
72 */
73 size_t passed;
74
75 /**
76 * Should the main function be run or not? This is ignored if any tests
77 * failed.
78 */
79 bool runMain;
80
81 /**
82 * Should we print a summary of the results?
83 */
84 bool summarize;
85
86 /**
87 * Simple check for whether execution should continue after unit tests
88 * have been run. Works with legacy code that expected a bool return.
89 *
90 * Returns:
91 * true if execution should continue after testing is complete, false if
92 * not.
93 */
94 bool opCast(T : bool)() const
95 {
96 return runMain && (executed == passed);
97 }
98
99 /// Simple return code that says unit tests pass, and main should be run
100 enum UnitTestResult pass = UnitTestResult(0, 0, true, false);
101 /// Simple return code that says unit tests failed.
102 enum UnitTestResult fail = UnitTestResult(1, 0, false, false);
103 }
104
105 /// Legacy module unit test handler
106 alias ModuleUnitTester = bool function();
107 /// Module unit test handler
108 alias ExtendedModuleUnitTester = UnitTestResult function();
109 private
110 {
111 alias CollectHandler = bool function(Object);
112 alias TraceHandler = Throwable.TraceInfo function(void* ptr);
113
114 alias ExceptionHandler = void delegate(Throwable);
115 extern (C) void _d_print_throwable(Throwable t);
116
117 extern (C) void* thread_stackBottom() nothrow @nogc;
118 }
119
120
121 shared static this()
122 {
123 // NOTE: Some module ctors will run before this handler is set, so it's
124 // still possible the app could exit without a stack trace. If
125 // this becomes an issue, the handler could be set in C main
126 // before the module ctors are run.
127 Runtime.traceHandler(&defaultTraceHandler, &defaultTraceDeallocator);
128 }
129
130
131 ///////////////////////////////////////////////////////////////////////////////
132 // Runtime
133 ///////////////////////////////////////////////////////////////////////////////
134
135 /**
136 * Stores the unprocessed arguments supplied when the
137 * process was started.
138 */
139 struct CArgs
140 {
141 int argc; /// The argument count.
142 char** argv; /// The arguments as a C array of strings.
143 }
144
145 /**
146 * This struct encapsulates all functionality related to the underlying runtime
147 * module for the calling context.
148 */
149 struct Runtime
150 {
151 /**
152 * Initializes the runtime. This call is to be used in instances where the
153 * standard program initialization process is not executed. This is most
154 * often in shared libraries or in libraries linked to a C program.
155 * If the runtime was already successfully initialized this returns true.
156 * Each call to initialize must be paired by a call to $(LREF terminate).
157 *
158 * Returns:
159 * true if initialization succeeded or false if initialization failed.
160 */
161 static bool initialize()
162 {
163 return !!rt_init();
164 }
165
166 /**
167 * Terminates the runtime. This call is to be used in instances where the
168 * standard program termination process will not be not executed. This is
169 * most often in shared libraries or in libraries linked to a C program.
170 * If the runtime was not successfully initialized the function returns false.
171 *
172 * Returns:
173 * true if termination succeeded or false if termination failed.
174 */
175 static bool terminate()
176 {
177 return !!rt_term();
178 }
179
180 /**
181 * Returns the arguments supplied when the process was started.
182 *
183 * Returns:
184 * The arguments supplied when this process was started.
185 */
186 extern(C) pragma(mangle, "rt_args") static @property string[] args();
187
188 /**
189 * Returns the unprocessed C arguments supplied when the process was started.
190 * Use this when you need to supply argc and argv to C libraries.
191 *
192 * Returns:
193 * A $(LREF CArgs) struct with the arguments supplied when this process was started.
194 *
195 * Example:
196 * ---
197 * import core.runtime;
198 *
199 * // A C library function requiring char** arguments
200 * extern(C) void initLibFoo(int argc, char** argv);
201 *
202 * void main()
203 * {
204 * auto args = Runtime.cArgs;
205 * initLibFoo(args.argc, args.argv);
206 * }
207 * ---
208 */
209 extern(C) pragma(mangle, "rt_cArgs") static @property CArgs cArgs() @nogc;
210
211 /**
212 * Locates a dynamic library with the supplied library name and dynamically
213 * loads it into the caller's address space. If the library contains a D
214 * runtime it will be integrated with the current runtime.
215 *
216 * Params:
217 * name = The name of the dynamic library to load.
218 *
219 * Returns:
220 * A reference to the library or null on error.
221 */
222 static void* loadLibrary()(const scope char[] name)
223 {
224 import core.stdc.stdlib : free, malloc;
225 version (Windows)
226 {
227 import core.sys.windows.winnls : CP_UTF8, MultiByteToWideChar;
228 import core.sys.windows.winnt : WCHAR;
229
230 if (name.length == 0) return null;
231 // Load a DLL at runtime
232 auto len = MultiByteToWideChar(
233 CP_UTF8, 0, name.ptr, cast(int)name.length, null, 0);
234 if (len == 0)
235 return null;
236
237 auto buf = cast(WCHAR*)malloc((len+1) * WCHAR.sizeof);
238 if (buf is null) return null;
239 scope (exit) free(buf);
240
241 len = MultiByteToWideChar(
242 CP_UTF8, 0, name.ptr, cast(int)name.length, buf, len);
243 if (len == 0)
244 return null;
245
246 buf[len] = '\0';
247
248 return rt_loadLibraryW(buf);
249 }
250 else version (Posix)
251 {
252 /* Need a 0-terminated C string for the dll name
253 */
254 immutable len = name.length;
255 auto buf = cast(char*)malloc(len + 1);
256 if (!buf) return null;
257 scope (exit) free(buf);
258
259 buf[0 .. len] = name[];
260 buf[len] = 0;
261
262 return rt_loadLibrary(buf);
263 }
264 }
265
266
267 /**
268 * Unloads the dynamic library referenced by p. If this library contains a
269 * D runtime then any necessary finalization or cleanup of that runtime
270 * will be performed.
271 *
272 * Params:
273 * p = A reference to the library to unload.
274 */
275 static bool unloadLibrary()(void* p)
276 {
277 return !!rt_unloadLibrary(p);
278 }
279
280
281 /**
282 * Overrides the default trace mechanism with a user-supplied version. A
283 * trace represents the context from which an exception was thrown, and the
284 * trace handler will be called when this occurs. The pointer supplied to
285 * this routine indicates the base address from which tracing should occur.
286 * If the supplied pointer is null then the trace routine should determine
287 * an appropriate calling context from which to begin the trace.
288 *
289 * If the deallocator is set, then it is called with the traceinfo when the
290 * exception is finalized. The deallocator is only set in the exception if
291 * the default handler is used to generate the trace info.
292 *
293 * Params:
294 * h = The new trace handler. Set to null to disable exception backtracing.
295 * d = The new trace deallocator. If non-null, this will be called on
296 * exception destruction with the trace info, only when the trace
297 * handler is used to generate TraceInfo.
298 */
299 extern(C) pragma(mangle, "rt_setTraceHandler") static @property void traceHandler(TraceHandler h,
300 Throwable.TraceDeallocator d = null);
301
302 /**
303 * Gets the current trace handler.
304 *
305 * Returns:
306 * The current trace handler or null if none has been set.
307 */
308 extern(C) pragma(mangle, "rt_getTraceHandler") static @property TraceHandler traceHandler();
309
310 /**
311 * Gets the current trace deallocator.
312 *
313 * Returns:
314 * The current trace deallocator or null if none has been set.
315 */
316 extern(C) pragma(mangle, "rt_getTraceDeallocator") static @property Throwable.TraceDeallocator traceDeallocator();
317
318 /**
319 * Overrides the default collect hander with a user-supplied version. This
320 * routine will be called for each resource object that is finalized in a
321 * non-deterministic manner--typically during a garbage collection cycle.
322 * If the supplied routine returns true then the object's dtor will called
323 * as normal, but if the routine returns false than the dtor will not be
324 * called. The default behavior is for all object dtors to be called.
325 *
326 * Params:
327 * h = The new collect handler. Set to null to use the default handler.
328 */
329 extern(C) pragma(mangle, "rt_setCollectHandler") static @property void collectHandler( CollectHandler h );
330
331
332 /**
333 * Gets the current collect handler.
334 *
335 * Returns:
336 * The current collect handler or null if none has been set.
337 */
338 extern(C) pragma(mangle, "rt_getCollectHandler") static @property CollectHandler collectHandler();
339
340
341 /**
342 * Overrides the default module unit tester with a user-supplied version.
343 * This routine will be called once on program initialization. The return
344 * value of this routine indicates to the runtime whether the tests ran
345 * without error.
346 *
347 * There are two options for handlers. The `bool` version is deprecated but
348 * will be kept for legacy support. Returning `true` from the handler is
349 * equivalent to returning `UnitTestResult.pass` from the extended version.
350 * Returning `false` from the handler is equivalent to returning
351 * `UnitTestResult.fail` from the extended version.
352 *
353 * See the documentation for `UnitTestResult` to see how you should set up
354 * the return structure.
355 *
356 * See the documentation for `runModuleUnitTests` for how the default
357 * algorithm works, or read the example below.
358 *
359 * Params:
360 * h = The new unit tester. Set both to null to use the default unit
361 * tester.
362 *
363 * Example:
364 * ---------
365 * shared static this()
366 * {
367 * import core.runtime;
368 *
369 * Runtime.extendedModuleUnitTester = &customModuleUnitTester;
370 * }
371 *
372 * UnitTestResult customModuleUnitTester()
373 * {
374 * import std.stdio;
375 *
376 * writeln("Using customModuleUnitTester");
377 *
378 * // Do the same thing as the default moduleUnitTester:
379 * UnitTestResult result;
380 * foreach (m; ModuleInfo)
381 * {
382 * if (m)
383 * {
384 * auto fp = m.unitTest;
385 *
386 * if (fp)
387 * {
388 * ++result.executed;
389 * try
390 * {
391 * fp();
392 * ++result.passed;
393 * }
394 * catch (Throwable e)
395 * {
396 * writeln(e);
397 * }
398 * }
399 * }
400 * }
401 * if (result.executed != result.passed)
402 * {
403 * result.runMain = false; // don't run main
404 * result.summarize = true; // print failure
405 * }
406 * else
407 * {
408 * result.runMain = true; // all UT passed
409 * result.summarize = false; // be quiet about it.
410 * }
411 * return result;
412 * }
413 * ---------
414 */
415 static @property void extendedModuleUnitTester( ExtendedModuleUnitTester h )
416 {
417 sm_extModuleUnitTester = h;
418 }
419
420 /// Ditto
421 static @property void moduleUnitTester( ModuleUnitTester h )
422 {
423 sm_moduleUnitTester = h;
424 }
425
426 /**
427 * Gets the current legacy module unit tester.
428 *
429 * This property should not be used, but is supported for legacy purposes.
430 *
431 * Note that if the extended unit test handler is set, this handler will
432 * be ignored.
433 *
434 * Returns:
435 * The current legacy module unit tester handler or null if none has been
436 * set.
437 */
438 static @property ModuleUnitTester moduleUnitTester()
439 {
440 return sm_moduleUnitTester;
441 }
442
443 /**
444 * Gets the current module unit tester.
445 *
446 * This handler overrides any legacy module unit tester set by the
447 * moduleUnitTester property.
448 *
449 * Returns:
450 * The current module unit tester handler or null if none has been
451 * set.
452 */
453 static @property ExtendedModuleUnitTester extendedModuleUnitTester()
454 {
455 return sm_extModuleUnitTester;
456 }
457
458 private:
459
460 // NOTE: This field will only ever be set in a static ctor and should
461 // never occur within any but the main thread, so it is safe to
462 // make it __gshared.
463 __gshared ExtendedModuleUnitTester sm_extModuleUnitTester = null;
464 __gshared ModuleUnitTester sm_moduleUnitTester = null;
465 }
466
467 /**
468 * Set source file path for coverage reports.
469 *
470 * Params:
471 * path = The new path name.
472 * Note:
473 * This is a dmd specific setting.
474 */
475 extern (C) void dmd_coverSourcePath(string path);
476
477 /**
478 * Set output path for coverage reports.
479 *
480 * Params:
481 * path = The new path name.
482 * Note:
483 * This is a dmd specific setting.
484 */
485 extern (C) void dmd_coverDestPath(string path);
486
487 /**
488 * Enable merging of coverage reports with existing data.
489 *
490 * Params:
491 * flag = enable/disable coverage merge mode
492 * Note:
493 * This is a dmd specific setting.
494 */
495 extern (C) void dmd_coverSetMerge(bool flag);
496
497 /**
498 * Set the output file name for profile reports (-profile switch).
499 * An empty name will set the output to stdout.
500 *
501 * Params:
502 * name = file name
503 * Note:
504 * This is a dmd specific setting.
505 */
506 extern (C) void trace_setlogfilename(string name);
507
508 /**
509 * Set the output file name for the optimized profile linker DEF file (-profile switch).
510 * An empty name will set the output to stdout.
511 *
512 * Params:
513 * name = file name
514 * Note:
515 * This is a dmd specific setting.
516 */
517 extern (C) void trace_setdeffilename(string name);
518
519 /**
520 * Set the output file name for memory profile reports (-profile=gc switch).
521 * An empty name will set the output to stdout.
522 *
523 * Params:
524 * name = file name
525 * Note:
526 * This is a dmd specific setting.
527 */
528 extern (C) void profilegc_setlogfilename(string name);
529
530 ///////////////////////////////////////////////////////////////////////////////
531 // Overridable Callbacks
532 ///////////////////////////////////////////////////////////////////////////////
533
534
535 /**
536 * This routine is called by the runtime to run module unit tests on startup.
537 * The user-supplied unit tester will be called if one has been set,
538 * otherwise all unit tests will be run in sequence.
539 *
540 * If the extended unittest handler is registered, this function returns the
541 * result from that handler directly.
542 *
543 * If a legacy boolean returning custom handler is used, `false` maps to
544 * `UnitTestResult.fail`, and `true` maps to `UnitTestResult.pass`. This was
545 * the original behavior of the unit testing system.
546 *
547 * If no unittest custom handlers are registered, the following algorithm is
548 * executed (the behavior can be affected by the `--DRT-testmode` switch
549 * below):
550 * 1. Execute any unittests present. For each that fails, print the stack
551 * trace and continue.
552 * 2. If no unittests were present, set summarize to false, and runMain to
553 * true.
554 * 3. Otherwise, set summarize to true, and runMain to false.
555 *
556 * See the documentation for `UnitTestResult` for details on how the runtime
557 * treats the return value from this function.
558 *
559 * If the switch `--DRT-testmode` is passed to the executable, it can have
560 * one of 3 values:
561 * 1. "run-main": even if unit tests are run (and all pass), runMain is set
562 to true.
563 * 2. "test-or-main": any unit tests present will cause the program to
564 * summarize the results and exit regardless of the result. This is the
565 * default.
566 * 3. "test-only", runMain is set to false, even with no tests present.
567 *
568 * This command-line parameter does not affect custom unit test handlers.
569 *
570 * Returns:
571 * A `UnitTestResult` struct indicating the result of running unit tests.
572 */
573 extern (C) UnitTestResult runModuleUnitTests()
574 {
575 version (Windows)
576 import core.sys.windows.stacktrace;
577
578 static if (__traits(compiles, new LibBacktrace(0)))
579 {
580 // segv handler
581 import core.sys.posix.signal : SA_RESETHAND, SA_SIGINFO, sigaction, sigaction_t, SIGBUS, sigfillset, siginfo_t,
582 SIGSEGV;
583
584 static extern (C) void unittestSegvHandler(int signum, siginfo_t* info, void* ptr)
585 {
586 import core.stdc.stdio;
587 fprintf(stderr, "Segmentation fault while running unittests:\n");
588 fprintf(stderr, "----------------\n");
589
590 // First frame is LibBacktrace ctor. Second is signal handler,
591 // but include that for now
592 scope bt = new LibBacktrace(1);
593
594 foreach (size_t i, const(char[]) msg; bt)
595 fprintf(stderr, "%s\n", msg.ptr ? msg.ptr : "???");
596 }
597
598 sigaction_t action = void;
599 sigaction_t oldseg = void;
600 sigaction_t oldbus = void;
601
602 (cast(byte*) &action)[0 .. action.sizeof] = 0;
603 sigfillset(&action.sa_mask); // block other signals
604 action.sa_flags = SA_SIGINFO | SA_RESETHAND;
605 action.sa_sigaction = &unittestSegvHandler;
606 sigaction(SIGSEGV, &action, &oldseg);
607 sigaction(SIGBUS, &action, &oldbus);
608 scope (exit)
609 {
610 sigaction(SIGSEGV, &oldseg, null);
611 sigaction(SIGBUS, &oldbus, null);
612 }
613 }
614 else static if (hasExecinfo)
615 {
616 // segv handler
617 import core.sys.posix.signal : SA_RESETHAND, SA_SIGINFO, sigaction, sigaction_t, SIGBUS, sigfillset, siginfo_t,
618 SIGSEGV;
619
620 static extern (C) void unittestSegvHandler( int signum, siginfo_t* info, void* ptr ) nothrow
621 {
622 enum MAXFRAMES = 128;
623 void*[MAXFRAMES] callstack;
624
625 auto numframes = backtrace( callstack.ptr, MAXFRAMES );
626 backtrace_symbols_fd( callstack.ptr, numframes, 2 );
627 }
628
629 sigaction_t action = void;
630 sigaction_t oldseg = void;
631 sigaction_t oldbus = void;
632
633 (cast(byte*) &action)[0 .. action.sizeof] = 0;
634 sigfillset( &action.sa_mask ); // block other signals
635 action.sa_flags = SA_SIGINFO | SA_RESETHAND;
636 action.sa_sigaction = &unittestSegvHandler;
637 sigaction( SIGSEGV, &action, &oldseg );
638 sigaction( SIGBUS, &action, &oldbus );
639 scope( exit )
640 {
641 sigaction( SIGSEGV, &oldseg, null );
642 sigaction( SIGBUS, &oldbus, null );
643 }
644 }
645
646 if (Runtime.sm_extModuleUnitTester !is null)
647 return Runtime.sm_extModuleUnitTester();
648 else if (Runtime.sm_moduleUnitTester !is null)
649 return Runtime.sm_moduleUnitTester() ? UnitTestResult.pass : UnitTestResult.fail;
650 UnitTestResult results;
651 foreach ( m; ModuleInfo )
652 {
653 if ( !m )
654 continue;
655 auto fp = m.unitTest;
656 if ( !fp )
657 continue;
658
659 import core.exception;
660 ++results.executed;
661 try
662 {
663 fp();
664 ++results.passed;
665 }
666 catch ( Throwable e )
667 {
668 if ( typeid(e) == typeid(AssertError) )
669 {
670 // Crude heuristic to figure whether the assertion originates in
671 // the unittested module. TODO: improve.
672 auto moduleName = m.name;
673 if (moduleName.length && e.file.length > moduleName.length
674 && e.file[0 .. moduleName.length] == moduleName)
675 {
676 import core.stdc.stdio : printf;
677 printf("%.*s(%llu): [unittest] %.*s\n",
678 cast(int) e.file.length, e.file.ptr, cast(ulong) e.line,
679 cast(int) e.message.length, e.message.ptr);
680
681 // Exception originates in the same module, don't print
682 // the stack trace.
683 // TODO: omit stack trace only if assert was thrown
684 // directly by the unittest.
685 continue;
686 }
687 }
688 // TODO: perhaps indent all of this stuff.
689 _d_print_throwable(e);
690 }
691 }
692
693 import core.internal.parseoptions : rt_configOption;
694
695 if (results.passed != results.executed)
696 {
697 // by default, we always print a summary if there are failures.
698 results.summarize = true;
699 }
700 else switch (rt_configOption("testmode", null, false))
701 {
702 case "run-main":
703 results.runMain = true;
704 break;
705 case "test-only":
706 // Never run main, always summarize
707 results.summarize = true;
708 break;
709 case "":
710 // By default, do not run main if tests are present.
711 case "test-or-main":
712 // only run main if there were no tests. Only summarize if we are not
713 // running main.
714 results.runMain = (results.executed == 0);
715 results.summarize = !results.runMain;
716 break;
717 default:
718 assert(0, "Unknown --DRT-testmode option: " ~ rt_configOption("testmode", null, false));
719 }
720
721 return results;
722 }
723
724 version (DefineBacktrace_using_UnwindBacktrace)
725 {
726 import core.internal.backtrace.unwind;
727
728 private int backtrace(void** buffer, int maxSize) nothrow
729 {
730 if (maxSize < 0) return 0;
731
732 struct State
733 {
734 void** buffer;
735 int maxSize;
736 int entriesWritten = 0;
737 }
738
739 static extern(C) int handler(_Unwind_Context* context, void* statePtr)
740 {
741 auto state = cast(State*)statePtr;
742 if (state.entriesWritten >= state.maxSize) return _URC_END_OF_STACK;
743
744 auto instructionPtr = _Unwind_GetIP(context);
745 if (!instructionPtr) return _URC_END_OF_STACK;
746
747 state.buffer[state.entriesWritten] = cast(void*)instructionPtr;
748 ++state.entriesWritten;
749
750 return _URC_NO_REASON;
751 }
752
753 State state;
754 state.buffer = buffer;
755 state.maxSize = maxSize;
756 _Unwind_Backtrace(&handler, &state);
757
758 return state.entriesWritten;
759 }
760 }
761
762 /**
763 * Get the default `Throwable.TraceInfo` implementation for the platform
764 *
765 * This functions returns a trace handler, allowing to inspect the
766 * current stack trace.
767 *
768 * IMPORTANT NOTE! the returned trace is potentially not GC allocated, and so
769 * you must call `defaultTraceDeallocator` when you are finished with the
770 * `TraceInfo`
771 *
772 * Params:
773 * ptr = (Windows only) The context to get the stack trace from.
774 * When `null` (the default), start from the current frame.
775 *
776 * Returns:
777 * A `Throwable.TraceInfo` implementation suitable to iterate over the stack,
778 * or `null`. If called from a finalizer (destructor), always returns `null`
779 * as trace handlers allocate.
780 */
781 Throwable.TraceInfo defaultTraceHandler( void* ptr = null ) // @nogc
782 {
783 // NOTE: with traces now being allocated using C malloc, no need to worry
784 // about GC reentrancy. This code left commented out for reference.
785 //
786 // avoid recursive GC calls in finalizer, trace handlers should be made @nogc instead
787 /*import core.memory : GC;
788 if (GC.inFinalizer)
789 return null;*/
790
791 static T allocate(T, Args...)(auto ref Args args) @nogc
792 {
793 import core.lifetime : emplace;
794 import core.stdc.stdlib : malloc;
795 auto result = cast(T)malloc(__traits(classInstanceSize, T));
796 return emplace(result, args);
797 }
798 static if (__traits(compiles, allocate!LibBacktrace(0)))
799 {
800 version (Posix)
801 static enum FIRSTFRAME = 4;
802 else version (Win64)
803 static enum FIRSTFRAME = 4;
804 else
805 static enum FIRSTFRAME = 0;
806 return allocate!LibBacktrace(FIRSTFRAME);
807 }
808 else static if (__traits(compiles, allocate!UnwindBacktrace(0)))
809 {
810 version (Posix)
811 static enum FIRSTFRAME = 5;
812 else version (Win64)
813 static enum FIRSTFRAME = 4;
814 else
815 static enum FIRSTFRAME = 0;
816 return allocate!UnwindBacktrace(FIRSTFRAME);
817 }
818 else version (Windows)
819 {
820 import core.sys.windows.stacktrace;
821 static if (__traits(compiles, allocate!StackTrace(0, null)))
822 {
823 import core.sys.windows.winnt : CONTEXT;
824 version (Win64)
825 enum FIRSTFRAME = 4;
826 else version (Win32)
827 enum FIRSTFRAME = 0;
828 return allocate!StackTrace(FIRSTFRAME, cast(CONTEXT*)ptr);
829 }
830 else
831 return null;
832 }
833 else static if (__traits(compiles, allocate!DefaultTraceInfo()))
834 return allocate!DefaultTraceInfo();
835 else
836 return null;
837 }
838
839 /// Example of a simple program printing its stack trace
840 unittest
841 {
842 import core.runtime;
843 import core.stdc.stdio : printf;
844
845 void main()
846 {
847 auto trace = defaultTraceHandler(null);
848 foreach (line; trace)
849 {
850 printf("%.*s\n", cast(int)line.length, line.ptr);
851 }
852 defaultTraceDeallocator(trace);
853 }
854 }
855
856 /***
857 * Deallocate a traceinfo generated by deaultTraceHander.
858 *
859 * Call this function on a TraceInfo generated via `defaultTraceHandler` when
860 * you are done with it. If necessary, this cleans up any manually managed
861 * resources from the `TraceInfo`, and invalidates it. After this, the object
862 * is no longer valid.
863 *
864 * Params:
865 * info = The `TraceInfo` to deallocate. This should only be a value that
866 * was returned by `defaultTraceHandler`.
867 */
868 void defaultTraceDeallocator(Throwable.TraceInfo info) nothrow
869 {
870 if (info is null)
871 return;
872 auto obj = cast(Object)info;
873 destroy(obj);
874 import core.stdc.stdlib : free;
875 free(cast(void *)obj);
876 }
877
878 version (LibBacktrace_TraceHandler)
879 {
880 }
881 /// Default implementation for most POSIX systems
882 else version (Posix) private class DefaultTraceInfo : Throwable.TraceInfo
883 {
884 import core.demangle;
885 import core.stdc.stdlib : free;
886 import core.stdc.string : strlen, memchr, memmove;
887
888 this() @nogc
889 {
890 // it may not be 1 but it is good enough to get
891 // in CALL instruction address range for backtrace
892 enum CALL_INSTRUCTION_SIZE = 1;
893
894 static if (__traits(compiles, backtrace((void**).init, int.init)))
895 numframes = cast(int) backtrace(this.callstack.ptr, MAXFRAMES);
896 // Backtrace succeeded, adjust the frame to point to the caller
897 if (numframes >= 2)
898 foreach (ref elem; this.callstack)
899 elem -= CALL_INSTRUCTION_SIZE;
900 else // backtrace() failed, do it ourselves
901 {
902 static void** getBasePtr() @nogc
903 {
904 version (D_InlineAsm_X86)
905 asm @nogc { naked; mov EAX, EBP; ret; }
906 else
907 version (D_InlineAsm_X86_64)
908 asm @nogc { naked; mov RAX, RBP; ret; }
909 else
910 return null;
911 }
912
913 auto stackTop = getBasePtr();
914 auto stackBottom = cast(void**) thread_stackBottom();
915 void* dummy;
916
917 if ( stackTop && &dummy < stackTop && stackTop < stackBottom )
918 {
919 auto stackPtr = stackTop;
920
921 for ( numframes = 0; stackTop <= stackPtr &&
922 stackPtr < stackBottom &&
923 numframes < MAXFRAMES; )
924 {
925 callstack[numframes++] = *(stackPtr + 1) - CALL_INSTRUCTION_SIZE;
926 stackPtr = cast(void**) *stackPtr;
927 }
928 }
929 }
930 }
931
932 override int opApply( scope int delegate(ref const(char[])) dg ) const
933 {
934 return opApply( (ref size_t, ref const(char[]) buf)
935 {
936 return dg( buf );
937 } );
938 }
939
940 override int opApply( scope int delegate(ref size_t, ref const(char[])) dg ) const
941 {
942 version (linux) enum enableDwarf = true;
943 else version (FreeBSD) enum enableDwarf = true;
944 else version (DragonFlyBSD) enum enableDwarf = true;
945 else version (OpenBSD) enum enableDwarf = true;
946 else version (Darwin) enum enableDwarf = true;
947 else enum enableDwarf = false;
948
949 static if (hasExecinfo)
950 {
951 const framelist = backtrace_symbols( callstack.ptr, numframes );
952 scope(exit) free(cast(void*) framelist);
953
954 static if (enableDwarf)
955 {
956 import core.internal.backtrace.dwarf;
957 return traceHandlerOpApplyImpl(numframes,
958 i => callstack[i],
959 (i) { auto str = framelist[i][0 .. strlen(framelist[i])]; return getMangledSymbolName(str); },
960 dg);
961 }
962 else
963 {
964 int ret = 0;
965 for (size_t pos = 0; pos < numframes; ++pos)
966 {
967 char[4096] fixbuf = void;
968 auto buf = framelist[pos][0 .. strlen(framelist[pos])];
969 buf = fixline( buf, fixbuf );
970 ret = dg( pos, buf );
971 if ( ret )
972 break;
973 }
974 return ret;
975 }
976 }
977 else
978 {
979 // https://code.woboq.org/userspace/glibc/debug/backtracesyms.c.html
980 // The logic that glibc's backtrace use is to check for for `dli_fname`,
981 // the file name, and error if not present, then check for `dli_sname`.
982 // In case `dli_fname` is present but not `dli_sname`, the address is
983 // printed related to the file. We just print the file.
984 static const(char)[] getFrameName (const(void)* ptr)
985 {
986 import core.sys.posix.dlfcn;
987 Dl_info info = void;
988 // Note: See the module documentation about `-L--export-dynamic`
989 if (dladdr(ptr, &info))
990 {
991 // Return symbol name if possible
992 if (info.dli_sname !is null && info.dli_sname[0] != '\0')
993 return info.dli_sname[0 .. strlen(info.dli_sname)];
994
995 // Fall back to file name
996 if (info.dli_fname !is null && info.dli_fname[0] != '\0')
997 return info.dli_fname[0 .. strlen(info.dli_fname)];
998 }
999
1000 // `dladdr` failed
1001 return "<ERROR: Unable to retrieve function name>";
1002 }
1003
1004 static if (enableDwarf)
1005 {
1006 import core.internal.backtrace.dwarf;
1007 return traceHandlerOpApplyImpl(numframes,
1008 i => callstack[i],
1009 i => getFrameName(callstack[i]),
1010 dg);
1011 }
1012 else
1013 {
1014 // Poor man solution. Does not show line numbers, but does (potentially) show a backtrace of function names.
1015 import core.internal.container.array;
1016 Array!(const(char)[]) frameNames;
1017 frameNames.length = numframes;
1018 size_t startIdx;
1019 foreach (idx; 0 .. numframes)
1020 {
1021 frameNames[idx] = getFrameName(callstack[idx]);
1022
1023 // NOTE: The first few frames with the current implementation are
1024 // inside core.runtime and the object code, so eliminate
1025 // these for readability.
1026 // They also might depend on build parameters, which would make
1027 // using a fixed number of frames otherwise brittle.
1028 version (LDC) enum BaseExceptionFunctionName = "_d_throw_exception";
1029 else enum BaseExceptionFunctionName = "_d_throwdwarf";
1030 if (!startIdx && frameNames[idx] == BaseExceptionFunctionName)
1031 startIdx = idx + 1;
1032 }
1033
1034 int ret = 0;
1035 foreach (idx; startIdx .. numframes)
1036 {
1037 ret = dg( idx, frameNames[idx] );
1038 if ( ret )
1039 break;
1040 }
1041 return ret;
1042 }
1043 }
1044 }
1045
1046 override string toString() const
1047 {
1048 string buf;
1049 foreach ( i, line; this )
1050 buf ~= i ? "\n" ~ line : line;
1051 return buf;
1052 }
1053
1054 private:
1055 int numframes;
1056 enum MAXFRAMES = 128;
1057 void*[MAXFRAMES] callstack = void;
1058
1059 private:
1060 static if (hasExecinfo)
1061 {
1062 const(char)[] fixline( const(char)[] buf, return ref char[4096] fixbuf ) const
1063 {
1064 size_t symBeg, symEnd;
1065
1066 getMangledSymbolName(buf, symBeg, symEnd);
1067
1068 enum min = (size_t a, size_t b) => a <= b ? a : b;
1069 if (symBeg == symEnd || symBeg >= fixbuf.length)
1070 {
1071 immutable len = min(buf.length, fixbuf.length);
1072 fixbuf[0 .. len] = buf[0 .. len];
1073 return fixbuf[0 .. len];
1074 }
1075 else
1076 {
1077 fixbuf[0 .. symBeg] = buf[0 .. symBeg];
1078
1079 auto sym = demangle(buf[symBeg .. symEnd], fixbuf[symBeg .. $], getCXXDemangler());
1080
1081 if (sym.ptr !is fixbuf.ptr + symBeg)
1082 {
1083 // demangle reallocated the buffer, copy the symbol to fixbuf
1084 immutable len = min(fixbuf.length - symBeg, sym.length);
1085 memmove(fixbuf.ptr + symBeg, sym.ptr, len);
1086 if (symBeg + len == fixbuf.length)
1087 return fixbuf[];
1088 }
1089
1090 immutable pos = symBeg + sym.length;
1091 assert(pos < fixbuf.length);
1092 immutable tail = buf.length - symEnd;
1093 immutable len = min(fixbuf.length - pos, tail);
1094 fixbuf[pos .. pos + len] = buf[symEnd .. symEnd + len];
1095 return fixbuf[0 .. pos + len];
1096 }
1097 }
1098 }
1099 }