RtsStartup.c 9.66 KB
Newer Older
1
/* -----------------------------------------------------------------------------
sof's avatar
sof committed
2
 * $Id: RtsStartup.c,v 1.75 2003/08/22 22:24:15 sof Exp $
3
 *
4
 * (c) The GHC Team, 1998-2002
5
6
7
8
9
 *
 * Main function for a standalone Haskell program.
 *
 * ---------------------------------------------------------------------------*/

10
#include "PosixSource.h"
11
12
13
14
15
#include "Rts.h"
#include "RtsAPI.h"
#include "RtsUtils.h"
#include "RtsFlags.h"  
#include "Storage.h"    /* initStorage, exitStorage */
16
#include "StablePriv.h" /* initStablePtrTable */
17
18
#include "Schedule.h"   /* initScheduler */
#include "Stats.h"      /* initStats */
19
#include "Signals.h"
sof's avatar
sof committed
20
#include "Timer.h"      /* startTimer, stopTimer */
21
#include "Weak.h"
22
#include "Ticky.h"
23
24
#include "StgRun.h"
#include "StgStartup.h"
25
#include "Prelude.h"		/* fixupRTStoPreludeRefs */
26
27
#include "HsFFI.h"
#include "Linker.h"
28
#include "ThreadLabels.h"
29

30
31
32
33
#if defined(RTS_GTK_FRONTPANEL)
#include "FrontPanel.h"
#endif

34
#if defined(PROFILING) || defined(DEBUG)
35
# include "Profiling.h"
36
# include "ProfHeap.h"
37
# include "RetainerProfile.h"
38
39
#endif

40
#if defined(GRAN)
41
42
43
44
45
# include "GranSimRts.h"
#endif

#if defined(GRAN) || defined(PAR)
# include "ParallelRts.h"
46
47
48
#endif

#if defined(PAR)
49
50
# include "Parallel.h"
# include "LLC.h"
51
52
#endif

sof's avatar
sof committed
53
54
55
56
#if defined(mingw32_TARGET_OS)
#include "win32/AsyncIO.h"
#endif

57
58
#include <stdlib.h>

59
60
61
62
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif

63
// Flag Structure
64
65
struct RTS_FLAGS RtsFlags;

66
67
// Count of how many outstanding hs_init()s there have been.
static int hs_init_count = 0;
68

69
70
71
/* -----------------------------------------------------------------------------
   Starting up the RTS
   -------------------------------------------------------------------------- */
72

sof's avatar
sof committed
73
void
74
hs_init(int *argc, char **argv[])
75
{
76
77
78
79
    hs_init_count++;
    if (hs_init_count > 1) {
	// second and subsequent inits are ignored
	return;
sof's avatar
sof committed
80
    }
sof's avatar
sof committed
81

82
83
84
    /* The very first thing we do is grab the start time...just in case we're
     * collecting timing statistics.
     */
85
    stat_startInit();
86
87

#ifdef PAR
88
89
90
91
92
93
94
95
96
    /*
     * The parallel system needs to be initialised and synchronised before
     * the program is run.  
     */ 
    startupParallelSystem(argv);
     
    if (*argv[0] == '-') { /* Strip off mainPE flag argument */
      argv++; 
      argc--;			
97
    }
98
99

    argv[1] = argv[0];   /* ignore the nPEs argument */
100
101
102
103
104
105
106
107
108
109
    argv++; argc--;
#endif

    /* Set the RTS flags to default values. */
    initRtsFlagsDefaults();

    /* Call the user hook to reset defaults, if present */
    defaultsHook();

    /* Parse the flags, separating the RTS flags from the programs args */
110
111
112
113
114
    if (argc != NULL && argv != NULL) {
	setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
	prog_argc = *argc;
	prog_argv = *argv;
    }
115

116
117
#if defined(PAR)
    /* NB: this really must be done after processing the RTS flags */
118
119
120
    IF_PAR_DEBUG(verbose,
                 fprintf(stderr, "==== Synchronising system (%d PEs)\n", nPEs));
    synchroniseSystem();             // calls initParallelSystem etc
121
122
#endif	/* PAR */

123
124
125
126
127
    /* initialise scheduler data structures (needs to be done before
     * initStorage()).
     */
    initScheduler();

128
129
130
131
132
133
134
135
136
137
#if defined(GRAN)
    /* And start GranSim profiling if required: */
    if (RtsFlags.GranFlags.GranSimStats.Full)
      init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
#elif defined(PAR)
    /* And start GUM profiling if required: */
    if (RtsFlags.ParFlags.ParStats.Full)
      init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv);
#endif	/* PAR || GRAN */

138
139
140
141
142
143
    /* initialize the storage manager */
    initStorage();

    /* initialise the stable pointer table */
    initStablePtrTable();

144
145
146
    /* initialise thread label table (tso->char*) */
    initThreadLabelTable();

147
#if defined(PROFILING) || defined(DEBUG)
148
149
150
    initProfiling1();
#endif

sof's avatar
sof committed
151
    /* start the virtual timer 'subsystem'. */
sof's avatar
sof committed
152
    startTimer(TICK_MILLISECS);
153

154
155
156
    /* Initialise the stats department */
    initStats();

sof's avatar
sof committed
157
#if defined(RTS_USER_SIGNALS)
sof's avatar
sof committed
158
    /* Initialise the user signal handler set */
159
    initUserSignals();
160
    /* Set up handler to run on SIGINT, etc. */
161
    initDefaultHandlers();
sof's avatar
sof committed
162
#endif
sof's avatar
sof committed
163
 
sof's avatar
sof committed
164
165
166
167
#if defined(mingw32_TARGET_OS)
    startupAsyncIO();
#endif

168
169
170
171
172
173
#ifdef RTS_GTK_FRONTPANEL
    if (RtsFlags.GcFlags.frontpanel) {
	initFrontPanel();
    }
#endif

174
175
176
177
#ifdef HAVE_LOCALE_H
    setlocale(LC_ALL,"");
#endif

178
    /* Record initialization times */
179
    stat_endInit();
180
181
}

182
183
184
185
186
187
188
189
190
191
// Compatibility interface
void
startupHaskell(int argc, char *argv[], void (*init_root)(void))
{
    hs_init(&argc, &argv);
    hs_add_root(init_root);
}


/* -----------------------------------------------------------------------------
192
   Getting/Setting the program's arguments.
193

194
   These are used by System.Environment.
195
196
197
198
199
   -------------------------------------------------------------------------- */

void
getProgArgv(int *argc, char **argv[])
{
sof's avatar
sof committed
200
201
    if (argc) { *argc = prog_argc; }
    if (argv) { *argv = prog_argv; }
202
203
}

204
205
206
207
208
209
210
211
212
213
214
215
void
setProgArgv(int argc, char *argv[])
{
   /* Usually this is done by startupHaskell, so we don't need to call this. 
      However, sometimes Hugs wants to change the arguments which Haskell
      getArgs >>= ... will be fed.  So you can do that by calling here
      _after_ calling startupHaskell.
   */
   prog_argc = argc;
   prog_argv = argv;
}

216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
/* -----------------------------------------------------------------------------
   Per-module initialisation

   This process traverses all the compiled modules in the program
   starting with "Main", and performing per-module initialisation for
   each one.

   So far, two things happen at initialisation time:

      - we register stable names for each foreign-exported function
        in that module.  This prevents foreign-exported entities, and
	things they depend on, from being garbage collected.

      - we supply a unique integer to each statically declared cost
        centre and cost centre stack in the program.

ken's avatar
ken committed
232
233
   The code generator inserts a small function "__stginit_<module>" in each
   module and calls the registration functions in each of the modules it
234
   imports.
235
236
237
238
239
240
241
242

   The init* functions are compiled in the same way as STG code,
   i.e. without normal C call/return conventions.  Hence we must use
   StgRun to call this stuff.
   -------------------------------------------------------------------------- */

/* The init functions use an explicit stack... 
 */
243
#define INIT_STACK_BLOCKS  4
244
static F_ *init_stack = NULL;
245

246
247
void
hs_add_root(void (*init_root)(void))
248
{
249
    bdescr *bd;
250
#ifdef SMP
251
    Capability cap;
252
#else
253
#define cap MainCapability
254
#endif
255
    nat init_sp;
256

257
258
259
260
    if (hs_init_count <= 0) {
	barf("hs_add_root() must be called after hs_init()");
    }

261
    init_sp = 0;
sof's avatar
sof committed
262
    bd = allocGroup(INIT_STACK_BLOCKS);
263
    init_stack = (F_ *)bd->start;
264
265
266
267
268
    init_stack[init_sp++] = (F_)stg_init_ret;
    if (init_root != NULL) {
	init_stack[init_sp++] = (F_)init_root;
    }
    
269
270
    cap.r.rSp = (P_)(init_stack + init_sp);
    StgRun((StgFunPtr)stg_init, &cap.r);
271
272

    freeGroup(bd);
273
274
275
276
277
278

#if defined(PROFILING) || defined(DEBUG)
    // This must be done after module initialisation.
    // ToDo: make this work in the presence of multiple hs_add_root()s.
    initProfiling2();
#endif
279
}
280

281
/* -----------------------------------------------------------------------------
282
283
   Shutting down the RTS
   -------------------------------------------------------------------------- */
sof's avatar
sof committed
284

285
void
286
hs_exit(void)
287
{
288
289
290
291
292
293
294
295
    if (hs_init_count <= 0) {
	barf("too many hs_exit()s");
    }
    hs_init_count--;
    if (hs_init_count > 0) {
	// ignore until it's the last one
	return;
    }
sof's avatar
sof committed
296

297
298
299
300
301
302
    /* start timing the shutdown */
    stat_startExit();
    
    /* stop all running tasks */
    exitScheduler();
    
303
#if !defined(GRAN)
304
305
    /* Finalize any remaining weak pointers */
    finalizeWeakPointersNow();
306
#endif
307
    
308
#if defined(GRAN)
309
310
311
    /* end_gr_simulation prints global stats if requested -- HWL */
    if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
	end_gr_simulation();
312
#endif
313
314
    
    /* stop the ticker */
sof's avatar
sof committed
315
    stopTimer();
316
317
318
319
320
    
    /* reset the standard file descriptors to blocking mode */
    resetNonBlockingFd(0);
    resetNonBlockingFd(1);
    resetNonBlockingFd(2);
321

322
#if defined(PAR)
323
324
325
326
327
    /* controlled exit; good thread! */
    shutdownParallelSystem(0);
    
    /* global statistics in parallel system */
    PAR_TICKY_PAR_END();
328
329
#endif

330
331
332
333
334
335
336
337
    /* stop timing the shutdown, we're about to print stats */
    stat_endExit();
    
    /* clean up things from the storage manager's point of view.
     * also outputs the stats (+RTS -s) info.
     */
    exitStorage();
    
338
339
340
341
342
343
#ifdef RTS_GTK_FRONTPANEL
    if (RtsFlags.GcFlags.frontpanel) {
	stopFrontPanel();
    }
#endif

344
#if defined(PROFILING) 
345
    reportCCSProfiling();
346
347
#endif

348
#if defined(PROFILING) || defined(DEBUG)
349
    endProfiling();
350
351
#endif

352
#ifdef PROFILING
353
354
355
356
    // Originally, this was in report_ccs_profiling().  Now, retainer
    // profiling might tack some extra stuff on to the end of this file
    // during endProfiling().
    fclose(prof_file);
357
#endif
358
    
359
#if defined(TICKY_TICKY)
360
361
    if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
#endif
sof's avatar
sof committed
362
363
364
365

#if defined(mingw32_TARGET_OS)
    shutdownAsyncIO();
#endif
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
}

// Compatibility interfaces
void
shutdownHaskell(void)
{
    hs_exit();
}

void
shutdownHaskellAndExit(int n)
{
    if (hs_init_count == 1) {
	OnExitHook();
	hs_exit();
#if defined(PAR)
	/* really exit (stg_exit() would call shutdownParallelSystem() again) */
	exit(n);
#else
	stg_exit(n);
386
#endif
387
    }
388
}
389
390

/* 
391
 * called from STG-land to exit the program
392
393
 */

394
395
396
397
#ifdef PAR
static int exit_started=rtsFalse;
#endif

398
void  
399
stg_exit(int n)
400
401
402
403
404
405
406
407
408
{ 
#ifdef PAR
  /* HACK: avoid a loop when exiting due to a stupid error */
  if (exit_started) 
    return;
  exit_started=rtsTrue;

  IF_PAR_DEBUG(verbose, fprintf(stderr,"==-- stg_exit %d on [%x]...", n, mytid));
  shutdownParallelSystem(n);
409
#endif
410
  exit(n);
411
}
412