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