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