1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2002
5 * Main function for a standalone Haskell program.
7 * ---------------------------------------------------------------------------*/
9 // PAPI uses caddr_t, which is not POSIX
10 // #include "PosixSource.h"
16 #include "OSThreads.h"
17 #include "Schedule.h" /* initScheduler */
18 #include "Stats.h" /* initStats */
19 #include "STM.h" /* initSTM */
21 #include "RtsSignals.h"
22 #include "Timer.h" /* startTimer, stopTimer */
26 #include "Prelude.h" /* fixupRTStoPreludeRefs */
29 #include "ThreadLabels.h"
30 #include "BlockAlloc.h"
32 #include "RtsTypeable.h"
36 #if defined(RTS_GTK_FRONTPANEL)
37 #include "FrontPanel.h"
40 #if defined(PROFILING) || defined(DEBUG)
41 # include "Profiling.h"
42 # include "ProfHeap.h"
43 # include "RetainerProfile.h"
47 # include "GranSimRts.h"
50 #if defined(GRAN) || defined(PAR)
51 # include "ParallelRts.h"
55 # include "Parallel.h"
59 #if defined(mingw32_HOST_OS)
60 #include "win32/AsyncIO.h"
76 // Count of how many outstanding hs_init()s there have been.
77 static int hs_init_count = 0;
79 // Here we save the terminal settings on the standard file
80 // descriptors, if we need to change them (eg. to support NoBuffering
82 static void *saved_termios[3] = {NULL,NULL,NULL};
85 __hscore_get_saved_termios(int fd)
87 return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
88 saved_termios[fd] : NULL;
92 __hscore_set_saved_termios(int fd, void* ts)
94 if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
95 saved_termios[fd] = ts;
99 /* -----------------------------------------------------------------------------
100 Initialise floating point unit on x86 (currently disabled. why?)
101 (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
102 -------------------------------------------------------------------------- */
104 #define X86_INIT_FPU 0
108 x86_init_fpu ( void )
110 __volatile unsigned short int fpu_cw;
112 // Grab the control word
113 __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
116 printf("fpu_cw: %x\n", fpu_cw);
119 // Set bits 8-9 to 10 (64-bit precision).
120 fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
122 // Store the new control word back
123 __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
127 /* -----------------------------------------------------------------------------
129 -------------------------------------------------------------------------- */
132 hs_init(int *argc, char **argv[])
135 if (hs_init_count > 1) {
136 // second and subsequent inits are ignored
140 /* The very first thing we do is grab the start time...just in case we're
141 * collecting timing statistics.
147 * The parallel system needs to be initialised and synchronised before
148 * the program is run.
150 startupParallelSystem(argv);
152 if (*argv[0] == '-') { /* Strip off mainPE flag argument */
157 argv[1] = argv[0]; /* ignore the nPEs argument */
161 /* Initialise the performance tracking library */
163 /* Must fix to abort gracefully */
164 if(PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT)
169 if ((err = PAPI_thread_init(osThreadId)) < 0) {
170 barf("PAPI_thread_init: %d",err);
176 /* Set the RTS flags to default values. */
178 initRtsFlagsDefaults();
180 /* Call the user hook to reset defaults, if present */
183 /* Parse the flags, separating the RTS flags from the programs args */
184 if (argc != NULL && argv != NULL) {
185 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
186 setProgArgv(*argc,*argv);
189 /* initTracing must be after setupRtsFlags() */
193 /* NB: this really must be done after processing the RTS flags */
194 IF_PAR_DEBUG(verbose,
195 debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
196 synchroniseSystem(); // calls initParallelSystem etc
199 /* Perform initialisation of adjustor thunk layer. */
202 /* initialise scheduler data structures (needs to be done before
208 /* And start GranSim profiling if required: */
209 if (RtsFlags.GranFlags.GranSimStats.Full)
210 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
212 /* And start GUM profiling if required: */
213 if (RtsFlags.ParFlags.ParStats.Full)
214 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
215 #endif /* PAR || GRAN */
217 /* initialize the storage manager */
220 /* initialise the stable pointer table */
221 initStablePtrTable();
223 /* initialise the shared Typeable store */
227 /* initialise thread label table (tso->char*) */
228 initThreadLabelTable();
231 #if defined(PROFILING) || defined(DEBUG)
235 /* start the virtual timer 'subsystem'. */
238 /* Initialise the stats department */
241 #if defined(RTS_USER_SIGNALS)
242 /* Initialise the user signal handler set */
244 /* Set up handler to run on SIGINT, etc. */
245 initDefaultHandlers();
248 #if defined(mingw32_HOST_OS)
252 #ifdef RTS_GTK_FRONTPANEL
253 if (RtsFlags.GcFlags.frontpanel) {
262 #if defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
266 /* Record initialization times */
270 // Compatibility interface
272 startupHaskell(int argc, char *argv[], void (*init_root)(void))
274 hs_init(&argc, &argv);
276 hs_add_root(init_root);
280 /* -----------------------------------------------------------------------------
281 Per-module initialisation
283 This process traverses all the compiled modules in the program
284 starting with "Main", and performing per-module initialisation for
287 So far, two things happen at initialisation time:
289 - we register stable names for each foreign-exported function
290 in that module. This prevents foreign-exported entities, and
291 things they depend on, from being garbage collected.
293 - we supply a unique integer to each statically declared cost
294 centre and cost centre stack in the program.
296 The code generator inserts a small function "__stginit_<module>" in each
297 module and calls the registration functions in each of the modules it
300 The init* functions are compiled in the same way as STG code,
301 i.e. without normal C call/return conventions. Hence we must use
302 StgRun to call this stuff.
303 -------------------------------------------------------------------------- */
305 /* The init functions use an explicit stack...
307 #define INIT_STACK_BLOCKS 4
308 static F_ *init_stack = NULL;
311 hs_add_root(void (*init_root)(void))
315 Capability *cap = &MainCapability;
317 if (hs_init_count <= 0) {
318 barf("hs_add_root() must be called after hs_init()");
321 /* The initialisation stack grows downward, with sp pointing
322 to the last occupied word */
323 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
324 bd = allocGroup_lock(INIT_STACK_BLOCKS);
325 init_stack = (F_ *)bd->start;
326 init_stack[--init_sp] = (F_)stg_init_finish;
327 if (init_root != NULL) {
328 init_stack[--init_sp] = (F_)init_root;
331 cap->r.rSp = (P_)(init_stack + init_sp);
332 StgRun((StgFunPtr)stg_init, &cap->r);
338 #if defined(PROFILING) || defined(DEBUG)
339 // This must be done after module initialisation.
340 // ToDo: make this work in the presence of multiple hs_add_root()s.
345 /* -----------------------------------------------------------------------------
346 Shutting down the RTS
347 -------------------------------------------------------------------------- */
352 if (hs_init_count <= 0) {
353 errorBelch("warning: too many hs_exit()s");
357 if (hs_init_count > 0) {
358 // ignore until it's the last one
362 /* start timing the shutdown */
365 #if defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
369 /* stop all running tasks */
373 /* end_gr_simulation prints global stats if requested -- HWL */
374 if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
378 /* stop the ticker */
381 /* reset the standard file descriptors to blocking mode */
382 resetNonBlockingFd(0);
383 resetNonBlockingFd(1);
384 resetNonBlockingFd(2);
387 // Reset the terminal settings on the standard file descriptors,
388 // if we changed them. See System.Posix.Internals.tcSetAttr for
389 // more details, including the reason we termporarily disable
393 sigset_t sigset, old_sigset;
394 sigemptyset(&sigset);
395 sigaddset(&sigset, SIGTTOU);
396 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
397 for (fd = 0; fd <= 2; fd++) {
398 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
400 tcsetattr(fd,TCSANOW,ts);
403 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
408 /* controlled exit; good thread! */
409 shutdownParallelSystem(0);
411 /* global statistics in parallel system */
415 /* stop timing the shutdown, we're about to print stats */
418 /* shutdown the hpc support (if needed) */
421 // clean up things from the storage manager's point of view.
422 // also outputs the stats (+RTS -s) info.
425 /* free shared Typeable store */
428 /* initialise the stable pointer table */
429 exitStablePtrTable();
431 /* free hash table storage */
434 #ifdef RTS_GTK_FRONTPANEL
435 if (RtsFlags.GcFlags.frontpanel) {
440 #if defined(PROFILING)
441 reportCCSProfiling();
444 #if defined(PROFILING) || defined(DEBUG)
449 // Originally, this was in report_ccs_profiling(). Now, retainer
450 // profiling might tack some extra stuff on to the end of this file
451 // during endProfiling().
455 #if defined(TICKY_TICKY)
456 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
459 #if defined(mingw32_HOST_OS)
463 // Finally, free all our storage.
467 // Compatibility interfaces
469 shutdownHaskell(void)
475 shutdownHaskellAndExit(int n)
477 if (hs_init_count == 1) {
481 /* really exit (stg_exit() would call shutdownParallelSystem() again) */
490 * called from STG-land to exit the program
494 static int exit_started=rtsFalse;
497 void (*exitFn)(int) = 0;
503 /* HACK: avoid a loop when exiting due to a stupid error */
506 exit_started=rtsTrue;
508 IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
509 shutdownParallelSystem(n);