f0b2170bad391220331e6f26fe537b1d800da25d
[ghc.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 "eventlog/EventLog.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 DEBUG
150 initTracing();
151 #endif
152
153 /* initialise scheduler data structures (needs to be done before
154 * initStorage()).
155 */
156 initScheduler();
157
158 /* initialize the storage manager */
159 initStorage();
160
161 /* initialise the stable pointer table */
162 initStablePtrTable();
163
164 /* Add some GC roots for things in the base package that the RTS
165 * knows about. We don't know whether these turn out to be CAFs
166 * or refer to CAFs, but we have to assume that they might.
167 */
168 getStablePtr((StgPtr)base_GHCziTopHandler_runIO_closure);
169 getStablePtr((StgPtr)base_GHCziTopHandler_runNonIO_closure);
170 getStablePtr((StgPtr)stackOverflow_closure);
171 getStablePtr((StgPtr)heapOverflow_closure);
172 getStablePtr((StgPtr)runFinalizerBatch_closure);
173 getStablePtr((StgPtr)unpackCString_closure);
174 getStablePtr((StgPtr)blockedIndefinitelyOnMVar_closure);
175 getStablePtr((StgPtr)nonTermination_closure);
176 getStablePtr((StgPtr)blockedIndefinitelyOnSTM_closure);
177
178 /* initialise the shared Typeable store */
179 initGlobalStore();
180
181 /* initialise file locking, if necessary */
182 #if !defined(mingw32_HOST_OS)
183 initFileLocking();
184 #endif
185
186 #if defined(DEBUG)
187 /* initialise thread label table (tso->char*) */
188 initThreadLabelTable();
189 #endif
190
191 initProfiling1();
192
193 #ifdef EVENTLOG
194 if (RtsFlags.EventLogFlags.doEventLogging) {
195 initEventLogging();
196 }
197 #endif
198
199 /* start the virtual timer 'subsystem'. */
200 initTimer();
201 startTimer();
202
203 #if defined(RTS_USER_SIGNALS)
204 if (RtsFlags.MiscFlags.install_signal_handlers) {
205 /* Initialise the user signal handler set */
206 initUserSignals();
207 /* Set up handler to run on SIGINT, etc. */
208 initDefaultHandlers();
209 }
210 #endif
211
212 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
213 startupAsyncIO();
214 #endif
215
216 #ifdef RTS_GTK_FRONTPANEL
217 if (RtsFlags.GcFlags.frontpanel) {
218 initFrontPanel();
219 }
220 #endif
221
222 #if X86_INIT_FPU
223 x86_init_fpu();
224 #endif
225
226 /* Record initialization times */
227 stat_endInit();
228 }
229
230 // Compatibility interface
231 void
232 startupHaskell(int argc, char *argv[], void (*init_root)(void))
233 {
234 hs_init(&argc, &argv);
235 if(init_root)
236 hs_add_root(init_root);
237 }
238
239
240 /* -----------------------------------------------------------------------------
241 Per-module initialisation
242
243 This process traverses all the compiled modules in the program
244 starting with "Main", and performing per-module initialisation for
245 each one.
246
247 So far, two things happen at initialisation time:
248
249 - we register stable names for each foreign-exported function
250 in that module. This prevents foreign-exported entities, and
251 things they depend on, from being garbage collected.
252
253 - we supply a unique integer to each statically declared cost
254 centre and cost centre stack in the program.
255
256 The code generator inserts a small function "__stginit_<module>" in each
257 module and calls the registration functions in each of the modules it
258 imports.
259
260 The init* functions are compiled in the same way as STG code,
261 i.e. without normal C call/return conventions. Hence we must use
262 StgRun to call this stuff.
263 -------------------------------------------------------------------------- */
264
265 /* The init functions use an explicit stack...
266 */
267 #define INIT_STACK_BLOCKS 4
268 static StgFunPtr *init_stack = NULL;
269
270 void
271 hs_add_root(void (*init_root)(void))
272 {
273 bdescr *bd;
274 nat init_sp;
275 Capability *cap;
276
277 cap = rts_lock();
278
279 if (hs_init_count <= 0) {
280 barf("hs_add_root() must be called after hs_init()");
281 }
282
283 /* The initialisation stack grows downward, with sp pointing
284 to the last occupied word */
285 init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
286 bd = allocGroup_lock(INIT_STACK_BLOCKS);
287 init_stack = (StgFunPtr *)bd->start;
288 init_stack[--init_sp] = (StgFunPtr)stg_init_finish;
289 if (init_root != NULL) {
290 init_stack[--init_sp] = (StgFunPtr)init_root;
291 }
292
293 cap->r.rSp = (P_)(init_stack + init_sp);
294 StgRun((StgFunPtr)stg_init, &cap->r);
295
296 freeGroup_lock(bd);
297
298 startupHpc();
299
300 // This must be done after module initialisation.
301 // ToDo: make this work in the presence of multiple hs_add_root()s.
302 initProfiling2();
303
304 rts_unlock(cap);
305
306 // ditto.
307 #if defined(THREADED_RTS)
308 ioManagerStart();
309 #endif
310 }
311
312 /* ----------------------------------------------------------------------------
313 * Shutting down the RTS
314 *
315 * The wait_foreign parameter means:
316 * True ==> wait for any threads doing foreign calls now.
317 * False ==> threads doing foreign calls may return in the
318 * future, but will immediately block on a mutex.
319 * (capability->lock).
320 *
321 * If this RTS is a DLL that we're about to unload, then you want
322 * safe=True, otherwise the thread might return to code that has been
323 * unloaded. If this is a standalone program that is about to exit,
324 * then you can get away with safe=False, which is better because we
325 * won't hang on exit if there is a blocked foreign call outstanding.
326 *
327 ------------------------------------------------------------------------- */
328
329 static void
330 hs_exit_(rtsBool wait_foreign)
331 {
332 if (hs_init_count <= 0) {
333 errorBelch("warning: too many hs_exit()s");
334 return;
335 }
336 hs_init_count--;
337 if (hs_init_count > 0) {
338 // ignore until it's the last one
339 return;
340 }
341
342 /* start timing the shutdown */
343 stat_startExit();
344
345 OnExitHook();
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 EVENTLOG
425 if (RtsFlags.EventLogFlags.doEventLogging) {
426 endEventLogging();
427 freeEventLogging();
428 }
429 #endif
430
431 #if defined(TICKY_TICKY)
432 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
433 #endif
434
435 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
436 shutdownAsyncIO(wait_foreign);
437 #endif
438
439 /* free hash table storage */
440 exitHashTable();
441
442 // Finally, free all our storage
443 freeStorage();
444
445 #if defined(DEBUG)
446 /* and shut down the allocator debugging */
447 shutdownAllocator();
448 #endif
449
450 }
451
452 // The real hs_exit():
453 void
454 hs_exit(void)
455 {
456 hs_exit_(rtsTrue);
457 // be safe; this might be a DLL
458 }
459
460 // Compatibility interfaces
461 void
462 shutdownHaskell(void)
463 {
464 hs_exit();
465 }
466
467 void
468 shutdownHaskellAndExit(int n)
469 {
470 // we're about to exit(), no need to wait for foreign calls to return.
471 hs_exit_(rtsFalse);
472
473 if (hs_init_count == 0) {
474 stg_exit(n);
475 }
476 }
477
478 #ifndef mingw32_HOST_OS
479 void
480 shutdownHaskellAndSignal(int sig)
481 {
482 hs_exit_(rtsFalse);
483 kill(getpid(),sig);
484 }
485 #endif
486
487 /*
488 * called from STG-land to exit the program
489 */
490
491 void (*exitFn)(int) = 0;
492
493 void
494 stg_exit(int n)
495 {
496 if (exitFn)
497 (*exitFn)(n);
498 exit(n);
499 }