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