Debian Codegraph @

libphobos/libdruntime/rt/dmain2.d

raw
1 /**
2 * Contains druntime startup and shutdown routines.
3 *
4 * Copyright: Copyright Digital Mars 2000 - 2018.
5 * License: Distributed under the
6 * $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0).
7 * (See accompanying file LICENSE)
8 * Authors: Walter Bright, Sean Kelly
9 * Source: $(DRUNTIMESRC rt/_dmain2.d)
10 */
11
12 module rt.dmain2;
13
14 import core.atomic;
15 import core.internal.parseoptions : rt_parseOption;
16 import core.stdc.errno : errno;
17 import core.stdc.stdio : fflush, fprintf, fwrite, stderr, stdout;
18 import core.stdc.stdlib : alloca, EXIT_FAILURE, EXIT_SUCCESS, free, malloc, realloc;
19 import core.stdc.string : strerror;
20 import rt.config : rt_cmdline_enabled, rt_configOption;
21 import rt.memory;
22 import rt.sections;
23
24 version (Windows)
25 {
26 import core.stdc.stdio : fileno;
27 import core.stdc.wchar_ : wcslen;
28 import core.sys.windows.basetsd : HANDLE;
29 import core.sys.windows.shellapi : CommandLineToArgvW;
30 import core.sys.windows.winbase : FreeLibrary, GetCommandLineW, GetProcAddress, IsDebuggerPresent, LoadLibraryW,
31 LocalFree, WriteFile;
32 import core.sys.windows.wincon : CONSOLE_SCREEN_BUFFER_INFO, GetConsoleOutputCP,
33 GetConsoleScreenBufferInfo;
34 import core.sys.windows.winnls : CP_UTF8, MultiByteToWideChar, WideCharToMultiByte;
35 import core.sys.windows.winnt : WCHAR;
36 import core.sys.windows.winuser : MB_ICONERROR, MessageBoxW;
37
38 pragma(lib, "shell32.lib"); // needed for CommandLineToArgvW
39
40 import core.stdc.stdio : _get_osfhandle;
41 }
42 else version (Posix)
43 {
44 import core.stdc.string : strlen;
45 }
46
47 // not sure why we can't define this in one place, but this is to keep this
48 // module from importing core.runtime.
49 struct UnitTestResult
50 {
51 size_t executed;
52 size_t passed;
53 bool runMain;
54 bool summarize;
55 }
56
57 extern (C) void _d_monitor_staticctor() @nogc nothrow;
58 extern (C) void _d_monitor_staticdtor() @nogc nothrow;
59 extern (C) void _d_critical_init() @nogc nothrow;
60 extern (C) void _d_critical_term() @nogc nothrow;
61 extern (C) void gc_init();
62 extern (C) void gc_term();
63 extern (C) void thread_init() @nogc nothrow;
64 extern (C) void thread_term() @nogc nothrow;
65 extern (C) void rt_moduleCtor();
66 extern (C) void rt_moduleTlsCtor();
67 extern (C) void rt_moduleDtor();
68 extern (C) void rt_moduleTlsDtor();
69 extern (C) void thread_joinAll();
70 extern (C) UnitTestResult runModuleUnitTests();
71 extern (C) void _d_initMonoTime() @nogc nothrow;
72
73 version (CRuntime_Microsoft)
74 {
75 extern(C) void init_msvc();
76 }
77
78 /* To get out-of-band access to the args[] passed to main().
79 */
80
81 __gshared string[] _d_args = null;
82
83 extern (C) string[] rt_args()
84 {
85 return _d_args;
86 }
87
88 // This variable is only ever set by a debugger on initialization so it should
89 // be fine to leave it as __gshared.
90 extern (C) __gshared bool rt_trapExceptions = true;
91
92 alias void delegate(Throwable) ExceptionHandler;
93
94 /**
95 * Keep track of how often rt_init/rt_term were called.
96 */
97 private shared size_t _initCount;
98
99 /**********************************************
100 * Initialize druntime.
101 * If a C program wishes to call D code, and there's no D main(), then it
102 * must call rt_init() and rt_term().
103 */
104 extern (C) int rt_init()
105 {
106 /* @@BUG 11380 @@ Need to synchronize rt_init/rt_term calls for
107 version (Shared) druntime, because multiple C threads might
108 initialize different D libraries without knowing about the
109 shared druntime. Also we need to attach any thread that calls
110 rt_init. */
111 if (atomicOp!"+="(_initCount, 1) > 1) return 1;
112
113 version (CRuntime_Microsoft)
114 init_msvc();
115
116 _d_monitor_staticctor();
117 _d_critical_init();
118
119 try
120 {
121 initSections();
122 // this initializes mono time before anything else to allow usage
123 // in other druntime systems.
124 _d_initMonoTime();
125 thread_init();
126 // TODO: fixme - calls GC.addRange -> Initializes GC
127 initStaticDataGC();
128 rt_moduleCtor();
129 rt_moduleTlsCtor();
130 return 1;
131 }
132 catch (Throwable t)
133 {
134 atomicStore!(MemoryOrder.raw)(_initCount, 0);
135 _d_print_throwable(t);
136 }
137 _d_critical_term();
138 _d_monitor_staticdtor();
139 return 0;
140 }
141
142 /**********************************************
143 * Terminate use of druntime.
144 */
145 extern (C) int rt_term()
146 {
147 if (atomicLoad!(MemoryOrder.raw)(_initCount) == 0) return 0; // was never initialized
148 if (atomicOp!"-="(_initCount, 1)) return 1;
149
150 try
151 {
152 rt_moduleTlsDtor();
153 thread_joinAll();
154 rt_moduleDtor();
155 gc_term();
156 thread_term();
157 return 1;
158 }
159 catch (Throwable t)
160 {
161 _d_print_throwable(t);
162 }
163 finally
164 {
165 finiSections();
166 _d_critical_term();
167 _d_monitor_staticdtor();
168 }
169 return 0;
170 }
171
172 /**
173 * Indicates whether druntime has been or is being initialized.
174 */
175 bool isRuntimeInitialized() @nogc nothrow {
176 return atomicLoad!(MemoryOrder.raw)(_initCount) != 0;
177 }
178
179 /**********************************************
180 * Trace handler
181 */
182 alias Throwable.TraceInfo function(void* ptr) TraceHandler;
183 private __gshared TraceHandler traceHandler = null;
184 private __gshared Throwable.TraceDeallocator traceDeallocator = null;
185
186
187 /**
188 * Overrides the default trace hander with a user-supplied version.
189 *
190 * Params:
191 * h = The new trace handler. Set to null to use the default handler.
192 * d = The new dealloactor to use.
193 */
194 extern (C) void rt_setTraceHandler(TraceHandler h, Throwable.TraceDeallocator d = null)
195 {
196 traceHandler = h;
197 traceDeallocator = d;
198 }
199
200 /**
201 * Return the current trace handler
202 */
203 extern (C) TraceHandler rt_getTraceHandler()
204 {
205 return traceHandler;
206 }
207
208 extern (C) Throwable.TraceDeallocator rt_getTraceDeallocator()
209 {
210 return traceDeallocator;
211 }
212
213 /**
214 * This function will be called when an exception is constructed. The
215 * user-supplied trace handler will be called if one has been supplied,
216 * otherwise no trace will be generated.
217 *
218 * Params:
219 * ptr = A pointer to the location from which to generate the trace, or null
220 * if the trace should be generated from within the trace handler
221 * itself.
222 *
223 * Returns:
224 * An object describing the current calling context or null if no handler is
225 * supplied.
226 */
227 extern (C) Throwable.TraceInfo _d_traceContext(void* ptr = null)
228 {
229 if (traceHandler is null)
230 return null;
231 return traceHandler(ptr);
232 }
233
234 /***********************************
235 * Provide out-of-band access to the original C argc/argv
236 * passed to this program via main(argc,argv).
237 */
238
239 struct CArgs
240 {
241 int argc;
242 char** argv;
243 }
244
245 __gshared CArgs _cArgs;
246
247 extern (C) CArgs rt_cArgs() @nogc
248 {
249 return _cArgs;
250 }
251
252 /// Type of the D main() function (`_Dmain`).
253 private alias extern(C) int function(char[][] args) MainFunc;
254
255 /**
256 * Sets up the D char[][] command-line args, initializes druntime,
257 * runs embedded unittests and then runs the given D main() function,
258 * optionally catching and printing any unhandled exceptions.
259 */
260 extern (C) int _d_run_main(int argc, char** argv, MainFunc mainFunc)
261 {
262 // Set up _cArgs and array of D char[] slices, then forward to _d_run_main2
263
264 // Remember the original C argc/argv
265 _cArgs.argc = argc;
266 _cArgs.argv = argv;
267
268 version (Windows)
269 {
270 /* Because we want args[] to be UTF-8, and Windows doesn't guarantee that,
271 * we ignore argc/argv and go get the Windows command line again as UTF-16.
272 * Then, reparse into wargc/wargs, and then use Windows API to convert
273 * to UTF-8.
274 */
275 const wCommandLine = GetCommandLineW();
276 immutable size_t wCommandLineLength = wcslen(wCommandLine);
277 int wargc;
278 auto wargs = CommandLineToArgvW(wCommandLine, &wargc);
279 // assert(wargc == argc); /* argc can be broken by Unicode arguments */
280
281 // Allocate args[] on the stack - use wargc
282 char[][] args = (cast(char[]*) alloca(wargc * (char[]).sizeof))[0 .. wargc];
283
284 // This is required because WideCharToMultiByte requires int as input.
285 assert(wCommandLineLength <= cast(size_t) int.max, "Wide char command line length must not exceed int.max");
286
287 immutable size_t totalArgsLength = WideCharToMultiByte(CP_UTF8, 0, wCommandLine, cast(int)wCommandLineLength, null, 0, null, null);
288 {
289 char* totalArgsBuff = cast(char*) alloca(totalArgsLength);
290 size_t j = 0;
291 foreach (i; 0 .. wargc)
292 {
293 immutable size_t wlen = wcslen(wargs[i]);
294 assert(wlen <= cast(size_t) int.max, "wlen cannot exceed int.max");
295 immutable int len = WideCharToMultiByte(CP_UTF8, 0, &wargs[i][0], cast(int) wlen, null, 0, null, null);
296 args[i] = totalArgsBuff[j .. j + len];
297 if (len == 0)
298 continue;
299 j += len;
300 assert(j <= totalArgsLength);
301 WideCharToMultiByte(CP_UTF8, 0, &wargs[i][0], cast(int) wlen, &args[i][0], len, null, null);
302 }
303 }
304 LocalFree(wargs);
305 wargs = null;
306 wargc = 0;
307 }
308 else version (Posix)
309 {
310 // Allocate args[] on the stack
311 char[][] args = (cast(char[]*) alloca(argc * (char[]).sizeof))[0 .. argc];
312
313 size_t totalArgsLength = 0;
314 foreach (i, ref arg; args)
315 {
316 arg = argv[i][0 .. strlen(argv[i])];
317 totalArgsLength += arg.length;
318 }
319 }
320 else
321 static assert(0);
322
323 return _d_run_main2(args, totalArgsLength, mainFunc);
324 }
325
326 /**
327 * Windows-specific version for wide command-line arguments, e.g.,
328 * from a wmain/wWinMain C entry point.
329 * This wide version uses the specified arguments, unlike narrow
330 * _d_run_main which uses the actual (wide) process arguments instead.
331 */
332 version (Windows)
333 extern (C) int _d_wrun_main(int argc, wchar** wargv, MainFunc mainFunc)
334 {
335 // Allocate args[] on the stack
336 char[][] args = (cast(char[]*) alloca(argc * (char[]).sizeof))[0 .. argc];
337
338 // 1st pass: compute each argument's length as UTF-16 and UTF-8
339 size_t totalArgsLength = 0;
340 foreach (i; 0 .. argc)
341 {
342 const warg = wargv[i];
343 const size_t wlen = wcslen(warg) + 1; // incl. terminating null
344 assert(wlen <= cast(size_t) int.max, "wlen cannot exceed int.max");
345 const int len = WideCharToMultiByte(CP_UTF8, 0, warg, cast(int) wlen, null, 0, null, null);
346 args[i] = (cast(char*) wlen)[0 .. len]; // args[i].ptr = wlen, args[i].length = len
347 totalArgsLength += len;
348 }
349
350 // Allocate a single buffer for all (null-terminated) argument strings in UTF-8 on the stack
351 char* utf8Buffer = cast(char*) alloca(totalArgsLength);
352
353 // 2nd pass: convert to UTF-8 and finalize `args`
354 char* utf8 = utf8Buffer;
355 foreach (i; 0 .. argc)
356 {
357 const wlen = cast(int) args[i].ptr;
358 const len = cast(int) args[i].length;
359 WideCharToMultiByte(CP_UTF8, 0, wargv[i], wlen, utf8, len, null, null);
360 args[i] = utf8[0 .. len-1]; // excl. terminating null
361 utf8 += len;
362 }
363
364 // Set C argc/argv; argv is a new stack-allocated array of UTF-8 C strings
365 char*[] argv = (cast(char**) alloca(argc * (char*).sizeof))[0 .. argc];
366 foreach (i, ref arg; argv)
367 arg = args[i].ptr;
368 _cArgs.argc = argc;
369 _cArgs.argv = argv.ptr;
370
371 totalArgsLength -= argc; // excl. null terminator per arg
372 return _d_run_main2(args, totalArgsLength, mainFunc);
373 }
374
375 private extern (C) int _d_run_main2(char[][] args, size_t totalArgsLength, MainFunc mainFunc)
376 {
377 int result;
378
379 version (FreeBSD) version (D_InlineAsm_X86)
380 {
381 /*
382 * FreeBSD/i386 sets the FPU precision mode to 53 bit double.
383 * Make it 64 bit extended.
384 */
385 ushort fpucw;
386 asm
387 {
388 fstsw fpucw;
389 or fpucw, 0b11_00_111111; // 11: use 64 bit extended-precision
390 // 111111: mask all FP exceptions
391 fldcw fpucw;
392 }
393 }
394 version (CRuntime_Microsoft)
395 {
396 // enable full precision for reals
397 version (D_InlineAsm_X86_64)
398 {
399 asm
400 {
401 push RAX;
402 fstcw word ptr [RSP];
403 or [RSP], 0b11_00_111111; // 11: use 64 bit extended-precision
404 // 111111: mask all FP exceptions
405 fldcw word ptr [RSP];
406 pop RAX;
407 }
408 }
409 else version (D_InlineAsm_X86)
410 {
411 asm
412 {
413 push EAX;
414 fstcw word ptr [ESP];
415 or [ESP], 0b11_00_111111; // 11: use 64 bit extended-precision
416 // 111111: mask all FP exceptions
417 fldcw word ptr [ESP];
418 pop EAX;
419 }
420 }
421 else version (GNU_InlineAsm)
422 {
423 size_t fpu_cw;
424 asm { "fstcw %0" : "=m" (fpu_cw); }
425 fpu_cw |= 0b11_00_111111; // 11: use 64 bit extended-precision
426 // 111111: mask all FP exceptions
427 asm { "fldcw %0" : "=m" (fpu_cw); }
428 }
429 }
430
431 /* Create a copy of args[] on the stack to be used for main, so that rt_args()
432 * cannot be modified by the user.
433 * Note that when this function returns, _d_args will refer to garbage.
434 */
435 {
436 _d_args = cast(string[]) args;
437 auto buff = cast(char[]*) alloca(args.length * (char[]).sizeof + totalArgsLength);
438
439 char[][] argsCopy = buff[0 .. args.length];
440 auto argBuff = cast(char*) (buff + args.length);
441 size_t j = 0;
442 bool parseOpts = rt_cmdline_enabled!();
443 foreach (arg; args)
444 {
445 // Do not pass Druntime options to the program
446 if (parseOpts && arg.length >= 6 && arg[0 .. 6] == "--DRT-")
447 continue;
448 // https://issues.dlang.org/show_bug.cgi?id=20459
449 if (arg == "--")
450 parseOpts = false;
451 argsCopy[j++] = (argBuff[0 .. arg.length] = arg[]);
452 argBuff += arg.length;
453 }
454 args = argsCopy[0..j];
455 }
456
457 auto useExceptionTrap = parseExceptionOptions();
458
459 version (Windows)
460 {
461 if (IsDebuggerPresent())
462 useExceptionTrap = false;
463 }
464
465 version (none)
466 {
467 // Causes test failures related to Fibers, not enabled by default yet
468 import etc.linux.memoryerror;
469 cast(void) registerMemoryAssertHandler();
470 }
471
472 void tryExec(scope void delegate() dg)
473 {
474 if (useExceptionTrap)
475 {
476 try
477 {
478 dg();
479 }
480 catch (Throwable t)
481 {
482 _d_print_throwable(t);
483 result = EXIT_FAILURE;
484 }
485 }
486 else
487 {
488 dg();
489 }
490 }
491
492 // NOTE: The lifetime of a process is much like the lifetime of an object:
493 // it is initialized, then used, then destroyed. If initialization
494 // fails, the successive two steps are never reached. However, if
495 // initialization succeeds, then cleanup will occur even if the use
496 // step fails in some way. Here, the use phase consists of running
497 // the user's main function. If main terminates with an exception,
498 // the exception is handled and then cleanup begins. An exception
499 // thrown during cleanup, however, will abort the cleanup process.
500 void runAll()
501 {
502 if (rt_init())
503 {
504 version(Shared) version(CRuntime_Microsoft) version (DigitalMars)
505 {
506 auto exeHandle = handleForAddr(mainFunc);
507 if (exeHandle)
508 if (!rt_initSharedModule(exeHandle))
509 exeHandle = null;
510 }
511 auto utResult = runModuleUnitTests();
512 assert(utResult.passed <= utResult.executed);
513 if (utResult.passed == utResult.executed)
514 {
515 if (utResult.summarize)
516 {
517 if (utResult.passed == 0)
518 .fprintf(.stderr, "No unittests run\n");
519 else
520 .fprintf(.stderr, "%d modules passed unittests\n",
521 cast(int)utResult.passed);
522 }
523 if (utResult.runMain)
524 tryExec({ result = mainFunc(args); });
525 else
526 result = EXIT_SUCCESS;
527 }
528 else
529 {
530 if (utResult.summarize)
531 .fprintf(.stderr, "%d/%d modules FAILED unittests\n",
532 cast(int)(utResult.executed - utResult.passed),
533 cast(int)utResult.executed);
534 result = EXIT_FAILURE;
535 }
536 version(Shared) version(CRuntime_Microsoft) version (DigitalMars)
537 {
538 if (exeHandle)
539 rt_termSharedModule(exeHandle);
540 }
541 }
542 else
543 result = EXIT_FAILURE;
544
545 if (!rt_term())
546 result = (result == EXIT_SUCCESS) ? EXIT_FAILURE : result;
547 }
548
549 tryExec(&runAll);
550
551 // Issue 10344: flush stdout and return nonzero on failure
552 if (.fflush(.stdout) != 0)
553 {
554 .fprintf(.stderr, "Failed to flush stdout: %s\n", .strerror(.errno));
555 if (result == 0)
556 {
557 result = EXIT_FAILURE;
558 }
559 }
560
561 return result;
562 }
563
564 private void formatThrowable(Throwable t, scope void delegate(in char[] s) nothrow sink)
565 {
566 foreach (u; t)
567 {
568 u.toString(sink); sink("\n");
569
570 auto e = cast(Error)u;
571 if (e is null || e.bypassedException is null) continue;
572
573 sink("=== Bypassed ===\n");
574 foreach (t2; e.bypassedException)
575 {
576 t2.toString(sink); sink("\n");
577 }
578 sink("=== ~Bypassed ===\n");
579 }
580 }
581
582 private auto parseExceptionOptions()
583 {
584 const optName = "trapExceptions";
585 auto option = rt_configOption(optName);
586 auto trap = rt_trapExceptions;
587 if (option.length)
588 rt_parseOption(optName, option, trap, "");
589 return trap;
590 }
591
592 extern (C) void _d_print_throwable(Throwable t)
593 {
594 // On Windows, a console may not be present to print the output to.
595 // Show a message box instead. If the console is present, convert to
596 // the correct encoding.
597 version (Windows)
598 {
599 static struct WSink
600 {
601 WCHAR* ptr; size_t len;
602
603 void sink(in char[] s) scope nothrow
604 {
605 if (!s.length) return;
606 const swlen = MultiByteToWideChar(
607 CP_UTF8, 0, s.ptr, cast(int)s.length, null, 0);
608 if (!swlen) return;
609
610 auto newPtr = cast(WCHAR*)realloc(ptr,
611 (this.len + swlen + 1) * WCHAR.sizeof);
612 if (!newPtr) return;
613 ptr = newPtr;
614 const written = MultiByteToWideChar(
615 CP_UTF8, 0, s.ptr, cast(int)s.length, ptr+len, swlen);
616 len += written;
617 }
618
619 typeof(ptr) get() { if (ptr) ptr[len] = 0; return ptr; }
620
621 void free() { .free(ptr); }
622 }
623
624 HANDLE windowsHandle(int fd)
625 {
626 return cast(HANDLE)_get_osfhandle(fd);
627 }
628
629 // ensure the exception is shown at the beginning of the line, while also
630 // checking whether stderr is a valid file
631 int written = fprintf(stderr, "\n");
632 if (written <= 0)
633 {
634 WSink buf;
635 formatThrowable(t, &buf.sink);
636
637 if (buf.ptr)
638 {
639 WSink caption;
640 if (t)
641 caption.sink(typeid(t).name);
642
643 // Avoid static user32.dll dependency for console applications
644 // by loading it dynamically as needed
645 if (auto user32 = LoadLibraryW("user32.dll"))
646 {
647 alias typeof(&MessageBoxW) PMessageBoxW;
648 if (auto pMessageBoxW = cast(PMessageBoxW) GetProcAddress(user32, "MessageBoxW"))
649 pMessageBoxW(null, buf.get(), caption.get(), MB_ICONERROR);
650 FreeLibrary(user32);
651 }
652 caption.free();
653 buf.free();
654 }
655 return;
656 }
657 auto hStdErr = windowsHandle(fileno(stderr));
658 CONSOLE_SCREEN_BUFFER_INFO sbi = void;
659 const isConsole = GetConsoleScreenBufferInfo(hStdErr, &sbi) != 0;
660 if (isConsole)
661 {
662 WSink buf;
663 formatThrowable(t, &buf.sink);
664
665 if (buf.ptr)
666 {
667 uint codepage = GetConsoleOutputCP();
668 const slen = WideCharToMultiByte(codepage, 0,
669 buf.ptr, cast(int)buf.len, null, 0, null, null);
670 if (auto sptr = cast(char*)malloc(slen * char.sizeof))
671 {
672 WideCharToMultiByte(codepage, 0,
673 buf.ptr, cast(int)buf.len, sptr, slen, null, null);
674 WriteFile(hStdErr, sptr, slen, null, null);
675 free(sptr);
676 }
677 buf.free();
678 }
679 return;
680 }
681 }
682
683 void sink(in char[] buf) scope nothrow
684 {
685 fwrite(buf.ptr, char.sizeof, buf.length, stderr);
686 }
687 formatThrowable(t, &sink);
688 }