fix #3910
[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. why?)
73    (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
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     // Free the full argv storage
349     freeFullProgArgv();
350
351 #if defined(THREADED_RTS)
352     ioManagerDie();
353 #endif
354
355     /* stop all running tasks */
356     exitScheduler(wait_foreign);
357
358     /* run C finalizers for all active weak pointers */
359     runAllCFinalizers(weak_ptr_list);
360     
361 #if defined(RTS_USER_SIGNALS)
362     if (RtsFlags.MiscFlags.install_signal_handlers) {
363         freeSignalHandlers();
364     }
365 #endif
366
367     /* stop the ticker */
368     stopTimer();
369     exitTimer(wait_foreign);
370
371     // set the terminal settings back to what they were
372 #if !defined(mingw32_HOST_OS)    
373     resetTerminalSettings();
374 #endif
375
376     // uninstall signal handlers
377     resetDefaultHandlers();
378
379     /* stop timing the shutdown, we're about to print stats */
380     stat_endExit();
381     
382     /* shutdown the hpc support (if needed) */
383     exitHpc();
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     /* free the tasks */
390     freeScheduler();
391
392     /* free shared Typeable store */
393     exitGlobalStore();
394
395     /* free linker data */
396     exitLinker();
397
398     /* free file locking tables, if necessary */
399 #if !defined(mingw32_HOST_OS)    
400     freeFileLocking();
401 #endif
402
403     /* free the stable pointer table */
404     exitStablePtrTable();
405
406 #if defined(DEBUG)
407     /* free the thread label table */
408     freeThreadLabelTable();
409 #endif
410
411 #ifdef RTS_GTK_FRONTPANEL
412     if (RtsFlags.GcFlags.frontpanel) {
413         stopFrontPanel();
414     }
415 #endif
416
417 #if defined(PROFILING) 
418     reportCCSProfiling();
419 #endif
420
421     endProfiling();
422     freeProfiling1();
423
424 #ifdef PROFILING
425     // Originally, this was in report_ccs_profiling().  Now, retainer
426     // profiling might tack some extra stuff on to the end of this file
427     // during endProfiling().
428     if (prof_file != NULL) fclose(prof_file);
429 #endif
430
431 #ifdef TRACING
432     endTracing();
433     freeTracing();
434 #endif
435
436 #if defined(TICKY_TICKY)
437     if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
438 #endif
439
440 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
441     shutdownAsyncIO(wait_foreign);
442 #endif
443
444     /* free hash table storage */
445     exitHashTable();
446
447     // Finally, free all our storage.  However, we only free the heap
448     // memory if we have waited for foreign calls to complete;
449     // otherwise a foreign call in progress may still be referencing
450     // heap memory (e.g. by being passed a ByteArray#).
451     freeStorage(wait_foreign);
452
453 }
454
455 // The real hs_exit():
456 void
457 hs_exit(void)
458 {
459     hs_exit_(rtsTrue);
460     // be safe; this might be a DLL
461 }
462
463 // Compatibility interfaces
464 void
465 shutdownHaskell(void)
466 {
467     hs_exit();
468 }
469
470 void
471 shutdownHaskellAndExit(int n)
472 {
473     // we're about to exit(), no need to wait for foreign calls to return.
474     hs_exit_(rtsFalse);
475
476     if (hs_init_count == 0) {
477         stg_exit(n);
478     }
479 }
480
481 #ifndef mingw32_HOST_OS
482 void
483 shutdownHaskellAndSignal(int sig)
484 {
485     hs_exit_(rtsFalse);
486     kill(getpid(),sig);
487 }
488 #endif
489
490 /* 
491  * called from STG-land to exit the program
492  */
493
494 void (*exitFn)(int) = 0;
495
496 void  
497 stg_exit(int n)
498
499   if (exitFn)
500     (*exitFn)(n);
501   exit(n);
502 }