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 # include "Profiling.h"
43 #if defined(PROFILING)
44 # include "ProfHeap.h"
45 # include "RetainerProfile.h"
49 # include "GranSimRts.h"
52 #if defined(GRAN) || defined(PAR)
53 # include "ParallelRts.h"
57 # include "Parallel.h"
61 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
62 #include "win32/AsyncIO.h"
78 // Count of how many outstanding hs_init()s there have been.
79 static int hs_init_count = 0;
81 // Here we save the terminal settings on the standard file
82 // descriptors, if we need to change them (eg. to support NoBuffering
84 static void *saved_termios[3] = {NULL,NULL,NULL};
87 __hscore_get_saved_termios(int fd)
89 return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
90 saved_termios[fd] : NULL;
94 __hscore_set_saved_termios(int fd, void* ts)
96 if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
97 saved_termios[fd] = ts;
101 /* -----------------------------------------------------------------------------
102 Initialise floating point unit on x86 (currently disabled. why?)
103 (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
104 -------------------------------------------------------------------------- */
106 #define X86_INIT_FPU 0
110 x86_init_fpu ( void )
112 __volatile unsigned short int fpu_cw;
114 // Grab the control word
115 __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
118 printf("fpu_cw: %x\n", fpu_cw);
121 // Set bits 8-9 to 10 (64-bit precision).
122 fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
124 // Store the new control word back
125 __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
129 /* -----------------------------------------------------------------------------
131 -------------------------------------------------------------------------- */
134 hs_init(int *argc, char **argv[])
137 if (hs_init_count > 1) {
138 // second and subsequent inits are ignored
143 /* Start off by initialising the allocator debugging so we can
148 /* Next we do is grab the start time...just in case we're
149 * collecting timing statistics.
155 * The parallel system needs to be initialised and synchronised before
156 * the program is run.
158 startupParallelSystem(argv);
160 if (*argv[0] == '-') { /* Strip off mainPE flag argument */
165 argv[1] = argv[0]; /* ignore the nPEs argument */
169 /* Initialise the performance tracking library */
173 if ((ver = PAPI_library_init(PAPI_VER_CURRENT)) != PAPI_VER_CURRENT) {
175 errorBelch("PAPI_library_init: wrong version: %x", ver);
176 stg_exit(EXIT_FAILURE);
178 sysErrorBelch("PAPI_library_init");
179 stg_exit(EXIT_FAILURE);
186 if ((err = PAPI_thread_init(osThreadId)) < 0) {
187 barf("PAPI_thread_init: %d",err);
193 /* Set the RTS flags to default values. */
195 initRtsFlagsDefaults();
197 /* Call the user hook to reset defaults, if present */
200 /* Parse the flags, separating the RTS flags from the programs args */
201 if (argc != NULL && argv != NULL) {
202 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
203 setProgArgv(*argc,*argv);
206 /* initTracing must be after setupRtsFlags() */
210 /* NB: this really must be done after processing the RTS flags */
211 IF_PAR_DEBUG(verbose,
212 debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
213 synchroniseSystem(); // calls initParallelSystem etc
216 /* Perform initialisation of adjustor thunk layer. */
219 /* initialise scheduler data structures (needs to be done before
225 /* And start GranSim profiling if required: */
226 if (RtsFlags.GranFlags.GranSimStats.Full)
227 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
229 /* And start GUM profiling if required: */
230 if (RtsFlags.ParFlags.ParStats.Full)
231 init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
232 #endif /* PAR || GRAN */
234 /* initialize the storage manager */
237 /* initialise the stable pointer table */
238 initStablePtrTable();
240 /* initialise the shared Typeable store */
244 /* initialise thread label table (tso->char*) */
245 initThreadLabelTable();
250 /* start the virtual timer 'subsystem'. */
253 /* Initialise the stats department */
256 #if defined(RTS_USER_SIGNALS)
257 if (RtsFlags.MiscFlags.install_signal_handlers) {
258 /* Initialise the user signal handler set */
260 /* Set up handler to run on SIGINT, etc. */
261 initDefaultHandlers();
265 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
269 #ifdef RTS_GTK_FRONTPANEL
270 if (RtsFlags.GcFlags.frontpanel) {
279 #if defined(THREADED_RTS)
283 /* Record initialization times */
287 // Compatibility interface
289 startupHaskell(int argc, char *argv[], void (*init_root)(void))
291 hs_init(&argc, &argv);
293 hs_add_root(init_root);
297 /* -----------------------------------------------------------------------------
298 Per-module initialisation
300 This process traverses all the compiled modules in the program
301 starting with "Main", and performing per-module initialisation for
304 So far, two things happen at initialisation time:
306 - we register stable names for each foreign-exported function
307 in that module. This prevents foreign-exported entities, and
308 things they depend on, from being garbage collected.
310 - we supply a unique integer to each statically declared cost
311 centre and cost centre stack in the program.
313 The code generator inserts a small function "__stginit_<module>" in each
314 module and calls the registration functions in each of the modules it
317 The init* functions are compiled in the same way as STG code,
318 i.e. without normal C call/return conventions. Hence we must use
319 StgRun to call this stuff.
320 -------------------------------------------------------------------------- */
322 /* The init functions use an explicit stack...
324 #define INIT_STACK_BLOCKS 4
325 static F_ *init_stack = NULL;
328 hs_add_root(void (*init_root)(void))
332 Capability *cap = &MainCapability;
334 if (hs_init_count <= 0) {
335 barf("hs_add_root() must be called after hs_init()");
338 /* The initialisation stack grows downward, with sp pointing
339 to the last occupied word */
340 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
341 bd = allocGroup_lock(INIT_STACK_BLOCKS);
342 init_stack = (F_ *)bd->start;
343 init_stack[--init_sp] = (F_)stg_init_finish;
344 if (init_root != NULL) {
345 init_stack[--init_sp] = (F_)init_root;
348 cap->r.rSp = (P_)(init_stack + init_sp);
349 StgRun((StgFunPtr)stg_init, &cap->r);
355 // This must be done after module initialisation.
356 // ToDo: make this work in the presence of multiple hs_add_root()s.
360 /* -----------------------------------------------------------------------------
361 Shutting down the RTS
362 -------------------------------------------------------------------------- */
367 if (hs_init_count <= 0) {
368 errorBelch("warning: too many hs_exit()s");
372 if (hs_init_count > 0) {
373 // ignore until it's the last one
377 /* start timing the shutdown */
380 #if defined(RTS_USER_SIGNALS)
381 if (RtsFlags.MiscFlags.install_signal_handlers) {
382 freeSignalHandlers();
386 #if defined(THREADED_RTS)
390 /* stop all running tasks */
394 /* end_gr_simulation prints global stats if requested -- HWL */
395 if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
399 /* stop the ticker */
402 /* reset the standard file descriptors to blocking mode */
403 resetNonBlockingFd(0);
404 resetNonBlockingFd(1);
405 resetNonBlockingFd(2);
408 // Reset the terminal settings on the standard file descriptors,
409 // if we changed them. See System.Posix.Internals.tcSetAttr for
410 // more details, including the reason we termporarily disable
414 sigset_t sigset, old_sigset;
415 sigemptyset(&sigset);
416 sigaddset(&sigset, SIGTTOU);
417 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
418 for (fd = 0; fd <= 2; fd++) {
419 struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
421 tcsetattr(fd,TCSANOW,ts);
424 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
429 /* controlled exit; good thread! */
430 shutdownParallelSystem(0);
432 /* global statistics in parallel system */
436 /* stop timing the shutdown, we're about to print stats */
439 /* shutdown the hpc support (if needed) */
442 // clean up things from the storage manager's point of view.
443 // also outputs the stats (+RTS -s) info.
449 /* free shared Typeable store */
452 /* free the stable pointer table */
453 exitStablePtrTable();
458 /* free the thread label table */
459 freeThreadLabelTable();
462 #ifdef RTS_GTK_FRONTPANEL
463 if (RtsFlags.GcFlags.frontpanel) {
468 #if defined(PROFILING)
469 reportCCSProfiling();
475 // Originally, this was in report_ccs_profiling(). Now, retainer
476 // profiling might tack some extra stuff on to the end of this file
477 // during endProfiling().
481 #if defined(TICKY_TICKY)
482 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
485 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
489 /* free hash table storage */
492 // Finally, free all our storage
496 /* and shut down the allocator debugging */
502 // Compatibility interfaces
504 shutdownHaskell(void)
510 shutdownHaskellAndExit(int n)
512 if (hs_init_count == 1) {
516 /* really exit (stg_exit() would call shutdownParallelSystem() again) */
525 * called from STG-land to exit the program
529 static int exit_started=rtsFalse;
532 void (*exitFn)(int) = 0;
538 /* HACK: avoid a loop when exiting due to a stupid error */
541 exit_started=rtsTrue;
543 IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
544 shutdownParallelSystem(n);