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