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 "ThrIOManager.h"
23 #include "Timer.h" /* startTimer, stopTimer */
27 #include "Prelude.h" /* fixupRTStoPreludeRefs */
30 #include "ThreadLabels.h"
31 #include "BlockAlloc.h"
33 #include "RtsTypeable.h"
37 #if defined(RTS_GTK_FRONTPANEL)
38 #include "FrontPanel.h"
41 #if defined(PROFILING) || defined(DEBUG)
42 # include "Profiling.h"
43 # include "ProfHeap.h"
44 # include "RetainerProfile.h"
48 # include "GranSimRts.h"
51 #if defined(GRAN) || defined(PAR)
52 # include "ParallelRts.h"
56 # include "Parallel.h"
60 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
61 #include "win32/AsyncIO.h"
77 // Count of how many outstanding hs_init()s there have been.
78 static int hs_init_count = 0;
80 // Here we save the terminal settings on the standard file
81 // descriptors, if we need to change them (eg. to support NoBuffering
83 static void *saved_termios[3] = {NULL,NULL,NULL};
86 __hscore_get_saved_termios(int fd)
88 return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
89 saved_termios[fd] : NULL;
93 __hscore_set_saved_termios(int fd, void* ts)
95 if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
96 saved_termios[fd] = ts;
100 /* -----------------------------------------------------------------------------
101 Initialise floating point unit on x86 (currently disabled. why?)
102 (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
103 -------------------------------------------------------------------------- */
105 #define X86_INIT_FPU 0
109 x86_init_fpu ( void )
111 __volatile unsigned short int fpu_cw;
113 // Grab the control word
114 __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
117 printf("fpu_cw: %x\n", fpu_cw);
120 // Set bits 8-9 to 10 (64-bit precision).
121 fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
123 // Store the new control word back
124 __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
128 /* -----------------------------------------------------------------------------
130 -------------------------------------------------------------------------- */
133 hs_init(int *argc, char **argv[])
136 if (hs_init_count > 1) {
137 // second and subsequent inits are ignored
141 /* The very first thing we do is grab the start time...just in case we're
142 * collecting timing statistics.
148 * The parallel system needs to be initialised and synchronised before
149 * the program is run.
151 startupParallelSystem(argv);
153 if (*argv[0] == '-') { /* Strip off mainPE flag argument */
158 argv[1] = argv[0]; /* ignore the nPEs argument */
162 /* Initialise the performance tracking library */
166 if ((ver = PAPI_library_init(PAPI_VER_CURRENT)) != PAPI_VER_CURRENT) {
168 errorBelch("PAPI_library_init: wrong version: %x", ver);
169 stg_exit(EXIT_FAILURE);
171 sysErrorBelch("PAPI_library_init");
172 stg_exit(EXIT_FAILURE);
179 if ((err = PAPI_thread_init(osThreadId)) < 0) {
180 barf("PAPI_thread_init: %d",err);
186 /* Set the RTS flags to default values. */
188 initRtsFlagsDefaults();
190 /* Call the user hook to reset defaults, if present */
193 /* Parse the flags, separating the RTS flags from the programs args */
194 if (argc != NULL && argv != NULL) {
195 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
196 setProgArgv(*argc,*argv);
199 /* initTracing must be after setupRtsFlags() */
203 /* NB: this really must be done after processing the RTS flags */
204 IF_PAR_DEBUG(verbose,
205 debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
206 synchroniseSystem(); // calls initParallelSystem etc
209 /* Perform initialisation of adjustor thunk layer. */
212 /* initialise scheduler data structures (needs to be done before
218 /* And start GranSim profiling if required: */
219 if (RtsFlags.GranFlags.GranSimStats.Full)
220 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
222 /* And start GUM profiling if required: */
223 if (RtsFlags.ParFlags.ParStats.Full)
224 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
225 #endif /* PAR || GRAN */
227 /* initialize the storage manager */
230 /* initialise the stable pointer table */
231 initStablePtrTable();
233 /* initialise the shared Typeable store */
237 /* initialise thread label table (tso->char*) */
238 initThreadLabelTable();
241 #if defined(PROFILING) || defined(DEBUG)
245 /* start the virtual timer 'subsystem'. */
248 /* Initialise the stats department */
251 #if defined(RTS_USER_SIGNALS)
252 /* Initialise the user signal handler set */
254 /* Set up handler to run on SIGINT, etc. */
255 initDefaultHandlers();
258 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
262 #ifdef RTS_GTK_FRONTPANEL
263 if (RtsFlags.GcFlags.frontpanel) {
272 #if defined(THREADED_RTS)
276 /* Record initialization times */
280 // Compatibility interface
282 startupHaskell(int argc, char *argv[], void (*init_root)(void))
284 hs_init(&argc, &argv);
286 hs_add_root(init_root);
290 /* -----------------------------------------------------------------------------
291 Per-module initialisation
293 This process traverses all the compiled modules in the program
294 starting with "Main", and performing per-module initialisation for
297 So far, two things happen at initialisation time:
299 - we register stable names for each foreign-exported function
300 in that module. This prevents foreign-exported entities, and
301 things they depend on, from being garbage collected.
303 - we supply a unique integer to each statically declared cost
304 centre and cost centre stack in the program.
306 The code generator inserts a small function "__stginit_<module>" in each
307 module and calls the registration functions in each of the modules it
310 The init* functions are compiled in the same way as STG code,
311 i.e. without normal C call/return conventions. Hence we must use
312 StgRun to call this stuff.
313 -------------------------------------------------------------------------- */
315 /* The init functions use an explicit stack...
317 #define INIT_STACK_BLOCKS 4
318 static F_ *init_stack = NULL;
321 hs_add_root(void (*init_root)(void))
325 Capability *cap = &MainCapability;
327 if (hs_init_count <= 0) {
328 barf("hs_add_root() must be called after hs_init()");
331 /* The initialisation stack grows downward, with sp pointing
332 to the last occupied word */
333 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
334 bd = allocGroup_lock(INIT_STACK_BLOCKS);
335 init_stack = (F_ *)bd->start;
336 init_stack[--init_sp] = (F_)stg_init_finish;
337 if (init_root != NULL) {
338 init_stack[--init_sp] = (F_)init_root;
341 cap->r.rSp = (P_)(init_stack + init_sp);
342 StgRun((StgFunPtr)stg_init, &cap->r);
348 #if defined(PROFILING) || defined(DEBUG)
349 // This must be done after module initialisation.
350 // ToDo: make this work in the presence of multiple hs_add_root()s.
355 /* -----------------------------------------------------------------------------
356 Shutting down the RTS
357 -------------------------------------------------------------------------- */
362 if (hs_init_count <= 0) {
363 errorBelch("warning: too many hs_exit()s");
367 if (hs_init_count > 0) {
368 // ignore until it's the last one
372 /* start timing the shutdown */
375 #if defined(THREADED_RTS)
379 /* stop all running tasks */
383 /* end_gr_simulation prints global stats if requested -- HWL */
384 if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
388 /* stop the ticker */
391 /* reset the standard file descriptors to blocking mode */
392 resetNonBlockingFd(0);
393 resetNonBlockingFd(1);
394 resetNonBlockingFd(2);
397 // Reset the terminal settings on the standard file descriptors,
398 // if we changed them. See System.Posix.Internals.tcSetAttr for
399 // more details, including the reason we termporarily disable
403 sigset_t sigset, old_sigset;
404 sigemptyset(&sigset);
405 sigaddset(&sigset, SIGTTOU);
406 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
407 for (fd = 0; fd <= 2; fd++) {
408 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
410 tcsetattr(fd,TCSANOW,ts);
413 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
418 /* controlled exit; good thread! */
419 shutdownParallelSystem(0);
421 /* global statistics in parallel system */
425 /* stop timing the shutdown, we're about to print stats */
428 /* shutdown the hpc support (if needed) */
431 // clean up things from the storage manager's point of view.
432 // also outputs the stats (+RTS -s) info.
435 /* free shared Typeable store */
438 /* initialise the stable pointer table */
439 exitStablePtrTable();
441 /* free hash table storage */
444 #ifdef RTS_GTK_FRONTPANEL
445 if (RtsFlags.GcFlags.frontpanel) {
450 #if defined(PROFILING)
451 reportCCSProfiling();
454 #if defined(PROFILING) || defined(DEBUG)
459 // Originally, this was in report_ccs_profiling(). Now, retainer
460 // profiling might tack some extra stuff on to the end of this file
461 // during endProfiling().
465 #if defined(TICKY_TICKY)
466 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
469 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
473 // Finally, free all our storage.
477 // Compatibility interfaces
479 shutdownHaskell(void)
485 shutdownHaskellAndExit(int n)
487 if (hs_init_count == 1) {
491 /* really exit (stg_exit() would call shutdownParallelSystem() again) */
500 * called from STG-land to exit the program
504 static int exit_started=rtsFalse;
507 void (*exitFn)(int) = 0;
513 /* HACK: avoid a loop when exiting due to a stupid error */
516 exit_started=rtsTrue;
518 IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
519 shutdownParallelSystem(n);