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 "Storage.h" /* initStorage, exitStorage */
16 #include "Schedule.h" /* initScheduler */
17 #include "Stats.h" /* initStats */
18 #include "STM.h" /* initSTM */
20 #include "RtsSignals.h"
21 #include "Timer.h" /* startTimer, stopTimer */
25 #include "Prelude.h" /* fixupRTStoPreludeRefs */
28 #include "ThreadLabels.h"
29 #include "BlockAlloc.h"
31 #include "RtsTypeable.h"
35 #if defined(RTS_GTK_FRONTPANEL)
36 #include "FrontPanel.h"
39 #if defined(PROFILING) || defined(DEBUG)
40 # include "Profiling.h"
41 # include "ProfHeap.h"
42 # include "RetainerProfile.h"
46 # include "GranSimRts.h"
49 #if defined(GRAN) || defined(PAR)
50 # include "ParallelRts.h"
54 # include "Parallel.h"
58 #if defined(mingw32_HOST_OS)
59 #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 /* The very first thing we do is grab the start time...just in case we're
136 * collecting timing statistics.
142 * The parallel system needs to be initialised and synchronised before
143 * the program is run.
145 startupParallelSystem(argv);
147 if (*argv[0] == '-') { /* Strip off mainPE flag argument */
152 argv[1] = argv[0]; /* ignore the nPEs argument */
156 /* Set the RTS flags to default values. */
157 initRtsFlagsDefaults();
159 /* Call the user hook to reset defaults, if present */
162 /* Parse the flags, separating the RTS flags from the programs args */
163 if (argc != NULL && argv != NULL) {
164 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
165 setProgArgv(*argc,*argv);
168 /* initTracing must be after setupRtsFlags() */
172 /* NB: this really must be done after processing the RTS flags */
173 IF_PAR_DEBUG(verbose,
174 debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
175 synchroniseSystem(); // calls initParallelSystem etc
178 /* Perform initialisation of adjustor thunk layer. */
181 /* initialise scheduler data structures (needs to be done before
187 /* And start GranSim profiling if required: */
188 if (RtsFlags.GranFlags.GranSimStats.Full)
189 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
191 /* And start GUM profiling if required: */
192 if (RtsFlags.ParFlags.ParStats.Full)
193 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
194 #endif /* PAR || GRAN */
196 /* initialize the storage manager */
199 /* initialise the stable pointer table */
200 initStablePtrTable();
202 /* initialise the shared Typeable store */
206 /* initialise thread label table (tso->char*) */
207 initThreadLabelTable();
210 #if defined(PROFILING) || defined(DEBUG)
214 /* start the virtual timer 'subsystem'. */
217 /* Initialise the stats department */
220 #if defined(RTS_USER_SIGNALS)
221 /* Initialise the user signal handler set */
223 /* Set up handler to run on SIGINT, etc. */
224 initDefaultHandlers();
227 #if defined(mingw32_HOST_OS)
231 #ifdef RTS_GTK_FRONTPANEL
232 if (RtsFlags.GcFlags.frontpanel) {
241 #if defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
245 /* Record initialization times */
249 // Compatibility interface
251 startupHaskell(int argc, char *argv[], void (*init_root)(void))
253 hs_init(&argc, &argv);
255 hs_add_root(init_root);
259 /* -----------------------------------------------------------------------------
260 Per-module initialisation
262 This process traverses all the compiled modules in the program
263 starting with "Main", and performing per-module initialisation for
266 So far, two things happen at initialisation time:
268 - we register stable names for each foreign-exported function
269 in that module. This prevents foreign-exported entities, and
270 things they depend on, from being garbage collected.
272 - we supply a unique integer to each statically declared cost
273 centre and cost centre stack in the program.
275 The code generator inserts a small function "__stginit_<module>" in each
276 module and calls the registration functions in each of the modules it
279 The init* functions are compiled in the same way as STG code,
280 i.e. without normal C call/return conventions. Hence we must use
281 StgRun to call this stuff.
282 -------------------------------------------------------------------------- */
284 /* The init functions use an explicit stack...
286 #define INIT_STACK_BLOCKS 4
287 static F_ *init_stack = NULL;
290 hs_add_root(void (*init_root)(void))
294 Capability *cap = &MainCapability;
296 if (hs_init_count <= 0) {
297 barf("hs_add_root() must be called after hs_init()");
300 /* The initialisation stack grows downward, with sp pointing
301 to the last occupied word */
302 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
303 bd = allocGroup_lock(INIT_STACK_BLOCKS);
304 init_stack = (F_ *)bd->start;
305 init_stack[--init_sp] = (F_)stg_init_finish;
306 if (init_root != NULL) {
307 init_stack[--init_sp] = (F_)init_root;
310 cap->r.rSp = (P_)(init_stack + init_sp);
311 StgRun((StgFunPtr)stg_init, &cap->r);
317 #if defined(PROFILING) || defined(DEBUG)
318 // This must be done after module initialisation.
319 // ToDo: make this work in the presence of multiple hs_add_root()s.
324 /* -----------------------------------------------------------------------------
325 Shutting down the RTS
326 -------------------------------------------------------------------------- */
331 if (hs_init_count <= 0) {
332 errorBelch("warning: too many hs_exit()s");
336 if (hs_init_count > 0) {
337 // ignore until it's the last one
341 /* start timing the shutdown */
344 #if defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
348 /* stop all running tasks */
352 /* end_gr_simulation prints global stats if requested -- HWL */
353 if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
357 /* stop the ticker */
360 /* reset the standard file descriptors to blocking mode */
361 resetNonBlockingFd(0);
362 resetNonBlockingFd(1);
363 resetNonBlockingFd(2);
366 // Reset the terminal settings on the standard file descriptors,
367 // if we changed them. See System.Posix.Internals.tcSetAttr for
368 // more details, including the reason we termporarily disable
372 sigset_t sigset, old_sigset;
373 sigemptyset(&sigset);
374 sigaddset(&sigset, SIGTTOU);
375 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
376 for (fd = 0; fd <= 2; fd++) {
377 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
379 tcsetattr(fd,TCSANOW,ts);
382 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
387 /* controlled exit; good thread! */
388 shutdownParallelSystem(0);
390 /* global statistics in parallel system */
394 /* stop timing the shutdown, we're about to print stats */
397 /* shutdown the hpc support (if needed) */
400 // clean up things from the storage manager's point of view.
401 // also outputs the stats (+RTS -s) info.
404 /* free shared Typeable store */
407 /* initialise the stable pointer table */
408 exitStablePtrTable();
410 /* free hash table storage */
413 #ifdef RTS_GTK_FRONTPANEL
414 if (RtsFlags.GcFlags.frontpanel) {
419 #if defined(PROFILING)
420 reportCCSProfiling();
423 #if defined(PROFILING) || defined(DEBUG)
428 // Originally, this was in report_ccs_profiling(). Now, retainer
429 // profiling might tack some extra stuff on to the end of this file
430 // during endProfiling().
434 #if defined(TICKY_TICKY)
435 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
438 #if defined(mingw32_HOST_OS)
442 // Finally, free all our storage.
446 // Compatibility interfaces
448 shutdownHaskell(void)
454 shutdownHaskellAndExit(int n)
456 if (hs_init_count == 1) {
460 /* really exit (stg_exit() would call shutdownParallelSystem() again) */
469 * called from STG-land to exit the program
473 static int exit_started=rtsFalse;
476 void (*exitFn)(int) = 0;
482 /* HACK: avoid a loop when exiting due to a stupid error */
485 exit_started=rtsTrue;
487 IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
488 shutdownParallelSystem(n);