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

mrchebas@gmail.com's avatar
mrchebas@gmail.com committed
9
// PAPI uses caddr_t, which is not POSIX
Simon Marlow's avatar
Simon Marlow committed
10 11 12
#ifndef USE_PAPI
#include "PosixSource.h"
#endif
mrchebas@gmail.com's avatar
mrchebas@gmail.com committed
13

14 15
#include "Rts.h"
#include "RtsAPI.h"
Simon Marlow's avatar
Simon Marlow committed
16 17 18
#include "HsFFI.h"

#include "sm/Storage.h"
19
#include "RtsUtils.h"
20
#include "Prelude.h"
21 22
#include "Schedule.h"   /* initScheduler */
#include "Stats.h"      /* initStats */
23
#include "STM.h"        /* initSTM */
24
#include "RtsSignals.h"
25
#include "Weak.h"
26
#include "Ticky.h"
27
#include "StgRun.h"
28
#include "Prelude.h"		/* fixupRTStoPreludeRefs */
29
#include "ThreadLabels.h"
Simon Marlow's avatar
Simon Marlow committed
30
#include "sm/BlockAlloc.h"
Simon Marlow's avatar
Simon Marlow committed
31
#include "Trace.h"
32
#include "Stable.h"
Simon Marlow's avatar
Simon Marlow committed
33
#include "Hash.h"
Simon Marlow's avatar
Simon Marlow committed
34 35 36
#include "Profiling.h"
#include "Timer.h"
#include "Globals.h"
37
void exitLinker( void );	// there is no Linker.h file to include
38

39 40 41 42
#if defined(RTS_GTK_FRONTPANEL)
#include "FrontPanel.h"
#endif

43
#if defined(PROFILING)
44
# include "ProfHeap.h"
45
# include "RetainerProfile.h"
46 47
#endif

48
#if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
sof's avatar
sof committed
49 50 51
#include "win32/AsyncIO.h"
#endif

Simon Marlow's avatar
Simon Marlow committed
52 53 54
#if !defined(mingw32_HOST_OS)
#include "posix/TTY.h"
#include "posix/FileLock.h"
55
#endif
Simon Marlow's avatar
Simon Marlow committed
56

Simon Marlow's avatar
Simon Marlow committed
57 58 59
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
60 61 62
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
63

mrchebas@gmail.com's avatar
mrchebas@gmail.com committed
64 65 66 67
#if USE_PAPI
#include "Papi.h"
#endif

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

71
/* -----------------------------------------------------------------------------
Simon Marlow's avatar
Simon Marlow committed
72 73
   Initialise floating point unit on x86 (currently disabled; See Note
   [x86 Floating point precision] in compiler/nativeGen/X86/Instr.hs)
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
   -------------------------------------------------------------------------- */

#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));
}
97 98
#endif

99 100 101
/* -----------------------------------------------------------------------------
   Starting up the RTS
   -------------------------------------------------------------------------- */
102

sof's avatar
sof committed
103
void
104
hs_init(int *argc, char **argv[])
105
{
106 107 108 109
    hs_init_count++;
    if (hs_init_count > 1) {
	// second and subsequent inits are ignored
	return;
sof's avatar
sof committed
110
    }
sof's avatar
sof committed
111

112 113
    setlocale(LC_CTYPE,"");

114 115
    /* Initialise the stats department, phase 0 */
    initStats0();
116 117

    /* Next we do is grab the start time...just in case we're
118 119
     * collecting timing statistics.
     */
120
    stat_startInit();
121 122

    /* Set the RTS flags to default values. */
mrchebas@gmail.com's avatar
mrchebas@gmail.com committed
123

124 125 126 127 128 129
    initRtsFlagsDefaults();

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

    /* Parse the flags, separating the RTS flags from the programs args */
130
    if (argc != NULL && argv != NULL) {
131
	setFullProgArgv(*argc,*argv);
132
	setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
133
	setProgArgv(*argc,*argv);
134
    }
135

136 137 138
    /* Initialise the stats department, phase 1 */
    initStats1();

139 140 141 142
#ifdef USE_PAPI
    papi_init();
#endif

Simon Marlow's avatar
Simon Marlow committed
143
    /* initTracing must be after setupRtsFlags() */
144
#ifdef TRACING
Simon Marlow's avatar
Simon Marlow committed
145
    initTracing();
Simon Marlow's avatar
Simon Marlow committed
146
#endif
147 148 149
    /* Dtrace events are always enabled
     */
    dtraceEventStartup();
Simon Marlow's avatar
Simon Marlow committed
150

151 152 153 154 155
    /* initialise scheduler data structures (needs to be done before
     * initStorage()).
     */
    initScheduler();

156 157 158 159 160 161
    /* initialize the storage manager */
    initStorage();

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

162 163 164
    /* Add some GC roots for things in the base package that the RTS
     * knows about.  We don't know whether these turn out to be CAFs
     * or refer to CAFs, but we have to assume that they might.
165
     */
166 167
    getStablePtr((StgPtr)runIO_closure);
    getStablePtr((StgPtr)runNonIO_closure);
168 169 170

    getStablePtr((StgPtr)runFinalizerBatch_closure);

171 172 173
    getStablePtr((StgPtr)stackOverflow_closure);
    getStablePtr((StgPtr)heapOverflow_closure);
    getStablePtr((StgPtr)unpackCString_closure);
Simon Marlow's avatar
Simon Marlow committed
174
    getStablePtr((StgPtr)blockedIndefinitelyOnMVar_closure);
175
    getStablePtr((StgPtr)nonTermination_closure);
Simon Marlow's avatar
Simon Marlow committed
176
    getStablePtr((StgPtr)blockedIndefinitelyOnSTM_closure);
177 178 179 180
    getStablePtr((StgPtr)nestedAtomically_closure);

    getStablePtr((StgPtr)runSparks_closure);
    getStablePtr((StgPtr)ensureIOManagerIsRunning_closure);
181
#ifndef mingw32_HOST_OS
182
    getStablePtr((StgPtr)runHandlers_closure);
183
#endif
184

ei@vuokko.info's avatar
ei@vuokko.info committed
185
    /* initialise the shared Typeable store */
186
    initGlobalStore();
ei@vuokko.info's avatar
ei@vuokko.info committed
187

188 189 190 191 192
    /* initialise file locking, if necessary */
#if !defined(mingw32_HOST_OS)    
    initFileLocking();
#endif

sof's avatar
sof committed
193
#if defined(DEBUG)
194 195
    /* initialise thread label table (tso->char*) */
    initThreadLabelTable();
sof's avatar
sof committed
196
#endif
197

198 199
    initProfiling1();

sof's avatar
sof committed
200
    /* start the virtual timer 'subsystem'. */
201
    initTimer();
202
    startTimer();
203

sof's avatar
sof committed
204
#if defined(RTS_USER_SIGNALS)
205 206 207 208 209 210
    if (RtsFlags.MiscFlags.install_signal_handlers) {
        /* Initialise the user signal handler set */
        initUserSignals();
        /* Set up handler to run on SIGINT, etc. */
        initDefaultHandlers();
    }
sof's avatar
sof committed
211
#endif
sof's avatar
sof committed
212
 
213
#if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
sof's avatar
sof committed
214 215 216
    startupAsyncIO();
#endif

217 218 219 220 221 222
#ifdef RTS_GTK_FRONTPANEL
    if (RtsFlags.GcFlags.frontpanel) {
	initFrontPanel();
    }
#endif

223 224
#if X86_INIT_FPU
    x86_init_fpu();
225 226
#endif

227
    /* Record initialization times */
228
    stat_endInit();
229 230
}

231 232 233 234 235
// Compatibility interface
void
startupHaskell(int argc, char *argv[], void (*init_root)(void))
{
    hs_init(&argc, &argv);
236 237
    if(init_root)
        hs_add_root(init_root);
238 239 240
}


241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
/* -----------------------------------------------------------------------------
   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
257 258
   The code generator inserts a small function "__stginit_<module>" in each
   module and calls the registration functions in each of the modules it
259
   imports.
260 261 262 263 264 265 266 267

   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... 
 */
268
#define INIT_STACK_BLOCKS  4
Simon Marlow's avatar
Simon Marlow committed
269
static StgFunPtr *init_stack = NULL;
270

271 272
void
hs_add_root(void (*init_root)(void))
273
{
274
    bdescr *bd;
275
    nat init_sp;
276 277 278
    Capability *cap;

    cap = rts_lock();
279

280 281 282 283
    if (hs_init_count <= 0) {
	barf("hs_add_root() must be called after hs_init()");
    }

284 285 286
    /* The initialisation stack grows downward, with sp pointing 
       to the last occupied word */
    init_sp = INIT_STACK_BLOCKS*BLOCK_SIZE_W;
287
    bd = allocGroup_lock(INIT_STACK_BLOCKS);
Simon Marlow's avatar
Simon Marlow committed
288 289
    init_stack = (StgFunPtr *)bd->start;
    init_stack[--init_sp] = (StgFunPtr)stg_init_finish;
290
    if (init_root != NULL) {
Simon Marlow's avatar
Simon Marlow committed
291
	init_stack[--init_sp] = (StgFunPtr)init_root;
292 293
    }
    
294 295
    cap->r.rSp = (P_)(init_stack + init_sp);
    StgRun((StgFunPtr)stg_init, &cap->r);
296

297
    freeGroup_lock(bd);
298

andy@galois.com's avatar
andy@galois.com committed
299 300
    startupHpc();

301 302 303
    // This must be done after module initialisation.
    // ToDo: make this work in the presence of multiple hs_add_root()s.
    initProfiling2();
Simon Marlow's avatar
Simon Marlow committed
304

305 306
    rts_unlock(cap);

Simon Marlow's avatar
Simon Marlow committed
307 308 309 310
    // ditto.
#if defined(THREADED_RTS)
    ioManagerStart();
#endif
311
}
312

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
/* ----------------------------------------------------------------------------
 * Shutting down the RTS
 *
 * The wait_foreign parameter means:
 *       True  ==> wait for any threads doing foreign calls now.
 *       False ==> threads doing foreign calls may return in the
 *                 future, but will immediately block on a mutex.
 *                 (capability->lock).
 * 
 * If this RTS is a DLL that we're about to unload, then you want
 * safe=True, otherwise the thread might return to code that has been
 * unloaded.  If this is a standalone program that is about to exit,
 * then you can get away with safe=False, which is better because we
 * won't hang on exit if there is a blocked foreign call outstanding.
 *
 ------------------------------------------------------------------------- */
sof's avatar
sof committed
329

330 331
static void
hs_exit_(rtsBool wait_foreign)
332
{
333
    if (hs_init_count <= 0) {
334 335
	errorBelch("warning: too many hs_exit()s");
	return;
336 337 338 339 340 341
    }
    hs_init_count--;
    if (hs_init_count > 0) {
	// ignore until it's the last one
	return;
    }
sof's avatar
sof committed
342

343 344 345
    /* start timing the shutdown */
    stat_startExit();
    
Simon Marlow's avatar
Simon Marlow committed
346 347
    OnExitHook();

348 349 350 351 352
    // sanity check
#if defined(DEBUG)
    checkFPUStack();
#endif

353 354 355
    // Free the full argv storage
    freeFullProgArgv();

356
#if defined(THREADED_RTS)
357 358 359
    ioManagerDie();
#endif

360
    /* stop all running tasks */
361
    exitScheduler(wait_foreign);
362 363 364

    /* run C finalizers for all active weak pointers */
    runAllCFinalizers(weak_ptr_list);
365
    
366 367 368 369 370 371
#if defined(RTS_USER_SIGNALS)
    if (RtsFlags.MiscFlags.install_signal_handlers) {
        freeSignalHandlers();
    }
#endif

372
    /* stop the ticker */
sof's avatar
sof committed
373
    stopTimer();
374
    exitTimer(wait_foreign);
375

Simon Marlow's avatar
Simon Marlow committed
376 377 378
    // set the terminal settings back to what they were
#if !defined(mingw32_HOST_OS)    
    resetTerminalSettings();
379 380
#endif

Simon Marlow's avatar
Simon Marlow committed
381 382 383
    // uninstall signal handlers
    resetDefaultHandlers();

384 385 386
    /* stop timing the shutdown, we're about to print stats */
    stat_endExit();
    
andy@galois.com's avatar
andy@galois.com committed
387 388 389
    /* shutdown the hpc support (if needed) */
    exitHpc();

Simon Marlow's avatar
Simon Marlow committed
390 391
    // clean up things from the storage manager's point of view.
    // also outputs the stats (+RTS -s) info.
392 393
    exitStorage();
    
394 395 396
    /* free the tasks */
    freeScheduler();

ei@vuokko.info's avatar
ei@vuokko.info committed
397
    /* free shared Typeable store */
398
    exitGlobalStore();
ei@vuokko.info's avatar
ei@vuokko.info committed
399

400 401 402
    /* free linker data */
    exitLinker();

403 404 405 406 407
    /* free file locking tables, if necessary */
#if !defined(mingw32_HOST_OS)    
    freeFileLocking();
#endif

Ian Lynagh's avatar
Ian Lynagh committed
408
    /* free the stable pointer table */
409 410
    exitStablePtrTable();

Ian Lynagh's avatar
Ian Lynagh committed
411 412 413 414 415
#if defined(DEBUG)
    /* free the thread label table */
    freeThreadLabelTable();
#endif

416 417 418 419 420 421
#ifdef RTS_GTK_FRONTPANEL
    if (RtsFlags.GcFlags.frontpanel) {
	stopFrontPanel();
    }
#endif

422
#if defined(PROFILING) 
423
    reportCCSProfiling();
424 425
#endif

426
    endProfiling();
427
    freeProfiling1();
428

429
#ifdef PROFILING
430 431 432
    // Originally, this was in report_ccs_profiling().  Now, retainer
    // profiling might tack some extra stuff on to the end of this file
    // during endProfiling().
433
    if (prof_file != NULL) fclose(prof_file);
434
#endif
Simon Marlow's avatar
Simon Marlow committed
435

436 437 438
#ifdef TRACING
    endTracing();
    freeTracing();
Simon Marlow's avatar
Simon Marlow committed
439 440
#endif

441
#if defined(TICKY_TICKY)
442 443
    if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
#endif
sof's avatar
sof committed
444

445
#if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
Simon Marlow's avatar
Simon Marlow committed
446
    shutdownAsyncIO(wait_foreign);
sof's avatar
sof committed
447
#endif
Simon Marlow's avatar
Simon Marlow committed
448

449 450 451
    /* free hash table storage */
    exitHashTable();

452 453 454 455 456
    // Finally, free all our storage.  However, we only free the heap
    // memory if we have waited for foreign calls to complete;
    // otherwise a foreign call in progress may still be referencing
    // heap memory (e.g. by being passed a ByteArray#).
    freeStorage(wait_foreign);
457

458 459
}

460 461 462 463 464 465 466 467
// The real hs_exit():
void
hs_exit(void)
{
    hs_exit_(rtsTrue);
    // be safe; this might be a DLL
}

468 469 470 471 472 473 474 475 476 477
// Compatibility interfaces
void
shutdownHaskell(void)
{
    hs_exit();
}

void
shutdownHaskellAndExit(int n)
{
Simon Marlow's avatar
Simon Marlow committed
478 479 480 481
    // we're about to exit(), no need to wait for foreign calls to return.
    hs_exit_(rtsFalse);

    if (hs_init_count == 0) {
482 483
	stg_exit(n);
    }
484
}
485

Simon Marlow's avatar
Simon Marlow committed
486 487 488 489 490 491 492 493 494
#ifndef mingw32_HOST_OS
void
shutdownHaskellAndSignal(int sig)
{
    hs_exit_(rtsFalse);
    kill(getpid(),sig);
}
#endif

495
/* 
496
 * called from STG-land to exit the program
497 498
 */

499 500
void (*exitFn)(int) = 0;

501
void  
502
stg_exit(int n)
503
{ 
504 505
  if (exitFn)
    (*exitFn)(n);
506
  exit(n);
507
}