[project @ 2001-12-06 07:07:12 by sof]
[ghc-hetmet.git] / ghc / rts / RtsStartup.c
1 /* -----------------------------------------------------------------------------
2  * $Id: RtsStartup.c,v 1.59 2001/12/06 07:07:12 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     /* start our haskell execution tasks */
174 #ifdef SMP
175     startTasks();
176 #endif
177
178     /* Initialise the stats department */
179     initStats();
180
181 #if !defined(mingw32_TARGET_OS) && !defined(PAR)
182     /* Initialise the user signal handler set */
183     initUserSignals();
184     /* Set up handler to run on SIGINT, etc. */
185     initDefaultHandlers();
186 #endif
187  
188 #ifdef RTS_GTK_FRONTPANEL
189     if (RtsFlags.GcFlags.frontpanel) {
190         initFrontPanel();
191     }
192 #endif
193
194     /* Record initialization times */
195     stat_endInit();
196 }
197
198 /* -----------------------------------------------------------------------------
199    Per-module initialisation
200
201    This process traverses all the compiled modules in the program
202    starting with "Main", and performing per-module initialisation for
203    each one.
204
205    So far, two things happen at initialisation time:
206
207       - we register stable names for each foreign-exported function
208         in that module.  This prevents foreign-exported entities, and
209         things they depend on, from being garbage collected.
210
211       - we supply a unique integer to each statically declared cost
212         centre and cost centre stack in the program.
213
214    The code generator inserts a small function "__stginit_<module>" in each
215    module and calls the registration functions in each of the modules it
216    imports.  So, if we call "__stginit_PrelMain", each reachable module in the
217    program will be registered (because PrelMain.mainIO calls Main.main).
218
219    The init* functions are compiled in the same way as STG code,
220    i.e. without normal C call/return conventions.  Hence we must use
221    StgRun to call this stuff.
222    -------------------------------------------------------------------------- */
223
224 /* The init functions use an explicit stack... 
225  */
226 #define INIT_STACK_BLOCKS  4
227 F_ *init_stack = NULL;
228 nat init_sp = 0;
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
240     init_sp = 0;
241     bd = allocGroup(INIT_STACK_BLOCKS);
242     init_stack = (F_ *)bd->start;
243     init_stack[init_sp++] = (F_)stg_init_ret;
244     init_stack[init_sp++] = (F_)__stginit_Prelude;
245     if (init_root != NULL) {
246         init_stack[init_sp++] = (F_)init_root;
247     }
248     
249     cap.r.rSp = (P_)(init_stack + init_sp);
250     StgRun((StgFunPtr)stg_init, &cap.r);
251
252     freeGroup(bd);
253 }
254
255 /* -----------------------------------------------------------------------------
256  * Shutting down the RTS - two ways of doing this, one which
257  * calls exit(), one that doesn't.
258  *
259  * (shutdownHaskellAndExit() is called by System.exitWith).
260  * -----------------------------------------------------------------------------
261  */
262 void
263 shutdownHaskellAndExit(int n)
264 {
265   OnExitHook();
266   shutdownHaskell();
267 #if defined(PAR)
268   /* really exit (stg_exit() would call shutdownParallelSystem() again) */
269   exit(n);
270 #else
271   stg_exit(n);
272 #endif
273 }
274
275 void
276 shutdownHaskell(void)
277 {
278   if (!rts_has_started_up)
279      return;
280
281   /* start timing the shutdown */
282   stat_startExit();
283
284 #if !defined(GRAN)
285   /* Finalize any remaining weak pointers */
286   finalizeWeakPointersNow();
287 #endif
288
289 #if defined(GRAN)
290   /* end_gr_simulation prints global stats if requested -- HWL */
291   if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
292     end_gr_simulation();
293 #endif
294
295   /* stop all running tasks */
296   exitScheduler();
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   report_ccs_profiling();
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   rts_has_started_up=0;
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(I_ 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