hs_exit()/shutdownHaskell(): wait for outstanding foreign calls to complete before...
[ghc.git] / rts / RtsStartup.c
1 /* -----------------------------------------------------------------------------
2 *
3 * (c) The GHC Team, 1998-2002
4 *
5 * Main function for a standalone Haskell program.
6 *
7 * ---------------------------------------------------------------------------*/
8
9 // PAPI uses caddr_t, which is not POSIX
10 // #include "PosixSource.h"
11
12 #include "Rts.h"
13 #include "RtsAPI.h"
14 #include "RtsUtils.h"
15 #include "RtsFlags.h"
16 #include "OSThreads.h"
17 #include "Schedule.h" /* initScheduler */
18 #include "Stats.h" /* initStats */
19 #include "STM.h" /* initSTM */
20 #include "Signals.h"
21 #include "RtsSignals.h"
22 #include "ThrIOManager.h"
23 #include "Timer.h" /* startTimer, stopTimer */
24 #include "Weak.h"
25 #include "Ticky.h"
26 #include "StgRun.h"
27 #include "Prelude.h" /* fixupRTStoPreludeRefs */
28 #include "HsFFI.h"
29 #include "Linker.h"
30 #include "ThreadLabels.h"
31 #include "BlockAlloc.h"
32 #include "Trace.h"
33 #include "RtsTypeable.h"
34 #include "Stable.h"
35 #include "Hpc.h"
36
37 #if defined(RTS_GTK_FRONTPANEL)
38 #include "FrontPanel.h"
39 #endif
40
41 # include "Profiling.h"
42
43 #if defined(PROFILING)
44 # include "ProfHeap.h"
45 # include "RetainerProfile.h"
46 #endif
47
48 #if defined(GRAN)
49 # include "GranSimRts.h"
50 #endif
51
52 #if defined(GRAN) || defined(PAR)
53 # include "ParallelRts.h"
54 #endif
55
56 #if defined(PAR)
57 # include "Parallel.h"
58 # include "LLC.h"
59 #endif
60
61 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
62 #include "win32/AsyncIO.h"
63 #endif
64
65 #include <stdlib.h>
66
67 #ifdef HAVE_TERMIOS_H
68 #include <termios.h>
69 #endif
70 #ifdef HAVE_SIGNAL_H
71 #include <signal.h>
72 #endif
73
74 #if USE_PAPI
75 #include "Papi.h"
76 #endif
77
78 // Count of how many outstanding hs_init()s there have been.
79 static int hs_init_count = 0;
80
81 // Here we save the terminal settings on the standard file
82 // descriptors, if we need to change them (eg. to support NoBuffering
83 // input).
84 static void *saved_termios[3] = {NULL,NULL,NULL};
85
86 void*
87 __hscore_get_saved_termios(int fd)
88 {
89 return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
90 saved_termios[fd] : NULL;
91 }
92
93 void
94 __hscore_set_saved_termios(int fd, void* ts)
95 {
96 if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
97 saved_termios[fd] = ts;
98 }
99 }
100
101 /* -----------------------------------------------------------------------------
102 Initialise floating point unit on x86 (currently disabled. why?)
103 (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
104 -------------------------------------------------------------------------- */
105
106 #define X86_INIT_FPU 0
107
108 #if X86_INIT_FPU
109 static void
110 x86_init_fpu ( void )
111 {
112 __volatile unsigned short int fpu_cw;
113
114 // Grab the control word
115 __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
116
117 #if 0
118 printf("fpu_cw: %x\n", fpu_cw);
119 #endif
120
121 // Set bits 8-9 to 10 (64-bit precision).
122 fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
123
124 // Store the new control word back
125 __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
126 }
127 #endif
128
129 /* -----------------------------------------------------------------------------
130 Starting up the RTS
131 -------------------------------------------------------------------------- */
132
133 void
134 hs_init(int *argc, char **argv[])
135 {
136 hs_init_count++;
137 if (hs_init_count > 1) {
138 // second and subsequent inits are ignored
139 return;
140 }
141
142 #if defined(DEBUG)
143 /* Start off by initialising the allocator debugging so we can
144 * use it anywhere */
145 initAllocator();
146 #endif
147
148 /* Next we do is grab the start time...just in case we're
149 * collecting timing statistics.
150 */
151 stat_startInit();
152
153 #ifdef PAR
154 /*
155 * The parallel system needs to be initialised and synchronised before
156 * the program is run.
157 */
158 startupParallelSystem(argv);
159
160 if (*argv[0] == '-') { /* Strip off mainPE flag argument */
161 argv++;
162 argc--;
163 }
164
165 argv[1] = argv[0]; /* ignore the nPEs argument */
166 argv++; argc--;
167 #endif
168
169 /* Initialise the performance tracking library */
170 #ifdef USE_PAPI
171 {
172 int ver;
173 if ((ver = PAPI_library_init(PAPI_VER_CURRENT)) != PAPI_VER_CURRENT) {
174 if (ver > 0) {
175 errorBelch("PAPI_library_init: wrong version: %x", ver);
176 stg_exit(EXIT_FAILURE);
177 } else {
178 sysErrorBelch("PAPI_library_init");
179 stg_exit(EXIT_FAILURE);
180 }
181 }
182 }
183 #ifdef THREADED_RTS
184 {
185 int err;
186 if ((err = PAPI_thread_init(osThreadId)) < 0) {
187 barf("PAPI_thread_init: %d",err);
188 }
189 }
190 #endif
191 #endif
192
193 /* Set the RTS flags to default values. */
194
195 initRtsFlagsDefaults();
196
197 /* Call the user hook to reset defaults, if present */
198 defaultsHook();
199
200 /* Parse the flags, separating the RTS flags from the programs args */
201 if (argc != NULL && argv != NULL) {
202 setFullProgArgv(*argc,*argv);
203 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
204 setProgArgv(*argc,*argv);
205 }
206
207 /* initTracing must be after setupRtsFlags() */
208 initTracing();
209
210 #if defined(PAR)
211 /* NB: this really must be done after processing the RTS flags */
212 IF_PAR_DEBUG(verbose,
213 debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
214 synchroniseSystem(); // calls initParallelSystem etc
215 #endif /* PAR */
216
217 /* initialise scheduler data structures (needs to be done before
218 * initStorage()).
219 */
220 initScheduler();
221
222 #if defined(GRAN)
223 /* And start GranSim profiling if required: */
224 if (RtsFlags.GranFlags.GranSimStats.Full)
225 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
226 #elif defined(PAR)
227 /* And start GUM profiling if required: */
228 if (RtsFlags.ParFlags.ParStats.Full)
229 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
230 #endif /* PAR || GRAN */
231
232 /* initialize the storage manager */
233 initStorage();
234
235 /* initialise the stable pointer table */
236 initStablePtrTable();
237
238 /* initialise the shared Typeable store */
239 initTypeableStore();
240
241 #if defined(DEBUG)
242 /* initialise thread label table (tso->char*) */
243 initThreadLabelTable();
244 #endif
245
246 initProfiling1();
247
248 /* start the virtual timer 'subsystem'. */
249 startTimer();
250
251 /* Initialise the stats department */
252 initStats();
253
254 #if defined(RTS_USER_SIGNALS)
255 if (RtsFlags.MiscFlags.install_signal_handlers) {
256 /* Initialise the user signal handler set */
257 initUserSignals();
258 /* Set up handler to run on SIGINT, etc. */
259 initDefaultHandlers();
260 }
261 #endif
262
263 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
264 startupAsyncIO();
265 #endif
266
267 #ifdef RTS_GTK_FRONTPANEL
268 if (RtsFlags.GcFlags.frontpanel) {
269 initFrontPanel();
270 }
271 #endif
272
273 #if X86_INIT_FPU
274 x86_init_fpu();
275 #endif
276
277 #if defined(THREADED_RTS)
278 ioManagerStart();
279 #endif
280
281 /* Record initialization times */
282 stat_endInit();
283 }
284
285 // Compatibility interface
286 void
287 startupHaskell(int argc, char *argv[], void (*init_root)(void))
288 {
289 hs_init(&argc, &argv);
290 if(init_root)
291 hs_add_root(init_root);
292 }
293
294
295 /* -----------------------------------------------------------------------------
296 Per-module initialisation
297
298 This process traverses all the compiled modules in the program
299 starting with "Main", and performing per-module initialisation for
300 each one.
301
302 So far, two things happen at initialisation time:
303
304 - we register stable names for each foreign-exported function
305 in that module. This prevents foreign-exported entities, and
306 things they depend on, from being garbage collected.
307
308 - we supply a unique integer to each statically declared cost
309 centre and cost centre stack in the program.
310
311 The code generator inserts a small function "__stginit_<module>" in each
312 module and calls the registration functions in each of the modules it
313 imports.
314
315 The init* functions are compiled in the same way as STG code,
316 i.e. without normal C call/return conventions. Hence we must use
317 StgRun to call this stuff.
318 -------------------------------------------------------------------------- */
319
320 /* The init functions use an explicit stack...
321 */
322 #define INIT_STACK_BLOCKS 4
323 static F_ *init_stack = NULL;
324
325 void
326 hs_add_root(void (*init_root)(void))
327 {
328 bdescr *bd;
329 nat init_sp;
330 Capability *cap = &MainCapability;
331
332 if (hs_init_count <= 0) {
333 barf("hs_add_root() must be called after hs_init()");
334 }
335
336 /* The initialisation stack grows downward, with sp pointing
337 to the last occupied word */
338 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
339 bd = allocGroup_lock(INIT_STACK_BLOCKS);
340 init_stack = (F_ *)bd->start;
341 init_stack[--init_sp] = (F_)stg_init_finish;
342 if (init_root != NULL) {
343 init_stack[--init_sp] = (F_)init_root;
344 }
345
346 cap->r.rSp = (P_)(init_stack + init_sp);
347 StgRun((StgFunPtr)stg_init, &cap->r);
348
349 freeGroup_lock(bd);
350
351 startupHpc();
352
353 // This must be done after module initialisation.
354 // ToDo: make this work in the presence of multiple hs_add_root()s.
355 initProfiling2();
356 }
357
358 /* ----------------------------------------------------------------------------
359 * Shutting down the RTS
360 *
361 * The wait_foreign parameter means:
362 * True ==> wait for any threads doing foreign calls now.
363 * False ==> threads doing foreign calls may return in the
364 * future, but will immediately block on a mutex.
365 * (capability->lock).
366 *
367 * If this RTS is a DLL that we're about to unload, then you want
368 * safe=True, otherwise the thread might return to code that has been
369 * unloaded. If this is a standalone program that is about to exit,
370 * then you can get away with safe=False, which is better because we
371 * won't hang on exit if there is a blocked foreign call outstanding.
372 *
373 ------------------------------------------------------------------------- */
374
375 static void
376 hs_exit_(rtsBool wait_foreign)
377 {
378 if (hs_init_count <= 0) {
379 errorBelch("warning: too many hs_exit()s");
380 return;
381 }
382 hs_init_count--;
383 if (hs_init_count > 0) {
384 // ignore until it's the last one
385 return;
386 }
387
388 /* start timing the shutdown */
389 stat_startExit();
390
391 #if defined(RTS_USER_SIGNALS)
392 if (RtsFlags.MiscFlags.install_signal_handlers) {
393 freeSignalHandlers();
394 }
395 #endif
396
397 #if defined(THREADED_RTS)
398 ioManagerDie();
399 #endif
400
401 /* stop all running tasks */
402 exitScheduler(wait_foreign);
403
404 #if defined(GRAN)
405 /* end_gr_simulation prints global stats if requested -- HWL */
406 if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
407 end_gr_simulation();
408 #endif
409
410 /* stop the ticker */
411 stopTimer();
412
413 /* reset the standard file descriptors to blocking mode */
414 resetNonBlockingFd(0);
415 resetNonBlockingFd(1);
416 resetNonBlockingFd(2);
417
418 #if HAVE_TERMIOS_H
419 // Reset the terminal settings on the standard file descriptors,
420 // if we changed them. See System.Posix.Internals.tcSetAttr for
421 // more details, including the reason we termporarily disable
422 // SIGTTOU here.
423 {
424 int fd;
425 sigset_t sigset, old_sigset;
426 sigemptyset(&sigset);
427 sigaddset(&sigset, SIGTTOU);
428 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
429 for (fd = 0; fd <= 2; fd++) {
430 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
431 if (ts != NULL) {
432 tcsetattr(fd,TCSANOW,ts);
433 }
434 }
435 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
436 }
437 #endif
438
439 #if defined(PAR)
440 /* controlled exit; good thread! */
441 shutdownParallelSystem(0);
442
443 /* global statistics in parallel system */
444 PAR_TICKY_PAR_END();
445 #endif
446
447 /* stop timing the shutdown, we're about to print stats */
448 stat_endExit();
449
450 /* shutdown the hpc support (if needed) */
451 exitHpc();
452
453 // clean up things from the storage manager's point of view.
454 // also outputs the stats (+RTS -s) info.
455 exitStorage();
456
457 /* free the tasks */
458 freeScheduler();
459
460 /* free shared Typeable store */
461 exitTypeableStore();
462
463 /* free the stable pointer table */
464 exitStablePtrTable();
465
466 freeProfiling1();
467
468 #if defined(DEBUG)
469 /* free the thread label table */
470 freeThreadLabelTable();
471 #endif
472
473 #ifdef RTS_GTK_FRONTPANEL
474 if (RtsFlags.GcFlags.frontpanel) {
475 stopFrontPanel();
476 }
477 #endif
478
479 #if defined(PROFILING)
480 reportCCSProfiling();
481 #endif
482
483 endProfiling();
484
485 #ifdef PROFILING
486 // Originally, this was in report_ccs_profiling(). Now, retainer
487 // profiling might tack some extra stuff on to the end of this file
488 // during endProfiling().
489 fclose(prof_file);
490 #endif
491
492 #if defined(TICKY_TICKY)
493 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
494 #endif
495
496 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
497 shutdownAsyncIO();
498 #endif
499
500 /* free hash table storage */
501 exitHashTable();
502
503 // Finally, free all our storage
504 freeStorage();
505
506 #if defined(DEBUG)
507 /* and shut down the allocator debugging */
508 shutdownAllocator();
509 #endif
510
511 }
512
513 // The real hs_exit():
514 void
515 hs_exit(void)
516 {
517 hs_exit_(rtsTrue);
518 // be safe; this might be a DLL
519 }
520
521 // Compatibility interfaces
522 void
523 shutdownHaskell(void)
524 {
525 hs_exit();
526 }
527
528 void
529 shutdownHaskellAndExit(int n)
530 {
531 if (hs_init_count == 1) {
532 OnExitHook();
533 hs_exit_(rtsFalse);
534 // we're about to exit(), no need to wait for foreign calls to return.
535 #if defined(PAR)
536 /* really exit (stg_exit() would call shutdownParallelSystem() again) */
537 exit(n);
538 #else
539 stg_exit(n);
540 #endif
541 }
542 }
543
544 /*
545 * called from STG-land to exit the program
546 */
547
548 #ifdef PAR
549 static int exit_started=rtsFalse;
550 #endif
551
552 void (*exitFn)(int) = 0;
553
554 void
555 stg_exit(int n)
556 {
557 #ifdef PAR
558 /* HACK: avoid a loop when exiting due to a stupid error */
559 if (exit_started)
560 return;
561 exit_started=rtsTrue;
562
563 IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
564 shutdownParallelSystem(n);
565 #endif
566 if (exitFn)
567 (*exitFn)(n);
568 exit(n);
569 }