[project @ 2002-12-11 15:36:20 by simonmar]
[ghc-hetmet.git] / ghc / rts / RtsStartup.c
1 /* -----------------------------------------------------------------------------
2  * $Id: RtsStartup.c,v 1.67 2002/12/11 15:36:48 simonmar Exp $
3  *
4  * (c) The GHC Team, 1998-2000
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 /*
56  * Flag Structure
57  */
58 struct RTS_FLAGS RtsFlags;
59
60 static int rts_has_started_up = 0;
61 #if defined(PAR)
62 ullong startTime = 0;
63 #endif
64
65 EXTFUN(__stginit_Prelude);
66 static void initModules ( void (*)(void) );
67
68 void
69 setProgArgv(int argc, char *argv[])
70 {
71    /* Usually this is done by startupHaskell, so we don't need to call this. 
72       However, sometimes Hugs wants to change the arguments which Haskell
73       getArgs >>= ... will be fed.  So you can do that by calling here
74       _after_ calling startupHaskell.
75    */
76    prog_argc = argc;
77    prog_argv = argv;
78 }
79
80 void
81 getProgArgv(int *argc, char **argv[])
82 {
83    *argc = prog_argc;
84    *argv = prog_argv;
85 }
86
87
88 void
89 startupHaskell(int argc, char *argv[], void (*init_root)(void))
90 {
91    /* To avoid repeated initialisations of the RTS */
92   if (rts_has_started_up) {
93     /* RTS is up and running, so only run the per-module initialisation code */
94     if (init_root) {
95       initModules(init_root);
96     }
97     return;
98   } else {
99     rts_has_started_up=1;
100   }
101
102     /* The very first thing we do is grab the start time...just in case we're
103      * collecting timing statistics.
104      */
105     stat_startInit();
106
107 #ifdef PAR
108     /*
109      * The parallel system needs to be initialised and synchronised before
110      * the program is run.  
111      */ 
112     startupParallelSystem(argv);
113      
114     if (*argv[0] == '-') { /* Strip off mainPE flag argument */
115       argv++; 
116       argc--;                   
117     }
118
119     argv[1] = argv[0];   /* ignore the nPEs argument */
120     argv++; argc--;
121 #endif
122
123     /* Set the RTS flags to default values. */
124     initRtsFlagsDefaults();
125
126     /* Call the user hook to reset defaults, if present */
127     defaultsHook();
128
129     /* Parse the flags, separating the RTS flags from the programs args */
130     setupRtsFlags(&argc, argv, &rts_argc, rts_argv);
131     prog_argc = argc;
132     prog_argv = argv;
133
134 #if defined(PAR)
135     /* NB: this really must be done after processing the RTS flags */
136     IF_PAR_DEBUG(verbose,
137                  fprintf(stderr, "==== Synchronising system (%d PEs)\n", nPEs));
138     synchroniseSystem();             // calls initParallelSystem etc
139 #endif  /* PAR */
140
141     /* initialise scheduler data structures (needs to be done before
142      * initStorage()).
143      */
144     initScheduler();
145
146 #if defined(GRAN)
147     /* And start GranSim profiling if required: */
148     if (RtsFlags.GranFlags.GranSimStats.Full)
149       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
150 #elif defined(PAR)
151     /* And start GUM profiling if required: */
152     if (RtsFlags.ParFlags.ParStats.Full)
153       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
154 #endif  /* PAR || GRAN */
155
156     /* initialize the storage manager */
157     initStorage();
158
159     /* initialise the stable pointer table */
160     initStablePtrTable();
161
162     /* initialise thread label table (tso->char*) */
163     initThreadLabelTable();
164
165 #if defined(PROFILING) || defined(DEBUG)
166     initProfiling1();
167 #endif
168
169     /* run the per-module initialisation code */
170     initModules(init_root);
171
172 #if defined(PROFILING) || defined(DEBUG)
173     initProfiling2();
174 #endif
175
176     /* start the virtual timer 'subsystem'. */
177     startVirtTimer(TICK_MILLISECS);
178
179     /* Initialise the stats department */
180     initStats();
181
182 #if !defined(mingw32_TARGET_OS) && !defined(PAR)
183     /* Initialise the user signal handler set */
184     initUserSignals();
185     /* Set up handler to run on SIGINT, etc. */
186     initDefaultHandlers();
187 #endif
188  
189 #ifdef RTS_GTK_FRONTPANEL
190     if (RtsFlags.GcFlags.frontpanel) {
191         initFrontPanel();
192     }
193 #endif
194
195     /* Record initialization times */
196     stat_endInit();
197 }
198
199 /* -----------------------------------------------------------------------------
200    Per-module initialisation
201
202    This process traverses all the compiled modules in the program
203    starting with "Main", and performing per-module initialisation for
204    each one.
205
206    So far, two things happen at initialisation time:
207
208       - we register stable names for each foreign-exported function
209         in that module.  This prevents foreign-exported entities, and
210         things they depend on, from being garbage collected.
211
212       - we supply a unique integer to each statically declared cost
213         centre and cost centre stack in the program.
214
215    The code generator inserts a small function "__stginit_<module>" in each
216    module and calls the registration functions in each of the modules it
217    imports.  So, if we call "__stginit_PrelMain", each reachable module in the
218    program will be registered (because PrelMain.mainIO calls Main.main).
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 F_ *init_stack = NULL;
229
230 static void
231 initModules ( 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     init_sp = 0;
242     bd = allocGroup(INIT_STACK_BLOCKS);
243     init_stack = (F_ *)bd->start;
244     init_stack[init_sp++] = (F_)stg_init_ret;
245 //    init_stack[init_sp++] = (F_)__stginit_Prelude;
246     if (init_root != NULL) {
247         init_stack[init_sp++] = (F_)init_root;
248     }
249     
250     cap.r.rSp = (P_)(init_stack + init_sp);
251     StgRun((StgFunPtr)stg_init, &cap.r);
252
253     freeGroup(bd);
254 }
255
256 /* -----------------------------------------------------------------------------
257  * Shutting down the RTS - two ways of doing this, one which
258  * calls exit(), one that doesn't.
259  *
260  * (shutdownHaskellAndExit() is called by System.exitWith).
261  * -----------------------------------------------------------------------------
262  */
263 void
264 shutdownHaskellAndExit(int n)
265 {
266   OnExitHook();
267   shutdownHaskell();
268 #if defined(PAR)
269   /* really exit (stg_exit() would call shutdownParallelSystem() again) */
270   exit(n);
271 #else
272   stg_exit(n);
273 #endif
274 }
275
276 void
277 shutdownHaskell(void)
278 {
279   if (!rts_has_started_up)
280      return;
281   rts_has_started_up=0;
282   
283   /* start timing the shutdown */
284   stat_startExit();
285
286   /* stop all running tasks */
287   exitScheduler();
288
289 #if !defined(GRAN)
290   /* Finalize any remaining weak pointers */
291   finalizeWeakPointersNow();
292 #endif
293
294 #if defined(GRAN)
295   /* end_gr_simulation prints global stats if requested -- HWL */
296   if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
297     end_gr_simulation();
298 #endif
299
300   /* stop the ticker */
301   stopVirtTimer();
302   
303   /* reset the standard file descriptors to blocking mode */
304   resetNonBlockingFd(0);
305   resetNonBlockingFd(1);
306   resetNonBlockingFd(2);
307
308 #if defined(PAR)
309   /* controlled exit; good thread! */
310   shutdownParallelSystem(0);
311
312   /* global statistics in parallel system */
313   PAR_TICKY_PAR_END();
314 #endif
315
316   /* stop timing the shutdown, we're about to print stats */
317   stat_endExit();
318
319   /* clean up things from the storage manager's point of view.
320    * also outputs the stats (+RTS -s) info.
321    */
322   exitStorage();
323
324 #ifdef RTS_GTK_FRONTPANEL
325     if (RtsFlags.GcFlags.frontpanel) {
326         stopFrontPanel();
327     }
328 #endif
329
330 #if defined(PROFILING) 
331   reportCCSProfiling();
332 #endif
333
334 #if defined(PROFILING) || defined(DEBUG)
335   endProfiling();
336 #endif
337
338 #ifdef PROFILING
339   // Originally, this was in report_ccs_profiling().  Now, retainer
340   // profiling might tack some extra stuff on to the end of this file
341   // during endProfiling().
342   fclose(prof_file);
343 #endif
344
345 #if defined(TICKY_TICKY)
346   if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
347 #endif
348 }
349
350 /* 
351  * called from STG-land to exit the program
352  */
353
354 #ifdef PAR
355 static int exit_started=rtsFalse;
356 #endif
357
358 void  
359 stg_exit(int n)
360
361 #ifdef PAR
362   /* HACK: avoid a loop when exiting due to a stupid error */
363   if (exit_started) 
364     return;
365   exit_started=rtsTrue;
366
367   IF_PAR_DEBUG(verbose, fprintf(stderr,"==-- stg_exit %d on [%x]...", n, mytid));
368   shutdownParallelSystem(n);
369 #endif
370   exit(n);
371 }
372