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"
71 // Count of how many outstanding hs_init()s there have been.
72 static int hs_init_count = 0;
74 // Here we save the terminal settings on the standard file
75 // descriptors, if we need to change them (eg. to support NoBuffering
77 static void *saved_termios[3] = {NULL,NULL,NULL};
80 __hscore_get_saved_termios(int fd)
82 return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
83 saved_termios[fd] : NULL;
87 __hscore_set_saved_termios(int fd, void* ts)
89 if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
90 saved_termios[fd] = ts;
94 /* -----------------------------------------------------------------------------
95 Initialise floating point unit on x86 (currently disabled. why?)
96 (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
97 -------------------------------------------------------------------------- */
99 #define X86_INIT_FPU 0
103 x86_init_fpu ( void )
105 __volatile unsigned short int fpu_cw;
107 // Grab the control word
108 __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
111 printf("fpu_cw: %x\n", fpu_cw);
114 // Set bits 8-9 to 10 (64-bit precision).
115 fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
117 // Store the new control word back
118 __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
122 /* -----------------------------------------------------------------------------
124 -------------------------------------------------------------------------- */
127 hs_init(int *argc, char **argv[])
130 if (hs_init_count > 1) {
131 // second and subsequent inits are ignored
135 /* Initialise the stats department, phase 0 */
138 /* Next we do is grab the start time...just in case we're
139 * collecting timing statistics.
144 /* Start off by initialising the allocator debugging so we can
149 /* Set the RTS flags to default values. */
151 initRtsFlagsDefaults();
153 /* Call the user hook to reset defaults, if present */
156 /* Parse the flags, separating the RTS flags from the programs args */
157 if (argc != NULL && argv != NULL) {
158 setFullProgArgv(*argc,*argv);
159 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
160 setProgArgv(*argc,*argv);
163 /* Initialise the stats department, phase 1 */
170 /* initTracing must be after setupRtsFlags() */
175 /* initialise scheduler data structures (needs to be done before
180 /* initialize the storage manager */
183 /* initialise the stable pointer table */
184 initStablePtrTable();
186 /* Add some GC roots for things in the base package that the RTS
187 * knows about. We don't know whether these turn out to be CAFs
188 * or refer to CAFs, but we have to assume that they might.
190 getStablePtr((StgPtr)base_GHCziTopHandler_runIO_closure);
191 getStablePtr((StgPtr)base_GHCziTopHandler_runNonIO_closure);
192 getStablePtr((StgPtr)stackOverflow_closure);
193 getStablePtr((StgPtr)heapOverflow_closure);
194 getStablePtr((StgPtr)runFinalizerBatch_closure);
195 getStablePtr((StgPtr)unpackCString_closure);
196 getStablePtr((StgPtr)blockedOnDeadMVar_closure);
197 getStablePtr((StgPtr)nonTermination_closure);
198 getStablePtr((StgPtr)blockedIndefinitely_closure);
200 /* initialise the shared Typeable store */
203 /* initialise file locking, if necessary */
204 #if !defined(mingw32_HOST_OS)
209 /* initialise thread label table (tso->char*) */
210 initThreadLabelTable();
216 if (RtsFlags.EventLogFlags.doEventLogging) {
221 /* start the virtual timer 'subsystem'. */
225 #if defined(RTS_USER_SIGNALS)
226 if (RtsFlags.MiscFlags.install_signal_handlers) {
227 /* Initialise the user signal handler set */
229 /* Set up handler to run on SIGINT, etc. */
230 initDefaultHandlers();
234 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
238 #ifdef RTS_GTK_FRONTPANEL
239 if (RtsFlags.GcFlags.frontpanel) {
248 /* Record initialization times */
252 // Compatibility interface
254 startupHaskell(int argc, char *argv[], void (*init_root)(void))
256 hs_init(&argc, &argv);
258 hs_add_root(init_root);
262 /* -----------------------------------------------------------------------------
263 Per-module initialisation
265 This process traverses all the compiled modules in the program
266 starting with "Main", and performing per-module initialisation for
269 So far, two things happen at initialisation time:
271 - we register stable names for each foreign-exported function
272 in that module. This prevents foreign-exported entities, and
273 things they depend on, from being garbage collected.
275 - we supply a unique integer to each statically declared cost
276 centre and cost centre stack in the program.
278 The code generator inserts a small function "__stginit_<module>" in each
279 module and calls the registration functions in each of the modules it
282 The init* functions are compiled in the same way as STG code,
283 i.e. without normal C call/return conventions. Hence we must use
284 StgRun to call this stuff.
285 -------------------------------------------------------------------------- */
287 /* The init functions use an explicit stack...
289 #define INIT_STACK_BLOCKS 4
290 static F_ *init_stack = NULL;
293 hs_add_root(void (*init_root)(void))
301 if (hs_init_count <= 0) {
302 barf("hs_add_root() must be called after hs_init()");
305 /* The initialisation stack grows downward, with sp pointing
306 to the last occupied word */
307 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
308 bd = allocGroup_lock(INIT_STACK_BLOCKS);
309 init_stack = (F_ *)bd->start;
310 init_stack[--init_sp] = (F_)stg_init_finish;
311 if (init_root != NULL) {
312 init_stack[--init_sp] = (F_)init_root;
315 cap->r.rSp = (P_)(init_stack + init_sp);
316 StgRun((StgFunPtr)stg_init, &cap->r);
322 // This must be done after module initialisation.
323 // ToDo: make this work in the presence of multiple hs_add_root()s.
329 #if defined(THREADED_RTS)
334 /* ----------------------------------------------------------------------------
335 * Shutting down the RTS
337 * The wait_foreign parameter means:
338 * True ==> wait for any threads doing foreign calls now.
339 * False ==> threads doing foreign calls may return in the
340 * future, but will immediately block on a mutex.
341 * (capability->lock).
343 * If this RTS is a DLL that we're about to unload, then you want
344 * safe=True, otherwise the thread might return to code that has been
345 * unloaded. If this is a standalone program that is about to exit,
346 * then you can get away with safe=False, which is better because we
347 * won't hang on exit if there is a blocked foreign call outstanding.
349 ------------------------------------------------------------------------- */
352 hs_exit_(rtsBool wait_foreign)
354 if (hs_init_count <= 0) {
355 errorBelch("warning: too many hs_exit()s");
359 if (hs_init_count > 0) {
360 // ignore until it's the last one
364 /* start timing the shutdown */
369 #if defined(THREADED_RTS)
373 /* stop all running tasks */
374 exitScheduler(wait_foreign);
376 /* run C finalizers for all active weak pointers */
377 runAllCFinalizers(weak_ptr_list);
379 #if defined(RTS_USER_SIGNALS)
380 if (RtsFlags.MiscFlags.install_signal_handlers) {
381 freeSignalHandlers();
385 /* stop the ticker */
389 /* reset the standard file descriptors to blocking mode */
390 resetNonBlockingFd(0);
391 resetNonBlockingFd(1);
392 resetNonBlockingFd(2);
395 // Reset the terminal settings on the standard file descriptors,
396 // if we changed them. See System.Posix.Internals.tcSetAttr for
397 // more details, including the reason we termporarily disable
401 sigset_t sigset, old_sigset;
402 sigemptyset(&sigset);
403 sigaddset(&sigset, SIGTTOU);
404 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
405 for (fd = 0; fd <= 2; fd++) {
406 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
408 tcsetattr(fd,TCSANOW,ts);
411 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
415 // uninstall signal handlers
416 resetDefaultHandlers();
418 /* stop timing the shutdown, we're about to print stats */
421 /* shutdown the hpc support (if needed) */
424 // clean up things from the storage manager's point of view.
425 // also outputs the stats (+RTS -s) info.
431 /* free shared Typeable store */
434 /* free file locking tables, if necessary */
435 #if !defined(mingw32_HOST_OS)
439 /* free the stable pointer table */
440 exitStablePtrTable();
443 /* free the thread label table */
444 freeThreadLabelTable();
447 #ifdef RTS_GTK_FRONTPANEL
448 if (RtsFlags.GcFlags.frontpanel) {
453 #if defined(PROFILING)
454 reportCCSProfiling();
461 // Originally, this was in report_ccs_profiling(). Now, retainer
462 // profiling might tack some extra stuff on to the end of this file
463 // during endProfiling().
464 if (prof_file != NULL) fclose(prof_file);
468 if (RtsFlags.EventLogFlags.doEventLogging) {
474 #if defined(TICKY_TICKY)
475 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
478 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
479 shutdownAsyncIO(wait_foreign);
482 /* free hash table storage */
485 // Finally, free all our storage
489 /* and shut down the allocator debugging */
495 // The real hs_exit():
500 // be safe; this might be a DLL
503 // Compatibility interfaces
505 shutdownHaskell(void)
511 shutdownHaskellAndExit(int n)
513 // we're about to exit(), no need to wait for foreign calls to return.
516 if (hs_init_count == 0) {
521 #ifndef mingw32_HOST_OS
523 shutdownHaskellAndSignal(int sig)
531 * called from STG-land to exit the program
534 void (*exitFn)(int) = 0;