[project @ 2005-02-03 10:57:06 by simonmar]
[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_HOST_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         setProgArgv(*argc,*argv);
163     }
164
165 #if defined(PAR)
166     /* NB: this really must be done after processing the RTS flags */
167     IF_PAR_DEBUG(verbose,
168                  debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
169     synchroniseSystem();             // calls initParallelSystem etc
170 #endif  /* PAR */
171
172     /* Perform initialisation of adjustor thunk layer. */
173     initAdjustor();
174
175     /* initialise scheduler data structures (needs to be done before
176      * initStorage()).
177      */
178     initScheduler();
179
180 #if defined(GRAN)
181     /* And start GranSim profiling if required: */
182     if (RtsFlags.GranFlags.GranSimStats.Full)
183       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
184 #elif defined(PAR)
185     /* And start GUM profiling if required: */
186     if (RtsFlags.ParFlags.ParStats.Full)
187       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
188 #endif  /* PAR || GRAN */
189
190     /* initialize the storage manager */
191     initStorage();
192
193     /* initialise the stable pointer table */
194     initStablePtrTable();
195
196 #if defined(DEBUG)
197     /* initialise thread label table (tso->char*) */
198     initThreadLabelTable();
199 #endif
200
201 #if defined(PROFILING) || defined(DEBUG)
202     initProfiling1();
203 #endif
204
205     /* start the virtual timer 'subsystem'. */
206     startTimer(TICK_MILLISECS);
207
208     /* Initialise the stats department */
209     initStats();
210
211 #if defined(RTS_USER_SIGNALS)
212     /* Initialise the user signal handler set */
213     initUserSignals();
214     /* Set up handler to run on SIGINT, etc. */
215     initDefaultHandlers();
216 #endif
217  
218 #if defined(mingw32_HOST_OS)
219     startupAsyncIO();
220 #endif
221
222     initSTM();
223
224 #ifdef RTS_GTK_FRONTPANEL
225     if (RtsFlags.GcFlags.frontpanel) {
226         initFrontPanel();
227     }
228 #endif
229
230 #ifdef HAVE_LOCALE_H
231     setlocale(LC_CTYPE,"");
232 #endif
233
234 #if X86_INIT_FPU
235     x86_init_fpu();
236 #endif
237
238     /* Record initialization times */
239     stat_endInit();
240 }
241
242 // Compatibility interface
243 void
244 startupHaskell(int argc, char *argv[], void (*init_root)(void))
245 {
246     hs_init(&argc, &argv);
247     hs_add_root(init_root);
248 }
249
250
251 /* -----------------------------------------------------------------------------
252    Per-module initialisation
253
254    This process traverses all the compiled modules in the program
255    starting with "Main", and performing per-module initialisation for
256    each one.
257
258    So far, two things happen at initialisation time:
259
260       - we register stable names for each foreign-exported function
261         in that module.  This prevents foreign-exported entities, and
262         things they depend on, from being garbage collected.
263
264       - we supply a unique integer to each statically declared cost
265         centre and cost centre stack in the program.
266
267    The code generator inserts a small function "__stginit_<module>" in each
268    module and calls the registration functions in each of the modules it
269    imports.
270
271    The init* functions are compiled in the same way as STG code,
272    i.e. without normal C call/return conventions.  Hence we must use
273    StgRun to call this stuff.
274    -------------------------------------------------------------------------- */
275
276 /* The init functions use an explicit stack... 
277  */
278 #define INIT_STACK_BLOCKS  4
279 static F_ *init_stack = NULL;
280
281 void
282 hs_add_root(void (*init_root)(void))
283 {
284     bdescr *bd;
285 #ifdef SMP
286     Capability cap;
287 #else
288 #define cap MainCapability
289 #endif
290     nat init_sp;
291
292     if (hs_init_count <= 0) {
293         barf("hs_add_root() must be called after hs_init()");
294     }
295
296     /* The initialisation stack grows downward, with sp pointing 
297        to the last occupied word */
298     init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
299     bd = allocGroup(INIT_STACK_BLOCKS);
300     init_stack = (F_ *)bd->start;
301     init_stack[--init_sp] = (F_)stg_init_finish;
302     if (init_root != NULL) {
303         init_stack[--init_sp] = (F_)init_root;
304     }
305     
306     cap.r.rSp = (P_)(init_stack + init_sp);
307     StgRun((StgFunPtr)stg_init, &cap.r);
308
309     freeGroup(bd);
310
311 #if defined(PROFILING) || defined(DEBUG)
312     // This must be done after module initialisation.
313     // ToDo: make this work in the presence of multiple hs_add_root()s.
314     initProfiling2();
315 #endif
316 }
317
318 /* -----------------------------------------------------------------------------
319    Shutting down the RTS
320    -------------------------------------------------------------------------- */
321
322 void
323 hs_exit(void)
324 {
325     if (hs_init_count <= 0) {
326         barf("too many hs_exit()s");
327     }
328     hs_init_count--;
329     if (hs_init_count > 0) {
330         // ignore until it's the last one
331         return;
332     }
333
334     /* start timing the shutdown */
335     stat_startExit();
336     
337     /* stop all running tasks */
338     exitScheduler();
339     
340 #if defined(GRAN)
341     /* end_gr_simulation prints global stats if requested -- HWL */
342     if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
343         end_gr_simulation();
344 #endif
345     
346     /* stop the ticker */
347     stopTimer();
348     
349     /* reset the standard file descriptors to blocking mode */
350     resetNonBlockingFd(0);
351     resetNonBlockingFd(1);
352     resetNonBlockingFd(2);
353
354 #if HAVE_TERMIOS_H
355     // Reset the terminal settings on the standard file descriptors,
356     // if we changed them.  See System.Posix.Internals.tcSetAttr for
357     // more details, including the reason we termporarily disable
358     // SIGTTOU here.
359     { 
360         int fd;
361         sigset_t sigset, old_sigset;
362         sigemptyset(&sigset);
363         sigaddset(&sigset, SIGTTOU);
364         sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
365         for (fd = 0; fd <= 2; fd++) {
366             struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
367             if (ts != NULL) {
368                 tcsetattr(fd,TCSANOW,ts);
369             }
370         }
371         sigprocmask(SIG_SETMASK, &old_sigset, NULL);
372     }
373 #endif
374
375 #if defined(PAR)
376     /* controlled exit; good thread! */
377     shutdownParallelSystem(0);
378     
379     /* global statistics in parallel system */
380     PAR_TICKY_PAR_END();
381 #endif
382
383     /* stop timing the shutdown, we're about to print stats */
384     stat_endExit();
385     
386     /* clean up things from the storage manager's point of view.
387      * also outputs the stats (+RTS -s) info.
388      */
389     exitStorage();
390     
391 #ifdef RTS_GTK_FRONTPANEL
392     if (RtsFlags.GcFlags.frontpanel) {
393         stopFrontPanel();
394     }
395 #endif
396
397 #if defined(PROFILING) 
398     reportCCSProfiling();
399 #endif
400
401 #if defined(PROFILING) || defined(DEBUG)
402     endProfiling();
403 #endif
404
405 #ifdef PROFILING
406     // Originally, this was in report_ccs_profiling().  Now, retainer
407     // profiling might tack some extra stuff on to the end of this file
408     // during endProfiling().
409     fclose(prof_file);
410 #endif
411     
412 #if defined(TICKY_TICKY)
413     if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
414 #endif
415
416 #if defined(mingw32_HOST_OS)
417     shutdownAsyncIO();
418 #endif
419 }
420
421 // Compatibility interfaces
422 void
423 shutdownHaskell(void)
424 {
425     hs_exit();
426 }
427
428 void
429 shutdownHaskellAndExit(int n)
430 {
431     if (hs_init_count == 1) {
432         OnExitHook();
433         hs_exit();
434 #if defined(PAR)
435         /* really exit (stg_exit() would call shutdownParallelSystem() again) */
436         exit(n);
437 #else
438         stg_exit(n);
439 #endif
440     }
441 }
442
443 /* 
444  * called from STG-land to exit the program
445  */
446
447 #ifdef PAR
448 static int exit_started=rtsFalse;
449 #endif
450
451 void  
452 stg_exit(int n)
453
454 #ifdef PAR
455   /* HACK: avoid a loop when exiting due to a stupid error */
456   if (exit_started) 
457     return;
458   exit_started=rtsTrue;
459
460   IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
461   shutdownParallelSystem(n);
462 #endif
463   exit(n);
464 }