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