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