[project @ 2001-02-09 12:09:33 by simonmar]
[ghc-hetmet.git] / ghc / rts / RtsStartup.c
1 /* -----------------------------------------------------------------------------
2  * $Id: RtsStartup.c,v 1.47 2001/02/09 12:09:33 simonmar Exp $
3  *
4  * (c) The GHC Team, 1998-2000
5  *
6  * Main function for a standalone Haskell program.
7  *
8  * ---------------------------------------------------------------------------*/
9
10 #include "Rts.h"
11 #include "RtsAPI.h"
12 #include "RtsUtils.h"
13 #include "RtsFlags.h"  
14 #include "Storage.h"    /* initStorage, exitStorage */
15 #include "StablePriv.h" /* initStablePtrTable */
16 #include "Schedule.h"   /* initScheduler */
17 #include "Stats.h"      /* initStats */
18 #include "Signals.h"
19 #include "Itimer.h"
20 #include "Weak.h"
21 #include "Ticky.h"
22 #include "StgRun.h"
23 #include "StgStartup.h"
24 #include "Prelude.h"            /* fixupRTStoPreludeRefs */
25
26 #ifdef GHCI
27 #include "HsFFI.h"
28 #include "Linker.h"
29 #endif
30
31 #if defined(RTS_GTK_FRONTPANEL)
32 #include "FrontPanel.h"
33 #endif
34
35 #if defined(PROFILING) || defined(DEBUG)
36 # include "Profiling.h"
37 # include "ProfHeap.h"
38 #endif
39
40 #if defined(GRAN)
41 #include "GranSimRts.h"
42 #include "ParallelRts.h"
43 #endif
44
45 #if defined(PAR)
46 #include "ParInit.h"
47 #include "Parallel.h"
48 #include "LLC.h"
49 #endif
50
51 /*
52  * Flag Structure
53  */
54 struct RTS_FLAGS RtsFlags;
55
56 static int rts_has_started_up = 0;
57 #if defined(PAR)
58 static ullong startTime = 0;
59 #endif
60
61 EXTFUN(__init_Prelude);
62 static void initModules ( void (*)(void) );
63
64 void
65 setProgArgv(int argc, char *argv[])
66 {
67    /* Usually this is done by startupHaskell, so we don't need to call this. 
68       However, sometimes Hugs wants to change the arguments which Haskell
69       getArgs >>= ... will be fed.  So you can do that by calling here
70       _after_ calling startupHaskell.
71    */
72    prog_argc = argc;
73    prog_argv = argv;
74 }
75
76 void
77 getProgArgv(int *argc, char **argv[])
78 {
79    *argc = prog_argc;
80    *argv = prog_argv;
81 }
82
83
84 void
85 startupHaskell(int argc, char *argv[], void (*init_root)(void))
86 {
87     /* To avoid repeated initialisations of the RTS */
88    if (rts_has_started_up)
89      return;
90    else
91      rts_has_started_up=1;
92
93     /* The very first thing we do is grab the start time...just in case we're
94      * collecting timing statistics.
95      */
96     stat_startInit();
97
98 #ifdef PAR
99 /*
100  * The parallel system needs to be initialised and synchronised before
101  * the program is run.  
102  */
103     fprintf(stderr, "startupHaskell: argv[0]=%s\n", argv[0]);
104     if (*argv[0] == '-') {     /* Look to see whether we're the Main Thread */
105         IAmMainThread = rtsTrue;
106         argv++; argc--;                 /* Strip off flag argument */
107         // IF_PAR_DEBUG(verbose,
108                      fprintf(stderr, "[%x] I am Main Thread\n", mytid);
109     }
110     /* 
111      * Grab the number of PEs out of the argument vector, and
112      * eliminate it from further argument processing.
113      */
114     nPEs = atoi(argv[1]);
115     argv[1] = argv[0];
116     argv++; argc--;
117     initEachPEHook();                  /* HWL: hook to be execed on each PE */
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     fprintf(stderr, "Synchronising system (%d PEs)\n", nPEs);
134     SynchroniseSystem();             // calls initParallelSystem etc
135 #endif  /* PAR */
136
137     /* initialise scheduler data structures (needs to be done before
138      * initStorage()).
139      */
140     initScheduler();
141
142 #if defined(GRAN)
143     /* And start GranSim profiling if required: */
144     if (RtsFlags.GranFlags.GranSimStats.Full)
145       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
146 #elif defined(PAR)
147     /* And start GUM profiling if required: */
148     if (RtsFlags.ParFlags.ParStats.Full)
149       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
150 #endif  /* PAR || GRAN */
151
152     /* initialize the storage manager */
153     initStorage();
154
155     /* initialise the object linker, if necessary */
156 #ifdef GHCI
157     initLinker();
158 #endif
159
160     /* initialise the stable pointer table */
161     initStablePtrTable();
162
163 #if defined(PROFILING) || defined(DEBUG)
164     initProfiling1();
165 #endif
166
167     /* run the per-module initialisation code */
168 #if !defined(INTERPRETER)
169     initModules(init_root);
170 #endif
171
172 #if defined(PROFILING) || defined(DEBUG)
173     initProfiling2();
174 #endif
175
176     /* start the ticker */
177     install_vtalrm_handler();
178     initialize_virtual_timer(TICK_MILLISECS);
179
180     /* start our haskell execution tasks */
181 #ifdef SMP
182     startTasks();
183 #endif
184
185     /* Initialise the stats department */
186     initStats();
187
188 #if !defined(mingw32_TARGET_OS) && !defined(PAR)
189     /* Initialise the user signal handler set */
190     initUserSignals();
191     /* Set up handler to run on SIGINT, etc. */
192     init_default_handlers();
193 #endif
194  
195 #if !defined(INTERPRETER)
196     /* Initialise pointers from the RTS to the prelude.  
197        Only for compiled code -- the interpreter
198        will call this itself later, so don't do so now.
199     */
200     fixupRTStoPreludeRefs(NULL);
201 #endif
202
203 #ifdef RTS_GTK_FRONTPANEL
204     if (RtsFlags.GcFlags.frontpanel) {
205         initFrontPanel();
206     }
207 #endif
208
209     /* Record initialization times */
210     stat_endInit();
211 }
212
213 /* -----------------------------------------------------------------------------
214    Per-module initialisation
215
216    This process traverses all the compiled modules in the program
217    starting with "Main", and performing per-module initialisation for
218    each one.
219
220    So far, two things happen at initialisation time:
221
222       - we register stable names for each foreign-exported function
223         in that module.  This prevents foreign-exported entities, and
224         things they depend on, from being garbage collected.
225
226       - we supply a unique integer to each statically declared cost
227         centre and cost centre stack in the program.
228
229    The code generator inserts a small function "__init_<module>" in each
230    module and calls the registration functions in each of the modules
231    it imports.  So, if we call "__init_PrelMain", each reachable module in the
232    program will be registered (because PrelMain.mainIO calls Main.main).
233
234    The init* functions are compiled in the same way as STG code,
235    i.e. without normal C call/return conventions.  Hence we must use
236    StgRun to call this stuff.
237    -------------------------------------------------------------------------- */
238
239 /* The init functions use an explicit stack... 
240  */
241 #define INIT_STACK_SIZE  (BLOCK_SIZE * 4)
242 F_ *init_stack = NULL;
243 nat init_sp = 0;
244
245 #ifndef INTERPRETER
246 static void
247 initModules ( void (*init_root)(void) )
248 {
249 #ifdef SMP
250     Capability cap;
251 #else
252 #define cap MainRegTable
253 #endif
254
255     init_sp = 0;
256     init_stack = (F_ *)allocate(INIT_STACK_SIZE / sizeof(W_));
257     init_stack[init_sp++] = (F_)stg_init_ret;
258     init_stack[init_sp++] = (F_)__init_Prelude;
259     if (init_root != NULL) {
260         init_stack[init_sp++] = (F_)init_root;
261     }
262     
263     cap.rSp = (P_)(init_stack + init_sp);
264     StgRun((StgFunPtr)stg_init, &cap);
265 }
266 #endif /* !INTERPRETER */
267
268 /* -----------------------------------------------------------------------------
269  * Shutting down the RTS - two ways of doing this, one which
270  * calls exit(), one that doesn't.
271  *
272  * (shutdownHaskellAndExit() is called by System.exitWith).
273  * -----------------------------------------------------------------------------
274  */
275 void
276 shutdownHaskellAndExit(int n)
277 {
278   OnExitHook();
279   shutdownHaskell();
280   stg_exit(n);
281 }
282
283 void
284 shutdownHaskell(void)
285 {
286   if (!rts_has_started_up)
287      return;
288
289   /* start timing the shutdown */
290   stat_startExit();
291
292 #if !defined(GRAN)
293   /* Finalize any remaining weak pointers */
294   finalizeWeakPointersNow();
295 #endif
296
297 #if defined(GRAN)
298   /* end_gr_simulation prints global stats if requested -- HWL */
299   if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
300     end_gr_simulation();
301 #endif
302
303   /* stop all running tasks */
304   exitScheduler();
305
306   /* stop the ticker */
307   initialize_virtual_timer(0);
308   
309   /* reset the standard file descriptors to blocking mode */
310   resetNonBlockingFd(0);
311   resetNonBlockingFd(1);
312   resetNonBlockingFd(2);
313
314 #if defined(PAR)
315   shutdownParallelSystem(0);
316 #endif
317
318   /* stop timing the shutdown, we're about to print stats */
319   stat_endExit();
320
321   /* clean up things from the storage manager's point of view.
322    * also outputs the stats (+RTS -s) info.
323    */
324   exitStorage();
325
326 #ifdef RTS_GTK_FRONTPANEL
327     if (RtsFlags.GcFlags.frontpanel) {
328         stopFrontPanel();
329     }
330 #endif
331
332 #if defined(PROFILING) || defined(DEBUG)
333   endProfiling();
334 #endif
335
336 #if defined(PROFILING) 
337   report_ccs_profiling();
338 #endif
339
340 #if defined(TICKY_TICKY)
341   if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
342 #endif
343
344   rts_has_started_up=0;
345
346 }
347
348 /* 
349  * called from STG-land to exit the program
350  */
351
352 void  
353 stg_exit(I_ n)
354 {
355 #if 0 /* def PAR */
356   par_exit(n);
357 #else
358   exit(n);
359 #endif
360 }
361