1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2002
5 * Main function for a standalone Haskell program.
7 * ---------------------------------------------------------------------------*/
9 #include "PosixSource.h"
14 #include "OSThreads.h"
15 #include "Schedule.h" /* initScheduler */
16 #include "Stats.h" /* initStats */
17 #include "STM.h" /* initSTM */
19 #include "RtsSignals.h"
20 #include "Timer.h" /* startTimer, stopTimer */
24 #include "Prelude.h" /* fixupRTStoPreludeRefs */
27 #include "ThreadLabels.h"
28 #include "BlockAlloc.h"
30 #include "RtsTypeable.h"
34 #if defined(RTS_GTK_FRONTPANEL)
35 #include "FrontPanel.h"
38 #if defined(PROFILING) || defined(DEBUG)
39 # include "Profiling.h"
40 # include "ProfHeap.h"
41 # include "RetainerProfile.h"
45 # include "GranSimRts.h"
48 #if defined(GRAN) || defined(PAR)
49 # include "ParallelRts.h"
53 # include "Parallel.h"
57 #if defined(mingw32_HOST_OS)
58 #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 /* The very first thing we do is grab the start time...just in case we're
135 * collecting timing statistics.
141 * The parallel system needs to be initialised and synchronised before
142 * the program is run.
144 startupParallelSystem(argv);
146 if (*argv[0] == '-') { /* Strip off mainPE flag argument */
151 argv[1] = argv[0]; /* ignore the nPEs argument */
155 /* 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 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
164 setProgArgv(*argc,*argv);
167 /* initTracing must be after setupRtsFlags() */
171 /* NB: this really must be done after processing the RTS flags */
172 IF_PAR_DEBUG(verbose,
173 debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
174 synchroniseSystem(); // calls initParallelSystem etc
177 /* Perform initialisation of adjustor thunk layer. */
180 /* initialise scheduler data structures (needs to be done before
186 /* And start GranSim profiling if required: */
187 if (RtsFlags.GranFlags.GranSimStats.Full)
188 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
190 /* And start GUM profiling if required: */
191 if (RtsFlags.ParFlags.ParStats.Full)
192 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
193 #endif /* PAR || GRAN */
195 /* initialize the storage manager */
198 /* initialise the stable pointer table */
199 initStablePtrTable();
201 /* initialise the shared Typeable store */
205 /* initialise thread label table (tso->char*) */
206 initThreadLabelTable();
209 #if defined(PROFILING) || defined(DEBUG)
213 /* start the virtual timer 'subsystem'. */
216 /* Initialise the stats department */
219 #if defined(RTS_USER_SIGNALS)
220 /* Initialise the user signal handler set */
222 /* Set up handler to run on SIGINT, etc. */
223 initDefaultHandlers();
226 #if defined(mingw32_HOST_OS)
230 #ifdef RTS_GTK_FRONTPANEL
231 if (RtsFlags.GcFlags.frontpanel) {
240 #if defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
244 /* Record initialization times */
248 // Compatibility interface
250 startupHaskell(int argc, char *argv[], void (*init_root)(void))
252 hs_init(&argc, &argv);
254 hs_add_root(init_root);
258 /* -----------------------------------------------------------------------------
259 Per-module initialisation
261 This process traverses all the compiled modules in the program
262 starting with "Main", and performing per-module initialisation for
265 So far, two things happen at initialisation time:
267 - we register stable names for each foreign-exported function
268 in that module. This prevents foreign-exported entities, and
269 things they depend on, from being garbage collected.
271 - we supply a unique integer to each statically declared cost
272 centre and cost centre stack in the program.
274 The code generator inserts a small function "__stginit_<module>" in each
275 module and calls the registration functions in each of the modules it
278 The init* functions are compiled in the same way as STG code,
279 i.e. without normal C call/return conventions. Hence we must use
280 StgRun to call this stuff.
281 -------------------------------------------------------------------------- */
283 /* The init functions use an explicit stack...
285 #define INIT_STACK_BLOCKS 4
286 static F_ *init_stack = NULL;
289 hs_add_root(void (*init_root)(void))
293 Capability *cap = &MainCapability;
295 if (hs_init_count <= 0) {
296 barf("hs_add_root() must be called after hs_init()");
299 /* The initialisation stack grows downward, with sp pointing
300 to the last occupied word */
301 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
302 bd = allocGroup_lock(INIT_STACK_BLOCKS);
303 init_stack = (F_ *)bd->start;
304 init_stack[--init_sp] = (F_)stg_init_finish;
305 if (init_root != NULL) {
306 init_stack[--init_sp] = (F_)init_root;
309 cap->r.rSp = (P_)(init_stack + init_sp);
310 StgRun((StgFunPtr)stg_init, &cap->r);
316 #if defined(PROFILING) || defined(DEBUG)
317 // This must be done after module initialisation.
318 // ToDo: make this work in the presence of multiple hs_add_root()s.
323 /* -----------------------------------------------------------------------------
324 Shutting down the RTS
325 -------------------------------------------------------------------------- */
330 if (hs_init_count <= 0) {
331 errorBelch("warning: too many hs_exit()s");
335 if (hs_init_count > 0) {
336 // ignore until it's the last one
340 /* start timing the shutdown */
343 #if defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
347 /* stop all running tasks */
351 /* end_gr_simulation prints global stats if requested -- HWL */
352 if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
356 /* stop the ticker */
359 /* reset the standard file descriptors to blocking mode */
360 resetNonBlockingFd(0);
361 resetNonBlockingFd(1);
362 resetNonBlockingFd(2);
365 // Reset the terminal settings on the standard file descriptors,
366 // if we changed them. See System.Posix.Internals.tcSetAttr for
367 // more details, including the reason we termporarily disable
371 sigset_t sigset, old_sigset;
372 sigemptyset(&sigset);
373 sigaddset(&sigset, SIGTTOU);
374 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
375 for (fd = 0; fd <= 2; fd++) {
376 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
378 tcsetattr(fd,TCSANOW,ts);
381 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
386 /* controlled exit; good thread! */
387 shutdownParallelSystem(0);
389 /* global statistics in parallel system */
393 /* stop timing the shutdown, we're about to print stats */
396 /* shutdown the hpc support (if needed) */
399 // clean up things from the storage manager's point of view.
400 // also outputs the stats (+RTS -s) info.
403 /* free shared Typeable store */
406 /* initialise the stable pointer table */
407 exitStablePtrTable();
409 /* free hash table storage */
412 #ifdef RTS_GTK_FRONTPANEL
413 if (RtsFlags.GcFlags.frontpanel) {
418 #if defined(PROFILING)
419 reportCCSProfiling();
422 #if defined(PROFILING) || defined(DEBUG)
427 // Originally, this was in report_ccs_profiling(). Now, retainer
428 // profiling might tack some extra stuff on to the end of this file
429 // during endProfiling().
433 #if defined(TICKY_TICKY)
434 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
437 #if defined(mingw32_HOST_OS)
441 // Finally, free all our storage.
445 // Compatibility interfaces
447 shutdownHaskell(void)
453 shutdownHaskellAndExit(int n)
455 if (hs_init_count == 1) {
459 /* really exit (stg_exit() would call shutdownParallelSystem() again) */
468 * called from STG-land to exit the program
472 static int exit_started=rtsFalse;
475 void (*exitFn)(int) = 0;
481 /* HACK: avoid a loop when exiting due to a stupid error */
484 exit_started=rtsTrue;
486 IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
487 shutdownParallelSystem(n);