[project @ 2003-01-30 10:19:07 by simonmar]
[ghc-hetmet.git] / ghc / rts / RtsStartup.c
1 /* -----------------------------------------------------------------------------
2  * $Id: RtsStartup.c,v 1.70 2003/01/30 10:19:07 simonmar Exp $
3  *
4  * (c) The GHC Team, 1998-2002
5  *
6  * Main function for a standalone Haskell program.
7  *
8  * ---------------------------------------------------------------------------*/
9
10 #include "PosixSource.h"
11 #include "Rts.h"
12 #include "RtsAPI.h"
13 #include "RtsUtils.h"
14 #include "RtsFlags.h"  
15 #include "Storage.h"    /* initStorage, exitStorage */
16 #include "StablePriv.h" /* initStablePtrTable */
17 #include "Schedule.h"   /* initScheduler */
18 #include "Stats.h"      /* initStats */
19 #include "Signals.h"
20 #include "Itimer.h"
21 #include "Weak.h"
22 #include "Ticky.h"
23 #include "StgRun.h"
24 #include "StgStartup.h"
25 #include "Prelude.h"            /* fixupRTStoPreludeRefs */
26 #include "HsFFI.h"
27 #include "Linker.h"
28 #include "ThreadLabels.h"
29
30 #if defined(RTS_GTK_FRONTPANEL)
31 #include "FrontPanel.h"
32 #endif
33
34 #if defined(PROFILING) || defined(DEBUG)
35 # include "Profiling.h"
36 # include "ProfHeap.h"
37 # include "RetainerProfile.h"
38 #endif
39
40 #if defined(GRAN)
41 # include "GranSimRts.h"
42 #endif
43
44 #if defined(GRAN) || defined(PAR)
45 # include "ParallelRts.h"
46 #endif
47
48 #if defined(PAR)
49 # include "Parallel.h"
50 # include "LLC.h"
51 #endif
52
53 #include <stdlib.h>
54
55 // Flag Structure
56 struct RTS_FLAGS RtsFlags;
57
58 // Count of how many outstanding hs_init()s there have been.
59 static int hs_init_count = 0;
60
61 /* -----------------------------------------------------------------------------
62    Starting up the RTS
63    -------------------------------------------------------------------------- */
64
65 void
66 hs_init(int *argc, char **argv[])
67 {
68     hs_init_count++;
69     if (hs_init_count > 1) {
70         // second and subsequent inits are ignored
71         return;
72     }
73
74     /* The very first thing we do is grab the start time...just in case we're
75      * collecting timing statistics.
76      */
77     stat_startInit();
78
79 #ifdef PAR
80     /*
81      * The parallel system needs to be initialised and synchronised before
82      * the program is run.  
83      */ 
84     startupParallelSystem(argv);
85      
86     if (*argv[0] == '-') { /* Strip off mainPE flag argument */
87       argv++; 
88       argc--;                   
89     }
90
91     argv[1] = argv[0];   /* ignore the nPEs argument */
92     argv++; argc--;
93 #endif
94
95     /* Set the RTS flags to default values. */
96     initRtsFlagsDefaults();
97
98     /* Call the user hook to reset defaults, if present */
99     defaultsHook();
100
101     /* Parse the flags, separating the RTS flags from the programs args */
102     if (argc != NULL && argv != NULL) {
103         setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
104         prog_argc = *argc;
105         prog_argv = *argv;
106     }
107
108 #if defined(PAR)
109     /* NB: this really must be done after processing the RTS flags */
110     IF_PAR_DEBUG(verbose,
111                  fprintf(stderr, "==== Synchronising system (%d PEs)\n", nPEs));
112     synchroniseSystem();             // calls initParallelSystem etc
113 #endif  /* PAR */
114
115     /* initialise scheduler data structures (needs to be done before
116      * initStorage()).
117      */
118     initScheduler();
119
120 #if defined(GRAN)
121     /* And start GranSim profiling if required: */
122     if (RtsFlags.GranFlags.GranSimStats.Full)
123       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
124 #elif defined(PAR)
125     /* And start GUM profiling if required: */
126     if (RtsFlags.ParFlags.ParStats.Full)
127       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
128 #endif  /* PAR || GRAN */
129
130     /* initialize the storage manager */
131     initStorage();
132
133     /* initialise the stable pointer table */
134     initStablePtrTable();
135
136     /* initialise thread label table (tso->char*) */
137     initThreadLabelTable();
138
139 #if defined(PROFILING) || defined(DEBUG)
140     initProfiling1();
141 #endif
142
143     /* start the virtual timer 'subsystem'. */
144     startVirtTimer(TICK_MILLISECS);
145
146     /* Initialise the stats department */
147     initStats();
148
149 #if !defined(mingw32_TARGET_OS) && !defined(PAR)
150     /* Initialise the user signal handler set */
151     initUserSignals();
152     /* Set up handler to run on SIGINT, etc. */
153     initDefaultHandlers();
154 #endif
155  
156 #ifdef RTS_GTK_FRONTPANEL
157     if (RtsFlags.GcFlags.frontpanel) {
158         initFrontPanel();
159     }
160 #endif
161
162     /* Record initialization times */
163     stat_endInit();
164 }
165
166 // Compatibility interface
167 void
168 startupHaskell(int argc, char *argv[], void (*init_root)(void))
169 {
170     hs_init(&argc, &argv);
171     hs_add_root(init_root);
172 }
173
174
175 /* -----------------------------------------------------------------------------
176    Getting/Setting the program's arguments.
177
178    These are used by System.Environment.
179    -------------------------------------------------------------------------- */
180
181 void
182 getProgArgv(int *argc, char **argv[])
183 {
184     *argc = prog_argc;
185     *argv = prog_argv;
186 }
187
188 void
189 setProgArgv(int argc, char *argv[])
190 {
191    /* Usually this is done by startupHaskell, so we don't need to call this. 
192       However, sometimes Hugs wants to change the arguments which Haskell
193       getArgs >>= ... will be fed.  So you can do that by calling here
194       _after_ calling startupHaskell.
195    */
196    prog_argc = argc;
197    prog_argv = argv;
198 }
199
200 /* -----------------------------------------------------------------------------
201    Per-module initialisation
202
203    This process traverses all the compiled modules in the program
204    starting with "Main", and performing per-module initialisation for
205    each one.
206
207    So far, two things happen at initialisation time:
208
209       - we register stable names for each foreign-exported function
210         in that module.  This prevents foreign-exported entities, and
211         things they depend on, from being garbage collected.
212
213       - we supply a unique integer to each statically declared cost
214         centre and cost centre stack in the program.
215
216    The code generator inserts a small function "__stginit_<module>" in each
217    module and calls the registration functions in each of the modules it
218    imports.
219
220    The init* functions are compiled in the same way as STG code,
221    i.e. without normal C call/return conventions.  Hence we must use
222    StgRun to call this stuff.
223    -------------------------------------------------------------------------- */
224
225 /* The init functions use an explicit stack... 
226  */
227 #define INIT_STACK_BLOCKS  4
228 static F_ *init_stack = NULL;
229
230 void
231 hs_add_root(void (*init_root)(void))
232 {
233     bdescr *bd;
234 #ifdef SMP
235     Capability cap;
236 #else
237 #define cap MainCapability
238 #endif
239     nat init_sp;
240
241     if (hs_init_count <= 0) {
242         barf("hs_add_root() must be called after hs_init()");
243     }
244
245     init_sp = 0;
246     bd = allocGroup(INIT_STACK_BLOCKS);
247     init_stack = (F_ *)bd->start;
248     init_stack[init_sp++] = (F_)stg_init_ret;
249     if (init_root != NULL) {
250         init_stack[init_sp++] = (F_)init_root;
251     }
252     
253     cap.r.rSp = (P_)(init_stack + init_sp);
254     StgRun((StgFunPtr)stg_init, &cap.r);
255
256     freeGroup(bd);
257
258 #if defined(PROFILING) || defined(DEBUG)
259     // This must be done after module initialisation.
260     // ToDo: make this work in the presence of multiple hs_add_root()s.
261     initProfiling2();
262 #endif
263 }
264
265 /* -----------------------------------------------------------------------------
266    Shutting down the RTS
267    -------------------------------------------------------------------------- */
268
269 void
270 hs_exit(void)
271 {
272     if (hs_init_count <= 0) {
273         barf("too many hs_exit()s");
274     }
275     hs_init_count--;
276     if (hs_init_count > 0) {
277         // ignore until it's the last one
278         return;
279     }
280
281     /* start timing the shutdown */
282     stat_startExit();
283     
284     /* stop all running tasks */
285     exitScheduler();
286     
287 #if !defined(GRAN)
288     /* Finalize any remaining weak pointers */
289     finalizeWeakPointersNow();
290 #endif
291     
292 #if defined(GRAN)
293     /* end_gr_simulation prints global stats if requested -- HWL */
294     if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
295         end_gr_simulation();
296 #endif
297     
298     /* stop the ticker */
299     stopVirtTimer();
300     
301     /* reset the standard file descriptors to blocking mode */
302     resetNonBlockingFd(0);
303     resetNonBlockingFd(1);
304     resetNonBlockingFd(2);
305
306 #if defined(PAR)
307     /* controlled exit; good thread! */
308     shutdownParallelSystem(0);
309     
310     /* global statistics in parallel system */
311     PAR_TICKY_PAR_END();
312 #endif
313
314     /* stop timing the shutdown, we're about to print stats */
315     stat_endExit();
316     
317     /* clean up things from the storage manager's point of view.
318      * also outputs the stats (+RTS -s) info.
319      */
320     exitStorage();
321     
322 #ifdef RTS_GTK_FRONTPANEL
323     if (RtsFlags.GcFlags.frontpanel) {
324         stopFrontPanel();
325     }
326 #endif
327
328 #if defined(PROFILING) 
329     reportCCSProfiling();
330 #endif
331
332 #if defined(PROFILING) || defined(DEBUG)
333     endProfiling();
334 #endif
335
336 #ifdef PROFILING
337     // Originally, this was in report_ccs_profiling().  Now, retainer
338     // profiling might tack some extra stuff on to the end of this file
339     // during endProfiling().
340     fclose(prof_file);
341 #endif
342     
343 #if defined(TICKY_TICKY)
344     if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
345 #endif
346 }
347
348 // Compatibility interfaces
349 void
350 shutdownHaskell(void)
351 {
352     hs_exit();
353 }
354
355 void
356 shutdownHaskellAndExit(int n)
357 {
358     if (hs_init_count == 1) {
359         OnExitHook();
360         hs_exit();
361 #if defined(PAR)
362         /* really exit (stg_exit() would call shutdownParallelSystem() again) */
363         exit(n);
364 #else
365         stg_exit(n);
366 #endif
367     }
368 }
369
370 /* 
371  * called from STG-land to exit the program
372  */
373
374 #ifdef PAR
375 static int exit_started=rtsFalse;
376 #endif
377
378 void  
379 stg_exit(int n)
380
381 #ifdef PAR
382   /* HACK: avoid a loop when exiting due to a stupid error */
383   if (exit_started) 
384     return;
385   exit_started=rtsTrue;
386
387   IF_PAR_DEBUG(verbose, fprintf(stderr,"==-- stg_exit %d on [%x]...", n, mytid));
388   shutdownParallelSystem(n);
389 #endif
390   exit(n);
391 }
392