04bad6d661d0ab4b78fa65aee50dc5566bc66960
[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 "Signals.h"
18 #include "Timer.h"      /* startTimer, stopTimer */
19 #include "Weak.h"
20 #include "Ticky.h"
21 #include "StgRun.h"
22 #include "Prelude.h"            /* fixupRTStoPreludeRefs */
23 #include "HsFFI.h"
24 #include "Linker.h"
25 #include "ThreadLabels.h"
26 #include "BlockAlloc.h"
27
28 #if defined(RTS_GTK_FRONTPANEL)
29 #include "FrontPanel.h"
30 #endif
31
32 #if defined(PROFILING) || defined(DEBUG)
33 # include "Profiling.h"
34 # include "ProfHeap.h"
35 # include "RetainerProfile.h"
36 #endif
37
38 #if defined(GRAN)
39 # include "GranSimRts.h"
40 #endif
41
42 #if defined(GRAN) || defined(PAR)
43 # include "ParallelRts.h"
44 #endif
45
46 #if defined(PAR)
47 # include "Parallel.h"
48 # include "LLC.h"
49 #endif
50
51 #if defined(mingw32_TARGET_OS)
52 #include "win32/AsyncIO.h"
53 #endif
54
55 #include <stdlib.h>
56
57 #ifdef HAVE_LOCALE_H
58 #include <locale.h>
59 #endif
60
61 #ifdef HAVE_TERMIOS_H
62 #include <termios.h>
63 #endif
64 #ifdef HAVE_SIGNAL_H
65 #include <signal.h>
66 #endif
67
68 // Count of how many outstanding hs_init()s there have been.
69 static int hs_init_count = 0;
70
71 // Here we save the terminal settings on the standard file
72 // descriptors, if we need to change them (eg. to support NoBuffering
73 // input).
74 static void *saved_termios[3] = {NULL,NULL,NULL};
75
76 void*
77 __hscore_get_saved_termios(int fd)
78 {
79   return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
80     saved_termios[fd] : NULL;
81 }
82
83 void
84 __hscore_set_saved_termios(int fd, void* ts)
85 {
86   if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
87     saved_termios[fd] = ts;
88   }
89 }
90
91 /* -----------------------------------------------------------------------------
92    Initialise floating point unit on x86 (currently disabled. why?)
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         prog_argc = *argc;
162         prog_argv = *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_TARGET_OS)
219     startupAsyncIO();
220 #endif
221
222 #ifdef RTS_GTK_FRONTPANEL
223     if (RtsFlags.GcFlags.frontpanel) {
224         initFrontPanel();
225     }
226 #endif
227
228 #ifdef HAVE_LOCALE_H
229     setlocale(LC_CTYPE,"");
230 #endif
231
232 #if X86_INIT_FPU
233     x86_init_fpu();
234 #endif
235
236     /* Record initialization times */
237     stat_endInit();
238 }
239
240 // Compatibility interface
241 void
242 startupHaskell(int argc, char *argv[], void (*init_root)(void))
243 {
244     hs_init(&argc, &argv);
245     hs_add_root(init_root);
246 }
247
248
249 /* -----------------------------------------------------------------------------
250    Getting/Setting the program's arguments.
251
252    These are used by System.Environment.
253    -------------------------------------------------------------------------- */
254
255 void
256 getProgArgv(int *argc, char **argv[])
257 {
258     if (argc) { *argc = prog_argc; }
259     if (argv) { *argv = prog_argv; }
260 }
261
262 void
263 setProgArgv(int argc, char *argv[])
264 {
265    /* Usually this is done by startupHaskell, so we don't need to call this. 
266       However, sometimes Hugs wants to change the arguments which Haskell
267       getArgs >>= ... will be fed.  So you can do that by calling here
268       _after_ calling startupHaskell.
269    */
270    prog_argc = argc;
271    prog_argv = argv;
272 }
273
274 /* -----------------------------------------------------------------------------
275    Per-module initialisation
276
277    This process traverses all the compiled modules in the program
278    starting with "Main", and performing per-module initialisation for
279    each one.
280
281    So far, two things happen at initialisation time:
282
283       - we register stable names for each foreign-exported function
284         in that module.  This prevents foreign-exported entities, and
285         things they depend on, from being garbage collected.
286
287       - we supply a unique integer to each statically declared cost
288         centre and cost centre stack in the program.
289
290    The code generator inserts a small function "__stginit_<module>" in each
291    module and calls the registration functions in each of the modules it
292    imports.
293
294    The init* functions are compiled in the same way as STG code,
295    i.e. without normal C call/return conventions.  Hence we must use
296    StgRun to call this stuff.
297    -------------------------------------------------------------------------- */
298
299 /* The init functions use an explicit stack... 
300  */
301 #define INIT_STACK_BLOCKS  4
302 static F_ *init_stack = NULL;
303
304 void
305 hs_add_root(void (*init_root)(void))
306 {
307     bdescr *bd;
308 #ifdef SMP
309     Capability cap;
310 #else
311 #define cap MainCapability
312 #endif
313     nat init_sp;
314
315     if (hs_init_count <= 0) {
316         barf("hs_add_root() must be called after hs_init()");
317     }
318
319     /* The initialisation stack grows downward, with sp pointing 
320        to the last occupied word */
321     init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
322     bd = allocGroup(INIT_STACK_BLOCKS);
323     init_stack = (F_ *)bd->start;
324     init_stack[--init_sp] = (F_)stg_init_finish;
325     if (init_root != NULL) {
326         init_stack[--init_sp] = (F_)init_root;
327     }
328     
329     cap.r.rSp = (P_)(init_stack + init_sp);
330     StgRun((StgFunPtr)stg_init, &cap.r);
331
332     freeGroup(bd);
333
334 #if defined(PROFILING) || defined(DEBUG)
335     // This must be done after module initialisation.
336     // ToDo: make this work in the presence of multiple hs_add_root()s.
337     initProfiling2();
338 #endif
339 }
340
341 /* -----------------------------------------------------------------------------
342    Shutting down the RTS
343    -------------------------------------------------------------------------- */
344
345 void
346 hs_exit(void)
347 {
348     if (hs_init_count <= 0) {
349         barf("too many hs_exit()s");
350     }
351     hs_init_count--;
352     if (hs_init_count > 0) {
353         // ignore until it's the last one
354         return;
355     }
356
357     /* start timing the shutdown */
358     stat_startExit();
359     
360 #if !defined(GRAN)
361     /* Finalize any remaining weak pointers */
362     finalizeWeakPointersNow();
363 #endif
364     
365     /* stop all running tasks */
366     exitScheduler();
367     
368 #if defined(GRAN)
369     /* end_gr_simulation prints global stats if requested -- HWL */
370     if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
371         end_gr_simulation();
372 #endif
373     
374     /* stop the ticker */
375     stopTimer();
376     
377     /* reset the standard file descriptors to blocking mode */
378     resetNonBlockingFd(0);
379     resetNonBlockingFd(1);
380     resetNonBlockingFd(2);
381
382 #if HAVE_TERMIOS_H
383     // Reset the terminal settings on the standard file descriptors,
384     // if we changed them.  See System.Posix.Internals.tcSetAttr for
385     // more details, including the reason we termporarily disable
386     // SIGTTOU here.
387     { 
388         int fd;
389         sigset_t sigset, old_sigset;
390         sigemptyset(&sigset);
391         sigaddset(&sigset, SIGTTOU);
392         sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
393         for (fd = 0; fd <= 2; fd++) {
394             struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
395             if (ts != NULL) {
396                 tcsetattr(fd,TCSANOW,ts);
397             }
398         }
399         sigprocmask(SIG_SETMASK, &old_sigset, NULL);
400     }
401 #endif
402
403 #if defined(PAR)
404     /* controlled exit; good thread! */
405     shutdownParallelSystem(0);
406     
407     /* global statistics in parallel system */
408     PAR_TICKY_PAR_END();
409 #endif
410
411     /* stop timing the shutdown, we're about to print stats */
412     stat_endExit();
413     
414     /* clean up things from the storage manager's point of view.
415      * also outputs the stats (+RTS -s) info.
416      */
417     exitStorage();
418     
419 #ifdef RTS_GTK_FRONTPANEL
420     if (RtsFlags.GcFlags.frontpanel) {
421         stopFrontPanel();
422     }
423 #endif
424
425 #if defined(PROFILING) 
426     reportCCSProfiling();
427 #endif
428
429 #if defined(PROFILING) || defined(DEBUG)
430     endProfiling();
431 #endif
432
433 #ifdef PROFILING
434     // Originally, this was in report_ccs_profiling().  Now, retainer
435     // profiling might tack some extra stuff on to the end of this file
436     // during endProfiling().
437     fclose(prof_file);
438 #endif
439     
440 #if defined(TICKY_TICKY)
441     if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
442 #endif
443
444 #if defined(mingw32_TARGET_OS)
445     shutdownAsyncIO();
446 #endif
447 }
448
449 // Compatibility interfaces
450 void
451 shutdownHaskell(void)
452 {
453     hs_exit();
454 }
455
456 void
457 shutdownHaskellAndExit(int n)
458 {
459     if (hs_init_count == 1) {
460         OnExitHook();
461         hs_exit();
462 #if defined(PAR)
463         /* really exit (stg_exit() would call shutdownParallelSystem() again) */
464         exit(n);
465 #else
466         stg_exit(n);
467 #endif
468     }
469 }
470
471 /* 
472  * called from STG-land to exit the program
473  */
474
475 #ifdef PAR
476 static int exit_started=rtsFalse;
477 #endif
478
479 void  
480 stg_exit(int n)
481
482 #ifdef PAR
483   /* HACK: avoid a loop when exiting due to a stupid error */
484   if (exit_started) 
485     return;
486   exit_started=rtsTrue;
487
488   IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
489   shutdownParallelSystem(n);
490 #endif
491   exit(n);
492 }