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