Free full_prog_argv at exit, closing a memory leak
[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
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 TRACING
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)runIO_closure);
169     getStablePtr((StgPtr)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     /* start the virtual timer 'subsystem'. */
194     initTimer();
195     startTimer();
196
197 #if defined(RTS_USER_SIGNALS)
198     if (RtsFlags.MiscFlags.install_signal_handlers) {
199         /* Initialise the user signal handler set */
200         initUserSignals();
201         /* Set up handler to run on SIGINT, etc. */
202         initDefaultHandlers();
203     }
204 #endif
205  
206 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
207     startupAsyncIO();
208 #endif
209
210 #ifdef RTS_GTK_FRONTPANEL
211     if (RtsFlags.GcFlags.frontpanel) {
212         initFrontPanel();
213     }
214 #endif
215
216 #if X86_INIT_FPU
217     x86_init_fpu();
218 #endif
219
220     /* Record initialization times */
221     stat_endInit();
222 }
223
224 // Compatibility interface
225 void
226 startupHaskell(int argc, char *argv[], void (*init_root)(void))
227 {
228     hs_init(&argc, &argv);
229     if(init_root)
230         hs_add_root(init_root);
231 }
232
233
234 /* -----------------------------------------------------------------------------
235    Per-module initialisation
236
237    This process traverses all the compiled modules in the program
238    starting with "Main", and performing per-module initialisation for
239    each one.
240
241    So far, two things happen at initialisation time:
242
243       - we register stable names for each foreign-exported function
244         in that module.  This prevents foreign-exported entities, and
245         things they depend on, from being garbage collected.
246
247       - we supply a unique integer to each statically declared cost
248         centre and cost centre stack in the program.
249
250    The code generator inserts a small function "__stginit_<module>" in each
251    module and calls the registration functions in each of the modules it
252    imports.
253
254    The init* functions are compiled in the same way as STG code,
255    i.e. without normal C call/return conventions.  Hence we must use
256    StgRun to call this stuff.
257    -------------------------------------------------------------------------- */
258
259 /* The init functions use an explicit stack... 
260  */
261 #define INIT_STACK_BLOCKS  4
262 static StgFunPtr *init_stack = NULL;
263
264 void
265 hs_add_root(void (*init_root)(void))
266 {
267     bdescr *bd;
268     nat init_sp;
269     Capability *cap;
270
271     cap = rts_lock();
272
273     if (hs_init_count <= 0) {
274         barf("hs_add_root() must be called after hs_init()");
275     }
276
277     /* The initialisation stack grows downward, with sp pointing 
278        to the last occupied word */
279     init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
280     bd = allocGroup_lock(INIT_STACK_BLOCKS);
281     init_stack = (StgFunPtr *)bd->start;
282     init_stack[--init_sp] = (StgFunPtr)stg_init_finish;
283     if (init_root != NULL) {
284         init_stack[--init_sp] = (StgFunPtr)init_root;
285     }
286     
287     cap->r.rSp = (P_)(init_stack + init_sp);
288     StgRun((StgFunPtr)stg_init, &cap->r);
289
290     freeGroup_lock(bd);
291
292     startupHpc();
293
294     // This must be done after module initialisation.
295     // ToDo: make this work in the presence of multiple hs_add_root()s.
296     initProfiling2();
297
298     rts_unlock(cap);
299
300     // ditto.
301 #if defined(THREADED_RTS)
302     ioManagerStart();
303 #endif
304 }
305
306 /* ----------------------------------------------------------------------------
307  * Shutting down the RTS
308  *
309  * The wait_foreign parameter means:
310  *       True  ==> wait for any threads doing foreign calls now.
311  *       False ==> threads doing foreign calls may return in the
312  *                 future, but will immediately block on a mutex.
313  *                 (capability->lock).
314  * 
315  * If this RTS is a DLL that we're about to unload, then you want
316  * safe=True, otherwise the thread might return to code that has been
317  * unloaded.  If this is a standalone program that is about to exit,
318  * then you can get away with safe=False, which is better because we
319  * won't hang on exit if there is a blocked foreign call outstanding.
320  *
321  ------------------------------------------------------------------------- */
322
323 static void
324 hs_exit_(rtsBool wait_foreign)
325 {
326     if (hs_init_count <= 0) {
327         errorBelch("warning: too many hs_exit()s");
328         return;
329     }
330     hs_init_count--;
331     if (hs_init_count > 0) {
332         // ignore until it's the last one
333         return;
334     }
335
336     /* start timing the shutdown */
337     stat_startExit();
338     
339     OnExitHook();
340
341     // Free the full argv storage
342     freeFullProgArgv();
343
344 #if defined(THREADED_RTS)
345     ioManagerDie();
346 #endif
347
348     /* stop all running tasks */
349     exitScheduler(wait_foreign);
350
351     /* run C finalizers for all active weak pointers */
352     runAllCFinalizers(weak_ptr_list);
353     
354 #if defined(RTS_USER_SIGNALS)
355     if (RtsFlags.MiscFlags.install_signal_handlers) {
356         freeSignalHandlers();
357     }
358 #endif
359
360     /* stop the ticker */
361     stopTimer();
362     exitTimer();
363
364     // set the terminal settings back to what they were
365 #if !defined(mingw32_HOST_OS)    
366     resetTerminalSettings();
367 #endif
368
369     // uninstall signal handlers
370     resetDefaultHandlers();
371
372     /* stop timing the shutdown, we're about to print stats */
373     stat_endExit();
374     
375     /* shutdown the hpc support (if needed) */
376     exitHpc();
377
378     // clean up things from the storage manager's point of view.
379     // also outputs the stats (+RTS -s) info.
380     exitStorage();
381     
382     /* free the tasks */
383     freeScheduler();
384
385     /* free shared Typeable store */
386     exitGlobalStore();
387
388     /* free file locking tables, if necessary */
389 #if !defined(mingw32_HOST_OS)    
390     freeFileLocking();
391 #endif
392
393     /* free the stable pointer table */
394     exitStablePtrTable();
395
396 #if defined(DEBUG)
397     /* free the thread label table */
398     freeThreadLabelTable();
399 #endif
400
401 #ifdef RTS_GTK_FRONTPANEL
402     if (RtsFlags.GcFlags.frontpanel) {
403         stopFrontPanel();
404     }
405 #endif
406
407 #if defined(PROFILING) 
408     reportCCSProfiling();
409 #endif
410
411     endProfiling();
412     freeProfiling1();
413
414 #ifdef PROFILING
415     // Originally, this was in report_ccs_profiling().  Now, retainer
416     // profiling might tack some extra stuff on to the end of this file
417     // during endProfiling().
418     if (prof_file != NULL) fclose(prof_file);
419 #endif
420
421 #ifdef TRACING
422     endTracing();
423     freeTracing();
424 #endif
425
426 #if defined(TICKY_TICKY)
427     if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
428 #endif
429
430 #if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
431     shutdownAsyncIO(wait_foreign);
432 #endif
433
434     /* free hash table storage */
435     exitHashTable();
436
437     // Finally, free all our storage
438     freeStorage();
439
440 #if defined(DEBUG)
441     /* and shut down the allocator debugging */
442     shutdownAllocator();
443 #endif
444
445 }
446
447 // The real hs_exit():
448 void
449 hs_exit(void)
450 {
451     hs_exit_(rtsTrue);
452     // be safe; this might be a DLL
453 }
454
455 // Compatibility interfaces
456 void
457 shutdownHaskell(void)
458 {
459     hs_exit();
460 }
461
462 void
463 shutdownHaskellAndExit(int n)
464 {
465     // we're about to exit(), no need to wait for foreign calls to return.
466     hs_exit_(rtsFalse);
467
468     if (hs_init_count == 0) {
469         stg_exit(n);
470     }
471 }
472
473 #ifndef mingw32_HOST_OS
474 void
475 shutdownHaskellAndSignal(int sig)
476 {
477     hs_exit_(rtsFalse);
478     kill(getpid(),sig);
479 }
480 #endif
481
482 /* 
483  * called from STG-land to exit the program
484  */
485
486 void (*exitFn)(int) = 0;
487
488 void  
489 stg_exit(int n)
490
491   if (exitFn)
492     (*exitFn)(n);
493   exit(n);
494 }