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