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 "Timer.h" /* startTimer, stopTimer */
24 #include "Prelude.h" /* fixupRTStoPreludeRefs */
27 #include "ThreadLabels.h"
28 #include "BlockAlloc.h"
30 #if defined(RTS_GTK_FRONTPANEL)
31 #include "FrontPanel.h"
34 #if defined(PROFILING) || defined(DEBUG)
35 # include "Profiling.h"
36 # include "ProfHeap.h"
37 # include "RetainerProfile.h"
41 # include "GranSimRts.h"
44 #if defined(GRAN) || defined(PAR)
45 # include "ParallelRts.h"
49 # include "Parallel.h"
53 #if defined(mingw32_HOST_OS)
54 #include "win32/AsyncIO.h"
66 // Count of how many outstanding hs_init()s there have been.
67 static int hs_init_count = 0;
69 // Here we save the terminal settings on the standard file
70 // descriptors, if we need to change them (eg. to support NoBuffering
72 static void *saved_termios[3] = {NULL,NULL,NULL};
75 __hscore_get_saved_termios(int fd)
77 return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
78 saved_termios[fd] : NULL;
82 __hscore_set_saved_termios(int fd, void* ts)
84 if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
85 saved_termios[fd] = ts;
89 /* -----------------------------------------------------------------------------
90 Initialise floating point unit on x86 (currently disabled. why?)
91 (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
92 -------------------------------------------------------------------------- */
94 #define X86_INIT_FPU 0
100 __volatile unsigned short int fpu_cw;
102 // Grab the control word
103 __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
106 printf("fpu_cw: %x\n", fpu_cw);
109 // Set bits 8-9 to 10 (64-bit precision).
110 fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
112 // Store the new control word back
113 __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
117 /* -----------------------------------------------------------------------------
119 -------------------------------------------------------------------------- */
122 hs_init(int *argc, char **argv[])
125 if (hs_init_count > 1) {
126 // second and subsequent inits are ignored
130 /* The very first thing we do is grab the start time...just in case we're
131 * collecting timing statistics.
137 * The parallel system needs to be initialised and synchronised before
138 * the program is run.
140 startupParallelSystem(argv);
142 if (*argv[0] == '-') { /* Strip off mainPE flag argument */
147 argv[1] = argv[0]; /* ignore the nPEs argument */
151 /* Set the RTS flags to default values. */
152 initRtsFlagsDefaults();
154 /* Call the user hook to reset defaults, if present */
157 /* Parse the flags, separating the RTS flags from the programs args */
158 if (argc != NULL && argv != NULL) {
159 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
160 setProgArgv(*argc,*argv);
164 /* NB: this really must be done after processing the RTS flags */
165 IF_PAR_DEBUG(verbose,
166 debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
167 synchroniseSystem(); // calls initParallelSystem etc
170 /* Perform initialisation of adjustor thunk layer. */
173 /* initialise scheduler data structures (needs to be done before
179 /* And start GranSim profiling if required: */
180 if (RtsFlags.GranFlags.GranSimStats.Full)
181 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
183 /* And start GUM profiling if required: */
184 if (RtsFlags.ParFlags.ParStats.Full)
185 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
186 #endif /* PAR || GRAN */
188 /* initialize the storage manager */
191 /* initialise the stable pointer table */
192 initStablePtrTable();
195 /* initialise thread label table (tso->char*) */
196 initThreadLabelTable();
199 #if defined(PROFILING) || defined(DEBUG)
203 /* start the virtual timer 'subsystem'. */
204 startTimer(TICK_MILLISECS);
206 /* Initialise the stats department */
209 #if defined(RTS_USER_SIGNALS)
210 /* Initialise the user signal handler set */
212 /* Set up handler to run on SIGINT, etc. */
213 initDefaultHandlers();
216 #if defined(mingw32_HOST_OS)
222 #ifdef RTS_GTK_FRONTPANEL
223 if (RtsFlags.GcFlags.frontpanel) {
232 /* Record initialization times */
236 // Compatibility interface
238 startupHaskell(int argc, char *argv[], void (*init_root)(void))
240 hs_init(&argc, &argv);
242 hs_add_root(init_root);
246 /* -----------------------------------------------------------------------------
247 Per-module initialisation
249 This process traverses all the compiled modules in the program
250 starting with "Main", and performing per-module initialisation for
253 So far, two things happen at initialisation time:
255 - we register stable names for each foreign-exported function
256 in that module. This prevents foreign-exported entities, and
257 things they depend on, from being garbage collected.
259 - we supply a unique integer to each statically declared cost
260 centre and cost centre stack in the program.
262 The code generator inserts a small function "__stginit_<module>" in each
263 module and calls the registration functions in each of the modules it
266 The init* functions are compiled in the same way as STG code,
267 i.e. without normal C call/return conventions. Hence we must use
268 StgRun to call this stuff.
269 -------------------------------------------------------------------------- */
271 /* The init functions use an explicit stack...
273 #define INIT_STACK_BLOCKS 4
274 static F_ *init_stack = NULL;
277 hs_add_root(void (*init_root)(void))
283 #define cap MainCapability
287 if (hs_init_count <= 0) {
288 barf("hs_add_root() must be called after hs_init()");
291 /* The initialisation stack grows downward, with sp pointing
292 to the last occupied word */
293 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
294 bd = allocGroup(INIT_STACK_BLOCKS);
295 init_stack = (F_ *)bd->start;
296 init_stack[--init_sp] = (F_)stg_init_finish;
297 if (init_root != NULL) {
298 init_stack[--init_sp] = (F_)init_root;
301 cap.r.rSp = (P_)(init_stack + init_sp);
302 StgRun((StgFunPtr)stg_init, &cap.r);
306 #if defined(PROFILING) || defined(DEBUG)
307 // This must be done after module initialisation.
308 // ToDo: make this work in the presence of multiple hs_add_root()s.
313 /* -----------------------------------------------------------------------------
314 Shutting down the RTS
315 -------------------------------------------------------------------------- */
320 if (hs_init_count <= 0) {
321 barf("too many hs_exit()s");
324 if (hs_init_count > 0) {
325 // ignore until it's the last one
329 /* start timing the shutdown */
332 /* stop all running tasks */
336 /* end_gr_simulation prints global stats if requested -- HWL */
337 if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
341 /* stop the ticker */
344 /* reset the standard file descriptors to blocking mode */
345 resetNonBlockingFd(0);
346 resetNonBlockingFd(1);
347 resetNonBlockingFd(2);
350 // Reset the terminal settings on the standard file descriptors,
351 // if we changed them. See System.Posix.Internals.tcSetAttr for
352 // more details, including the reason we termporarily disable
356 sigset_t sigset, old_sigset;
357 sigemptyset(&sigset);
358 sigaddset(&sigset, SIGTTOU);
359 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
360 for (fd = 0; fd <= 2; fd++) {
361 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
363 tcsetattr(fd,TCSANOW,ts);
366 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
371 /* controlled exit; good thread! */
372 shutdownParallelSystem(0);
374 /* global statistics in parallel system */
378 /* stop timing the shutdown, we're about to print stats */
381 /* clean up things from the storage manager's point of view.
382 * also outputs the stats (+RTS -s) info.
386 #ifdef RTS_GTK_FRONTPANEL
387 if (RtsFlags.GcFlags.frontpanel) {
392 #if defined(PROFILING)
393 reportCCSProfiling();
396 #if defined(PROFILING) || defined(DEBUG)
401 // Originally, this was in report_ccs_profiling(). Now, retainer
402 // profiling might tack some extra stuff on to the end of this file
403 // during endProfiling().
407 #if defined(TICKY_TICKY)
408 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
411 #if defined(mingw32_HOST_OS)
416 // Compatibility interfaces
418 shutdownHaskell(void)
424 shutdownHaskellAndExit(int n)
426 if (hs_init_count == 1) {
430 /* really exit (stg_exit() would call shutdownParallelSystem() again) */
439 * called from STG-land to exit the program
443 static int exit_started=rtsFalse;
450 /* HACK: avoid a loop when exiting due to a stupid error */
453 exit_started=rtsTrue;
455 IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
456 shutdownParallelSystem(n);