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 #if defined(RTS_GTK_FRONTPANEL)
32 #include "FrontPanel.h"
35 #if defined(PROFILING) || defined(DEBUG)
36 # include "Profiling.h"
37 # include "ProfHeap.h"
38 # include "RetainerProfile.h"
42 # include "GranSimRts.h"
45 #if defined(GRAN) || defined(PAR)
46 # include "ParallelRts.h"
50 # include "Parallel.h"
54 #if defined(mingw32_HOST_OS)
55 #include "win32/AsyncIO.h"
67 // Count of how many outstanding hs_init()s there have been.
68 static int hs_init_count = 0;
70 // Here we save the terminal settings on the standard file
71 // descriptors, if we need to change them (eg. to support NoBuffering
73 static void *saved_termios[3] = {NULL,NULL,NULL};
76 __hscore_get_saved_termios(int fd)
78 return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
79 saved_termios[fd] : NULL;
83 __hscore_set_saved_termios(int fd, void* ts)
85 if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
86 saved_termios[fd] = ts;
90 /* -----------------------------------------------------------------------------
91 Initialise floating point unit on x86 (currently disabled. why?)
92 (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
93 -------------------------------------------------------------------------- */
95 #define X86_INIT_FPU 0
101 __volatile unsigned short int fpu_cw;
103 // Grab the control word
104 __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
107 printf("fpu_cw: %x\n", fpu_cw);
110 // Set bits 8-9 to 10 (64-bit precision).
111 fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
113 // Store the new control word back
114 __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
118 /* -----------------------------------------------------------------------------
120 -------------------------------------------------------------------------- */
123 hs_init(int *argc, char **argv[])
126 if (hs_init_count > 1) {
127 // second and subsequent inits are ignored
131 /* The very first thing we do is grab the start time...just in case we're
132 * collecting timing statistics.
138 * The parallel system needs to be initialised and synchronised before
139 * the program is run.
141 startupParallelSystem(argv);
143 if (*argv[0] == '-') { /* Strip off mainPE flag argument */
148 argv[1] = argv[0]; /* ignore the nPEs argument */
152 /* Set the RTS flags to default values. */
153 initRtsFlagsDefaults();
155 /* Call the user hook to reset defaults, if present */
158 /* Parse the flags, separating the RTS flags from the programs args */
159 if (argc != NULL && argv != NULL) {
160 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
161 setProgArgv(*argc,*argv);
165 /* NB: this really must be done after processing the RTS flags */
166 IF_PAR_DEBUG(verbose,
167 debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
168 synchroniseSystem(); // calls initParallelSystem etc
171 /* Perform initialisation of adjustor thunk layer. */
174 /* initialise scheduler data structures (needs to be done before
180 /* And start GranSim profiling if required: */
181 if (RtsFlags.GranFlags.GranSimStats.Full)
182 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
184 /* And start GUM profiling if required: */
185 if (RtsFlags.ParFlags.ParStats.Full)
186 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
187 #endif /* PAR || GRAN */
189 /* initialize the storage manager */
192 /* initialise the stable pointer table */
193 initStablePtrTable();
196 /* initialise thread label table (tso->char*) */
197 initThreadLabelTable();
200 #if defined(PROFILING) || defined(DEBUG)
204 /* start the virtual timer 'subsystem'. */
205 startTimer(TICK_MILLISECS);
207 /* Initialise the stats department */
210 #if defined(RTS_USER_SIGNALS)
211 /* Initialise the user signal handler set */
213 /* Set up handler to run on SIGINT, etc. */
214 initDefaultHandlers();
217 #if defined(mingw32_HOST_OS)
221 #ifdef RTS_GTK_FRONTPANEL
222 if (RtsFlags.GcFlags.frontpanel) {
231 /* Record initialization times */
235 // Compatibility interface
237 startupHaskell(int argc, char *argv[], void (*init_root)(void))
239 hs_init(&argc, &argv);
241 hs_add_root(init_root);
245 /* -----------------------------------------------------------------------------
246 Per-module initialisation
248 This process traverses all the compiled modules in the program
249 starting with "Main", and performing per-module initialisation for
252 So far, two things happen at initialisation time:
254 - we register stable names for each foreign-exported function
255 in that module. This prevents foreign-exported entities, and
256 things they depend on, from being garbage collected.
258 - we supply a unique integer to each statically declared cost
259 centre and cost centre stack in the program.
261 The code generator inserts a small function "__stginit_<module>" in each
262 module and calls the registration functions in each of the modules it
265 The init* functions are compiled in the same way as STG code,
266 i.e. without normal C call/return conventions. Hence we must use
267 StgRun to call this stuff.
268 -------------------------------------------------------------------------- */
270 /* The init functions use an explicit stack...
272 #define INIT_STACK_BLOCKS 4
273 static F_ *init_stack = NULL;
276 hs_add_root(void (*init_root)(void))
280 Capability *cap = &MainCapability;
282 if (hs_init_count <= 0) {
283 barf("hs_add_root() must be called after hs_init()");
286 /* The initialisation stack grows downward, with sp pointing
287 to the last occupied word */
288 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
289 bd = allocGroup_lock(INIT_STACK_BLOCKS);
290 init_stack = (F_ *)bd->start;
291 init_stack[--init_sp] = (F_)stg_init_finish;
292 if (init_root != NULL) {
293 init_stack[--init_sp] = (F_)init_root;
296 cap->r.rSp = (P_)(init_stack + init_sp);
297 StgRun((StgFunPtr)stg_init, &cap->r);
301 #if defined(PROFILING) || defined(DEBUG)
302 // This must be done after module initialisation.
303 // ToDo: make this work in the presence of multiple hs_add_root()s.
308 /* -----------------------------------------------------------------------------
309 Shutting down the RTS
310 -------------------------------------------------------------------------- */
315 if (hs_init_count <= 0) {
316 barf("too many hs_exit()s");
319 if (hs_init_count > 0) {
320 // ignore until it's the last one
324 /* start timing the shutdown */
327 /* stop all running tasks */
331 /* end_gr_simulation prints global stats if requested -- HWL */
332 if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
336 /* stop the ticker */
339 /* reset the standard file descriptors to blocking mode */
340 resetNonBlockingFd(0);
341 resetNonBlockingFd(1);
342 resetNonBlockingFd(2);
345 // Reset the terminal settings on the standard file descriptors,
346 // if we changed them. See System.Posix.Internals.tcSetAttr for
347 // more details, including the reason we termporarily disable
351 sigset_t sigset, old_sigset;
352 sigemptyset(&sigset);
353 sigaddset(&sigset, SIGTTOU);
354 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
355 for (fd = 0; fd <= 2; fd++) {
356 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
358 tcsetattr(fd,TCSANOW,ts);
361 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
366 /* controlled exit; good thread! */
367 shutdownParallelSystem(0);
369 /* global statistics in parallel system */
373 /* stop timing the shutdown, we're about to print stats */
376 /* clean up things from the storage manager's point of view.
377 * also outputs the stats (+RTS -s) info.
381 #ifdef RTS_GTK_FRONTPANEL
382 if (RtsFlags.GcFlags.frontpanel) {
387 #if defined(PROFILING)
388 reportCCSProfiling();
391 #if defined(PROFILING) || defined(DEBUG)
396 // Originally, this was in report_ccs_profiling(). Now, retainer
397 // profiling might tack some extra stuff on to the end of this file
398 // during endProfiling().
402 #if defined(TICKY_TICKY)
403 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
406 #if defined(mingw32_HOST_OS)
411 // Compatibility interfaces
413 shutdownHaskell(void)
419 shutdownHaskellAndExit(int n)
421 if (hs_init_count == 1) {
425 /* really exit (stg_exit() would call shutdownParallelSystem() again) */
434 * called from STG-land to exit the program
438 static int exit_started=rtsFalse;
445 /* HACK: avoid a loop when exiting due to a stupid error */
448 exit_started=rtsTrue;
450 IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
451 shutdownParallelSystem(n);