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 "RtsTypeable.h"
38 #if defined(RTS_GTK_FRONTPANEL)
39 #include "FrontPanel.h"
42 # include "Profiling.h"
44 #if defined(PROFILING)
45 # include "ProfHeap.h"
46 # include "RetainerProfile.h"
50 # include "GranSimRts.h"
53 #if defined(GRAN) || defined(PAR)
54 # include "ParallelRts.h"
58 # include "Parallel.h"
62 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
63 #include "win32/AsyncIO.h"
82 // Count of how many outstanding hs_init()s there have been.
83 static int hs_init_count = 0;
85 // Here we save the terminal settings on the standard file
86 // descriptors, if we need to change them (eg. to support NoBuffering
88 static void *saved_termios[3] = {NULL,NULL,NULL};
91 __hscore_get_saved_termios(int fd)
93 return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
94 saved_termios[fd] : NULL;
98 __hscore_set_saved_termios(int fd, void* ts)
100 if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
101 saved_termios[fd] = ts;
105 /* -----------------------------------------------------------------------------
106 Initialise floating point unit on x86 (currently disabled. why?)
107 (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
108 -------------------------------------------------------------------------- */
110 #define X86_INIT_FPU 0
114 x86_init_fpu ( void )
116 __volatile unsigned short int fpu_cw;
118 // Grab the control word
119 __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
122 printf("fpu_cw: %x\n", fpu_cw);
125 // Set bits 8-9 to 10 (64-bit precision).
126 fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
128 // Store the new control word back
129 __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
133 /* -----------------------------------------------------------------------------
135 -------------------------------------------------------------------------- */
138 hs_init(int *argc, char **argv[])
141 if (hs_init_count > 1) {
142 // second and subsequent inits are ignored
146 /* Initialise the stats department, phase 0 */
149 /* Next we do is grab the start time...just in case we're
150 * collecting timing statistics.
155 /* Start off by initialising the allocator debugging so we can
162 * The parallel system needs to be initialised and synchronised before
163 * the program is run.
165 startupParallelSystem(argv);
167 if (*argv[0] == '-') { /* Strip off mainPE flag argument */
172 argv[1] = argv[0]; /* ignore the nPEs argument */
176 /* Set the RTS flags to default values. */
178 initRtsFlagsDefaults();
180 /* Call the user hook to reset defaults, if present */
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);
190 /* Initialise the stats department, phase 1 */
197 /* initTracing must be after setupRtsFlags() */
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
207 /* initialise scheduler data structures (needs to be done before
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);
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 */
222 /* initialize the storage manager */
225 /* initialise the stable pointer table */
226 initStablePtrTable();
228 /* Add some GC roots (using stable pointers): these are needed by
229 * all foreign export stubs, so they have to be treated as
231 getStablePtr((StgPtr)base_GHCziTopHandler_runIO_closure);
232 getStablePtr((StgPtr)base_GHCziTopHandler_runNonIO_closure);
234 /* initialise the shared Typeable store */
237 /* initialise file locking, if necessary */
238 #if !defined(mingw32_HOST_OS)
243 /* initialise thread label table (tso->char*) */
244 initThreadLabelTable();
249 /* start the virtual timer 'subsystem'. */
253 #if defined(RTS_USER_SIGNALS)
254 if (RtsFlags.MiscFlags.install_signal_handlers) {
255 /* Initialise the user signal handler set */
257 /* Set up handler to run on SIGINT, etc. */
258 initDefaultHandlers();
262 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
266 #ifdef RTS_GTK_FRONTPANEL
267 if (RtsFlags.GcFlags.frontpanel) {
276 /* Record initialization times */
280 // Compatibility interface
282 startupHaskell(int argc, char *argv[], void (*init_root)(void))
284 hs_init(&argc, &argv);
286 hs_add_root(init_root);
290 /* -----------------------------------------------------------------------------
291 Per-module initialisation
293 This process traverses all the compiled modules in the program
294 starting with "Main", and performing per-module initialisation for
297 So far, two things happen at initialisation time:
299 - we register stable names for each foreign-exported function
300 in that module. This prevents foreign-exported entities, and
301 things they depend on, from being garbage collected.
303 - we supply a unique integer to each statically declared cost
304 centre and cost centre stack in the program.
306 The code generator inserts a small function "__stginit_<module>" in each
307 module and calls the registration functions in each of the modules it
310 The init* functions are compiled in the same way as STG code,
311 i.e. without normal C call/return conventions. Hence we must use
312 StgRun to call this stuff.
313 -------------------------------------------------------------------------- */
315 /* The init functions use an explicit stack...
317 #define INIT_STACK_BLOCKS 4
318 static F_ *init_stack = NULL;
321 hs_add_root(void (*init_root)(void))
329 if (hs_init_count <= 0) {
330 barf("hs_add_root() must be called after hs_init()");
333 /* The initialisation stack grows downward, with sp pointing
334 to the last occupied word */
335 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
336 bd = allocGroup_lock(INIT_STACK_BLOCKS);
337 init_stack = (F_ *)bd->start;
338 init_stack[--init_sp] = (F_)stg_init_finish;
339 if (init_root != NULL) {
340 init_stack[--init_sp] = (F_)init_root;
343 cap->r.rSp = (P_)(init_stack + init_sp);
344 StgRun((StgFunPtr)stg_init, &cap->r);
350 // This must be done after module initialisation.
351 // ToDo: make this work in the presence of multiple hs_add_root()s.
357 #if defined(THREADED_RTS)
362 /* ----------------------------------------------------------------------------
363 * Shutting down the RTS
365 * The wait_foreign parameter means:
366 * True ==> wait for any threads doing foreign calls now.
367 * False ==> threads doing foreign calls may return in the
368 * future, but will immediately block on a mutex.
369 * (capability->lock).
371 * If this RTS is a DLL that we're about to unload, then you want
372 * safe=True, otherwise the thread might return to code that has been
373 * unloaded. If this is a standalone program that is about to exit,
374 * then you can get away with safe=False, which is better because we
375 * won't hang on exit if there is a blocked foreign call outstanding.
377 ------------------------------------------------------------------------- */
380 hs_exit_(rtsBool wait_foreign)
382 if (hs_init_count <= 0) {
383 errorBelch("warning: too many hs_exit()s");
387 if (hs_init_count > 0) {
388 // ignore until it's the last one
392 /* start timing the shutdown */
397 #if defined(RTS_USER_SIGNALS)
398 if (RtsFlags.MiscFlags.install_signal_handlers) {
399 freeSignalHandlers();
403 #if defined(THREADED_RTS)
407 /* stop all running tasks */
408 exitScheduler(wait_foreign);
411 /* end_gr_simulation prints global stats if requested -- HWL */
412 if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
416 /* stop the ticker */
420 /* reset the standard file descriptors to blocking mode */
421 resetNonBlockingFd(0);
422 resetNonBlockingFd(1);
423 resetNonBlockingFd(2);
426 // Reset the terminal settings on the standard file descriptors,
427 // if we changed them. See System.Posix.Internals.tcSetAttr for
428 // more details, including the reason we termporarily disable
432 sigset_t sigset, old_sigset;
433 sigemptyset(&sigset);
434 sigaddset(&sigset, SIGTTOU);
435 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
436 for (fd = 0; fd <= 2; fd++) {
437 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
439 tcsetattr(fd,TCSANOW,ts);
442 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
447 /* controlled exit; good thread! */
448 shutdownParallelSystem(0);
450 /* global statistics in parallel system */
454 // uninstall signal handlers
455 resetDefaultHandlers();
457 /* stop timing the shutdown, we're about to print stats */
460 /* shutdown the hpc support (if needed) */
463 // clean up things from the storage manager's point of view.
464 // also outputs the stats (+RTS -s) info.
470 /* free shared Typeable store */
473 /* free file locking tables, if necessary */
474 #if !defined(mingw32_HOST_OS)
478 /* free the stable pointer table */
479 exitStablePtrTable();
482 /* free the thread label table */
483 freeThreadLabelTable();
486 #ifdef RTS_GTK_FRONTPANEL
487 if (RtsFlags.GcFlags.frontpanel) {
492 #if defined(PROFILING)
493 reportCCSProfiling();
500 // Originally, this was in report_ccs_profiling(). Now, retainer
501 // profiling might tack some extra stuff on to the end of this file
502 // during endProfiling().
503 if (prof_file != NULL) fclose(prof_file);
506 #if defined(TICKY_TICKY)
507 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
510 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
511 shutdownAsyncIO(wait_foreign);
514 /* free hash table storage */
517 // Finally, free all our storage
521 /* and shut down the allocator debugging */
527 // The real hs_exit():
532 // be safe; this might be a DLL
535 // Compatibility interfaces
537 shutdownHaskell(void)
543 shutdownHaskellAndExit(int n)
545 // we're about to exit(), no need to wait for foreign calls to return.
548 if (hs_init_count == 0) {
550 /* really exit (stg_exit() would call shutdownParallelSystem() again) */
558 #ifndef mingw32_HOST_OS
560 shutdownHaskellAndSignal(int sig)
568 * called from STG-land to exit the program
572 static int exit_started=rtsFalse;
575 void (*exitFn)(int) = 0;
581 /* HACK: avoid a loop when exiting due to a stupid error */
584 exit_started=rtsTrue;
586 IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
587 shutdownParallelSystem(n);