[project @ 2001-09-04 18:29:20 by ken]
[ghc-hetmet.git] / ghc / rts / RtsStartup.c
1 /* -----------------------------------------------------------------------------
2  * $Id: RtsStartup.c,v 1.53 2001/09/04 18:29:21 ken 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 #endif
37
38 #if defined(GRAN)
39 # include "GranSimRts.h"
40 #endif
41
42 #if defined(GRAN) || defined(PAR)
43 # include "ParallelRts.h"
44 #endif
45
46 #if defined(PAR)
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 ullong startTime = 0;
59 #endif
60
61 EXTFUN(__stginit_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     startupParallelSystem(argv);
104      
105     if (*argv[0] == '-') { /* Strip off mainPE flag argument */
106       argv++; 
107       argc--;                   
108     }
109
110     argv[1] = argv[0];   /* ignore the nPEs argument */
111     argv++; argc--;
112 #endif
113
114     /* Set the RTS flags to default values. */
115     initRtsFlagsDefaults();
116
117     /* Call the user hook to reset defaults, if present */
118     defaultsHook();
119
120     /* Parse the flags, separating the RTS flags from the programs args */
121     setupRtsFlags(&argc, argv, &rts_argc, rts_argv);
122     prog_argc = argc;
123     prog_argv = argv;
124
125 #if defined(PAR)
126     /* NB: this really must be done after processing the RTS flags */
127     IF_PAR_DEBUG(verbose,
128                  fprintf(stderr, "==== Synchronising system (%d PEs)\n", nPEs));
129     synchroniseSystem();             // calls initParallelSystem etc
130 #endif  /* PAR */
131
132     /* initialise scheduler data structures (needs to be done before
133      * initStorage()).
134      */
135     initScheduler();
136
137 #if defined(GRAN)
138     /* And start GranSim profiling if required: */
139     if (RtsFlags.GranFlags.GranSimStats.Full)
140       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
141 #elif defined(PAR)
142     /* And start GUM profiling if required: */
143     if (RtsFlags.ParFlags.ParStats.Full)
144       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
145 #endif  /* PAR || GRAN */
146
147     /* initialize the storage manager */
148     initStorage();
149
150     /* initialise the stable pointer table */
151     initStablePtrTable();
152
153 #if defined(PROFILING) || defined(DEBUG)
154     initProfiling1();
155 #endif
156
157     /* run the per-module initialisation code */
158     initModules(init_root);
159
160 #if defined(PROFILING) || defined(DEBUG)
161     initProfiling2();
162 #endif
163
164     /* start the ticker */
165     install_vtalrm_handler();
166     initialize_virtual_timer(TICK_MILLISECS);
167
168     /* start our haskell execution tasks */
169 #ifdef SMP
170     startTasks();
171 #endif
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     init_default_handlers();
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_SIZE  (BLOCK_SIZE * 4)
222 F_ *init_stack = NULL;
223 nat init_sp = 0;
224
225 static void
226 initModules ( void (*init_root)(void) )
227 {
228 #ifdef SMP
229     Capability cap;
230 #else
231 #define cap MainRegTable
232 #endif
233
234     init_sp = 0;
235     init_stack = (F_ *)allocate(INIT_STACK_SIZE / sizeof(W_));
236     init_stack[init_sp++] = (F_)stg_init_ret;
237     init_stack[init_sp++] = (F_)__stginit_Prelude;
238     if (init_root != NULL) {
239         init_stack[init_sp++] = (F_)init_root;
240     }
241     
242     cap.rSp = (P_)(init_stack + init_sp);
243     StgRun((StgFunPtr)stg_init, &cap);
244 }
245
246 /* -----------------------------------------------------------------------------
247  * Shutting down the RTS - two ways of doing this, one which
248  * calls exit(), one that doesn't.
249  *
250  * (shutdownHaskellAndExit() is called by System.exitWith).
251  * -----------------------------------------------------------------------------
252  */
253 void
254 shutdownHaskellAndExit(int n)
255 {
256   OnExitHook();
257   shutdownHaskell();
258 #if defined(PAR)
259   /* really exit (stg_exit() would call shutdownParallelSystem() again) */
260   exit(n);
261 #else
262   stg_exit(n);
263 #endif
264 }
265
266 void
267 shutdownHaskell(void)
268 {
269   if (!rts_has_started_up)
270      return;
271
272   /* start timing the shutdown */
273   stat_startExit();
274
275 #if !defined(GRAN)
276   /* Finalize any remaining weak pointers */
277   finalizeWeakPointersNow();
278 #endif
279
280 #if defined(GRAN)
281   /* end_gr_simulation prints global stats if requested -- HWL */
282   if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
283     end_gr_simulation();
284 #endif
285
286   /* stop all running tasks */
287   exitScheduler();
288
289   /* stop the ticker */
290   initialize_virtual_timer(0);
291   
292   /* reset the standard file descriptors to blocking mode */
293   resetNonBlockingFd(0);
294   resetNonBlockingFd(1);
295   resetNonBlockingFd(2);
296
297 #if defined(PAR)
298   /* controlled exit; good thread! */
299   shutdownParallelSystem(0);
300
301   /* global statistics in parallel system */
302   PAR_TICKY_PAR_END();
303 #endif
304
305   /* stop timing the shutdown, we're about to print stats */
306   stat_endExit();
307
308   /* clean up things from the storage manager's point of view.
309    * also outputs the stats (+RTS -s) info.
310    */
311   exitStorage();
312
313 #ifdef RTS_GTK_FRONTPANEL
314     if (RtsFlags.GcFlags.frontpanel) {
315         stopFrontPanel();
316     }
317 #endif
318
319 #if defined(PROFILING) || defined(DEBUG)
320   endProfiling();
321 #endif
322
323 #if defined(PROFILING) 
324   report_ccs_profiling();
325 #endif
326
327 #if defined(TICKY_TICKY)
328   if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
329 #endif
330
331   rts_has_started_up=0;
332 }
333
334 /* 
335  * called from STG-land to exit the program
336  */
337
338 #ifdef PAR
339 static int exit_started=rtsFalse;
340 #endif
341
342 void  
343 stg_exit(I_ n)
344
345 #ifdef PAR
346   /* HACK: avoid a loop when exiting due to a stupid error */
347   if (exit_started) 
348     return;
349   exit_started=rtsTrue;
350
351   IF_PAR_DEBUG(verbose, fprintf(stderr,"==-- stg_exit %d on [%x]...", n, mytid));
352   shutdownParallelSystem(n);
353 #endif
354   exit(n);
355 }
356