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