RtsStartup.c 11.3 KB
Newer Older
1
/* -----------------------------------------------------------------------------
2
 *
3
 * (c) The GHC Team, 1998-2002
4 5 6 7 8
 *
 * Main function for a standalone Haskell program.
 *
 * ---------------------------------------------------------------------------*/

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

32 33 34 35
#if defined(RTS_GTK_FRONTPANEL)
#include "FrontPanel.h"
#endif

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

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

#if defined(GRAN) || defined(PAR)
# include "ParallelRts.h"
48 49 50
#endif

#if defined(PAR)
51 52
# include "Parallel.h"
# include "LLC.h"
53 54
#endif

55
#if defined(mingw32_HOST_OS)
sof's avatar
sof committed
56 57 58
#include "win32/AsyncIO.h"
#endif

59 60
#include <stdlib.h>

61 62 63 64 65 66 67
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif

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

71 72 73
// Here we save the terminal settings on the standard file
// descriptors, if we need to change them (eg. to support NoBuffering
// input).
74 75 76 77 78
static void *saved_termios[3] = {NULL,NULL,NULL};

void*
__hscore_get_saved_termios(int fd)
{
79
  return (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) ?
80 81 82 83 84 85
    saved_termios[fd] : NULL;
}

void
__hscore_set_saved_termios(int fd, void* ts)
{
86
  if (0 <= fd && fd < (int)(sizeof(saved_termios) / sizeof(*saved_termios))) {
87 88 89
    saved_termios[fd] = ts;
  }
}
90

91 92
/* -----------------------------------------------------------------------------
   Initialise floating point unit on x86 (currently disabled. why?)
93
   (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
   -------------------------------------------------------------------------- */

#define X86_INIT_FPU 0

#if X86_INIT_FPU
static void
x86_init_fpu ( void )
{
  __volatile unsigned short int fpu_cw;

  // Grab the control word
  __asm __volatile ("fnstcw %0" : "=m" (fpu_cw));

#if 0
  printf("fpu_cw: %x\n", fpu_cw);
#endif

  // Set bits 8-9 to 10 (64-bit precision).
  fpu_cw = (fpu_cw & 0xfcff) | 0x0200;

  // Store the new control word back
  __asm __volatile ("fldcw %0" : : "m" (fpu_cw));
}
117 118
#endif

119 120 121
/* -----------------------------------------------------------------------------
   Starting up the RTS
   -------------------------------------------------------------------------- */
122

sof's avatar
sof committed
123
void
124
hs_init(int *argc, char **argv[])
125
{
126 127 128 129
    hs_init_count++;
    if (hs_init_count > 1) {
	// second and subsequent inits are ignored
	return;
sof's avatar
sof committed
130
    }
sof's avatar
sof committed
131

132 133 134
    /* The very first thing we do is grab the start time...just in case we're
     * collecting timing statistics.
     */
135
    stat_startInit();
136 137

#ifdef PAR
138 139 140 141 142 143 144 145 146
    /*
     * 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--;			
147
    }
148 149

    argv[1] = argv[0];   /* ignore the nPEs argument */
150 151 152 153 154 155 156 157 158 159
    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 */
160 161
    if (argc != NULL && argv != NULL) {
	setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
162
	setProgArgv(*argc,*argv);
163
    }
164

Simon Marlow's avatar
Simon Marlow committed
165 166 167
    /* initTracing must be after setupRtsFlags() */
    initTracing();

168 169
#if defined(PAR)
    /* NB: this really must be done after processing the RTS flags */
170
    IF_PAR_DEBUG(verbose,
171
                 debugBelch("==== Synchronising system (%d PEs)\n", nPEs));
172
    synchroniseSystem();             // calls initParallelSystem etc
173 174
#endif	/* PAR */

175 176 177
    /* Perform initialisation of adjustor thunk layer. */
    initAdjustor();

178 179 180 181 182
    /* initialise scheduler data structures (needs to be done before
     * initStorage()).
     */
    initScheduler();

183 184 185 186 187 188 189 190 191 192
#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 */

193 194 195 196 197 198
    /* initialize the storage manager */
    initStorage();

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

sof's avatar
sof committed
199
#if defined(DEBUG)
200 201
    /* initialise thread label table (tso->char*) */
    initThreadLabelTable();
sof's avatar
sof committed
202
#endif
203

204
#if defined(PROFILING) || defined(DEBUG)
205 206 207
    initProfiling1();
#endif

sof's avatar
sof committed
208
    /* start the virtual timer 'subsystem'. */
sof's avatar
sof committed
209
    startTimer(TICK_MILLISECS);
210

211 212 213
    /* Initialise the stats department */
    initStats();

sof's avatar
sof committed
214
#if defined(RTS_USER_SIGNALS)
sof's avatar
sof committed
215
    /* Initialise the user signal handler set */
216
    initUserSignals();
217
    /* Set up handler to run on SIGINT, etc. */
218
    initDefaultHandlers();
sof's avatar
sof committed
219
#endif
sof's avatar
sof committed
220
 
221
#if defined(mingw32_HOST_OS)
sof's avatar
sof committed
222 223 224
    startupAsyncIO();
#endif

225 226 227 228 229 230
#ifdef RTS_GTK_FRONTPANEL
    if (RtsFlags.GcFlags.frontpanel) {
	initFrontPanel();
    }
#endif

231 232
#if X86_INIT_FPU
    x86_init_fpu();
233 234
#endif

235 236 237 238
#if defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
    ioManagerStart();
#endif

239
    /* Record initialization times */
240
    stat_endInit();
241 242
}

243 244 245 246 247
// Compatibility interface
void
startupHaskell(int argc, char *argv[], void (*init_root)(void))
{
    hs_init(&argc, &argv);
248 249
    if(init_root)
        hs_add_root(init_root);
250 251 252
}


253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
/* -----------------------------------------------------------------------------
   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
269 270
   The code generator inserts a small function "__stginit_<module>" in each
   module and calls the registration functions in each of the modules it
271
   imports.
272 273 274 275 276 277 278 279

   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... 
 */
280
#define INIT_STACK_BLOCKS  4
281
static F_ *init_stack = NULL;
282

283 284
void
hs_add_root(void (*init_root)(void))
285
{
286
    bdescr *bd;
287
    nat init_sp;
288
    Capability *cap = &MainCapability;
289

290 291 292 293
    if (hs_init_count <= 0) {
	barf("hs_add_root() must be called after hs_init()");
    }

294 295 296
    /* The initialisation stack grows downward, with sp pointing 
       to the last occupied word */
    init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
297
    bd = allocGroup_lock(INIT_STACK_BLOCKS);
298
    init_stack = (F_ *)bd->start;
299
    init_stack[--init_sp] = (F_)stg_init_finish;
300
    if (init_root != NULL) {
301
	init_stack[--init_sp] = (F_)init_root;
302 303
    }
    
304 305
    cap->r.rSp = (P_)(init_stack + init_sp);
    StgRun((StgFunPtr)stg_init, &cap->r);
306

307
    freeGroup_lock(bd);
308 309 310 311 312 313

#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
314
}
315

316
/* -----------------------------------------------------------------------------
317 318
   Shutting down the RTS
   -------------------------------------------------------------------------- */
sof's avatar
sof committed
319

320
void
321
hs_exit(void)
322
{
323
    if (hs_init_count <= 0) {
324 325
	errorBelch("warning: too many hs_exit()s");
	return;
326 327 328 329 330 331
    }
    hs_init_count--;
    if (hs_init_count > 0) {
	// ignore until it's the last one
	return;
    }
sof's avatar
sof committed
332

333 334 335
    /* start timing the shutdown */
    stat_startExit();
    
336 337 338 339
#if defined(THREADED_RTS) && !defined(mingw32_HOST_OS)
    ioManagerDie();
#endif

340 341 342
    /* stop all running tasks */
    exitScheduler();
    
343
#if defined(GRAN)
344 345 346
    /* end_gr_simulation prints global stats if requested -- HWL */
    if (!RtsFlags.GranFlags.GranSimStats.Suppressed)
	end_gr_simulation();
347
#endif
348 349
    
    /* stop the ticker */
sof's avatar
sof committed
350
    stopTimer();
351 352 353 354 355
    
    /* reset the standard file descriptors to blocking mode */
    resetNonBlockingFd(0);
    resetNonBlockingFd(1);
    resetNonBlockingFd(2);
356

357 358 359 360 361 362 363 364 365 366 367 368
#if HAVE_TERMIOS_H
    // Reset the terminal settings on the standard file descriptors,
    // if we changed them.  See System.Posix.Internals.tcSetAttr for
    // more details, including the reason we termporarily disable
    // SIGTTOU here.
    { 
	int fd;
	sigset_t sigset, old_sigset;
	sigemptyset(&sigset);
	sigaddset(&sigset, SIGTTOU);
	sigprocmask(SIG_BLOCK, &sigset, &old_sigset);
	for (fd = 0; fd <= 2; fd++) {
369 370 371
	    struct termios* ts = (struct termios*)__hscore_get_saved_termios(fd);
	    if (ts != NULL) {
		tcsetattr(fd,TCSANOW,ts);
372 373 374 375 376 377
	    }
	}
	sigprocmask(SIG_SETMASK, &old_sigset, NULL);
    }
#endif

378
#if defined(PAR)
379 380 381 382 383
    /* controlled exit; good thread! */
    shutdownParallelSystem(0);
    
    /* global statistics in parallel system */
    PAR_TICKY_PAR_END();
384 385
#endif

386 387 388
    /* stop timing the shutdown, we're about to print stats */
    stat_endExit();
    
Simon Marlow's avatar
Simon Marlow committed
389 390
    // clean up things from the storage manager's point of view.
    // also outputs the stats (+RTS -s) info.
391 392
    exitStorage();
    
393 394 395 396 397 398
    /* initialise the stable pointer table */
    exitStablePtrTable();

    /* free hash table storage */
    exitHashTable();

399 400 401 402 403 404
#ifdef RTS_GTK_FRONTPANEL
    if (RtsFlags.GcFlags.frontpanel) {
	stopFrontPanel();
    }
#endif

405
#if defined(PROFILING) 
406
    reportCCSProfiling();
407 408
#endif

409
#if defined(PROFILING) || defined(DEBUG)
410
    endProfiling();
411 412
#endif

413
#ifdef PROFILING
414 415 416 417
    // 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);
418
#endif
Simon Marlow's avatar
Simon Marlow committed
419

420
#if defined(TICKY_TICKY)
421 422
    if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
#endif
sof's avatar
sof committed
423

424
#if defined(mingw32_HOST_OS)
sof's avatar
sof committed
425 426
    shutdownAsyncIO();
#endif
Simon Marlow's avatar
Simon Marlow committed
427 428 429

    // Finally, free all our storage.
    freeStorage();
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
}

// 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);
450
#endif
451
    }
452
}
453 454

/* 
455
 * called from STG-land to exit the program
456 457
 */

458 459 460 461
#ifdef PAR
static int exit_started=rtsFalse;
#endif

462
void  
463
stg_exit(int n)
464 465 466 467 468 469 470
{ 
#ifdef PAR
  /* HACK: avoid a loop when exiting due to a stupid error */
  if (exit_started) 
    return;
  exit_started=rtsTrue;

471
  IF_PAR_DEBUG(verbose, debugBelch("==-- stg_exit %d on [%x]...", n, mytid));
472
  shutdownParallelSystem(n);
473
#endif
474
  exit(n);
475
}