[project @ 2001-11-22 14:25:11 by simonmar]
[ghc-hetmet.git] / ghc / rts / RtsStartup.c
1 /* -----------------------------------------------------------------------------
2  * $Id: RtsStartup.c,v 1.56 2001/11/22 14:25:12 simonmar 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      return;
91    else
92      rts_has_started_up=1;
93
94     /* The very first thing we do is grab the start time...just in case we're
95      * collecting timing statistics.
96      */
97     stat_startInit();
98
99 #ifdef PAR
100     /*
101      * The parallel system needs to be initialised and synchronised before
102      * the program is run.  
103      */ 
104     startupParallelSystem(argv);
105      
106     if (*argv[0] == '-') { /* Strip off mainPE flag argument */
107       argv++; 
108       argc--;                   
109     }
110
111     argv[1] = argv[0];   /* ignore the nPEs argument */
112     argv++; argc--;
113 #endif
114
115     /* Set the RTS flags to default values. */
116     initRtsFlagsDefaults();
117
118     /* Call the user hook to reset defaults, if present */
119     defaultsHook();
120
121     /* Parse the flags, separating the RTS flags from the programs args */
122     setupRtsFlags(&argc, argv, &rts_argc, rts_argv);
123     prog_argc = argc;
124     prog_argv = argv;
125
126 #if defined(PAR)
127     /* NB: this really must be done after processing the RTS flags */
128     IF_PAR_DEBUG(verbose,
129                  fprintf(stderr, "==== Synchronising system (%d PEs)\n", nPEs));
130     synchroniseSystem();             // calls initParallelSystem etc
131 #endif  /* PAR */
132
133     /* initialise scheduler data structures (needs to be done before
134      * initStorage()).
135      */
136     initScheduler();
137
138 #if defined(GRAN)
139     /* And start GranSim profiling if required: */
140     if (RtsFlags.GranFlags.GranSimStats.Full)
141       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
142 #elif defined(PAR)
143     /* And start GUM profiling if required: */
144     if (RtsFlags.ParFlags.ParStats.Full)
145       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
146 #endif  /* PAR || GRAN */
147
148     /* initialize the storage manager */
149     initStorage();
150
151     /* initialise the stable pointer table */
152     initStablePtrTable();
153
154 #if defined(PROFILING) || defined(DEBUG)
155     initProfiling1();
156 #endif
157
158     /* run the per-module initialisation code */
159     initModules(init_root);
160
161 #if defined(PROFILING) || defined(DEBUG)
162     initProfiling2();
163 #endif
164
165     /* start the ticker */
166     install_vtalrm_handler();
167     initialize_virtual_timer(TICK_MILLISECS);
168
169     /* start our haskell execution tasks */
170 #ifdef SMP
171     startTasks();
172 #endif
173
174     /* Initialise the stats department */
175     initStats();
176
177 #if !defined(mingw32_TARGET_OS) && !defined(PAR)
178     /* Initialise the user signal handler set */
179     initUserSignals();
180     /* Set up handler to run on SIGINT, etc. */
181     initDefaultHandlers();
182 #endif
183  
184 #ifdef RTS_GTK_FRONTPANEL
185     if (RtsFlags.GcFlags.frontpanel) {
186         initFrontPanel();
187     }
188 #endif
189
190     /* Record initialization times */
191     stat_endInit();
192 }
193
194 /* -----------------------------------------------------------------------------
195    Per-module initialisation
196
197    This process traverses all the compiled modules in the program
198    starting with "Main", and performing per-module initialisation for
199    each one.
200
201    So far, two things happen at initialisation time:
202
203       - we register stable names for each foreign-exported function
204         in that module.  This prevents foreign-exported entities, and
205         things they depend on, from being garbage collected.
206
207       - we supply a unique integer to each statically declared cost
208         centre and cost centre stack in the program.
209
210    The code generator inserts a small function "__stginit_<module>" in each
211    module and calls the registration functions in each of the modules it
212    imports.  So, if we call "__stginit_PrelMain", each reachable module in the
213    program will be registered (because PrelMain.mainIO calls Main.main).
214
215    The init* functions are compiled in the same way as STG code,
216    i.e. without normal C call/return conventions.  Hence we must use
217    StgRun to call this stuff.
218    -------------------------------------------------------------------------- */
219
220 /* The init functions use an explicit stack... 
221  */
222 #define INIT_STACK_BLOCKS  4
223 F_ *init_stack = NULL;
224 nat init_sp = 0;
225
226 static void
227 initModules ( void (*init_root)(void) )
228 {
229     bdescr *bd;
230 #ifdef SMP
231     Capability cap;
232 #else
233 #define cap MainCapability
234 #endif
235
236     init_sp = 0;
237     bd = allocGroup(4);
238     init_stack = (F_ *)bd->start;
239     init_stack[init_sp++] = (F_)stg_init_ret;
240     init_stack[init_sp++] = (F_)__stginit_Prelude;
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 - two ways of doing this, one which
253  * calls exit(), one that doesn't.
254  *
255  * (shutdownHaskellAndExit() is called by System.exitWith).
256  * -----------------------------------------------------------------------------
257  */
258 void
259 shutdownHaskellAndExit(int n)
260 {
261   OnExitHook();
262   shutdownHaskell();
263 #if defined(PAR)
264   /* really exit (stg_exit() would call shutdownParallelSystem() again) */
265   exit(n);
266 #else
267   stg_exit(n);
268 #endif
269 }
270
271 void
272 shutdownHaskell(void)
273 {
274   if (!rts_has_started_up)
275      return;
276
277   /* start timing the shutdown */
278   stat_startExit();
279
280 #ifdef PROFILING
281   // @LDV profiling
282   // 
283   // Note: 
284   //   We do not need to perform a major garbage collection because all the
285   //   closures created since the last census will not affect the profiling
286   //   statistics anyhow.
287   // 
288   // Note: 
289   //   We ignore any object created afterwards. 
290   //   finalizeWeakPointersNow() may corrupt the heap (because it executes 
291   //   rts_evalIO(), which adds an initial evaluation stack again).
292   //   Thus, we call LdvCensusKillAll() here, and prohibit LDV profiling
293   //   afterwards. 
294   //   Acutally, it is pointless to call LdvCensusKillAll() any later because
295   //   no object created later will be taken into account for profiling.
296   if (RtsFlags.ProfFlags.doHeapProfile == HEAP_BY_LDV) 
297     LdvCensusKillAll();
298 #endif
299
300 #if !defined(GRAN)
301   /* Finalize any remaining weak pointers */
302   finalizeWeakPointersNow();
303 #endif
304
305 #if defined(GRAN)
306   /* end_gr_simulation prints global stats if requested -- HWL */
307   if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
308     end_gr_simulation();
309 #endif
310
311   /* stop all running tasks */
312   exitScheduler();
313
314   /* stop the ticker */
315   initialize_virtual_timer(0);
316   
317   /* reset the standard file descriptors to blocking mode */
318   resetNonBlockingFd(0);
319   resetNonBlockingFd(1);
320   resetNonBlockingFd(2);
321
322 #if defined(PAR)
323   /* controlled exit; good thread! */
324   shutdownParallelSystem(0);
325
326   /* global statistics in parallel system */
327   PAR_TICKY_PAR_END();
328 #endif
329
330   /* stop timing the shutdown, we're about to print stats */
331   stat_endExit();
332
333   /* clean up things from the storage manager's point of view.
334    * also outputs the stats (+RTS -s) info.
335    */
336   exitStorage();
337
338 #ifdef RTS_GTK_FRONTPANEL
339     if (RtsFlags.GcFlags.frontpanel) {
340         stopFrontPanel();
341     }
342 #endif
343
344 #if defined(PROFILING) 
345   report_ccs_profiling();
346 #endif
347
348 #if defined(PROFILING) || defined(DEBUG)
349   endProfiling();
350 #endif
351
352 #ifdef PROFILING
353   // Originally, this was in report_ccs_profiling().  Now, retainer
354   // profiling might tack some extra stuff on to the end of this file
355   // during endProfiling().
356   fclose(prof_file);
357 #endif
358
359 #if defined(TICKY_TICKY)
360   if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
361 #endif
362
363   rts_has_started_up=0;
364 }
365
366 /* 
367  * called from STG-land to exit the program
368  */
369
370 #ifdef PAR
371 static int exit_started=rtsFalse;
372 #endif
373
374 void  
375 stg_exit(I_ n)
376
377 #ifdef PAR
378   /* HACK: avoid a loop when exiting due to a stupid error */
379   if (exit_started) 
380     return;
381   exit_started=rtsTrue;
382
383   IF_PAR_DEBUG(verbose, fprintf(stderr,"==-- stg_exit %d on [%x]...", n, mytid));
384   shutdownParallelSystem(n);
385 #endif
386   exit(n);
387 }
388