RtsStartup.c 9.55 KB
Newer Older
1
/* -----------------------------------------------------------------------------
sof's avatar
sof committed
2
 * $Id: RtsStartup.c,v 1.72 2003/02/22 04:51:53 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
// Flag Structure
60 61
struct RTS_FLAGS RtsFlags;

62 63
// Count of how many outstanding hs_init()s there have been.
static int hs_init_count = 0;
64

65 66 67
/* -----------------------------------------------------------------------------
   Starting up the RTS
   -------------------------------------------------------------------------- */
68

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

78 79 80
    /* The very first thing we do is grab the start time...just in case we're
     * collecting timing statistics.
     */
81
    stat_startInit();
82 83

#ifdef PAR
84 85 86 87 88 89 90 91 92
    /*
     * 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--;			
93
    }
94 95

    argv[1] = argv[0];   /* ignore the nPEs argument */
96 97 98 99 100 101 102 103 104 105
    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 */
106 107 108 109 110
    if (argc != NULL && argv != NULL) {
	setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
	prog_argc = *argc;
	prog_argv = *argv;
    }
111

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

119 120 121 122 123
    /* initialise scheduler data structures (needs to be done before
     * initStorage()).
     */
    initScheduler();

124 125 126 127 128 129 130 131 132 133
#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 */

134 135 136 137 138 139
    /* initialize the storage manager */
    initStorage();

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

140 141 142
    /* initialise thread label table (tso->char*) */
    initThreadLabelTable();

143
#if defined(PROFILING) || defined(DEBUG)
144 145 146
    initProfiling1();
#endif

sof's avatar
sof committed
147
    /* start the virtual timer 'subsystem'. */
sof's avatar
sof committed
148
    startTimer(TICK_MILLISECS);
149

150 151 152
    /* Initialise the stats department */
    initStats();

sof's avatar
sof committed
153
#if !defined(mingw32_TARGET_OS) && !defined(PAR)
sof's avatar
sof committed
154
    /* Initialise the user signal handler set */
155
    initUserSignals();
156
    /* Set up handler to run on SIGINT, etc. */
157
    initDefaultHandlers();
sof's avatar
sof committed
158
#endif
sof's avatar
sof committed
159
 
sof's avatar
sof committed
160 161 162 163
#if defined(mingw32_TARGET_OS)
    startupAsyncIO();
#endif

164 165 166 167 168 169
#ifdef RTS_GTK_FRONTPANEL
    if (RtsFlags.GcFlags.frontpanel) {
	initFrontPanel();
    }
#endif

170
    /* Record initialization times */
171
    stat_endInit();
172 173
}

174 175 176 177 178 179 180 181 182 183
// Compatibility interface
void
startupHaskell(int argc, char *argv[], void (*init_root)(void))
{
    hs_init(&argc, &argv);
    hs_add_root(init_root);
}


/* -----------------------------------------------------------------------------
184
   Getting/Setting the program's arguments.
185

186
   These are used by System.Environment.
187 188 189 190 191 192 193 194 195
   -------------------------------------------------------------------------- */

void
getProgArgv(int *argc, char **argv[])
{
    *argc = prog_argc;
    *argv = prog_argv;
}

196 197 198 199 200 201 202 203 204 205 206 207
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;
}

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
/* -----------------------------------------------------------------------------
   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
224 225
   The code generator inserts a small function "__stginit_<module>" in each
   module and calls the registration functions in each of the modules it
226
   imports.
227 228 229 230 231 232 233 234

   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... 
 */
235
#define INIT_STACK_BLOCKS  4
236
static F_ *init_stack = NULL;
237

238 239
void
hs_add_root(void (*init_root)(void))
240
{
241
    bdescr *bd;
242
#ifdef SMP
243
    Capability cap;
244
#else
245
#define cap MainCapability
246
#endif
247
    nat init_sp;
248

249 250 251 252
    if (hs_init_count <= 0) {
	barf("hs_add_root() must be called after hs_init()");
    }

253
    init_sp = 0;
sof's avatar
sof committed
254
    bd = allocGroup(INIT_STACK_BLOCKS);
255
    init_stack = (F_ *)bd->start;
256 257 258 259 260
    init_stack[init_sp++] = (F_)stg_init_ret;
    if (init_root != NULL) {
	init_stack[init_sp++] = (F_)init_root;
    }
    
261 262
    cap.r.rSp = (P_)(init_stack + init_sp);
    StgRun((StgFunPtr)stg_init, &cap.r);
263 264

    freeGroup(bd);
265 266 267 268 269 270

#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
271
}
272

273
/* -----------------------------------------------------------------------------
274 275
   Shutting down the RTS
   -------------------------------------------------------------------------- */
sof's avatar
sof committed
276

277
void
278
hs_exit(void)
279
{
280 281 282 283 284 285 286 287
    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
288

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

314
#if defined(PAR)
315 316 317 318 319
    /* controlled exit; good thread! */
    shutdownParallelSystem(0);
    
    /* global statistics in parallel system */
    PAR_TICKY_PAR_END();
320 321
#endif

322 323 324 325 326 327 328 329
    /* 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();
    
330 331 332 333 334 335
#ifdef RTS_GTK_FRONTPANEL
    if (RtsFlags.GcFlags.frontpanel) {
	stopFrontPanel();
    }
#endif

336
#if defined(PROFILING) 
337
    reportCCSProfiling();
338 339
#endif

340
#if defined(PROFILING) || defined(DEBUG)
341
    endProfiling();
342 343
#endif

344
#ifdef PROFILING
345 346 347 348
    // 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);
349
#endif
350
    
351
#if defined(TICKY_TICKY)
352 353
    if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
#endif
sof's avatar
sof committed
354 355 356 357

#if defined(mingw32_TARGET_OS)
    shutdownAsyncIO();
#endif
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
}

// 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);
378
#endif
379
    }
380
}
381 382

/* 
383
 * called from STG-land to exit the program
384 385
 */

386 387 388 389
#ifdef PAR
static int exit_started=rtsFalse;
#endif

390
void  
391
stg_exit(int n)
392 393 394 395 396 397 398 399 400
{ 
#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);
401
#endif
402
  exit(n);
403
}
404