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"
37 #if defined(RTS_GTK_FRONTPANEL)
38 #include "FrontPanel.h"
41 #if defined(PROFILING) || defined(DEBUG)
42 # include "Profiling.h"
43 # include "ProfHeap.h"
44 # include "RetainerProfile.h"
48 # include "GranSimRts.h"
51 #if defined(GRAN) || defined(PAR)
52 # include "ParallelRts.h"
56 # include "Parallel.h"
60 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
61 #include "win32/AsyncIO.h"
77 // Count of how many outstanding hs_init()s there have been.
78 static int hs_init_count = 0;
80 // Here we save the terminal settings on the standard file
81 // descriptors, if we need to change them (eg. to support NoBuffering
83 static void *saved_termios[3] = {NULL,NULL,NULL};
86 __hscore_get_saved_termios(int fd)
88 return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
89 saved_termios[fd] : NULL;
93 __hscore_set_saved_termios(int fd, void* ts)
95 if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
96 saved_termios[fd] = ts;
100 /* -----------------------------------------------------------------------------
101 Initialise floating point unit on x86 (currently disabled. why?)
102 (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
103 -------------------------------------------------------------------------- */
105 #define X86_INIT_FPU 0
109 x86_init_fpu ( void )
111 __volatile unsigned short int fpu_cw;
113 // Grab the control word
114 __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
117 printf("fpu_cw: %x\n", fpu_cw);
120 // Set bits 8-9 to 10 (64-bit precision).
121 fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
123 // Store the new control word back
124 __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
128 /* -----------------------------------------------------------------------------
130 -------------------------------------------------------------------------- */
133 hs_init(int *argc, char **argv[])
136 if (hs_init_count > 1) {
137 // second and subsequent inits are ignored
142 /* Start off by initialising the allocator debugging so we can
147 /* Next we do is grab the start time...just in case we're
148 * collecting timing statistics.
154 * The parallel system needs to be initialised and synchronised before
155 * the program is run.
157 startupParallelSystem(argv);
159 if (*argv[0] == '-') { /* Strip off mainPE flag argument */
164 argv[1] = argv[0]; /* ignore the nPEs argument */
168 /* Initialise the performance tracking library */
172 if ((ver = PAPI_library_init(PAPI_VER_CURRENT)) != PAPI_VER_CURRENT) {
174 errorBelch("PAPI_library_init: wrong version: %x", ver);
175 stg_exit(EXIT_FAILURE);
177 sysErrorBelch("PAPI_library_init");
178 stg_exit(EXIT_FAILURE);
185 if ((err = PAPI_thread_init(osThreadId)) < 0) {
186 barf("PAPI_thread_init: %d",err);
192 /* Set the RTS flags to default values. */
194 initRtsFlagsDefaults();
196 /* Call the user hook to reset defaults, if present */
199 /* Parse the flags, separating the RTS flags from the programs args */
200 if (argc != NULL && argv != NULL) {
201 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
202 setProgArgv(*argc,*argv);
205 /* initTracing must be after setupRtsFlags() */
209 /* NB: this really must be done after processing the RTS flags */
210 IF_PAR_DEBUG(verbose,
211 debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
212 synchroniseSystem(); // calls initParallelSystem etc
215 /* Perform initialisation of adjustor thunk layer. */
218 /* initialise scheduler data structures (needs to be done before
224 /* And start GranSim profiling if required: */
225 if (RtsFlags.GranFlags.GranSimStats.Full)
226 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
228 /* And start GUM profiling if required: */
229 if (RtsFlags.ParFlags.ParStats.Full)
230 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
231 #endif /* PAR || GRAN */
233 /* initialize the storage manager */
236 /* initialise the stable pointer table */
237 initStablePtrTable();
239 /* initialise the shared Typeable store */
243 /* initialise thread label table (tso->char*) */
244 initThreadLabelTable();
247 #if defined(PROFILING) || defined(DEBUG)
251 /* start the virtual timer 'subsystem'. */
254 /* Initialise the stats department */
257 #if defined(RTS_USER_SIGNALS)
258 if (RtsFlags.MiscFlags.install_signal_handlers) {
259 /* Initialise the user signal handler set */
261 /* Set up handler to run on SIGINT, etc. */
262 initDefaultHandlers();
266 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
270 #ifdef RTS_GTK_FRONTPANEL
271 if (RtsFlags.GcFlags.frontpanel) {
280 #if defined(THREADED_RTS)
284 /* Record initialization times */
288 // Compatibility interface
290 startupHaskell(int argc, char *argv[], void (*init_root)(void))
292 hs_init(&argc, &argv);
294 hs_add_root(init_root);
298 /* -----------------------------------------------------------------------------
299 Per-module initialisation
301 This process traverses all the compiled modules in the program
302 starting with "Main", and performing per-module initialisation for
305 So far, two things happen at initialisation time:
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.
311 - we supply a unique integer to each statically declared cost
312 centre and cost centre stack in the program.
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
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 -------------------------------------------------------------------------- */
323 /* The init functions use an explicit stack...
325 #define INIT_STACK_BLOCKS 4
326 static F_ *init_stack = NULL;
329 hs_add_root(void (*init_root)(void))
333 Capability *cap = &MainCapability;
335 if (hs_init_count <= 0) {
336 barf("hs_add_root() must be called after hs_init()");
339 /* The initialisation stack grows downward, with sp pointing
340 to the last occupied word */
341 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
342 bd = allocGroup_lock(INIT_STACK_BLOCKS);
343 init_stack = (F_ *)bd->start;
344 init_stack[--init_sp] = (F_)stg_init_finish;
345 if (init_root != NULL) {
346 init_stack[--init_sp] = (F_)init_root;
349 cap->r.rSp = (P_)(init_stack + init_sp);
350 StgRun((StgFunPtr)stg_init, &cap->r);
356 #if defined(PROFILING) || defined(DEBUG)
357 // This must be done after module initialisation.
358 // ToDo: make this work in the presence of multiple hs_add_root()s.
363 /* -----------------------------------------------------------------------------
364 Shutting down the RTS
365 -------------------------------------------------------------------------- */
370 if (hs_init_count <= 0) {
371 errorBelch("warning: too many hs_exit()s");
375 if (hs_init_count > 0) {
376 // ignore until it's the last one
380 /* start timing the shutdown */
383 #if defined(RTS_USER_SIGNALS)
384 if (RtsFlags.MiscFlags.install_signal_handlers) {
385 freeSignalHandlers();
389 #if defined(THREADED_RTS)
393 /* stop all running tasks */
397 /* end_gr_simulation prints global stats if requested -- HWL */
398 if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
402 /* stop the ticker */
405 /* reset the standard file descriptors to blocking mode */
406 resetNonBlockingFd(0);
407 resetNonBlockingFd(1);
408 resetNonBlockingFd(2);
411 // Reset the terminal settings on the standard file descriptors,
412 // if we changed them. See System.Posix.Internals.tcSetAttr for
413 // more details, including the reason we termporarily disable
417 sigset_t sigset, old_sigset;
418 sigemptyset(&sigset);
419 sigaddset(&sigset, SIGTTOU);
420 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
421 for (fd = 0; fd <= 2; fd++) {
422 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
424 tcsetattr(fd,TCSANOW,ts);
427 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
432 /* controlled exit; good thread! */
433 shutdownParallelSystem(0);
435 /* global statistics in parallel system */
439 /* stop timing the shutdown, we're about to print stats */
442 /* shutdown the hpc support (if needed) */
445 // clean up things from the storage manager's point of view.
446 // also outputs the stats (+RTS -s) info.
452 /* free shared Typeable store */
455 /* free the stable pointer table */
456 exitStablePtrTable();
458 #if defined(PROFILING) || defined(DEBUG)
463 /* free the thread label table */
464 freeThreadLabelTable();
467 /* free hash table storage */
470 #ifdef RTS_GTK_FRONTPANEL
471 if (RtsFlags.GcFlags.frontpanel) {
476 #if defined(PROFILING)
477 reportCCSProfiling();
480 #if defined(PROFILING) || defined(DEBUG)
485 // Originally, this was in report_ccs_profiling(). Now, retainer
486 // profiling might tack some extra stuff on to the end of this file
487 // during endProfiling().
491 #if defined(TICKY_TICKY)
492 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
495 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
499 // Finally, free all our storage
503 /* and shut down the allocator debugging */
509 // Compatibility interfaces
511 shutdownHaskell(void)
517 shutdownHaskellAndExit(int n)
519 if (hs_init_count == 1) {
523 /* really exit (stg_exit() would call shutdownParallelSystem() again) */
532 * called from STG-land to exit the program
536 static int exit_started=rtsFalse;
539 void (*exitFn)(int) = 0;
545 /* HACK: avoid a loop when exiting due to a stupid error */
548 exit_started=rtsTrue;
550 IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
551 shutdownParallelSystem(n);