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 "Timer.h" /* startTimer, stopTimer */
26 #include "Prelude.h" /* fixupRTStoPreludeRefs */
29 #include "ThreadLabels.h"
30 #include "BlockAlloc.h"
32 #include "RtsTypeable.h"
36 #if defined(RTS_GTK_FRONTPANEL)
37 #include "FrontPanel.h"
40 #if defined(PROFILING) || defined(DEBUG)
41 # include "Profiling.h"
42 # include "ProfHeap.h"
43 # include "RetainerProfile.h"
47 # include "GranSimRts.h"
50 #if defined(GRAN) || defined(PAR)
51 # include "ParallelRts.h"
55 # include "Parallel.h"
59 #if defined(mingw32_HOST_OS)
60 #include "win32/AsyncIO.h"
76 // Count of how many outstanding hs_init()s there have been.
77 static int hs_init_count = 0;
79 // Here we save the terminal settings on the standard file
80 // descriptors, if we need to change them (eg. to support NoBuffering
82 static void *saved_termios[3] = {NULL,NULL,NULL};
85 __hscore_get_saved_termios(int fd)
87 return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
88 saved_termios[fd] : NULL;
92 __hscore_set_saved_termios(int fd, void* ts)
94 if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
95 saved_termios[fd] = ts;
99 /* -----------------------------------------------------------------------------
100 Initialise floating point unit on x86 (currently disabled. why?)
101 (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
102 -------------------------------------------------------------------------- */
104 #define X86_INIT_FPU 0
108 x86_init_fpu ( void )
110 __volatile unsigned short int fpu_cw;
112 // Grab the control word
113 __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
116 printf("fpu_cw: %x\n", fpu_cw);
119 // Set bits 8-9 to 10 (64-bit precision).
120 fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
122 // Store the new control word back
123 __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
127 /* -----------------------------------------------------------------------------
129 -------------------------------------------------------------------------- */
132 hs_init(int *argc, char **argv[])
135 if (hs_init_count > 1) {
136 // second and subsequent inits are ignored
140 /* The very first thing we do is grab the start time...just in case we're
141 * collecting timing statistics.
147 * The parallel system needs to be initialised and synchronised before
148 * the program is run.
150 startupParallelSystem(argv);
152 if (*argv[0] == '-') { /* Strip off mainPE flag argument */
157 argv[1] = argv[0]; /* ignore the nPEs argument */
161 /* Initialise the performance tracking library */
165 if ((ver = PAPI_library_init(PAPI_VER_CURRENT)) != PAPI_VER_CURRENT) {
167 errorBelch("PAPI_library_init: wrong version: %x", ver);
168 stg_exit(EXIT_FAILURE);
170 sysErrorBelch("PAPI_library_init");
171 stg_exit(EXIT_FAILURE);
178 if ((err = PAPI_thread_init(osThreadId)) < 0) {
179 barf("PAPI_thread_init: %d",err);
185 /* Set the RTS flags to default values. */
187 initRtsFlagsDefaults();
189 /* Call the user hook to reset defaults, if present */
192 /* Parse the flags, separating the RTS flags from the programs args */
193 if (argc != NULL && argv != NULL) {
194 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
195 setProgArgv(*argc,*argv);
198 /* initTracing must be after setupRtsFlags() */
202 /* NB: this really must be done after processing the RTS flags */
203 IF_PAR_DEBUG(verbose,
204 debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
205 synchroniseSystem(); // calls initParallelSystem etc
208 /* Perform initialisation of adjustor thunk layer. */
211 /* initialise scheduler data structures (needs to be done before
217 /* And start GranSim profiling if required: */
218 if (RtsFlags.GranFlags.GranSimStats.Full)
219 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
221 /* And start GUM profiling if required: */
222 if (RtsFlags.ParFlags.ParStats.Full)
223 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
224 #endif /* PAR || GRAN */
226 /* initialize the storage manager */
229 /* initialise the stable pointer table */
230 initStablePtrTable();
232 /* initialise the shared Typeable store */
236 /* initialise thread label table (tso->char*) */
237 initThreadLabelTable();
240 #if defined(PROFILING) || defined(DEBUG)
244 /* start the virtual timer 'subsystem'. */
247 /* Initialise the stats department */
250 #if defined(RTS_USER_SIGNALS)
251 /* Initialise the user signal handler set */
253 /* Set up handler to run on SIGINT, etc. */
254 initDefaultHandlers();
257 #if defined(mingw32_HOST_OS)
261 #ifdef RTS_GTK_FRONTPANEL
262 if (RtsFlags.GcFlags.frontpanel) {
271 #if defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
275 /* Record initialization times */
279 // Compatibility interface
281 startupHaskell(int argc, char *argv[], void (*init_root)(void))
283 hs_init(&argc, &argv);
285 hs_add_root(init_root);
289 /* -----------------------------------------------------------------------------
290 Per-module initialisation
292 This process traverses all the compiled modules in the program
293 starting with "Main", and performing per-module initialisation for
296 So far, two things happen at initialisation time:
298 - we register stable names for each foreign-exported function
299 in that module. This prevents foreign-exported entities, and
300 things they depend on, from being garbage collected.
302 - we supply a unique integer to each statically declared cost
303 centre and cost centre stack in the program.
305 The code generator inserts a small function "__stginit_<module>" in each
306 module and calls the registration functions in each of the modules it
309 The init* functions are compiled in the same way as STG code,
310 i.e. without normal C call/return conventions. Hence we must use
311 StgRun to call this stuff.
312 -------------------------------------------------------------------------- */
314 /* The init functions use an explicit stack...
316 #define INIT_STACK_BLOCKS 4
317 static F_ *init_stack = NULL;
320 hs_add_root(void (*init_root)(void))
324 Capability *cap = &MainCapability;
326 if (hs_init_count <= 0) {
327 barf("hs_add_root() must be called after hs_init()");
330 /* The initialisation stack grows downward, with sp pointing
331 to the last occupied word */
332 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
333 bd = allocGroup_lock(INIT_STACK_BLOCKS);
334 init_stack = (F_ *)bd->start;
335 init_stack[--init_sp] = (F_)stg_init_finish;
336 if (init_root != NULL) {
337 init_stack[--init_sp] = (F_)init_root;
340 cap->r.rSp = (P_)(init_stack + init_sp);
341 StgRun((StgFunPtr)stg_init, &cap->r);
347 #if defined(PROFILING) || defined(DEBUG)
348 // This must be done after module initialisation.
349 // ToDo: make this work in the presence of multiple hs_add_root()s.
354 /* -----------------------------------------------------------------------------
355 Shutting down the RTS
356 -------------------------------------------------------------------------- */
361 if (hs_init_count <= 0) {
362 errorBelch("warning: too many hs_exit()s");
366 if (hs_init_count > 0) {
367 // ignore until it's the last one
371 /* start timing the shutdown */
374 #if defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
378 /* stop all running tasks */
382 /* end_gr_simulation prints global stats if requested -- HWL */
383 if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
387 /* stop the ticker */
390 /* reset the standard file descriptors to blocking mode */
391 resetNonBlockingFd(0);
392 resetNonBlockingFd(1);
393 resetNonBlockingFd(2);
396 // Reset the terminal settings on the standard file descriptors,
397 // if we changed them. See System.Posix.Internals.tcSetAttr for
398 // more details, including the reason we termporarily disable
402 sigset_t sigset, old_sigset;
403 sigemptyset(&sigset);
404 sigaddset(&sigset, SIGTTOU);
405 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
406 for (fd = 0; fd <= 2; fd++) {
407 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
409 tcsetattr(fd,TCSANOW,ts);
412 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
417 /* controlled exit; good thread! */
418 shutdownParallelSystem(0);
420 /* global statistics in parallel system */
424 /* stop timing the shutdown, we're about to print stats */
427 /* shutdown the hpc support (if needed) */
430 // clean up things from the storage manager's point of view.
431 // also outputs the stats (+RTS -s) info.
434 /* free shared Typeable store */
437 /* initialise the stable pointer table */
438 exitStablePtrTable();
440 /* free hash table storage */
443 #ifdef RTS_GTK_FRONTPANEL
444 if (RtsFlags.GcFlags.frontpanel) {
449 #if defined(PROFILING)
450 reportCCSProfiling();
453 #if defined(PROFILING) || defined(DEBUG)
458 // Originally, this was in report_ccs_profiling(). Now, retainer
459 // profiling might tack some extra stuff on to the end of this file
460 // during endProfiling().
464 #if defined(TICKY_TICKY)
465 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
468 #if defined(mingw32_HOST_OS)
472 // Finally, free all our storage.
476 // Compatibility interfaces
478 shutdownHaskell(void)
484 shutdownHaskellAndExit(int n)
486 if (hs_init_count == 1) {
490 /* really exit (stg_exit() would call shutdownParallelSystem() again) */
499 * called from STG-land to exit the program
503 static int exit_started=rtsFalse;
506 void (*exitFn)(int) = 0;
512 /* HACK: avoid a loop when exiting due to a stupid error */
515 exit_started=rtsTrue;
517 IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
518 shutdownParallelSystem(n);