Fix building RTS with gcc 2.*; declare all variables at the top of a block
[ghc-hetmet.git] / rts / RtsStartup.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 1998-2002
4  *
5  * Main function for a standalone Haskell program.
6  *
7  * ---------------------------------------------------------------------------*/
8
9 // PAPI uses caddr_t, which is not POSIX
10 // #include "PosixSource.h"
11
12 #include "Rts.h"
13 #include "RtsAPI.h"
14 #include "RtsUtils.h"
15 #include "RtsFlags.h"  
16 #include "OSThreads.h"
17 #include "Schedule.h"   /* initScheduler */
18 #include "Stats.h"      /* initStats */
19 #include "STM.h"        /* initSTM */
20 #include "Signals.h"
21 #include "RtsSignals.h"
22 #include "ThrIOManager.h"
23 #include "Timer.h"      /* startTimer, stopTimer */
24 #include "Weak.h"
25 #include "Ticky.h"
26 #include "StgRun.h"
27 #include "Prelude.h"            /* fixupRTStoPreludeRefs */
28 #include "HsFFI.h"
29 #include "Linker.h"
30 #include "ThreadLabels.h"
31 #include "BlockAlloc.h"
32 #include "Trace.h"
33 #include "RtsTypeable.h"
34 #include "Stable.h"
35 #include "Hpc.h"
36
37 #if defined(RTS_GTK_FRONTPANEL)
38 #include "FrontPanel.h"
39 #endif
40
41 # include "Profiling.h"
42
43 #if defined(PROFILING)
44 # include "ProfHeap.h"
45 # include "RetainerProfile.h"
46 #endif
47
48 #if defined(GRAN)
49 # include "GranSimRts.h"
50 #endif
51
52 #if defined(GRAN) || defined(PAR)
53 # include "ParallelRts.h"
54 #endif
55
56 #if defined(PAR)
57 # include "Parallel.h"
58 # include "LLC.h"
59 #endif
60
61 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
62 #include "win32/AsyncIO.h"
63 #endif
64
65 #include <stdlib.h>
66
67 #ifdef HAVE_TERMIOS_H
68 #include <termios.h>
69 #endif
70 #ifdef HAVE_SIGNAL_H
71 #include <signal.h>
72 #endif
73
74 #if USE_PAPI
75 #include "Papi.h"
76 #endif
77
78 // Count of how many outstanding hs_init()s there have been.
79 static int hs_init_count = 0;
80
81 // Here we save the terminal settings on the standard file
82 // descriptors, if we need to change them (eg. to support NoBuffering
83 // input).
84 static void *saved_termios[3] = {NULL,NULL,NULL};
85
86 void*
87 __hscore_get_saved_termios(int fd)
88 {
89   return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
90     saved_termios[fd] : NULL;
91 }
92
93 void
94 __hscore_set_saved_termios(int fd, void* ts)
95 {
96   if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
97     saved_termios[fd] = ts;
98   }
99 }
100
101 /* -----------------------------------------------------------------------------
102    Initialise floating point unit on x86 (currently disabled. why?)
103    (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
104    -------------------------------------------------------------------------- */
105
106 #define X86_INIT_FPU 0
107
108 #if X86_INIT_FPU
109 static void
110 x86_init_fpu ( void )
111 {
112   __volatile unsigned short int fpu_cw;
113
114   // Grab the control word
115   __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
116
117 #if 0
118   printf("fpu_cw: %x\n", fpu_cw);
119 #endif
120
121   // Set bits 8-9 to 10 (64-bit precision).
122   fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
123
124   // Store the new control word back
125   __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
126 }
127 #endif
128
129 /* -----------------------------------------------------------------------------
130    Starting up the RTS
131    -------------------------------------------------------------------------- */
132
133 void
134 hs_init(int *argc, char **argv[])
135 {
136     hs_init_count++;
137     if (hs_init_count > 1) {
138         // second and subsequent inits are ignored
139         return;
140     }
141
142 #if defined(DEBUG)
143     /* Start off by initialising the allocator debugging so we can
144      * use it anywhere */
145     initAllocator();
146 #endif
147
148     /* Next we do is grab the start time...just in case we're
149      * collecting timing statistics.
150      */
151     stat_startInit();
152
153 #ifdef PAR
154     /*
155      * The parallel system needs to be initialised and synchronised before
156      * the program is run.  
157      */ 
158     startupParallelSystem(argv);
159      
160     if (*argv[0] == '-') { /* Strip off mainPE flag argument */
161       argv++; 
162       argc--;                   
163     }
164
165     argv[1] = argv[0];   /* ignore the nPEs argument */
166     argv++; argc--;
167 #endif
168
169     /* Initialise the performance tracking library */
170 #ifdef USE_PAPI
171     {
172         int ver;
173         if ((ver = PAPI_library_init(PAPI_VER_CURRENT)) != PAPI_VER_CURRENT) {
174             if (ver > 0) {
175                 errorBelch("PAPI_library_init: wrong version: %x", ver);
176                 stg_exit(EXIT_FAILURE);
177             } else {
178                 sysErrorBelch("PAPI_library_init");
179                 stg_exit(EXIT_FAILURE);
180             }
181         }
182     }
183 #ifdef THREADED_RTS
184     {
185         int err;
186         if ((err = PAPI_thread_init(osThreadId)) < 0) {
187             barf("PAPI_thread_init: %d",err);
188         }
189     }
190 #endif
191 #endif
192
193     /* Set the RTS flags to default values. */
194
195     initRtsFlagsDefaults();
196
197     /* Call the user hook to reset defaults, if present */
198     defaultsHook();
199
200     /* Parse the flags, separating the RTS flags from the programs args */
201     if (argc != NULL && argv != NULL) {
202         setFullProgArgv(*argc,*argv);
203         setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
204         setProgArgv(*argc,*argv);
205     }
206
207     /* initTracing must be after setupRtsFlags() */
208     initTracing();
209
210 #if defined(PAR)
211     /* NB: this really must be done after processing the RTS flags */
212     IF_PAR_DEBUG(verbose,
213                  debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
214     synchroniseSystem();             // calls initParallelSystem etc
215 #endif  /* PAR */
216
217     /* initialise scheduler data structures (needs to be done before
218      * initStorage()).
219      */
220     initScheduler();
221
222 #if defined(GRAN)
223     /* And start GranSim profiling if required: */
224     if (RtsFlags.GranFlags.GranSimStats.Full)
225       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
226 #elif defined(PAR)
227     /* And start GUM profiling if required: */
228     if (RtsFlags.ParFlags.ParStats.Full)
229       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
230 #endif  /* PAR || GRAN */
231
232     /* initialize the storage manager */
233     initStorage();
234
235     /* initialise the stable pointer table */
236     initStablePtrTable();
237
238     /* initialise the shared Typeable store */
239     initTypeableStore();
240
241 #if defined(DEBUG)
242     /* initialise thread label table (tso->char*) */
243     initThreadLabelTable();
244 #endif
245
246     initProfiling1();
247
248     /* start the virtual timer 'subsystem'. */
249     initTimer();
250     startTimer();
251
252     /* Initialise the stats department */
253     initStats();
254
255 #if defined(RTS_USER_SIGNALS)
256     if (RtsFlags.MiscFlags.install_signal_handlers) {
257         /* Initialise the user signal handler set */
258         initUserSignals();
259         /* Set up handler to run on SIGINT, etc. */
260         initDefaultHandlers();
261     }
262 #endif
263  
264 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
265     startupAsyncIO();
266 #endif
267
268 #ifdef RTS_GTK_FRONTPANEL
269     if (RtsFlags.GcFlags.frontpanel) {
270         initFrontPanel();
271     }
272 #endif
273
274 #if X86_INIT_FPU
275     x86_init_fpu();
276 #endif
277
278 #if defined(THREADED_RTS)
279     ioManagerStart();
280 #endif
281
282     /* Record initialization times */
283     stat_endInit();
284 }
285
286 // Compatibility interface
287 void
288 startupHaskell(int argc, char *argv[], void (*init_root)(void))
289 {
290     hs_init(&argc, &argv);
291     if(init_root)
292         hs_add_root(init_root);
293 }
294
295
296 /* -----------------------------------------------------------------------------
297    Per-module initialisation
298
299    This process traverses all the compiled modules in the program
300    starting with "Main", and performing per-module initialisation for
301    each one.
302
303    So far, two things happen at initialisation time:
304
305       - we register stable names for each foreign-exported function
306         in that module.  This prevents foreign-exported entities, and
307         things they depend on, from being garbage collected.
308
309       - we supply a unique integer to each statically declared cost
310         centre and cost centre stack in the program.
311
312    The code generator inserts a small function "__stginit_<module>" in each
313    module and calls the registration functions in each of the modules it
314    imports.
315
316    The init* functions are compiled in the same way as STG code,
317    i.e. without normal C call/return conventions.  Hence we must use
318    StgRun to call this stuff.
319    -------------------------------------------------------------------------- */
320
321 /* The init functions use an explicit stack... 
322  */
323 #define INIT_STACK_BLOCKS  4
324 static F_ *init_stack = NULL;
325
326 void
327 hs_add_root(void (*init_root)(void))
328 {
329     bdescr *bd;
330     nat init_sp;
331     Capability *cap = &MainCapability;
332
333     if (hs_init_count <= 0) {
334         barf("hs_add_root() must be called after hs_init()");
335     }
336
337     /* The initialisation stack grows downward, with sp pointing 
338        to the last occupied word */
339     init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
340     bd = allocGroup_lock(INIT_STACK_BLOCKS);
341     init_stack = (F_ *)bd->start;
342     init_stack[--init_sp] = (F_)stg_init_finish;
343     if (init_root != NULL) {
344         init_stack[--init_sp] = (F_)init_root;
345     }
346     
347     cap->r.rSp = (P_)(init_stack + init_sp);
348     StgRun((StgFunPtr)stg_init, &cap->r);
349
350     freeGroup_lock(bd);
351
352     startupHpc();
353
354     // This must be done after module initialisation.
355     // ToDo: make this work in the presence of multiple hs_add_root()s.
356     initProfiling2();
357 }
358
359 /* ----------------------------------------------------------------------------
360  * Shutting down the RTS
361  *
362  * The wait_foreign parameter means:
363  *       True  ==> wait for any threads doing foreign calls now.
364  *       False ==> threads doing foreign calls may return in the
365  *                 future, but will immediately block on a mutex.
366  *                 (capability->lock).
367  * 
368  * If this RTS is a DLL that we're about to unload, then you want
369  * safe=True, otherwise the thread might return to code that has been
370  * unloaded.  If this is a standalone program that is about to exit,
371  * then you can get away with safe=False, which is better because we
372  * won't hang on exit if there is a blocked foreign call outstanding.
373  *
374  ------------------------------------------------------------------------- */
375
376 static void
377 hs_exit_(rtsBool wait_foreign)
378 {
379     if (hs_init_count <= 0) {
380         errorBelch("warning: too many hs_exit()s");
381         return;
382     }
383     hs_init_count--;
384     if (hs_init_count > 0) {
385         // ignore until it's the last one
386         return;
387     }
388
389     /* start timing the shutdown */
390     stat_startExit();
391     
392 #if defined(RTS_USER_SIGNALS)
393     if (RtsFlags.MiscFlags.install_signal_handlers) {
394         freeSignalHandlers();
395     }
396 #endif
397
398 #if defined(THREADED_RTS)
399     ioManagerDie();
400 #endif
401
402     /* stop all running tasks */
403     exitScheduler(wait_foreign);
404     
405 #if defined(GRAN)
406     /* end_gr_simulation prints global stats if requested -- HWL */
407     if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
408         end_gr_simulation();
409 #endif
410     
411     /* stop the ticker */
412     stopTimer();
413     exitTimer();
414
415     /* reset the standard file descriptors to blocking mode */
416     resetNonBlockingFd(0);
417     resetNonBlockingFd(1);
418     resetNonBlockingFd(2);
419
420 #if HAVE_TERMIOS_H
421     // Reset the terminal settings on the standard file descriptors,
422     // if we changed them.  See System.Posix.Internals.tcSetAttr for
423     // more details, including the reason we termporarily disable
424     // SIGTTOU here.
425     { 
426         int fd;
427         sigset_t sigset, old_sigset;
428         sigemptyset(&sigset);
429         sigaddset(&sigset, SIGTTOU);
430         sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
431         for (fd = 0; fd <= 2; fd++) {
432             struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
433             if (ts != NULL) {
434                 tcsetattr(fd,TCSANOW,ts);
435             }
436         }
437         sigprocmask(SIG_SETMASK, &old_sigset, NULL);
438     }
439 #endif
440
441 #if defined(PAR)
442     /* controlled exit; good thread! */
443     shutdownParallelSystem(0);
444     
445     /* global statistics in parallel system */
446     PAR_TICKY_PAR_END();
447 #endif
448
449     /* stop timing the shutdown, we're about to print stats */
450     stat_endExit();
451     
452     /* shutdown the hpc support (if needed) */
453     exitHpc();
454
455     // clean up things from the storage manager's point of view.
456     // also outputs the stats (+RTS -s) info.
457     exitStorage();
458     
459     /* free the tasks */
460     freeScheduler();
461
462     /* free shared Typeable store */
463     exitTypeableStore();
464
465     /* free the stable pointer table */
466     exitStablePtrTable();
467
468 #if defined(DEBUG)
469     /* free the thread label table */
470     freeThreadLabelTable();
471 #endif
472
473 #ifdef RTS_GTK_FRONTPANEL
474     if (RtsFlags.GcFlags.frontpanel) {
475         stopFrontPanel();
476     }
477 #endif
478
479 #if defined(PROFILING) 
480     reportCCSProfiling();
481 #endif
482
483     endProfiling();
484     freeProfiling1();
485
486 #ifdef PROFILING
487     // Originally, this was in report_ccs_profiling().  Now, retainer
488     // profiling might tack some extra stuff on to the end of this file
489     // during endProfiling().
490     fclose(prof_file);
491 #endif
492
493 #if defined(TICKY_TICKY)
494     if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
495 #endif
496
497 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
498     shutdownAsyncIO(wait_foreign);
499 #endif
500
501     /* free hash table storage */
502     exitHashTable();
503
504     // Finally, free all our storage
505     freeStorage();
506
507 #if defined(DEBUG)
508     /* and shut down the allocator debugging */
509     shutdownAllocator();
510 #endif
511
512 }
513
514 // The real hs_exit():
515 void
516 hs_exit(void)
517 {
518     hs_exit_(rtsTrue);
519     // be safe; this might be a DLL
520 }
521
522 // Compatibility interfaces
523 void
524 shutdownHaskell(void)
525 {
526     hs_exit();
527 }
528
529 void
530 shutdownHaskellAndExit(int n)
531 {
532     if (hs_init_count == 1) {
533         OnExitHook();
534         hs_exit_(rtsFalse);
535         // we're about to exit(), no need to wait for foreign calls to return.
536 #if defined(PAR)
537         /* really exit (stg_exit() would call shutdownParallelSystem() again) */
538         exit(n);
539 #else
540         stg_exit(n);
541 #endif
542     }
543 }
544
545 /* 
546  * called from STG-land to exit the program
547  */
548
549 #ifdef PAR
550 static int exit_started=rtsFalse;
551 #endif
552
553 void (*exitFn)(int) = 0;
554
555 void  
556 stg_exit(int n)
557
558 #ifdef PAR
559   /* HACK: avoid a loop when exiting due to a stupid error */
560   if (exit_started) 
561     return;
562   exit_started=rtsTrue;
563
564   IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
565   shutdownParallelSystem(n);
566 #endif
567   if (exitFn)
568     (*exitFn)(n);
569   exit(n);
570 }