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