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