1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2002
5 * Main function for a standalone Haskell program.
7 * ---------------------------------------------------------------------------*/
9 // PAPI uses caddr_t, which is not POSIX
10 // #include "PosixSource.h"
16 #include "OSThreads.h"
17 #include "Schedule.h" /* initScheduler */
18 #include "Stats.h" /* initStats */
19 #include "STM.h" /* initSTM */
21 #include "RtsSignals.h"
22 #include "ThrIOManager.h"
23 #include "Timer.h" /* startTimer, stopTimer */
27 #include "Prelude.h" /* fixupRTStoPreludeRefs */
30 #include "ThreadLabels.h"
31 #include "BlockAlloc.h"
33 #include "RtsGlobals.h"
39 #if defined(RTS_GTK_FRONTPANEL)
40 #include "FrontPanel.h"
43 # include "Profiling.h"
45 #if defined(PROFILING)
46 # include "ProfHeap.h"
47 # include "RetainerProfile.h"
51 # include "GranSimRts.h"
54 #if defined(GRAN) || defined(PAR)
55 # include "ParallelRts.h"
59 # include "Parallel.h"
63 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
64 #include "win32/AsyncIO.h"
83 // Count of how many outstanding hs_init()s there have been.
84 static int hs_init_count = 0;
86 // Here we save the terminal settings on the standard file
87 // descriptors, if we need to change them (eg. to support NoBuffering
89 static void *saved_termios[3] = {NULL,NULL,NULL};
92 __hscore_get_saved_termios(int fd)
94 return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
95 saved_termios[fd] : NULL;
99 __hscore_set_saved_termios(int fd, void* ts)
101 if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
102 saved_termios[fd] = ts;
106 /* -----------------------------------------------------------------------------
107 Initialise floating point unit on x86 (currently disabled. why?)
108 (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
109 -------------------------------------------------------------------------- */
111 #define X86_INIT_FPU 0
115 x86_init_fpu ( void )
117 __volatile unsigned short int fpu_cw;
119 // Grab the control word
120 __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
123 printf("fpu_cw: %x\n", fpu_cw);
126 // Set bits 8-9 to 10 (64-bit precision).
127 fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
129 // Store the new control word back
130 __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
134 /* -----------------------------------------------------------------------------
136 -------------------------------------------------------------------------- */
139 hs_init(int *argc, char **argv[])
142 if (hs_init_count > 1) {
143 // second and subsequent inits are ignored
147 /* Initialise the stats department, phase 0 */
150 /* Next we do is grab the start time...just in case we're
151 * collecting timing statistics.
156 /* Start off by initialising the allocator debugging so we can
163 * The parallel system needs to be initialised and synchronised before
164 * the program is run.
166 startupParallelSystem(argv);
168 if (*argv[0] == '-') { /* Strip off mainPE flag argument */
173 argv[1] = argv[0]; /* ignore the nPEs argument */
177 /* Set the RTS flags to default values. */
179 initRtsFlagsDefaults();
181 /* Call the user hook to reset defaults, if present */
184 /* Parse the flags, separating the RTS flags from the programs args */
185 if (argc != NULL && argv != NULL) {
186 setFullProgArgv(*argc,*argv);
187 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
188 setProgArgv(*argc,*argv);
191 /* Initialise the stats department, phase 1 */
198 /* initTracing must be after setupRtsFlags() */
204 /* NB: this really must be done after processing the RTS flags */
205 IF_PAR_DEBUG(verbose,
206 debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
207 synchroniseSystem(); // calls initParallelSystem etc
210 /* initialise scheduler data structures (needs to be done before
216 /* And start GranSim profiling if required: */
217 if (RtsFlags.GranFlags.GranSimStats.Full)
218 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
220 /* And start GUM profiling if required: */
221 if (RtsFlags.ParFlags.ParStats.Full)
222 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
223 #endif /* PAR || GRAN */
225 /* initialize the storage manager */
228 /* initialise the stable pointer table */
229 initStablePtrTable();
231 /* Add some GC roots for things in the base package that the RTS
232 * knows about. We don't know whether these turn out to be CAFs
233 * or refer to CAFs, but we have to assume that they might.
235 getStablePtr((StgPtr)base_GHCziTopHandler_runIO_closure);
236 getStablePtr((StgPtr)base_GHCziTopHandler_runNonIO_closure);
237 getStablePtr((StgPtr)stackOverflow_closure);
238 getStablePtr((StgPtr)heapOverflow_closure);
239 getStablePtr((StgPtr)runFinalizerBatch_closure);
240 getStablePtr((StgPtr)unpackCString_closure);
241 getStablePtr((StgPtr)blockedOnDeadMVar_closure);
242 getStablePtr((StgPtr)nonTermination_closure);
243 getStablePtr((StgPtr)blockedIndefinitely_closure);
245 /* initialise the shared Typeable store */
248 /* initialise file locking, if necessary */
249 #if !defined(mingw32_HOST_OS)
254 /* initialise thread label table (tso->char*) */
255 initThreadLabelTable();
261 if (RtsFlags.EventLogFlags.doEventLogging) {
266 /* start the virtual timer 'subsystem'. */
270 #if defined(RTS_USER_SIGNALS)
271 if (RtsFlags.MiscFlags.install_signal_handlers) {
272 /* Initialise the user signal handler set */
274 /* Set up handler to run on SIGINT, etc. */
275 initDefaultHandlers();
279 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
283 #ifdef RTS_GTK_FRONTPANEL
284 if (RtsFlags.GcFlags.frontpanel) {
293 /* Record initialization times */
297 // Compatibility interface
299 startupHaskell(int argc, char *argv[], void (*init_root)(void))
301 hs_init(&argc, &argv);
303 hs_add_root(init_root);
307 /* -----------------------------------------------------------------------------
308 Per-module initialisation
310 This process traverses all the compiled modules in the program
311 starting with "Main", and performing per-module initialisation for
314 So far, two things happen at initialisation time:
316 - we register stable names for each foreign-exported function
317 in that module. This prevents foreign-exported entities, and
318 things they depend on, from being garbage collected.
320 - we supply a unique integer to each statically declared cost
321 centre and cost centre stack in the program.
323 The code generator inserts a small function "__stginit_<module>" in each
324 module and calls the registration functions in each of the modules it
327 The init* functions are compiled in the same way as STG code,
328 i.e. without normal C call/return conventions. Hence we must use
329 StgRun to call this stuff.
330 -------------------------------------------------------------------------- */
332 /* The init functions use an explicit stack...
334 #define INIT_STACK_BLOCKS 4
335 static F_ *init_stack = NULL;
338 hs_add_root(void (*init_root)(void))
346 if (hs_init_count <= 0) {
347 barf("hs_add_root() must be called after hs_init()");
350 /* The initialisation stack grows downward, with sp pointing
351 to the last occupied word */
352 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
353 bd = allocGroup_lock(INIT_STACK_BLOCKS);
354 init_stack = (F_ *)bd->start;
355 init_stack[--init_sp] = (F_)stg_init_finish;
356 if (init_root != NULL) {
357 init_stack[--init_sp] = (F_)init_root;
360 cap->r.rSp = (P_)(init_stack + init_sp);
361 StgRun((StgFunPtr)stg_init, &cap->r);
367 // This must be done after module initialisation.
368 // ToDo: make this work in the presence of multiple hs_add_root()s.
374 #if defined(THREADED_RTS)
379 /* ----------------------------------------------------------------------------
380 * Shutting down the RTS
382 * The wait_foreign parameter means:
383 * True ==> wait for any threads doing foreign calls now.
384 * False ==> threads doing foreign calls may return in the
385 * future, but will immediately block on a mutex.
386 * (capability->lock).
388 * If this RTS is a DLL that we're about to unload, then you want
389 * safe=True, otherwise the thread might return to code that has been
390 * unloaded. If this is a standalone program that is about to exit,
391 * then you can get away with safe=False, which is better because we
392 * won't hang on exit if there is a blocked foreign call outstanding.
394 ------------------------------------------------------------------------- */
397 hs_exit_(rtsBool wait_foreign)
399 if (hs_init_count <= 0) {
400 errorBelch("warning: too many hs_exit()s");
404 if (hs_init_count > 0) {
405 // ignore until it's the last one
409 /* start timing the shutdown */
414 #if defined(THREADED_RTS)
418 /* stop all running tasks */
419 exitScheduler(wait_foreign);
421 /* run C finalizers for all active weak pointers */
422 runAllCFinalizers(weak_ptr_list);
424 #if defined(RTS_USER_SIGNALS)
425 if (RtsFlags.MiscFlags.install_signal_handlers) {
426 freeSignalHandlers();
431 /* end_gr_simulation prints global stats if requested -- HWL */
432 if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
436 /* stop the ticker */
440 /* reset the standard file descriptors to blocking mode */
441 resetNonBlockingFd(0);
442 resetNonBlockingFd(1);
443 resetNonBlockingFd(2);
446 // Reset the terminal settings on the standard file descriptors,
447 // if we changed them. See System.Posix.Internals.tcSetAttr for
448 // more details, including the reason we termporarily disable
452 sigset_t sigset, old_sigset;
453 sigemptyset(&sigset);
454 sigaddset(&sigset, SIGTTOU);
455 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
456 for (fd = 0; fd <= 2; fd++) {
457 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
459 tcsetattr(fd,TCSANOW,ts);
462 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
467 /* controlled exit; good thread! */
468 shutdownParallelSystem(0);
470 /* global statistics in parallel system */
474 // uninstall signal handlers
475 resetDefaultHandlers();
477 /* stop timing the shutdown, we're about to print stats */
480 /* shutdown the hpc support (if needed) */
483 // clean up things from the storage manager's point of view.
484 // also outputs the stats (+RTS -s) info.
490 /* free shared Typeable store */
493 /* free file locking tables, if necessary */
494 #if !defined(mingw32_HOST_OS)
498 /* free the stable pointer table */
499 exitStablePtrTable();
502 /* free the thread label table */
503 freeThreadLabelTable();
506 #ifdef RTS_GTK_FRONTPANEL
507 if (RtsFlags.GcFlags.frontpanel) {
512 #if defined(PROFILING)
513 reportCCSProfiling();
520 // Originally, this was in report_ccs_profiling(). Now, retainer
521 // profiling might tack some extra stuff on to the end of this file
522 // during endProfiling().
523 if (prof_file != NULL) fclose(prof_file);
527 if (RtsFlags.EventLogFlags.doEventLogging) {
533 #if defined(TICKY_TICKY)
534 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
537 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
538 shutdownAsyncIO(wait_foreign);
541 /* free hash table storage */
544 // Finally, free all our storage
548 /* and shut down the allocator debugging */
554 // The real hs_exit():
559 // be safe; this might be a DLL
562 // Compatibility interfaces
564 shutdownHaskell(void)
570 shutdownHaskellAndExit(int n)
572 // we're about to exit(), no need to wait for foreign calls to return.
575 if (hs_init_count == 0) {
577 /* really exit (stg_exit() would call shutdownParallelSystem() again) */
585 #ifndef mingw32_HOST_OS
587 shutdownHaskellAndSignal(int sig)
595 * called from STG-land to exit the program
599 static int exit_started=rtsFalse;
602 void (*exitFn)(int) = 0;
608 /* HACK: avoid a loop when exiting due to a stupid error */
611 exit_started=rtsTrue;
613 IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
614 shutdownParallelSystem(n);