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;
92 static void x86_init_fpu ( void );
95 /* -----------------------------------------------------------------------------
97 -------------------------------------------------------------------------- */
100 hs_init(int *argc, char **argv[])
103 if (hs_init_count > 1) {
104 // second and subsequent inits are ignored
108 /* The very first thing we do is grab the start time...just in case we're
109 * collecting timing statistics.
115 * The parallel system needs to be initialised and synchronised before
116 * the program is run.
118 startupParallelSystem(argv);
120 if (*argv[0] == '-') { /* Strip off mainPE flag argument */
125 argv[1] = argv[0]; /* ignore the nPEs argument */
129 /* Set the RTS flags to default values. */
130 initRtsFlagsDefaults();
132 /* Call the user hook to reset defaults, if present */
135 /* Parse the flags, separating the RTS flags from the programs args */
136 if (argc != NULL && argv != NULL) {
137 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
143 /* NB: this really must be done after processing the RTS flags */
144 IF_PAR_DEBUG(verbose,
145 debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
146 synchroniseSystem(); // calls initParallelSystem etc
149 /* Perform initialisation of adjustor thunk layer. */
152 /* initialise scheduler data structures (needs to be done before
158 /* And start GranSim profiling if required: */
159 if (RtsFlags.GranFlags.GranSimStats.Full)
160 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
162 /* And start GUM profiling if required: */
163 if (RtsFlags.ParFlags.ParStats.Full)
164 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
165 #endif /* PAR || GRAN */
167 /* initialize the storage manager */
170 /* initialise the stable pointer table */
171 initStablePtrTable();
173 /* initialise thread label table (tso->char*) */
174 initThreadLabelTable();
176 #if defined(PROFILING) || defined(DEBUG)
180 /* start the virtual timer 'subsystem'. */
181 startTimer(TICK_MILLISECS);
183 /* Initialise the stats department */
186 #if defined(RTS_USER_SIGNALS)
187 /* Initialise the user signal handler set */
189 /* Set up handler to run on SIGINT, etc. */
190 initDefaultHandlers();
193 #if defined(mingw32_TARGET_OS)
197 #ifdef RTS_GTK_FRONTPANEL
198 if (RtsFlags.GcFlags.frontpanel) {
204 setlocale(LC_CTYPE,"");
211 /* Record initialization times */
215 // Compatibility interface
217 startupHaskell(int argc, char *argv[], void (*init_root)(void))
219 hs_init(&argc, &argv);
220 hs_add_root(init_root);
224 /* -----------------------------------------------------------------------------
225 Getting/Setting the program's arguments.
227 These are used by System.Environment.
228 -------------------------------------------------------------------------- */
231 getProgArgv(int *argc, char **argv[])
233 if (argc) { *argc = prog_argc; }
234 if (argv) { *argv = prog_argv; }
238 setProgArgv(int argc, char *argv[])
240 /* Usually this is done by startupHaskell, so we don't need to call this.
241 However, sometimes Hugs wants to change the arguments which Haskell
242 getArgs >>= ... will be fed. So you can do that by calling here
243 _after_ calling startupHaskell.
249 /* -----------------------------------------------------------------------------
250 Per-module initialisation
252 This process traverses all the compiled modules in the program
253 starting with "Main", and performing per-module initialisation for
256 So far, two things happen at initialisation time:
258 - we register stable names for each foreign-exported function
259 in that module. This prevents foreign-exported entities, and
260 things they depend on, from being garbage collected.
262 - we supply a unique integer to each statically declared cost
263 centre and cost centre stack in the program.
265 The code generator inserts a small function "__stginit_<module>" in each
266 module and calls the registration functions in each of the modules it
269 The init* functions are compiled in the same way as STG code,
270 i.e. without normal C call/return conventions. Hence we must use
271 StgRun to call this stuff.
272 -------------------------------------------------------------------------- */
274 /* The init functions use an explicit stack...
276 #define INIT_STACK_BLOCKS 4
277 static F_ *init_stack = NULL;
280 hs_add_root(void (*init_root)(void))
286 #define cap MainCapability
290 if (hs_init_count <= 0) {
291 barf("hs_add_root() must be called after hs_init()");
294 /* The initialisation stack grows downward, with sp pointing
295 to the last occupied word */
296 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
297 bd = allocGroup(INIT_STACK_BLOCKS);
298 init_stack = (F_ *)bd->start;
299 init_stack[--init_sp] = (F_)stg_init_finish;
300 if (init_root != NULL) {
301 init_stack[--init_sp] = (F_)init_root;
304 cap.r.rSp = (P_)(init_stack + init_sp);
305 StgRun((StgFunPtr)stg_init, &cap.r);
309 #if defined(PROFILING) || defined(DEBUG)
310 // This must be done after module initialisation.
311 // ToDo: make this work in the presence of multiple hs_add_root()s.
316 /* -----------------------------------------------------------------------------
317 Shutting down the RTS
318 -------------------------------------------------------------------------- */
323 if (hs_init_count <= 0) {
324 barf("too many hs_exit()s");
327 if (hs_init_count > 0) {
328 // ignore until it's the last one
332 /* start timing the shutdown */
336 /* Finalize any remaining weak pointers */
337 finalizeWeakPointersNow();
340 /* stop all running tasks */
344 /* end_gr_simulation prints global stats if requested -- HWL */
345 if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
349 /* stop the ticker */
352 /* reset the standard file descriptors to blocking mode */
353 resetNonBlockingFd(0);
354 resetNonBlockingFd(1);
355 resetNonBlockingFd(2);
358 // Reset the terminal settings on the standard file descriptors,
359 // if we changed them. See System.Posix.Internals.tcSetAttr for
360 // more details, including the reason we termporarily disable
364 sigset_t sigset, old_sigset;
365 sigemptyset(&sigset);
366 sigaddset(&sigset, SIGTTOU);
367 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
368 for (fd = 0; fd <= 2; fd++) {
369 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
371 tcsetattr(fd,TCSANOW,ts);
374 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
379 /* controlled exit; good thread! */
380 shutdownParallelSystem(0);
382 /* global statistics in parallel system */
386 /* stop timing the shutdown, we're about to print stats */
389 /* clean up things from the storage manager's point of view.
390 * also outputs the stats (+RTS -s) info.
394 #ifdef RTS_GTK_FRONTPANEL
395 if (RtsFlags.GcFlags.frontpanel) {
400 #if defined(PROFILING)
401 reportCCSProfiling();
404 #if defined(PROFILING) || defined(DEBUG)
409 // Originally, this was in report_ccs_profiling(). Now, retainer
410 // profiling might tack some extra stuff on to the end of this file
411 // during endProfiling().
415 #if defined(TICKY_TICKY)
416 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
419 #if defined(mingw32_TARGET_OS)
424 // Compatibility interfaces
426 shutdownHaskell(void)
432 shutdownHaskellAndExit(int n)
434 if (hs_init_count == 1) {
438 /* really exit (stg_exit() would call shutdownParallelSystem() again) */
447 * called from STG-land to exit the program
451 static int exit_started=rtsFalse;
458 /* HACK: avoid a loop when exiting due to a stupid error */
461 exit_started=rtsTrue;
463 IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
464 shutdownParallelSystem(n);
469 /* -----------------------------------------------------------------------------
470 Initialise floating point unit on x86
471 -------------------------------------------------------------------------- */
475 x86_init_fpu ( void )
477 __volatile unsigned short int fpu_cw;
479 // Grab the control word
480 __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
483 printf("fpu_cw: %x\n", fpu_cw);
486 // Set bits 8-9 to 10 (64-bit precision).
487 fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
489 // Store the new control word back
490 __asm __volatile ("fldcw %0" : : "m" (fpu_cw));