b85b15305f8e41faae8287881085d850692624da
[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 #ifndef USE_PAPI
11 #include "PosixSource.h"
12 #endif
13
14 #include "Rts.h"
15 #include "RtsAPI.h"
16 #include "HsFFI.h"
17
18 #include "sm/Storage.h"
19 #include "RtsUtils.h"
20 #include "Prelude.h"
21 #include "Schedule.h"   /* initScheduler */
22 #include "Stats.h"      /* initStats */
23 #include "STM.h"        /* initSTM */
24 #include "RtsSignals.h"
25 #include "Weak.h"
26 #include "Ticky.h"
27 #include "StgRun.h"
28 #include "Prelude.h"            /* fixupRTStoPreludeRefs */
29 #include "ThreadLabels.h"
30 #include "sm/BlockAlloc.h"
31 #include "Trace.h"
32 #include "Stable.h"
33 #include "Hash.h"
34 #include "Profiling.h"
35 #include "Timer.h"
36 #include "Globals.h"
37
38 #if defined(RTS_GTK_FRONTPANEL)
39 #include "FrontPanel.h"
40 #endif
41
42 #if defined(PROFILING)
43 # include "ProfHeap.h"
44 # include "RetainerProfile.h"
45 #endif
46
47 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
48 #include "win32/AsyncIO.h"
49 #endif
50
51 #if !defined(mingw32_HOST_OS)
52 #include "posix/TTY.h"
53 #include "posix/FileLock.h"
54 #endif
55
56 #ifdef HAVE_UNISTD_H
57 #include <unistd.h>
58 #endif
59 #ifdef HAVE_LOCALE_H
60 #include <locale.h>
61 #endif
62
63 #if USE_PAPI
64 #include "Papi.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 /* -----------------------------------------------------------------------------
71    Initialise floating point unit on x86 (currently disabled. why?)
72    (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
73    -------------------------------------------------------------------------- */
74
75 #define X86_INIT_FPU 0
76
77 #if X86_INIT_FPU
78 static void
79 x86_init_fpu ( void )
80 {
81   __volatile unsigned short int fpu_cw;
82
83   // Grab the control word
84   __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
85
86 #if 0
87   printf("fpu_cw: %x\n", fpu_cw);
88 #endif
89
90   // Set bits 8-9 to 10 (64-bit precision).
91   fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
92
93   // Store the new control word back
94   __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
95 }
96 #endif
97
98 /* -----------------------------------------------------------------------------
99    Starting up the RTS
100    -------------------------------------------------------------------------- */
101
102 void
103 hs_init(int *argc, char **argv[])
104 {
105     hs_init_count++;
106     if (hs_init_count > 1) {
107         // second and subsequent inits are ignored
108         return;
109     }
110
111     setlocale(LC_CTYPE,"");
112
113     /* Initialise the stats department, phase 0 */
114     initStats0();
115
116     /* Next we do is grab the start time...just in case we're
117      * collecting timing statistics.
118      */
119     stat_startInit();
120
121 #if defined(DEBUG)
122     /* Start off by initialising the allocator debugging so we can
123      * use it anywhere */
124     initAllocator();
125 #endif
126
127     /* Set the RTS flags to default values. */
128
129     initRtsFlagsDefaults();
130
131     /* Call the user hook to reset defaults, if present */
132     defaultsHook();
133
134     /* Parse the flags, separating the RTS flags from the programs args */
135     if (argc != NULL && argv != NULL) {
136         setFullProgArgv(*argc,*argv);
137         setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
138         setProgArgv(*argc,*argv);
139     }
140
141     /* Initialise the stats department, phase 1 */
142     initStats1();
143
144 #ifdef USE_PAPI
145     papi_init();
146 #endif
147
148     /* initTracing must be after setupRtsFlags() */
149 #ifdef TRACING
150     initTracing();
151 #endif
152     /* Dtrace events are always enabled
153      */
154     dtraceEventStartup();
155
156     /* initialise scheduler data structures (needs to be done before
157      * initStorage()).
158      */
159     initScheduler();
160
161     /* initialize the storage manager */
162     initStorage();
163
164     /* initialise the stable pointer table */
165     initStablePtrTable();
166
167     /* Add some GC roots for things in the base package that the RTS
168      * knows about.  We don't know whether these turn out to be CAFs
169      * or refer to CAFs, but we have to assume that they might.
170      */
171     getStablePtr((StgPtr)runIO_closure);
172     getStablePtr((StgPtr)runNonIO_closure);
173     getStablePtr((StgPtr)stackOverflow_closure);
174     getStablePtr((StgPtr)heapOverflow_closure);
175     getStablePtr((StgPtr)runFinalizerBatch_closure);
176     getStablePtr((StgPtr)unpackCString_closure);
177     getStablePtr((StgPtr)blockedIndefinitelyOnMVar_closure);
178     getStablePtr((StgPtr)nonTermination_closure);
179     getStablePtr((StgPtr)blockedIndefinitelyOnSTM_closure);
180
181     /* initialise the shared Typeable store */
182     initGlobalStore();
183
184     /* initialise file locking, if necessary */
185 #if !defined(mingw32_HOST_OS)    
186     initFileLocking();
187 #endif
188
189 #if defined(DEBUG)
190     /* initialise thread label table (tso->char*) */
191     initThreadLabelTable();
192 #endif
193
194     initProfiling1();
195
196     /* start the virtual timer 'subsystem'. */
197     initTimer();
198     startTimer();
199
200 #if defined(RTS_USER_SIGNALS)
201     if (RtsFlags.MiscFlags.install_signal_handlers) {
202         /* Initialise the user signal handler set */
203         initUserSignals();
204         /* Set up handler to run on SIGINT, etc. */
205         initDefaultHandlers();
206     }
207 #endif
208  
209 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
210     startupAsyncIO();
211 #endif
212
213 #ifdef RTS_GTK_FRONTPANEL
214     if (RtsFlags.GcFlags.frontpanel) {
215         initFrontPanel();
216     }
217 #endif
218
219 #if X86_INIT_FPU
220     x86_init_fpu();
221 #endif
222
223     /* Record initialization times */
224     stat_endInit();
225 }
226
227 // Compatibility interface
228 void
229 startupHaskell(int argc, char *argv[], void (*init_root)(void))
230 {
231     hs_init(&argc, &argv);
232     if(init_root)
233         hs_add_root(init_root);
234 }
235
236
237 /* -----------------------------------------------------------------------------
238    Per-module initialisation
239
240    This process traverses all the compiled modules in the program
241    starting with "Main", and performing per-module initialisation for
242    each one.
243
244    So far, two things happen at initialisation time:
245
246       - we register stable names for each foreign-exported function
247         in that module.  This prevents foreign-exported entities, and
248         things they depend on, from being garbage collected.
249
250       - we supply a unique integer to each statically declared cost
251         centre and cost centre stack in the program.
252
253    The code generator inserts a small function "__stginit_<module>" in each
254    module and calls the registration functions in each of the modules it
255    imports.
256
257    The init* functions are compiled in the same way as STG code,
258    i.e. without normal C call/return conventions.  Hence we must use
259    StgRun to call this stuff.
260    -------------------------------------------------------------------------- */
261
262 /* The init functions use an explicit stack... 
263  */
264 #define INIT_STACK_BLOCKS  4
265 static StgFunPtr *init_stack = NULL;
266
267 void
268 hs_add_root(void (*init_root)(void))
269 {
270     bdescr *bd;
271     nat init_sp;
272     Capability *cap;
273
274     cap = rts_lock();
275
276     if (hs_init_count <= 0) {
277         barf("hs_add_root() must be called after hs_init()");
278     }
279
280     /* The initialisation stack grows downward, with sp pointing 
281        to the last occupied word */
282     init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
283     bd = allocGroup_lock(INIT_STACK_BLOCKS);
284     init_stack = (StgFunPtr *)bd->start;
285     init_stack[--init_sp] = (StgFunPtr)stg_init_finish;
286     if (init_root != NULL) {
287         init_stack[--init_sp] = (StgFunPtr)init_root;
288     }
289     
290     cap->r.rSp = (P_)(init_stack + init_sp);
291     StgRun((StgFunPtr)stg_init, &cap->r);
292
293     freeGroup_lock(bd);
294
295     startupHpc();
296
297     // This must be done after module initialisation.
298     // ToDo: make this work in the presence of multiple hs_add_root()s.
299     initProfiling2();
300
301     rts_unlock(cap);
302
303     // ditto.
304 #if defined(THREADED_RTS)
305     ioManagerStart();
306 #endif
307 }
308
309 /* ----------------------------------------------------------------------------
310  * Shutting down the RTS
311  *
312  * The wait_foreign parameter means:
313  *       True  ==> wait for any threads doing foreign calls now.
314  *       False ==> threads doing foreign calls may return in the
315  *                 future, but will immediately block on a mutex.
316  *                 (capability->lock).
317  * 
318  * If this RTS is a DLL that we're about to unload, then you want
319  * safe=True, otherwise the thread might return to code that has been
320  * unloaded.  If this is a standalone program that is about to exit,
321  * then you can get away with safe=False, which is better because we
322  * won't hang on exit if there is a blocked foreign call outstanding.
323  *
324  ------------------------------------------------------------------------- */
325
326 static void
327 hs_exit_(rtsBool wait_foreign)
328 {
329     if (hs_init_count <= 0) {
330         errorBelch("warning: too many hs_exit()s");
331         return;
332     }
333     hs_init_count--;
334     if (hs_init_count > 0) {
335         // ignore until it's the last one
336         return;
337     }
338
339     /* start timing the shutdown */
340     stat_startExit();
341     
342     OnExitHook();
343
344     // Free the full argv storage
345     freeFullProgArgv();
346
347 #if defined(THREADED_RTS)
348     ioManagerDie();
349 #endif
350
351     /* stop all running tasks */
352     exitScheduler(wait_foreign);
353
354     /* run C finalizers for all active weak pointers */
355     runAllCFinalizers(weak_ptr_list);
356     
357 #if defined(RTS_USER_SIGNALS)
358     if (RtsFlags.MiscFlags.install_signal_handlers) {
359         freeSignalHandlers();
360     }
361 #endif
362
363     /* stop the ticker */
364     stopTimer();
365     exitTimer();
366
367     // set the terminal settings back to what they were
368 #if !defined(mingw32_HOST_OS)    
369     resetTerminalSettings();
370 #endif
371
372     // uninstall signal handlers
373     resetDefaultHandlers();
374
375     /* stop timing the shutdown, we're about to print stats */
376     stat_endExit();
377     
378     /* shutdown the hpc support (if needed) */
379     exitHpc();
380
381     // clean up things from the storage manager's point of view.
382     // also outputs the stats (+RTS -s) info.
383     exitStorage();
384     
385     /* free the tasks */
386     freeScheduler();
387
388     /* free shared Typeable store */
389     exitGlobalStore();
390
391     /* free file locking tables, if necessary */
392 #if !defined(mingw32_HOST_OS)    
393     freeFileLocking();
394 #endif
395
396     /* free the stable pointer table */
397     exitStablePtrTable();
398
399 #if defined(DEBUG)
400     /* free the thread label table */
401     freeThreadLabelTable();
402 #endif
403
404 #ifdef RTS_GTK_FRONTPANEL
405     if (RtsFlags.GcFlags.frontpanel) {
406         stopFrontPanel();
407     }
408 #endif
409
410 #if defined(PROFILING) 
411     reportCCSProfiling();
412 #endif
413
414     endProfiling();
415     freeProfiling1();
416
417 #ifdef PROFILING
418     // Originally, this was in report_ccs_profiling().  Now, retainer
419     // profiling might tack some extra stuff on to the end of this file
420     // during endProfiling().
421     if (prof_file != NULL) fclose(prof_file);
422 #endif
423
424 #ifdef TRACING
425     endTracing();
426     freeTracing();
427 #endif
428
429 #if defined(TICKY_TICKY)
430     if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
431 #endif
432
433 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
434     shutdownAsyncIO(wait_foreign);
435 #endif
436
437     /* free hash table storage */
438     exitHashTable();
439
440     // Finally, free all our storage
441     freeStorage();
442
443 #if defined(DEBUG)
444     /* and shut down the allocator debugging */
445     shutdownAllocator();
446 #endif
447
448 }
449
450 // The real hs_exit():
451 void
452 hs_exit(void)
453 {
454     hs_exit_(rtsTrue);
455     // be safe; this might be a DLL
456 }
457
458 // Compatibility interfaces
459 void
460 shutdownHaskell(void)
461 {
462     hs_exit();
463 }
464
465 void
466 shutdownHaskellAndExit(int n)
467 {
468     // we're about to exit(), no need to wait for foreign calls to return.
469     hs_exit_(rtsFalse);
470
471     if (hs_init_count == 0) {
472         stg_exit(n);
473     }
474 }
475
476 #ifndef mingw32_HOST_OS
477 void
478 shutdownHaskellAndSignal(int sig)
479 {
480     hs_exit_(rtsFalse);
481     kill(getpid(),sig);
482 }
483 #endif
484
485 /* 
486  * called from STG-land to exit the program
487  */
488
489 void (*exitFn)(int) = 0;
490
491 void  
492 stg_exit(int n)
493
494   if (exitFn)
495     (*exitFn)(n);
496   exit(n);
497 }