1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2002
5 * Main function for a standalone Haskell program.
7 * ---------------------------------------------------------------------------*/
9 #include "PosixSource.h"
14 #include "Storage.h" /* initStorage, exitStorage */
15 #include "Schedule.h" /* initScheduler */
16 #include "Stats.h" /* initStats */
18 #include "Timer.h" /* startTimer, stopTimer */
22 #include "Prelude.h" /* fixupRTStoPreludeRefs */
25 #include "ThreadLabels.h"
26 #include "BlockAlloc.h"
28 #if defined(RTS_GTK_FRONTPANEL)
29 #include "FrontPanel.h"
32 #if defined(PROFILING) || defined(DEBUG)
33 # include "Profiling.h"
34 # include "ProfHeap.h"
35 # include "RetainerProfile.h"
39 # include "GranSimRts.h"
42 #if defined(GRAN) || defined(PAR)
43 # include "ParallelRts.h"
47 # include "Parallel.h"
51 #if defined(mingw32_TARGET_OS)
52 #include "win32/AsyncIO.h"
68 // Count of how many outstanding hs_init()s there have been.
69 static int hs_init_count = 0;
71 // Here we save the terminal settings on the standard file
72 // descriptors, if we need to change them (eg. to support NoBuffering
74 static void *saved_termios[3] = {NULL,NULL,NULL};
77 __hscore_get_saved_termios(int fd)
79 return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
80 saved_termios[fd] : NULL;
84 __hscore_set_saved_termios(int fd, void* ts)
86 if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
87 saved_termios[fd] = ts;
91 /* -----------------------------------------------------------------------------
92 Initialise floating point unit on x86 (currently disabled. why?)
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);
166 /* NB: this really must be done after processing the RTS flags */
167 IF_PAR_DEBUG(verbose,
168 debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
169 synchroniseSystem(); // calls initParallelSystem etc
172 /* Perform initialisation of adjustor thunk layer. */
175 /* initialise scheduler data structures (needs to be done before
181 /* And start GranSim profiling if required: */
182 if (RtsFlags.GranFlags.GranSimStats.Full)
183 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
185 /* And start GUM profiling if required: */
186 if (RtsFlags.ParFlags.ParStats.Full)
187 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
188 #endif /* PAR || GRAN */
190 /* initialize the storage manager */
193 /* initialise the stable pointer table */
194 initStablePtrTable();
196 /* initialise thread label table (tso->char*) */
197 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_TARGET_OS)
220 #ifdef RTS_GTK_FRONTPANEL
221 if (RtsFlags.GcFlags.frontpanel) {
227 setlocale(LC_CTYPE,"");
234 /* Record initialization times */
238 // Compatibility interface
240 startupHaskell(int argc, char *argv[], void (*init_root)(void))
242 hs_init(&argc, &argv);
243 hs_add_root(init_root);
247 /* -----------------------------------------------------------------------------
248 Getting/Setting the program's arguments.
250 These are used by System.Environment.
251 -------------------------------------------------------------------------- */
254 getProgArgv(int *argc, char **argv[])
256 if (argc) { *argc = prog_argc; }
257 if (argv) { *argv = prog_argv; }
261 setProgArgv(int argc, char *argv[])
263 /* Usually this is done by startupHaskell, so we don't need to call this.
264 However, sometimes Hugs wants to change the arguments which Haskell
265 getArgs >>= ... will be fed. So you can do that by calling here
266 _after_ calling startupHaskell.
272 /* -----------------------------------------------------------------------------
273 Per-module initialisation
275 This process traverses all the compiled modules in the program
276 starting with "Main", and performing per-module initialisation for
279 So far, two things happen at initialisation time:
281 - we register stable names for each foreign-exported function
282 in that module. This prevents foreign-exported entities, and
283 things they depend on, from being garbage collected.
285 - we supply a unique integer to each statically declared cost
286 centre and cost centre stack in the program.
288 The code generator inserts a small function "__stginit_<module>" in each
289 module and calls the registration functions in each of the modules it
292 The init* functions are compiled in the same way as STG code,
293 i.e. without normal C call/return conventions. Hence we must use
294 StgRun to call this stuff.
295 -------------------------------------------------------------------------- */
297 /* The init functions use an explicit stack...
299 #define INIT_STACK_BLOCKS 4
300 static F_ *init_stack = NULL;
303 hs_add_root(void (*init_root)(void))
309 #define cap MainCapability
313 if (hs_init_count <= 0) {
314 barf("hs_add_root() must be called after hs_init()");
317 /* The initialisation stack grows downward, with sp pointing
318 to the last occupied word */
319 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
320 bd = allocGroup(INIT_STACK_BLOCKS);
321 init_stack = (F_ *)bd->start;
322 init_stack[--init_sp] = (F_)stg_init_finish;
323 if (init_root != NULL) {
324 init_stack[--init_sp] = (F_)init_root;
327 cap.r.rSp = (P_)(init_stack + init_sp);
328 StgRun((StgFunPtr)stg_init, &cap.r);
332 #if defined(PROFILING) || defined(DEBUG)
333 // This must be done after module initialisation.
334 // ToDo: make this work in the presence of multiple hs_add_root()s.
339 /* -----------------------------------------------------------------------------
340 Shutting down the RTS
341 -------------------------------------------------------------------------- */
346 if (hs_init_count <= 0) {
347 barf("too many hs_exit()s");
350 if (hs_init_count > 0) {
351 // ignore until it's the last one
355 /* start timing the shutdown */
359 /* Finalize any remaining weak pointers */
360 finalizeWeakPointersNow();
363 /* stop all running tasks */
367 /* end_gr_simulation prints global stats if requested -- HWL */
368 if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
372 /* stop the ticker */
375 /* reset the standard file descriptors to blocking mode */
376 resetNonBlockingFd(0);
377 resetNonBlockingFd(1);
378 resetNonBlockingFd(2);
381 // Reset the terminal settings on the standard file descriptors,
382 // if we changed them. See System.Posix.Internals.tcSetAttr for
383 // more details, including the reason we termporarily disable
387 sigset_t sigset, old_sigset;
388 sigemptyset(&sigset);
389 sigaddset(&sigset, SIGTTOU);
390 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
391 for (fd = 0; fd <= 2; fd++) {
392 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
394 tcsetattr(fd,TCSANOW,ts);
397 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
402 /* controlled exit; good thread! */
403 shutdownParallelSystem(0);
405 /* global statistics in parallel system */
409 /* stop timing the shutdown, we're about to print stats */
412 /* clean up things from the storage manager's point of view.
413 * also outputs the stats (+RTS -s) info.
417 #ifdef RTS_GTK_FRONTPANEL
418 if (RtsFlags.GcFlags.frontpanel) {
423 #if defined(PROFILING)
424 reportCCSProfiling();
427 #if defined(PROFILING) || defined(DEBUG)
432 // Originally, this was in report_ccs_profiling(). Now, retainer
433 // profiling might tack some extra stuff on to the end of this file
434 // during endProfiling().
438 #if defined(TICKY_TICKY)
439 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
442 #if defined(mingw32_TARGET_OS)
447 // Compatibility interfaces
449 shutdownHaskell(void)
455 shutdownHaskellAndExit(int n)
457 if (hs_init_count == 1) {
461 /* really exit (stg_exit() would call shutdownParallelSystem() again) */
470 * called from STG-land to exit the program
474 static int exit_started=rtsFalse;
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);