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"
39 #if defined(RTS_GTK_FRONTPANEL)
40 #include "FrontPanel.h"
43 # include "Profiling.h"
45 #if defined(PROFILING)
46 # include "ProfHeap.h"
47 # include "RetainerProfile.h"
50 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
51 #include "win32/AsyncIO.h"
70 // Count of how many outstanding hs_init()s there have been.
71 static int hs_init_count = 0;
73 // Here we save the terminal settings on the standard file
74 // descriptors, if we need to change them (eg. to support NoBuffering
76 static void *saved_termios[3] = {NULL,NULL,NULL};
79 __hscore_get_saved_termios(int fd)
81 return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
82 saved_termios[fd] : NULL;
86 __hscore_set_saved_termios(int fd, void* ts)
88 if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
89 saved_termios[fd] = ts;
93 /* -----------------------------------------------------------------------------
94 Initialise floating point unit on x86 (currently disabled. why?)
95 (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
96 -------------------------------------------------------------------------- */
98 #define X86_INIT_FPU 0
102 x86_init_fpu ( void )
104 __volatile unsigned short int fpu_cw;
106 // Grab the control word
107 __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
110 printf("fpu_cw: %x\n", fpu_cw);
113 // Set bits 8-9 to 10 (64-bit precision).
114 fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
116 // Store the new control word back
117 __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
121 /* -----------------------------------------------------------------------------
123 -------------------------------------------------------------------------- */
126 hs_init(int *argc, char **argv[])
129 if (hs_init_count > 1) {
130 // second and subsequent inits are ignored
134 /* Initialise the stats department, phase 0 */
137 /* Next we do is grab the start time...just in case we're
138 * collecting timing statistics.
143 /* Start off by initialising the allocator debugging so we can
148 /* Set the RTS flags to default values. */
150 initRtsFlagsDefaults();
152 /* Call the user hook to reset defaults, if present */
155 /* Parse the flags, separating the RTS flags from the programs args */
156 if (argc != NULL && argv != NULL) {
157 setFullProgArgv(*argc,*argv);
158 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
159 setProgArgv(*argc,*argv);
162 /* Initialise the stats department, phase 1 */
169 /* initTracing must be after setupRtsFlags() */
174 /* initialise scheduler data structures (needs to be done before
179 /* initialize the storage manager */
182 /* initialise the stable pointer table */
183 initStablePtrTable();
185 /* Add some GC roots for things in the base package that the RTS
186 * knows about. We don't know whether these turn out to be CAFs
187 * or refer to CAFs, but we have to assume that they might.
189 getStablePtr((StgPtr)base_GHCziTopHandler_runIO_closure);
190 getStablePtr((StgPtr)base_GHCziTopHandler_runNonIO_closure);
191 getStablePtr((StgPtr)stackOverflow_closure);
192 getStablePtr((StgPtr)heapOverflow_closure);
193 getStablePtr((StgPtr)runFinalizerBatch_closure);
194 getStablePtr((StgPtr)unpackCString_closure);
195 getStablePtr((StgPtr)blockedOnDeadMVar_closure);
196 getStablePtr((StgPtr)nonTermination_closure);
197 getStablePtr((StgPtr)blockedIndefinitely_closure);
199 /* initialise the shared Typeable store */
202 /* initialise file locking, if necessary */
203 #if !defined(mingw32_HOST_OS)
208 /* initialise thread label table (tso->char*) */
209 initThreadLabelTable();
215 if (RtsFlags.EventLogFlags.doEventLogging) {
220 /* start the virtual timer 'subsystem'. */
224 #if defined(RTS_USER_SIGNALS)
225 if (RtsFlags.MiscFlags.install_signal_handlers) {
226 /* Initialise the user signal handler set */
228 /* Set up handler to run on SIGINT, etc. */
229 initDefaultHandlers();
233 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
237 #ifdef RTS_GTK_FRONTPANEL
238 if (RtsFlags.GcFlags.frontpanel) {
247 /* Record initialization times */
251 // Compatibility interface
253 startupHaskell(int argc, char *argv[], void (*init_root)(void))
255 hs_init(&argc, &argv);
257 hs_add_root(init_root);
261 /* -----------------------------------------------------------------------------
262 Per-module initialisation
264 This process traverses all the compiled modules in the program
265 starting with "Main", and performing per-module initialisation for
268 So far, two things happen at initialisation time:
270 - we register stable names for each foreign-exported function
271 in that module. This prevents foreign-exported entities, and
272 things they depend on, from being garbage collected.
274 - we supply a unique integer to each statically declared cost
275 centre and cost centre stack in the program.
277 The code generator inserts a small function "__stginit_<module>" in each
278 module and calls the registration functions in each of the modules it
281 The init* functions are compiled in the same way as STG code,
282 i.e. without normal C call/return conventions. Hence we must use
283 StgRun to call this stuff.
284 -------------------------------------------------------------------------- */
286 /* The init functions use an explicit stack...
288 #define INIT_STACK_BLOCKS 4
289 static F_ *init_stack = NULL;
292 hs_add_root(void (*init_root)(void))
300 if (hs_init_count <= 0) {
301 barf("hs_add_root() must be called after hs_init()");
304 /* The initialisation stack grows downward, with sp pointing
305 to the last occupied word */
306 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
307 bd = allocGroup_lock(INIT_STACK_BLOCKS);
308 init_stack = (F_ *)bd->start;
309 init_stack[--init_sp] = (F_)stg_init_finish;
310 if (init_root != NULL) {
311 init_stack[--init_sp] = (F_)init_root;
314 cap->r.rSp = (P_)(init_stack + init_sp);
315 StgRun((StgFunPtr)stg_init, &cap->r);
321 // This must be done after module initialisation.
322 // ToDo: make this work in the presence of multiple hs_add_root()s.
328 #if defined(THREADED_RTS)
333 /* ----------------------------------------------------------------------------
334 * Shutting down the RTS
336 * The wait_foreign parameter means:
337 * True ==> wait for any threads doing foreign calls now.
338 * False ==> threads doing foreign calls may return in the
339 * future, but will immediately block on a mutex.
340 * (capability->lock).
342 * If this RTS is a DLL that we're about to unload, then you want
343 * safe=True, otherwise the thread might return to code that has been
344 * unloaded. If this is a standalone program that is about to exit,
345 * then you can get away with safe=False, which is better because we
346 * won't hang on exit if there is a blocked foreign call outstanding.
348 ------------------------------------------------------------------------- */
351 hs_exit_(rtsBool wait_foreign)
353 if (hs_init_count <= 0) {
354 errorBelch("warning: too many hs_exit()s");
358 if (hs_init_count > 0) {
359 // ignore until it's the last one
363 /* start timing the shutdown */
368 #if defined(THREADED_RTS)
372 /* stop all running tasks */
373 exitScheduler(wait_foreign);
375 /* run C finalizers for all active weak pointers */
376 runAllCFinalizers(weak_ptr_list);
378 #if defined(RTS_USER_SIGNALS)
379 if (RtsFlags.MiscFlags.install_signal_handlers) {
380 freeSignalHandlers();
384 /* stop the ticker */
388 /* reset the standard file descriptors to blocking mode */
389 resetNonBlockingFd(0);
390 resetNonBlockingFd(1);
391 resetNonBlockingFd(2);
394 // Reset the terminal settings on the standard file descriptors,
395 // if we changed them. See System.Posix.Internals.tcSetAttr for
396 // more details, including the reason we termporarily disable
400 sigset_t sigset, old_sigset;
401 sigemptyset(&sigset);
402 sigaddset(&sigset, SIGTTOU);
403 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
404 for (fd = 0; fd <= 2; fd++) {
405 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
407 tcsetattr(fd,TCSANOW,ts);
410 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
414 // uninstall signal handlers
415 resetDefaultHandlers();
417 /* stop timing the shutdown, we're about to print stats */
420 /* shutdown the hpc support (if needed) */
423 // clean up things from the storage manager's point of view.
424 // also outputs the stats (+RTS -s) info.
430 /* free shared Typeable store */
433 /* free file locking tables, if necessary */
434 #if !defined(mingw32_HOST_OS)
438 /* free the stable pointer table */
439 exitStablePtrTable();
442 /* free the thread label table */
443 freeThreadLabelTable();
446 #ifdef RTS_GTK_FRONTPANEL
447 if (RtsFlags.GcFlags.frontpanel) {
452 #if defined(PROFILING)
453 reportCCSProfiling();
460 // Originally, this was in report_ccs_profiling(). Now, retainer
461 // profiling might tack some extra stuff on to the end of this file
462 // during endProfiling().
463 if (prof_file != NULL) fclose(prof_file);
467 if (RtsFlags.EventLogFlags.doEventLogging) {
473 #if defined(TICKY_TICKY)
474 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
477 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
478 shutdownAsyncIO(wait_foreign);
481 /* free hash table storage */
484 // Finally, free all our storage
488 /* and shut down the allocator debugging */
494 // The real hs_exit():
499 // be safe; this might be a DLL
502 // Compatibility interfaces
504 shutdownHaskell(void)
510 shutdownHaskellAndExit(int n)
512 // we're about to exit(), no need to wait for foreign calls to return.
515 if (hs_init_count == 0) {
520 #ifndef mingw32_HOST_OS
522 shutdownHaskellAndSignal(int sig)
530 * called from STG-land to exit the program
533 void (*exitFn)(int) = 0;