1 /* -----------------------------------------------------------------------------
2 * $Id: RtsStartup.c,v 1.76 2003/09/24 10:32:11 simonmar Exp $
4 * (c) The GHC Team, 1998-2002
6 * Main function for a standalone Haskell program.
8 * ---------------------------------------------------------------------------*/
10 #include "PosixSource.h"
15 #include "Storage.h" /* initStorage, exitStorage */
16 #include "StablePriv.h" /* initStablePtrTable */
17 #include "Schedule.h" /* initScheduler */
18 #include "Stats.h" /* initStats */
20 #include "Timer.h" /* startTimer, stopTimer */
24 #include "StgStartup.h"
25 #include "Prelude.h" /* fixupRTStoPreludeRefs */
28 #include "ThreadLabels.h"
30 #if defined(RTS_GTK_FRONTPANEL)
31 #include "FrontPanel.h"
34 #if defined(PROFILING) || defined(DEBUG)
35 # include "Profiling.h"
36 # include "ProfHeap.h"
37 # include "RetainerProfile.h"
41 # include "GranSimRts.h"
44 #if defined(GRAN) || defined(PAR)
45 # include "ParallelRts.h"
49 # include "Parallel.h"
53 #if defined(mingw32_TARGET_OS)
54 #include "win32/AsyncIO.h"
71 struct RTS_FLAGS RtsFlags;
73 // Count of how many outstanding hs_init()s there have been.
74 static int hs_init_count = 0;
77 // Here we save the terminal settings on the standard file
78 // descriptors, if we need to change them (eg. to support NoBuffering
80 struct termios *saved_termios[3] = {NULL,NULL,NULL};
83 /* -----------------------------------------------------------------------------
85 -------------------------------------------------------------------------- */
88 hs_init(int *argc, char **argv[])
91 if (hs_init_count > 1) {
92 // second and subsequent inits are ignored
96 /* The very first thing we do is grab the start time...just in case we're
97 * collecting timing statistics.
103 * The parallel system needs to be initialised and synchronised before
104 * the program is run.
106 startupParallelSystem(argv);
108 if (*argv[0] == '-') { /* Strip off mainPE flag argument */
113 argv[1] = argv[0]; /* ignore the nPEs argument */
117 /* Set the RTS flags to default values. */
118 initRtsFlagsDefaults();
120 /* Call the user hook to reset defaults, if present */
123 /* Parse the flags, separating the RTS flags from the programs args */
124 if (argc != NULL && argv != NULL) {
125 setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
131 /* NB: this really must be done after processing the RTS flags */
132 IF_PAR_DEBUG(verbose,
133 fprintf(stderr, "==== Synchronising system (%d PEs)\n", nPEs));
134 synchroniseSystem(); // calls initParallelSystem etc
137 /* initialise scheduler data structures (needs to be done before
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);
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 */
152 /* initialize the storage manager */
155 /* initialise the stable pointer table */
156 initStablePtrTable();
158 /* initialise thread label table (tso->char*) */
159 initThreadLabelTable();
161 #if defined(PROFILING) || defined(DEBUG)
165 /* start the virtual timer 'subsystem'. */
166 startTimer(TICK_MILLISECS);
168 /* Initialise the stats department */
171 #if defined(RTS_USER_SIGNALS)
172 /* Initialise the user signal handler set */
174 /* Set up handler to run on SIGINT, etc. */
175 initDefaultHandlers();
178 #if defined(mingw32_TARGET_OS)
182 #ifdef RTS_GTK_FRONTPANEL
183 if (RtsFlags.GcFlags.frontpanel) {
189 setlocale(LC_ALL,"");
192 /* Record initialization times */
196 // Compatibility interface
198 startupHaskell(int argc, char *argv[], void (*init_root)(void))
200 hs_init(&argc, &argv);
201 hs_add_root(init_root);
205 /* -----------------------------------------------------------------------------
206 Getting/Setting the program's arguments.
208 These are used by System.Environment.
209 -------------------------------------------------------------------------- */
212 getProgArgv(int *argc, char **argv[])
214 if (argc) { *argc = prog_argc; }
215 if (argv) { *argv = prog_argv; }
219 setProgArgv(int argc, char *argv[])
221 /* Usually this is done by startupHaskell, so we don't need to call this.
222 However, sometimes Hugs wants to change the arguments which Haskell
223 getArgs >>= ... will be fed. So you can do that by calling here
224 _after_ calling startupHaskell.
230 /* -----------------------------------------------------------------------------
231 Per-module initialisation
233 This process traverses all the compiled modules in the program
234 starting with "Main", and performing per-module initialisation for
237 So far, two things happen at initialisation time:
239 - we register stable names for each foreign-exported function
240 in that module. This prevents foreign-exported entities, and
241 things they depend on, from being garbage collected.
243 - we supply a unique integer to each statically declared cost
244 centre and cost centre stack in the program.
246 The code generator inserts a small function "__stginit_<module>" in each
247 module and calls the registration functions in each of the modules it
250 The init* functions are compiled in the same way as STG code,
251 i.e. without normal C call/return conventions. Hence we must use
252 StgRun to call this stuff.
253 -------------------------------------------------------------------------- */
255 /* The init functions use an explicit stack...
257 #define INIT_STACK_BLOCKS 4
258 static F_ *init_stack = NULL;
261 hs_add_root(void (*init_root)(void))
267 #define cap MainCapability
271 if (hs_init_count <= 0) {
272 barf("hs_add_root() must be called after hs_init()");
276 bd = allocGroup(INIT_STACK_BLOCKS);
277 init_stack = (F_ *)bd->start;
278 init_stack[init_sp++] = (F_)stg_init_ret;
279 if (init_root != NULL) {
280 init_stack[init_sp++] = (F_)init_root;
283 cap.r.rSp = (P_)(init_stack + init_sp);
284 StgRun((StgFunPtr)stg_init, &cap.r);
288 #if defined(PROFILING) || defined(DEBUG)
289 // This must be done after module initialisation.
290 // ToDo: make this work in the presence of multiple hs_add_root()s.
295 /* -----------------------------------------------------------------------------
296 Shutting down the RTS
297 -------------------------------------------------------------------------- */
302 if (hs_init_count <= 0) {
303 barf("too many hs_exit()s");
306 if (hs_init_count > 0) {
307 // ignore until it's the last one
311 /* start timing the shutdown */
314 /* stop all running tasks */
318 /* Finalize any remaining weak pointers */
319 finalizeWeakPointersNow();
323 /* end_gr_simulation prints global stats if requested -- HWL */
324 if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
328 /* stop the ticker */
331 /* reset the standard file descriptors to blocking mode */
332 resetNonBlockingFd(0);
333 resetNonBlockingFd(1);
334 resetNonBlockingFd(2);
337 // Reset the terminal settings on the standard file descriptors,
338 // if we changed them. See System.Posix.Internals.tcSetAttr for
339 // more details, including the reason we termporarily disable
343 sigset_t sigset, old_sigset;
344 sigemptyset(&sigset);
345 sigaddset(&sigset, SIGTTOU);
346 sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
347 for (fd = 0; fd <= 2; fd++) {
348 if (saved_termios[fd] != NULL) {
349 tcsetattr(fd,TCSANOW,saved_termios[fd]);
352 sigprocmask(SIG_SETMASK, &old_sigset, NULL);
357 /* controlled exit; good thread! */
358 shutdownParallelSystem(0);
360 /* global statistics in parallel system */
364 /* stop timing the shutdown, we're about to print stats */
367 /* clean up things from the storage manager's point of view.
368 * also outputs the stats (+RTS -s) info.
372 #ifdef RTS_GTK_FRONTPANEL
373 if (RtsFlags.GcFlags.frontpanel) {
378 #if defined(PROFILING)
379 reportCCSProfiling();
382 #if defined(PROFILING) || defined(DEBUG)
387 // Originally, this was in report_ccs_profiling(). Now, retainer
388 // profiling might tack some extra stuff on to the end of this file
389 // during endProfiling().
393 #if defined(TICKY_TICKY)
394 if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
397 #if defined(mingw32_TARGET_OS)
402 // Compatibility interfaces
404 shutdownHaskell(void)
410 shutdownHaskellAndExit(int n)
412 if (hs_init_count == 1) {
416 /* really exit (stg_exit() would call shutdownParallelSystem() again) */
425 * called from STG-land to exit the program
429 static int exit_started=rtsFalse;
436 /* HACK: avoid a loop when exiting due to a stupid error */
439 exit_started=rtsTrue;
441 IF_PAR_DEBUG(verbose, fprintf(stderr,"==-- stg_exit %d on [%x]...", n, mytid));
442 shutdownParallelSystem(n);