[project @ 2001-02-09 13:09:16 by simonmar]
[ghc-hetmet.git] / ghc / rts / RtsStartup.c
1 /* -----------------------------------------------------------------------------
2  * $Id: RtsStartup.c,v 1.48 2001/02/09 13:09:16 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     initModules(init_root);
169
170 #if defined(PROFILING) || defined(DEBUG)
171     initProfiling2();
172 #endif
173
174     /* start the ticker */
175     install_vtalrm_handler();
176     initialize_virtual_timer(TICK_MILLISECS);
177
178     /* start our haskell execution tasks */
179 #ifdef SMP
180     startTasks();
181 #endif
182
183     /* Initialise the stats department */
184     initStats();
185
186 #if !defined(mingw32_TARGET_OS) && !defined(PAR)
187     /* Initialise the user signal handler set */
188     initUserSignals();
189     /* Set up handler to run on SIGINT, etc. */
190     init_default_handlers();
191 #endif
192  
193 #ifdef RTS_GTK_FRONTPANEL
194     if (RtsFlags.GcFlags.frontpanel) {
195         initFrontPanel();
196     }
197 #endif
198
199     /* Record initialization times */
200     stat_endInit();
201 }
202
203 /* -----------------------------------------------------------------------------
204    Per-module initialisation
205
206    This process traverses all the compiled modules in the program
207    starting with "Main", and performing per-module initialisation for
208    each one.
209
210    So far, two things happen at initialisation time:
211
212       - we register stable names for each foreign-exported function
213         in that module.  This prevents foreign-exported entities, and
214         things they depend on, from being garbage collected.
215
216       - we supply a unique integer to each statically declared cost
217         centre and cost centre stack in the program.
218
219    The code generator inserts a small function "__init_<module>" in each
220    module and calls the registration functions in each of the modules
221    it imports.  So, if we call "__init_PrelMain", each reachable module in the
222    program will be registered (because PrelMain.mainIO calls Main.main).
223
224    The init* functions are compiled in the same way as STG code,
225    i.e. without normal C call/return conventions.  Hence we must use
226    StgRun to call this stuff.
227    -------------------------------------------------------------------------- */
228
229 /* The init functions use an explicit stack... 
230  */
231 #define INIT_STACK_SIZE  (BLOCK_SIZE * 4)
232 F_ *init_stack = NULL;
233 nat init_sp = 0;
234
235 static void
236 initModules ( void (*init_root)(void) )
237 {
238 #ifdef SMP
239     Capability cap;
240 #else
241 #define cap MainRegTable
242 #endif
243
244     init_sp = 0;
245     init_stack = (F_ *)allocate(INIT_STACK_SIZE / sizeof(W_));
246     init_stack[init_sp++] = (F_)stg_init_ret;
247     init_stack[init_sp++] = (F_)__init_Prelude;
248     if (init_root != NULL) {
249         init_stack[init_sp++] = (F_)init_root;
250     }
251     
252     cap.rSp = (P_)(init_stack + init_sp);
253     StgRun((StgFunPtr)stg_init, &cap);
254 }
255
256 /* -----------------------------------------------------------------------------
257  * Shutting down the RTS - two ways of doing this, one which
258  * calls exit(), one that doesn't.
259  *
260  * (shutdownHaskellAndExit() is called by System.exitWith).
261  * -----------------------------------------------------------------------------
262  */
263 void
264 shutdownHaskellAndExit(int n)
265 {
266   OnExitHook();
267   shutdownHaskell();
268   stg_exit(n);
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 #if !defined(GRAN)
281   /* Finalize any remaining weak pointers */
282   finalizeWeakPointersNow();
283 #endif
284
285 #if defined(GRAN)
286   /* end_gr_simulation prints global stats if requested -- HWL */
287   if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
288     end_gr_simulation();
289 #endif
290
291   /* stop all running tasks */
292   exitScheduler();
293
294   /* stop the ticker */
295   initialize_virtual_timer(0);
296   
297   /* reset the standard file descriptors to blocking mode */
298   resetNonBlockingFd(0);
299   resetNonBlockingFd(1);
300   resetNonBlockingFd(2);
301
302 #if defined(PAR)
303   shutdownParallelSystem(0);
304 #endif
305
306   /* stop timing the shutdown, we're about to print stats */
307   stat_endExit();
308
309   /* clean up things from the storage manager's point of view.
310    * also outputs the stats (+RTS -s) info.
311    */
312   exitStorage();
313
314 #ifdef RTS_GTK_FRONTPANEL
315     if (RtsFlags.GcFlags.frontpanel) {
316         stopFrontPanel();
317     }
318 #endif
319
320 #if defined(PROFILING) || defined(DEBUG)
321   endProfiling();
322 #endif
323
324 #if defined(PROFILING) 
325   report_ccs_profiling();
326 #endif
327
328 #if defined(TICKY_TICKY)
329   if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
330 #endif
331
332   rts_has_started_up=0;
333
334 }
335
336 /* 
337  * called from STG-land to exit the program
338  */
339
340 void  
341 stg_exit(I_ n)
342 {
343 #if 0 /* def PAR */
344   par_exit(n);
345 #else
346   exit(n);
347 #endif
348 }
349