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