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"
40 #if defined(RTS_GTK_FRONTPANEL)
41 #include "FrontPanel.h"
44 # include "Profiling.h"
46 #if defined(PROFILING)
47 # include "ProfHeap.h"
48 # include "RetainerProfile.h"
51 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
52 #include "win32/AsyncIO.h"
74 // Count of how many outstanding hs_init()s there have been.
75 static int hs_init_count = 0;
77 // Here we save the terminal settings on the standard file
78 // descriptors, if we need to change them (eg. to support NoBuffering
80 static void *saved_termios[3] = {NULL,NULL,NULL};
83 __hscore_get_saved_termios(int fd)
85 return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
86 saved_termios[fd] : NULL;
90 __hscore_set_saved_termios(int fd, void* ts)
92 if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
93 saved_termios[fd] = ts;
97 /* -----------------------------------------------------------------------------
98 Initialise floating point unit on x86 (currently disabled. why?)
99 (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
100 -------------------------------------------------------------------------- */
102 #define X86_INIT_FPU 0
106 x86_init_fpu ( void )
108 __volatile unsigned short int fpu_cw;
110 // Grab the control word
111 __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
114 printf("fpu_cw: %x\n", fpu_cw);
117 // Set bits 8-9 to 10 (64-bit precision).
118 fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
120 // Store the new control word back
121 __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
125 /* -----------------------------------------------------------------------------
127 -------------------------------------------------------------------------- */
130 hs_init(int *argc, char **argv[])
133 if (hs_init_count > 1) {
134 // second and subsequent inits are ignored
138 setlocale(LC_CTYPE,"");
140 /* Initialise the stats department, phase 0 */
143 /* Next we do is grab the start time...just in case we're
144 * collecting timing statistics.
149 /* Start off by initialising the allocator debugging so we can
154 /* Set the RTS flags to default values. */
156 initRtsFlagsDefaults();
158 /* Call the user hook to reset defaults, if present */
161 /* Parse the flags, separating the RTS flags from the programs args */
162 if (argc != NULL && argv != NULL) {
163 setFullProgArgv(*argc,*argv);
164 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
165 setProgArgv(*argc,*argv);
168 /* Initialise the stats department, phase 1 */
175 /* initTracing must be after setupRtsFlags() */
180 /* initialise scheduler data structures (needs to be done before
185 /* initialize the storage manager */
188 /* initialise the stable pointer table */
189 initStablePtrTable();
191 /* Add some GC roots for things in the base package that the RTS
192 * knows about. We don't know whether these turn out to be CAFs
193 * or refer to CAFs, but we have to assume that they might.
195 getStablePtr((StgPtr)base_GHCziTopHandler_runIO_closure);
196 getStablePtr((StgPtr)base_GHCziTopHandler_runNonIO_closure);
197 getStablePtr((StgPtr)stackOverflow_closure);
198 getStablePtr((StgPtr)heapOverflow_closure);
199 getStablePtr((StgPtr)runFinalizerBatch_closure);
200 getStablePtr((StgPtr)unpackCString_closure);
201 getStablePtr((StgPtr)blockedOnDeadMVar_closure);
202 getStablePtr((StgPtr)nonTermination_closure);
203 getStablePtr((StgPtr)blockedIndefinitely_closure);
205 /* initialise the shared Typeable store */
208 /* initialise file locking, if necessary */
209 #if !defined(mingw32_HOST_OS)
214 /* initialise thread label table (tso->char*) */
215 initThreadLabelTable();
221 if (RtsFlags.EventLogFlags.doEventLogging) {
226 /* start the virtual timer 'subsystem'. */
230 #if defined(RTS_USER_SIGNALS)
231 if (RtsFlags.MiscFlags.install_signal_handlers) {
232 /* Initialise the user signal handler set */
234 /* Set up handler to run on SIGINT, etc. */
235 initDefaultHandlers();
239 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
243 #ifdef RTS_GTK_FRONTPANEL
244 if (RtsFlags.GcFlags.frontpanel) {
253 /* Record initialization times */
257 // Compatibility interface
259 startupHaskell(int argc, char *argv[], void (*init_root)(void))
261 hs_init(&argc, &argv);
263 hs_add_root(init_root);
267 /* -----------------------------------------------------------------------------
268 Per-module initialisation
270 This process traverses all the compiled modules in the program
271 starting with "Main", and performing per-module initialisation for
274 So far, two things happen at initialisation time:
276 - we register stable names for each foreign-exported function
277 in that module. This prevents foreign-exported entities, and
278 things they depend on, from being garbage collected.
280 - we supply a unique integer to each statically declared cost
281 centre and cost centre stack in the program.
283 The code generator inserts a small function "__stginit_<module>" in each
284 module and calls the registration functions in each of the modules it
287 The init* functions are compiled in the same way as STG code,
288 i.e. without normal C call/return conventions. Hence we must use
289 StgRun to call this stuff.
290 -------------------------------------------------------------------------- */
292 /* The init functions use an explicit stack...
294 #define INIT_STACK_BLOCKS 4
295 static F_ *init_stack = NULL;
298 hs_add_root(void (*init_root)(void))
306 if (hs_init_count <= 0) {
307 barf("hs_add_root() must be called after hs_init()");
310 /* The initialisation stack grows downward, with sp pointing
311 to the last occupied word */
312 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
313 bd = allocGroup_lock(INIT_STACK_BLOCKS);
314 init_stack = (F_ *)bd->start;
315 init_stack[--init_sp] = (F_)stg_init_finish;
316 if (init_root != NULL) {
317 init_stack[--init_sp] = (F_)init_root;
320 cap->r.rSp = (P_)(init_stack + init_sp);
321 StgRun((StgFunPtr)stg_init, &cap->r);
327 // This must be done after module initialisation.
328 // ToDo: make this work in the presence of multiple hs_add_root()s.
334 #if defined(THREADED_RTS)
339 /* ----------------------------------------------------------------------------
340 * Shutting down the RTS
342 * The wait_foreign parameter means:
343 * True ==> wait for any threads doing foreign calls now.
344 * False ==> threads doing foreign calls may return in the
345 * future, but will immediately block on a mutex.
346 * (capability->lock).
348 * If this RTS is a DLL that we're about to unload, then you want
349 * safe=True, otherwise the thread might return to code that has been
350 * unloaded. If this is a standalone program that is about to exit,
351 * then you can get away with safe=False, which is better because we
352 * won't hang on exit if there is a blocked foreign call outstanding.
354 ------------------------------------------------------------------------- */
357 hs_exit_(rtsBool wait_foreign)
359 if (hs_init_count <= 0) {
360 errorBelch("warning: too many hs_exit()s");
364 if (hs_init_count > 0) {
365 // ignore until it's the last one
369 /* start timing the shutdown */
374 #if defined(THREADED_RTS)
378 /* stop all running tasks */
379 exitScheduler(wait_foreign);
381 /* run C finalizers for all active weak pointers */
382 runAllCFinalizers(weak_ptr_list);
384 #if defined(RTS_USER_SIGNALS)
385 if (RtsFlags.MiscFlags.install_signal_handlers) {
386 freeSignalHandlers();
390 /* stop the ticker */
394 /* reset the standard file descriptors to blocking mode */
395 resetNonBlockingFd(0);
396 resetNonBlockingFd(1);
397 resetNonBlockingFd(2);
400 // Reset the terminal settings on the standard file descriptors,
401 // if we changed them. See System.Posix.Internals.tcSetAttr for
402 // more details, including the reason we termporarily disable
406 sigset_t sigset, old_sigset;
407 sigemptyset(&sigset);
408 sigaddset(&sigset, SIGTTOU);
409 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
410 for (fd = 0; fd <= 2; fd++) {
411 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
413 tcsetattr(fd,TCSANOW,ts);
416 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
420 // uninstall signal handlers
421 resetDefaultHandlers();
423 /* stop timing the shutdown, we're about to print stats */
426 /* shutdown the hpc support (if needed) */
429 // clean up things from the storage manager's point of view.
430 // also outputs the stats (+RTS -s) info.
436 /* free shared Typeable store */
439 /* free file locking tables, if necessary */
440 #if !defined(mingw32_HOST_OS)
444 /* free the stable pointer table */
445 exitStablePtrTable();
448 /* free the thread label table */
449 freeThreadLabelTable();
452 #ifdef RTS_GTK_FRONTPANEL
453 if (RtsFlags.GcFlags.frontpanel) {
458 #if defined(PROFILING)
459 reportCCSProfiling();
466 // Originally, this was in report_ccs_profiling(). Now, retainer
467 // profiling might tack some extra stuff on to the end of this file
468 // during endProfiling().
469 if (prof_file != NULL) fclose(prof_file);
473 if (RtsFlags.EventLogFlags.doEventLogging) {
479 #if defined(TICKY_TICKY)
480 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
483 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
484 shutdownAsyncIO(wait_foreign);
487 /* free hash table storage */
490 // Finally, free all our storage
494 /* and shut down the allocator debugging */
500 // The real hs_exit():
505 // be safe; this might be a DLL
508 // Compatibility interfaces
510 shutdownHaskell(void)
516 shutdownHaskellAndExit(int n)
518 // we're about to exit(), no need to wait for foreign calls to return.
521 if (hs_init_count == 0) {
526 #ifndef mingw32_HOST_OS
528 shutdownHaskellAndSignal(int sig)
536 * called from STG-land to exit the program
539 void (*exitFn)(int) = 0;