RtsStartup.c 11.6 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 72
/* -----------------------------------------------------------------------------
   Initialise floating point unit on x86 (currently disabled. why?)
73
   (see comment in ghc/compiler/nativeGen/MachInstrs.lhs).
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 123 124 125 126 127
#if defined(DEBUG)
    /* Start off by initialising the allocator debugging so we can
     * use it anywhere */
    initAllocator();
#endif

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

130 131 132 133 134 135
    initRtsFlagsDefaults();

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

    /* Parse the flags, separating the RTS flags from the programs args */
136
    if (argc != NULL && argv != NULL) {
137
	setFullProgArgv(*argc,*argv);
138
	setupRtsFlags(argc, *argv, &rts_argc, rts_argv);
139
	setProgArgv(*argc,*argv);
140
    }
141

142 143 144
    /* Initialise the stats department, phase 1 */
    initStats1();

145 146 147 148
#ifdef USE_PAPI
    papi_init();
#endif

Simon Marlow's avatar
Simon Marlow committed
149
    /* initTracing must be after setupRtsFlags() */
150
#ifdef TRACING
Simon Marlow's avatar
Simon Marlow committed
151
    initTracing();
Simon Marlow's avatar
Simon Marlow committed
152
#endif
153 154 155
    /* Dtrace events are always enabled
     */
    dtraceEventStartup();
Simon Marlow's avatar
Simon Marlow committed
156

157 158 159 160 161
    /* initialise scheduler data structures (needs to be done before
     * initStorage()).
     */
    initScheduler();

162 163 164 165 166 167
    /* initialize the storage manager */
    initStorage();

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

168 169 170
    /* 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.
171
     */
172 173
    getStablePtr((StgPtr)runIO_closure);
    getStablePtr((StgPtr)runNonIO_closure);
174 175 176 177
    getStablePtr((StgPtr)stackOverflow_closure);
    getStablePtr((StgPtr)heapOverflow_closure);
    getStablePtr((StgPtr)runFinalizerBatch_closure);
    getStablePtr((StgPtr)unpackCString_closure);
Simon Marlow's avatar
Simon Marlow committed
178
    getStablePtr((StgPtr)blockedIndefinitelyOnMVar_closure);
179
    getStablePtr((StgPtr)nonTermination_closure);
Simon Marlow's avatar
Simon Marlow committed
180
    getStablePtr((StgPtr)blockedIndefinitelyOnSTM_closure);
181

ei@vuokko.info's avatar
ei@vuokko.info committed
182
    /* initialise the shared Typeable store */
183
    initGlobalStore();
ei@vuokko.info's avatar
ei@vuokko.info committed
184

185 186 187 188 189
    /* initialise file locking, if necessary */
#if !defined(mingw32_HOST_OS)    
    initFileLocking();
#endif

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

195 196
    initProfiling1();

sof's avatar
sof committed
197
    /* start the virtual timer 'subsystem'. */
198
    initTimer();
199
    startTimer();
200

sof's avatar
sof committed
201
#if defined(RTS_USER_SIGNALS)
202 203 204 205 206 207
    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
208
#endif
sof's avatar
sof committed
209
 
210
#if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
sof's avatar
sof committed
211 212 213
    startupAsyncIO();
#endif

214 215 216 217 218 219
#ifdef RTS_GTK_FRONTPANEL
    if (RtsFlags.GcFlags.frontpanel) {
	initFrontPanel();
    }
#endif

220 221
#if X86_INIT_FPU
    x86_init_fpu();
222 223
#endif

224
    /* Record initialization times */
225
    stat_endInit();
226 227
}

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


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

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

268 269
void
hs_add_root(void (*init_root)(void))
270
{
271
    bdescr *bd;
272
    nat init_sp;
273 274 275
    Capability *cap;

    cap = rts_lock();
276

277 278 279 280
    if (hs_init_count <= 0) {
	barf("hs_add_root() must be called after hs_init()");
    }

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

294
    freeGroup_lock(bd);
295

andy@galois.com's avatar
andy@galois.com committed
296 297
    startupHpc();

298 299 300
    // 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
301

302 303
    rts_unlock(cap);

Simon Marlow's avatar
Simon Marlow committed
304 305 306 307
    // ditto.
#if defined(THREADED_RTS)
    ioManagerStart();
#endif
308
}
309

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
/* ----------------------------------------------------------------------------
 * 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
326

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

340 341 342
    /* start timing the shutdown */
    stat_startExit();
    
Simon Marlow's avatar
Simon Marlow committed
343 344
    OnExitHook();

345 346 347
    // Free the full argv storage
    freeFullProgArgv();

348
#if defined(THREADED_RTS)
349 350 351
    ioManagerDie();
#endif

352
    /* stop all running tasks */
353
    exitScheduler(wait_foreign);
354 355 356

    /* run C finalizers for all active weak pointers */
    runAllCFinalizers(weak_ptr_list);
357
    
358 359 360 361 362 363
#if defined(RTS_USER_SIGNALS)
    if (RtsFlags.MiscFlags.install_signal_handlers) {
        freeSignalHandlers();
    }
#endif

364
    /* stop the ticker */
sof's avatar
sof committed
365
    stopTimer();
366
    exitTimer();
367

Simon Marlow's avatar
Simon Marlow committed
368 369 370
    // set the terminal settings back to what they were
#if !defined(mingw32_HOST_OS)    
    resetTerminalSettings();
371 372
#endif

Simon Marlow's avatar
Simon Marlow committed
373 374 375
    // uninstall signal handlers
    resetDefaultHandlers();

376 377 378
    /* stop timing the shutdown, we're about to print stats */
    stat_endExit();
    
andy@galois.com's avatar
andy@galois.com committed
379 380 381
    /* shutdown the hpc support (if needed) */
    exitHpc();

Simon Marlow's avatar
Simon Marlow committed
382 383
    // clean up things from the storage manager's point of view.
    // also outputs the stats (+RTS -s) info.
384 385
    exitStorage();
    
386 387 388
    /* free the tasks */
    freeScheduler();

ei@vuokko.info's avatar
ei@vuokko.info committed
389
    /* free shared Typeable store */
390
    exitGlobalStore();
ei@vuokko.info's avatar
ei@vuokko.info committed
391

392 393 394
    /* free linker data */
    exitLinker();

395 396 397 398 399
    /* free file locking tables, if necessary */
#if !defined(mingw32_HOST_OS)    
    freeFileLocking();
#endif

Ian Lynagh's avatar
Ian Lynagh committed
400
    /* free the stable pointer table */
401 402
    exitStablePtrTable();

Ian Lynagh's avatar
Ian Lynagh committed
403 404 405 406 407
#if defined(DEBUG)
    /* free the thread label table */
    freeThreadLabelTable();
#endif

408 409 410 411 412 413
#ifdef RTS_GTK_FRONTPANEL
    if (RtsFlags.GcFlags.frontpanel) {
	stopFrontPanel();
    }
#endif

414
#if defined(PROFILING) 
415
    reportCCSProfiling();
416 417
#endif

418
    endProfiling();
419
    freeProfiling1();
420

421
#ifdef PROFILING
422 423 424
    // Originally, this was in report_ccs_profiling().  Now, retainer
    // profiling might tack some extra stuff on to the end of this file
    // during endProfiling().
425
    if (prof_file != NULL) fclose(prof_file);
426
#endif
Simon Marlow's avatar
Simon Marlow committed
427

428 429 430
#ifdef TRACING
    endTracing();
    freeTracing();
Simon Marlow's avatar
Simon Marlow committed
431 432
#endif

433
#if defined(TICKY_TICKY)
434 435
    if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
#endif
sof's avatar
sof committed
436

437
#if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
Simon Marlow's avatar
Simon Marlow committed
438
    shutdownAsyncIO(wait_foreign);
sof's avatar
sof committed
439
#endif
Simon Marlow's avatar
Simon Marlow committed
440

441 442 443
    /* free hash table storage */
    exitHashTable();

444
    // Finally, free all our storage
Simon Marlow's avatar
Simon Marlow committed
445
    freeStorage();
446 447 448 449 450 451

#if defined(DEBUG)
    /* and shut down the allocator debugging */
    shutdownAllocator();
#endif

452 453
}

454 455 456 457 458 459 460 461
// The real hs_exit():
void
hs_exit(void)
{
    hs_exit_(rtsTrue);
    // be safe; this might be a DLL
}

462 463 464 465 466 467 468 469 470 471
// Compatibility interfaces
void
shutdownHaskell(void)
{
    hs_exit();
}

void
shutdownHaskellAndExit(int n)
{
Simon Marlow's avatar
Simon Marlow committed
472 473 474 475
    // we're about to exit(), no need to wait for foreign calls to return.
    hs_exit_(rtsFalse);

    if (hs_init_count == 0) {
476 477
	stg_exit(n);
    }
478
}
479

Simon Marlow's avatar
Simon Marlow committed
480 481 482 483 484 485 486 487 488
#ifndef mingw32_HOST_OS
void
shutdownHaskellAndSignal(int sig)
{
    hs_exit_(rtsFalse);
    kill(getpid(),sig);
}
#endif

489
/* 
490
 * called from STG-land to exit the program
491 492
 */

493 494
void (*exitFn)(int) = 0;

495
void  
496
stg_exit(int n)
497
{ 
498 499
  if (exitFn)
    (*exitFn)(n);
500
  exit(n);
501
}