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
11 #include "PosixSource.h"
18 #include "sm/Storage.h"
20 #include "Schedule.h" /* initScheduler */
21 #include "Stats.h" /* initStats */
22 #include "STM.h" /* initSTM */
23 #include "RtsSignals.h"
27 #include "Prelude.h" /* fixupRTStoPreludeRefs */
28 #include "ThreadLabels.h"
29 #include "sm/BlockAlloc.h"
32 #include "eventlog/EventLog.h"
34 #include "Profiling.h"
38 #if defined(RTS_GTK_FRONTPANEL)
39 #include "FrontPanel.h"
42 #if defined(PROFILING)
43 # include "ProfHeap.h"
44 # include "RetainerProfile.h"
47 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
48 #include "win32/AsyncIO.h"
51 #if !defined(mingw32_HOST_OS)
52 #include "posix/TTY.h"
53 #include "posix/FileLock.h"
67 // Count of how many outstanding hs_init()s there have been.
68 static int hs_init_count = 0;
70 /* -----------------------------------------------------------------------------
71 Initialise floating point unit on x86 (currently disabled. why?)
72 (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
73 -------------------------------------------------------------------------- */
75 #define X86_INIT_FPU 0
81 __volatile unsigned short int fpu_cw;
83 // Grab the control word
84 __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
87 printf("fpu_cw: %x\n", fpu_cw);
90 // Set bits 8-9 to 10 (64-bit precision).
91 fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
93 // Store the new control word back
94 __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
98 /* -----------------------------------------------------------------------------
100 -------------------------------------------------------------------------- */
103 hs_init(int *argc, char **argv[])
106 if (hs_init_count > 1) {
107 // second and subsequent inits are ignored
111 setlocale(LC_CTYPE,"");
113 /* Initialise the stats department, phase 0 */
116 /* Next we do is grab the start time...just in case we're
117 * collecting timing statistics.
122 /* Start off by initialising the allocator debugging so we can
127 /* Set the RTS flags to default values. */
129 initRtsFlagsDefaults();
131 /* Call the user hook to reset defaults, if present */
134 /* Parse the flags, separating the RTS flags from the programs args */
135 if (argc != NULL && argv != NULL) {
136 setFullProgArgv(*argc,*argv);
137 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
138 setProgArgv(*argc,*argv);
141 /* Initialise the stats department, phase 1 */
148 /* initTracing must be after setupRtsFlags() */
153 /* initialise scheduler data structures (needs to be done before
158 /* initialize the storage manager */
161 /* initialise the stable pointer table */
162 initStablePtrTable();
164 /* Add some GC roots for things in the base package that the RTS
165 * knows about. We don't know whether these turn out to be CAFs
166 * or refer to CAFs, but we have to assume that they might.
168 getStablePtr((StgPtr)base_GHCziTopHandler_runIO_closure);
169 getStablePtr((StgPtr)base_GHCziTopHandler_runNonIO_closure);
170 getStablePtr((StgPtr)stackOverflow_closure);
171 getStablePtr((StgPtr)heapOverflow_closure);
172 getStablePtr((StgPtr)runFinalizerBatch_closure);
173 getStablePtr((StgPtr)unpackCString_closure);
174 getStablePtr((StgPtr)blockedOnDeadMVar_closure);
175 getStablePtr((StgPtr)nonTermination_closure);
176 getStablePtr((StgPtr)blockedIndefinitely_closure);
178 /* initialise the shared Typeable store */
181 /* initialise file locking, if necessary */
182 #if !defined(mingw32_HOST_OS)
187 /* initialise thread label table (tso->char*) */
188 initThreadLabelTable();
194 if (RtsFlags.EventLogFlags.doEventLogging) {
199 /* start the virtual timer 'subsystem'. */
203 #if defined(RTS_USER_SIGNALS)
204 if (RtsFlags.MiscFlags.install_signal_handlers) {
205 /* Initialise the user signal handler set */
207 /* Set up handler to run on SIGINT, etc. */
208 initDefaultHandlers();
212 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
216 #ifdef RTS_GTK_FRONTPANEL
217 if (RtsFlags.GcFlags.frontpanel) {
226 /* Record initialization times */
230 // Compatibility interface
232 startupHaskell(int argc, char *argv[], void (*init_root)(void))
234 hs_init(&argc, &argv);
236 hs_add_root(init_root);
240 /* -----------------------------------------------------------------------------
241 Per-module initialisation
243 This process traverses all the compiled modules in the program
244 starting with "Main", and performing per-module initialisation for
247 So far, two things happen at initialisation time:
249 - we register stable names for each foreign-exported function
250 in that module. This prevents foreign-exported entities, and
251 things they depend on, from being garbage collected.
253 - we supply a unique integer to each statically declared cost
254 centre and cost centre stack in the program.
256 The code generator inserts a small function "__stginit_<module>" in each
257 module and calls the registration functions in each of the modules it
260 The init* functions are compiled in the same way as STG code,
261 i.e. without normal C call/return conventions. Hence we must use
262 StgRun to call this stuff.
263 -------------------------------------------------------------------------- */
265 /* The init functions use an explicit stack...
267 #define INIT_STACK_BLOCKS 4
268 static StgFunPtr *init_stack = NULL;
271 hs_add_root(void (*init_root)(void))
279 if (hs_init_count <= 0) {
280 barf("hs_add_root() must be called after hs_init()");
283 /* The initialisation stack grows downward, with sp pointing
284 to the last occupied word */
285 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
286 bd = allocGroup_lock(INIT_STACK_BLOCKS);
287 init_stack = (StgFunPtr *)bd->start;
288 init_stack[--init_sp] = (StgFunPtr)stg_init_finish;
289 if (init_root != NULL) {
290 init_stack[--init_sp] = (StgFunPtr)init_root;
293 cap->r.rSp = (P_)(init_stack + init_sp);
294 StgRun((StgFunPtr)stg_init, &cap->r);
300 // This must be done after module initialisation.
301 // ToDo: make this work in the presence of multiple hs_add_root()s.
307 #if defined(THREADED_RTS)
312 /* ----------------------------------------------------------------------------
313 * Shutting down the RTS
315 * The wait_foreign parameter means:
316 * True ==> wait for any threads doing foreign calls now.
317 * False ==> threads doing foreign calls may return in the
318 * future, but will immediately block on a mutex.
319 * (capability->lock).
321 * If this RTS is a DLL that we're about to unload, then you want
322 * safe=True, otherwise the thread might return to code that has been
323 * unloaded. If this is a standalone program that is about to exit,
324 * then you can get away with safe=False, which is better because we
325 * won't hang on exit if there is a blocked foreign call outstanding.
327 ------------------------------------------------------------------------- */
330 hs_exit_(rtsBool wait_foreign)
332 if (hs_init_count <= 0) {
333 errorBelch("warning: too many hs_exit()s");
337 if (hs_init_count > 0) {
338 // ignore until it's the last one
342 /* start timing the shutdown */
347 #if defined(THREADED_RTS)
351 /* stop all running tasks */
352 exitScheduler(wait_foreign);
354 /* run C finalizers for all active weak pointers */
355 runAllCFinalizers(weak_ptr_list);
357 #if defined(RTS_USER_SIGNALS)
358 if (RtsFlags.MiscFlags.install_signal_handlers) {
359 freeSignalHandlers();
363 /* stop the ticker */
367 // set the terminal settings back to what they were
368 #if !defined(mingw32_HOST_OS)
369 resetTerminalSettings();
372 // uninstall signal handlers
373 resetDefaultHandlers();
375 /* stop timing the shutdown, we're about to print stats */
378 /* shutdown the hpc support (if needed) */
381 // clean up things from the storage manager's point of view.
382 // also outputs the stats (+RTS -s) info.
388 /* free shared Typeable store */
391 /* free file locking tables, if necessary */
392 #if !defined(mingw32_HOST_OS)
396 /* free the stable pointer table */
397 exitStablePtrTable();
400 /* free the thread label table */
401 freeThreadLabelTable();
404 #ifdef RTS_GTK_FRONTPANEL
405 if (RtsFlags.GcFlags.frontpanel) {
410 #if defined(PROFILING)
411 reportCCSProfiling();
418 // Originally, this was in report_ccs_profiling(). Now, retainer
419 // profiling might tack some extra stuff on to the end of this file
420 // during endProfiling().
421 if (prof_file != NULL) fclose(prof_file);
425 if (RtsFlags.EventLogFlags.doEventLogging) {
431 #if defined(TICKY_TICKY)
432 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
435 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
436 shutdownAsyncIO(wait_foreign);
439 /* free hash table storage */
442 // Finally, free all our storage
446 /* and shut down the allocator debugging */
452 // The real hs_exit():
457 // be safe; this might be a DLL
460 // Compatibility interfaces
462 shutdownHaskell(void)
468 shutdownHaskellAndExit(int n)
470 // we're about to exit(), no need to wait for foreign calls to return.
473 if (hs_init_count == 0) {
478 #ifndef mingw32_HOST_OS
480 shutdownHaskellAndSignal(int sig)
488 * called from STG-land to exit the program
491 void (*exitFn)(int) = 0;