Implement the RTS side of GHC.Environment.getFullArgs
[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     startTimer();
250
251     /* Initialise the stats department */
252     initStats();
253
254 #if defined(RTS_USER_SIGNALS)
255     if (RtsFlags.MiscFlags.install_signal_handlers) {
256         /* Initialise the user signal handler set */
257         initUserSignals();
258         /* Set up handler to run on SIGINT, etc. */
259         initDefaultHandlers();
260     }
261 #endif
262  
263 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
264     startupAsyncIO();
265 #endif
266
267 #ifdef RTS_GTK_FRONTPANEL
268     if (RtsFlags.GcFlags.frontpanel) {
269         initFrontPanel();
270     }
271 #endif
272
273 #if X86_INIT_FPU
274     x86_init_fpu();
275 #endif
276
277 #if defined(THREADED_RTS)
278     ioManagerStart();
279 #endif
280
281     /* Record initialization times */
282     stat_endInit();
283 }
284
285 // Compatibility interface
286 void
287 startupHaskell(int argc, char *argv[], void (*init_root)(void))
288 {
289     hs_init(&argc, &argv);
290     if(init_root)
291         hs_add_root(init_root);
292 }
293
294
295 /* -----------------------------------------------------------------------------
296    Per-module initialisation
297
298    This process traverses all the compiled modules in the program
299    starting with "Main", and performing per-module initialisation for
300    each one.
301
302    So far, two things happen at initialisation time:
303
304       - we register stable names for each foreign-exported function
305         in that module.  This prevents foreign-exported entities, and
306         things they depend on, from being garbage collected.
307
308       - we supply a unique integer to each statically declared cost
309         centre and cost centre stack in the program.
310
311    The code generator inserts a small function "__stginit_<module>" in each
312    module and calls the registration functions in each of the modules it
313    imports.
314
315    The init* functions are compiled in the same way as STG code,
316    i.e. without normal C call/return conventions.  Hence we must use
317    StgRun to call this stuff.
318    -------------------------------------------------------------------------- */
319
320 /* The init functions use an explicit stack... 
321  */
322 #define INIT_STACK_BLOCKS  4
323 static F_ *init_stack = NULL;
324
325 void
326 hs_add_root(void (*init_root)(void))
327 {
328     bdescr *bd;
329     nat init_sp;
330     Capability *cap = &MainCapability;
331
332     if (hs_init_count <= 0) {
333         barf("hs_add_root() must be called after hs_init()");
334     }
335
336     /* The initialisation stack grows downward, with sp pointing 
337        to the last occupied word */
338     init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
339     bd = allocGroup_lock(INIT_STACK_BLOCKS);
340     init_stack = (F_ *)bd->start;
341     init_stack[--init_sp] = (F_)stg_init_finish;
342     if (init_root != NULL) {
343         init_stack[--init_sp] = (F_)init_root;
344     }
345     
346     cap->r.rSp = (P_)(init_stack + init_sp);
347     StgRun((StgFunPtr)stg_init, &cap->r);
348
349     freeGroup_lock(bd);
350
351     startupHpc();
352
353     // This must be done after module initialisation.
354     // ToDo: make this work in the presence of multiple hs_add_root()s.
355     initProfiling2();
356 }
357
358 /* -----------------------------------------------------------------------------
359    Shutting down the RTS
360    -------------------------------------------------------------------------- */
361
362 void
363 hs_exit(void)
364 {
365     if (hs_init_count <= 0) {
366         errorBelch("warning: too many hs_exit()s");
367         return;
368     }
369     hs_init_count--;
370     if (hs_init_count > 0) {
371         // ignore until it's the last one
372         return;
373     }
374
375     /* start timing the shutdown */
376     stat_startExit();
377     
378 #if defined(RTS_USER_SIGNALS)
379     if (RtsFlags.MiscFlags.install_signal_handlers) {
380         freeSignalHandlers();
381     }
382 #endif
383
384 #if defined(THREADED_RTS)
385     ioManagerDie();
386 #endif
387
388     /* stop all running tasks */
389     exitScheduler();
390     
391 #if defined(GRAN)
392     /* end_gr_simulation prints global stats if requested -- HWL */
393     if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
394         end_gr_simulation();
395 #endif
396     
397     /* stop the ticker */
398     stopTimer();
399
400     /* reset the standard file descriptors to blocking mode */
401     resetNonBlockingFd(0);
402     resetNonBlockingFd(1);
403     resetNonBlockingFd(2);
404
405 #if HAVE_TERMIOS_H
406     // Reset the terminal settings on the standard file descriptors,
407     // if we changed them.  See System.Posix.Internals.tcSetAttr for
408     // more details, including the reason we termporarily disable
409     // SIGTTOU here.
410     { 
411         int fd;
412         sigset_t sigset, old_sigset;
413         sigemptyset(&sigset);
414         sigaddset(&sigset, SIGTTOU);
415         sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
416         for (fd = 0; fd <= 2; fd++) {
417             struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
418             if (ts != NULL) {
419                 tcsetattr(fd,TCSANOW,ts);
420             }
421         }
422         sigprocmask(SIG_SETMASK, &old_sigset, NULL);
423     }
424 #endif
425
426 #if defined(PAR)
427     /* controlled exit; good thread! */
428     shutdownParallelSystem(0);
429     
430     /* global statistics in parallel system */
431     PAR_TICKY_PAR_END();
432 #endif
433
434     /* stop timing the shutdown, we're about to print stats */
435     stat_endExit();
436     
437     /* shutdown the hpc support (if needed) */
438     exitHpc();
439
440     // clean up things from the storage manager's point of view.
441     // also outputs the stats (+RTS -s) info.
442     exitStorage();
443     
444     /* free the tasks */
445     freeScheduler();
446
447     /* free shared Typeable store */
448     exitTypeableStore();
449
450     /* free the stable pointer table */
451     exitStablePtrTable();
452
453     freeProfiling1();
454
455 #if defined(DEBUG)
456     /* free the thread label table */
457     freeThreadLabelTable();
458 #endif
459
460 #ifdef RTS_GTK_FRONTPANEL
461     if (RtsFlags.GcFlags.frontpanel) {
462         stopFrontPanel();
463     }
464 #endif
465
466 #if defined(PROFILING) 
467     reportCCSProfiling();
468 #endif
469
470     endProfiling();
471
472 #ifdef PROFILING
473     // Originally, this was in report_ccs_profiling().  Now, retainer
474     // profiling might tack some extra stuff on to the end of this file
475     // during endProfiling().
476     fclose(prof_file);
477 #endif
478
479 #if defined(TICKY_TICKY)
480     if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
481 #endif
482
483 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
484     shutdownAsyncIO();
485 #endif
486
487     /* free hash table storage */
488     exitHashTable();
489
490     // Finally, free all our storage
491     freeStorage();
492
493 #if defined(DEBUG)
494     /* and shut down the allocator debugging */
495     shutdownAllocator();
496 #endif
497
498 }
499
500 // Compatibility interfaces
501 void
502 shutdownHaskell(void)
503 {
504     hs_exit();
505 }
506
507 void
508 shutdownHaskellAndExit(int n)
509 {
510     if (hs_init_count == 1) {
511         OnExitHook();
512         hs_exit();
513 #if defined(PAR)
514         /* really exit (stg_exit() would call shutdownParallelSystem() again) */
515         exit(n);
516 #else
517         stg_exit(n);
518 #endif
519     }
520 }
521
522 /* 
523  * called from STG-land to exit the program
524  */
525
526 #ifdef PAR
527 static int exit_started=rtsFalse;
528 #endif
529
530 void (*exitFn)(int) = 0;
531
532 void  
533 stg_exit(int n)
534
535 #ifdef PAR
536   /* HACK: avoid a loop when exiting due to a stupid error */
537   if (exit_started) 
538     return;
539   exit_started=rtsTrue;
540
541   IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
542   shutdownParallelSystem(n);
543 #endif
544   if (exitFn)
545     (*exitFn)(n);
546   exit(n);
547 }