[project @ 2005-04-15 05:29:48 by wolfgang]
[ghc-hetmet.git] / ghc / rts / RtsStartup.c
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 1998-2002
4  *
5  * Main function for a standalone Haskell program.
6  *
7  * ---------------------------------------------------------------------------*/
8
9 #include "PosixSource.h"
10 #include "Rts.h"
11 #include "RtsAPI.h"
12 #include "RtsUtils.h"
13 #include "RtsFlags.h"  
14 #include "OSThreads.h"
15 #include "Storage.h"    /* initStorage, exitStorage */
16 #include "Schedule.h"   /* initScheduler */
17 #include "Stats.h"      /* initStats */
18 #include "STM.h"        /* initSTM */
19 #include "Signals.h"
20 #include "Timer.h"      /* startTimer, stopTimer */
21 #include "Weak.h"
22 #include "Ticky.h"
23 #include "StgRun.h"
24 #include "Prelude.h"            /* fixupRTStoPreludeRefs */
25 #include "HsFFI.h"
26 #include "Linker.h"
27 #include "ThreadLabels.h"
28 #include "BlockAlloc.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 #if defined(mingw32_HOST_OS)
54 #include "win32/AsyncIO.h"
55 #endif
56
57 #include <stdlib.h>
58
59 #ifdef HAVE_TERMIOS_H
60 #include <termios.h>
61 #endif
62 #ifdef HAVE_SIGNAL_H
63 #include <signal.h>
64 #endif
65
66 // Count of how many outstanding hs_init()s there have been.
67 static int hs_init_count = 0;
68
69 // Here we save the terminal settings on the standard file
70 // descriptors, if we need to change them (eg. to support NoBuffering
71 // input).
72 static void *saved_termios[3] = {NULL,NULL,NULL};
73
74 void*
75 __hscore_get_saved_termios(int fd)
76 {
77   return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
78     saved_termios[fd] : NULL;
79 }
80
81 void
82 __hscore_set_saved_termios(int fd, void* ts)
83 {
84   if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
85     saved_termios[fd] = ts;
86   }
87 }
88
89 /* -----------------------------------------------------------------------------
90    Initialise floating point unit on x86 (currently disabled. why?)
91    -------------------------------------------------------------------------- */
92
93 #define X86_INIT_FPU 0
94
95 #if X86_INIT_FPU
96 static void
97 x86_init_fpu ( void )
98 {
99   __volatile unsigned short int fpu_cw;
100
101   // Grab the control word
102   __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));
103
104 #if 0
105   printf("fpu_cw: %x\n", fpu_cw);
106 #endif
107
108   // Set bits 8-9 to 10 (64-bit precision).
109   fpu_cw = (fpu_cw & 0xfcff) | 0x0200;
110
111   // Store the new control word back
112   __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
113 }
114 #endif
115
116 /* -----------------------------------------------------------------------------
117    Starting up the RTS
118    -------------------------------------------------------------------------- */
119
120 void
121 hs_init(int *argc, char **argv[])
122 {
123     hs_init_count++;
124     if (hs_init_count > 1) {
125         // second and subsequent inits are ignored
126         return;
127     }
128
129     /* The very first thing we do is grab the start time...just in case we're
130      * collecting timing statistics.
131      */
132     stat_startInit();
133
134 #ifdef PAR
135     /*
136      * The parallel system needs to be initialised and synchronised before
137      * the program is run.  
138      */ 
139     startupParallelSystem(argv);
140      
141     if (*argv[0] == '-') { /* Strip off mainPE flag argument */
142       argv++; 
143       argc--;                   
144     }
145
146     argv[1] = argv[0];   /* ignore the nPEs argument */
147     argv++; argc--;
148 #endif
149
150     /* Set the RTS flags to default values. */
151     initRtsFlagsDefaults();
152
153     /* Call the user hook to reset defaults, if present */
154     defaultsHook();
155
156     /* Parse the flags, separating the RTS flags from the programs args */
157     if (argc != NULL && argv != NULL) {
158         setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
159         setProgArgv(*argc,*argv);
160     }
161
162 #if defined(PAR)
163     /* NB: this really must be done after processing the RTS flags */
164     IF_PAR_DEBUG(verbose,
165                  debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
166     synchroniseSystem();             // calls initParallelSystem etc
167 #endif  /* PAR */
168
169     /* Perform initialisation of adjustor thunk layer. */
170     initAdjustor();
171
172     /* initialise scheduler data structures (needs to be done before
173      * initStorage()).
174      */
175     initScheduler();
176
177 #if defined(GRAN)
178     /* And start GranSim profiling if required: */
179     if (RtsFlags.GranFlags.GranSimStats.Full)
180       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
181 #elif defined(PAR)
182     /* And start GUM profiling if required: */
183     if (RtsFlags.ParFlags.ParStats.Full)
184       init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
185 #endif  /* PAR || GRAN */
186
187     /* initialize the storage manager */
188     initStorage();
189
190     /* initialise the stable pointer table */
191     initStablePtrTable();
192
193 #if defined(DEBUG)
194     /* initialise thread label table (tso->char*) */
195     initThreadLabelTable();
196 #endif
197
198 #if defined(PROFILING) || defined(DEBUG)
199     initProfiling1();
200 #endif
201
202     /* start the virtual timer 'subsystem'. */
203     startTimer(TICK_MILLISECS);
204
205     /* Initialise the stats department */
206     initStats();
207
208 #if defined(RTS_USER_SIGNALS)
209     /* Initialise the user signal handler set */
210     initUserSignals();
211     /* Set up handler to run on SIGINT, etc. */
212     initDefaultHandlers();
213 #endif
214  
215 #if defined(mingw32_HOST_OS)
216     startupAsyncIO();
217 #endif
218
219     initSTM();
220
221 #ifdef RTS_GTK_FRONTPANEL
222     if (RtsFlags.GcFlags.frontpanel) {
223         initFrontPanel();
224     }
225 #endif
226
227 #if X86_INIT_FPU
228     x86_init_fpu();
229 #endif
230
231     /* Record initialization times */
232     stat_endInit();
233 }
234
235 // Compatibility interface
236 void
237 startupHaskell(int argc, char *argv[], void (*init_root)(void))
238 {
239     hs_init(&argc, &argv);
240     if(init_root)
241         hs_add_root(init_root);
242 }
243
244
245 /* -----------------------------------------------------------------------------
246    Per-module initialisation
247
248    This process traverses all the compiled modules in the program
249    starting with "Main", and performing per-module initialisation for
250    each one.
251
252    So far, two things happen at initialisation time:
253
254       - we register stable names for each foreign-exported function
255         in that module.  This prevents foreign-exported entities, and
256         things they depend on, from being garbage collected.
257
258       - we supply a unique integer to each statically declared cost
259         centre and cost centre stack in the program.
260
261    The code generator inserts a small function "__stginit_<module>" in each
262    module and calls the registration functions in each of the modules it
263    imports.
264
265    The init* functions are compiled in the same way as STG code,
266    i.e. without normal C call/return conventions.  Hence we must use
267    StgRun to call this stuff.
268    -------------------------------------------------------------------------- */
269
270 /* The init functions use an explicit stack... 
271  */
272 #define INIT_STACK_BLOCKS  4
273 static F_ *init_stack = NULL;
274
275 void
276 hs_add_root(void (*init_root)(void))
277 {
278     bdescr *bd;
279 #ifdef SMP
280     Capability cap;
281 #else
282 #define cap MainCapability
283 #endif
284     nat init_sp;
285
286     if (hs_init_count <= 0) {
287         barf("hs_add_root() must be called after hs_init()");
288     }
289
290     /* The initialisation stack grows downward, with sp pointing 
291        to the last occupied word */
292     init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
293     bd = allocGroup(INIT_STACK_BLOCKS);
294     init_stack = (F_ *)bd->start;
295     init_stack[--init_sp] = (F_)stg_init_finish;
296     if (init_root != NULL) {
297         init_stack[--init_sp] = (F_)init_root;
298     }
299     
300     cap.r.rSp = (P_)(init_stack + init_sp);
301     StgRun((StgFunPtr)stg_init, &cap.r);
302
303     freeGroup(bd);
304
305 #if defined(PROFILING) || defined(DEBUG)
306     // This must be done after module initialisation.
307     // ToDo: make this work in the presence of multiple hs_add_root()s.
308     initProfiling2();
309 #endif
310 }
311
312 /* -----------------------------------------------------------------------------
313    Shutting down the RTS
314    -------------------------------------------------------------------------- */
315
316 void
317 hs_exit(void)
318 {
319     if (hs_init_count <= 0) {
320         barf("too many hs_exit()s");
321     }
322     hs_init_count--;
323     if (hs_init_count > 0) {
324         // ignore until it's the last one
325         return;
326     }
327
328     /* start timing the shutdown */
329     stat_startExit();
330     
331     /* stop all running tasks */
332     exitScheduler();
333     
334 #if defined(GRAN)
335     /* end_gr_simulation prints global stats if requested -- HWL */
336     if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
337         end_gr_simulation();
338 #endif
339     
340     /* stop the ticker */
341     stopTimer();
342     
343     /* reset the standard file descriptors to blocking mode */
344     resetNonBlockingFd(0);
345     resetNonBlockingFd(1);
346     resetNonBlockingFd(2);
347
348 #if HAVE_TERMIOS_H
349     // Reset the terminal settings on the standard file descriptors,
350     // if we changed them.  See System.Posix.Internals.tcSetAttr for
351     // more details, including the reason we termporarily disable
352     // SIGTTOU here.
353     { 
354         int fd;
355         sigset_t sigset, old_sigset;
356         sigemptyset(&sigset);
357         sigaddset(&sigset, SIGTTOU);
358         sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
359         for (fd = 0; fd <= 2; fd++) {
360             struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
361             if (ts != NULL) {
362                 tcsetattr(fd,TCSANOW,ts);
363             }
364         }
365         sigprocmask(SIG_SETMASK, &old_sigset, NULL);
366     }
367 #endif
368
369 #if defined(PAR)
370     /* controlled exit; good thread! */
371     shutdownParallelSystem(0);
372     
373     /* global statistics in parallel system */
374     PAR_TICKY_PAR_END();
375 #endif
376
377     /* stop timing the shutdown, we're about to print stats */
378     stat_endExit();
379     
380     /* clean up things from the storage manager's point of view.
381      * also outputs the stats (+RTS -s) info.
382      */
383     exitStorage();
384     
385 #ifdef RTS_GTK_FRONTPANEL
386     if (RtsFlags.GcFlags.frontpanel) {
387         stopFrontPanel();
388     }
389 #endif
390
391 #if defined(PROFILING) 
392     reportCCSProfiling();
393 #endif
394
395 #if defined(PROFILING) || defined(DEBUG)
396     endProfiling();
397 #endif
398
399 #ifdef PROFILING
400     // Originally, this was in report_ccs_profiling().  Now, retainer
401     // profiling might tack some extra stuff on to the end of this file
402     // during endProfiling().
403     fclose(prof_file);
404 #endif
405     
406 #if defined(TICKY_TICKY)
407     if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
408 #endif
409
410 #if defined(mingw32_HOST_OS)
411     shutdownAsyncIO();
412 #endif
413 }
414
415 // Compatibility interfaces
416 void
417 shutdownHaskell(void)
418 {
419     hs_exit();
420 }
421
422 void
423 shutdownHaskellAndExit(int n)
424 {
425     if (hs_init_count == 1) {
426         OnExitHook();
427         hs_exit();
428 #if defined(PAR)
429         /* really exit (stg_exit() would call shutdownParallelSystem() again) */
430         exit(n);
431 #else
432         stg_exit(n);
433 #endif
434     }
435 }
436
437 /* 
438  * called from STG-land to exit the program
439  */
440
441 #ifdef PAR
442 static int exit_started=rtsFalse;
443 #endif
444
445 void  
446 stg_exit(int n)
447
448 #ifdef PAR
449   /* HACK: avoid a loop when exiting due to a stupid error */
450   if (exit_started) 
451     return;
452   exit_started=rtsTrue;
453
454   IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
455   shutdownParallelSystem(n);
456 #endif
457   exit(n);
458 }