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"
79 // Count of how many outstanding hs_init()s there have been.
80 static int hs_init_count = 0;
82 // Here we save the terminal settings on the standard file
83 // descriptors, if we need to change them (eg. to support NoBuffering
85 static void *saved_termios[3] = {NULL,NULL,NULL};
88 __hscore_get_saved_termios(int fd)
90 return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
91 saved_termios[fd] : NULL;
95 __hscore_set_saved_termios(int fd, void* ts)
97 if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
98 saved_termios[fd] = ts;
102 /* -----------------------------------------------------------------------------
103 Initialise floating point unit on x86 (currently disabled. why?)
104 (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
105 -------------------------------------------------------------------------- */
107 #define X86_INIT_FPU 0
111 x86_init_fpu ( void )
113 __volatile unsigned short int fpu_cw;
115 // Grab the control word
116 __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
119 printf("fpu_cw: %x\n", fpu_cw);
122 // Set bits 8-9 to 10 (64-bit precision).
123 fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
125 // Store the new control word back
126 __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
130 /* -----------------------------------------------------------------------------
132 -------------------------------------------------------------------------- */
135 hs_init(int *argc, char **argv[])
138 if (hs_init_count > 1) {
139 // second and subsequent inits are ignored
144 /* Start off by initialising the allocator debugging so we can
149 /* Next we do is grab the start time...just in case we're
150 * collecting timing statistics.
156 * The parallel system needs to be initialised and synchronised before
157 * the program is run.
159 startupParallelSystem(argv);
161 if (*argv[0] == '-') { /* Strip off mainPE flag argument */
166 argv[1] = argv[0]; /* ignore the nPEs argument */
170 /* Initialise the performance tracking library */
174 if ((ver = PAPI_library_init(PAPI_VER_CURRENT)) != PAPI_VER_CURRENT) {
176 errorBelch("PAPI_library_init: wrong version: %x", ver);
177 stg_exit(EXIT_FAILURE);
179 sysErrorBelch("PAPI_library_init");
180 stg_exit(EXIT_FAILURE);
187 if ((err = PAPI_thread_init(osThreadId)) < 0) {
188 barf("PAPI_thread_init: %d",err);
194 /* Set the RTS flags to default values. */
196 initRtsFlagsDefaults();
198 /* Call the user hook to reset defaults, if present */
201 /* Parse the flags, separating the RTS flags from the programs args */
202 if (argc != NULL && argv != NULL) {
203 setFullProgArgv(*argc,*argv);
204 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
205 setProgArgv(*argc,*argv);
208 /* initTracing must be after setupRtsFlags() */
212 /* NB: this really must be done after processing the RTS flags */
213 IF_PAR_DEBUG(verbose,
214 debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
215 synchroniseSystem(); // calls initParallelSystem etc
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 */
242 /* initialise file locking, if necessary */
243 #if !defined(mingw32_HOST_OS)
248 /* initialise thread label table (tso->char*) */
249 initThreadLabelTable();
254 /* start the virtual timer 'subsystem'. */
258 /* Initialise the stats department */
261 #if defined(RTS_USER_SIGNALS)
262 if (RtsFlags.MiscFlags.install_signal_handlers) {
263 /* Initialise the user signal handler set */
265 /* Set up handler to run on SIGINT, etc. */
266 initDefaultHandlers();
270 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
274 #ifdef RTS_GTK_FRONTPANEL
275 if (RtsFlags.GcFlags.frontpanel) {
284 #if defined(THREADED_RTS)
288 /* Record initialization times */
292 // Compatibility interface
294 startupHaskell(int argc, char *argv[], void (*init_root)(void))
296 hs_init(&argc, &argv);
298 hs_add_root(init_root);
302 /* -----------------------------------------------------------------------------
303 Per-module initialisation
305 This process traverses all the compiled modules in the program
306 starting with "Main", and performing per-module initialisation for
309 So far, two things happen at initialisation time:
311 - we register stable names for each foreign-exported function
312 in that module. This prevents foreign-exported entities, and
313 things they depend on, from being garbage collected.
315 - we supply a unique integer to each statically declared cost
316 centre and cost centre stack in the program.
318 The code generator inserts a small function "__stginit_<module>" in each
319 module and calls the registration functions in each of the modules it
322 The init* functions are compiled in the same way as STG code,
323 i.e. without normal C call/return conventions. Hence we must use
324 StgRun to call this stuff.
325 -------------------------------------------------------------------------- */
327 /* The init functions use an explicit stack...
329 #define INIT_STACK_BLOCKS 4
330 static F_ *init_stack = NULL;
333 hs_add_root(void (*init_root)(void))
337 Capability *cap = &MainCapability;
339 if (hs_init_count <= 0) {
340 barf("hs_add_root() must be called after hs_init()");
343 /* The initialisation stack grows downward, with sp pointing
344 to the last occupied word */
345 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
346 bd = allocGroup_lock(INIT_STACK_BLOCKS);
347 init_stack = (F_ *)bd->start;
348 init_stack[--init_sp] = (F_)stg_init_finish;
349 if (init_root != NULL) {
350 init_stack[--init_sp] = (F_)init_root;
353 cap->r.rSp = (P_)(init_stack + init_sp);
354 StgRun((StgFunPtr)stg_init, &cap->r);
360 // This must be done after module initialisation.
361 // ToDo: make this work in the presence of multiple hs_add_root()s.
365 /* ----------------------------------------------------------------------------
366 * Shutting down the RTS
368 * The wait_foreign parameter means:
369 * True ==> wait for any threads doing foreign calls now.
370 * False ==> threads doing foreign calls may return in the
371 * future, but will immediately block on a mutex.
372 * (capability->lock).
374 * If this RTS is a DLL that we're about to unload, then you want
375 * safe=True, otherwise the thread might return to code that has been
376 * unloaded. If this is a standalone program that is about to exit,
377 * then you can get away with safe=False, which is better because we
378 * won't hang on exit if there is a blocked foreign call outstanding.
380 ------------------------------------------------------------------------- */
383 hs_exit_(rtsBool wait_foreign)
385 if (hs_init_count <= 0) {
386 errorBelch("warning: too many hs_exit()s");
390 if (hs_init_count > 0) {
391 // ignore until it's the last one
395 /* start timing the shutdown */
398 #if defined(RTS_USER_SIGNALS)
399 if (RtsFlags.MiscFlags.install_signal_handlers) {
400 freeSignalHandlers();
404 #if defined(THREADED_RTS)
408 /* stop all running tasks */
409 exitScheduler(wait_foreign);
412 /* end_gr_simulation prints global stats if requested -- HWL */
413 if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
417 /* stop the ticker */
421 /* reset the standard file descriptors to blocking mode */
422 resetNonBlockingFd(0);
423 resetNonBlockingFd(1);
424 resetNonBlockingFd(2);
427 // Reset the terminal settings on the standard file descriptors,
428 // if we changed them. See System.Posix.Internals.tcSetAttr for
429 // more details, including the reason we termporarily disable
433 sigset_t sigset, old_sigset;
434 sigemptyset(&sigset);
435 sigaddset(&sigset, SIGTTOU);
436 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
437 for (fd = 0; fd <= 2; fd++) {
438 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
440 tcsetattr(fd,TCSANOW,ts);
443 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
448 /* controlled exit; good thread! */
449 shutdownParallelSystem(0);
451 /* global statistics in parallel system */
455 /* stop timing the shutdown, we're about to print stats */
458 /* shutdown the hpc support (if needed) */
461 // clean up things from the storage manager's point of view.
462 // also outputs the stats (+RTS -s) info.
468 /* free shared Typeable store */
471 /* free file locking tables, if necessary */
472 #if !defined(mingw32_HOST_OS)
476 /* free the stable pointer table */
477 exitStablePtrTable();
480 /* free the thread label table */
481 freeThreadLabelTable();
484 #ifdef RTS_GTK_FRONTPANEL
485 if (RtsFlags.GcFlags.frontpanel) {
490 #if defined(PROFILING)
491 reportCCSProfiling();
498 // Originally, this was in report_ccs_profiling(). Now, retainer
499 // profiling might tack some extra stuff on to the end of this file
500 // during endProfiling().
504 #if defined(TICKY_TICKY)
505 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
508 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
509 shutdownAsyncIO(wait_foreign);
512 /* free hash table storage */
515 // Finally, free all our storage
519 /* and shut down the allocator debugging */
525 // The real hs_exit():
530 // be safe; this might be a DLL
533 // Compatibility interfaces
535 shutdownHaskell(void)
541 shutdownHaskellAndExit(int n)
543 if (hs_init_count == 1) {
546 // we're about to exit(), no need to wait for foreign calls to return.
548 /* really exit (stg_exit() would call shutdownParallelSystem() again) */
557 * called from STG-land to exit the program
561 static int exit_started=rtsFalse;
564 void (*exitFn)(int) = 0;
570 /* HACK: avoid a loop when exiting due to a stupid error */
573 exit_started=rtsTrue;
575 IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
576 shutdownParallelSystem(n);