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