RtsStartup.c 10.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.
 *
 * ---------------------------------------------------------------------------*/

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

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

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

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

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

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

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

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

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

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

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

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

113 114
    setlocale(LC_CTYPE,"");

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

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

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

125 126 127 128 129 130
    initRtsFlagsDefaults();

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

    /* Parse the flags, separating the RTS flags from the programs args */
131
    if (argc != NULL && argv != NULL) {
132
	setFullProgArgv(*argc,*argv);
133
        setupRtsFlags(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 228 229 230 231 232 233 234 235 236 237
    startupHpc();

    // This must be done after module initialisation.
    // ToDo: make this work in the presence of multiple hs_add_root()s.
    initProfiling2();

    // ditto.
#if defined(THREADED_RTS)
    ioManagerStart();
#endif

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

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


250
/* -----------------------------------------------------------------------------
251
   hs_add_root: backwards compatibility.  (see #3252)
252 253
   -------------------------------------------------------------------------- */

254
void
255
hs_add_root(void (*init_root)(void) STG_UNUSED)
256
{
257
    /* nothing */
258
}
259

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
/* ----------------------------------------------------------------------------
 * 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
276

277 278
static void
hs_exit_(rtsBool wait_foreign)
279
{
280
    if (hs_init_count <= 0) {
281 282
	errorBelch("warning: too many hs_exit()s");
	return;
283 284 285 286 287 288
    }
    hs_init_count--;
    if (hs_init_count > 0) {
	// ignore until it's the last one
	return;
    }
sof's avatar
sof committed
289

290 291 292
    /* start timing the shutdown */
    stat_startExit();
    
Simon Marlow's avatar
Simon Marlow committed
293 294
    OnExitHook();

295 296 297 298 299
    // sanity check
#if defined(DEBUG)
    checkFPUStack();
#endif

300 301 302
    // Free the full argv storage
    freeFullProgArgv();

303
#if defined(THREADED_RTS)
304 305 306
    ioManagerDie();
#endif

307
    /* stop all running tasks */
308
    exitScheduler(wait_foreign);
309 310 311

    /* run C finalizers for all active weak pointers */
    runAllCFinalizers(weak_ptr_list);
312
    
313 314 315 316 317 318
#if defined(RTS_USER_SIGNALS)
    if (RtsFlags.MiscFlags.install_signal_handlers) {
        freeSignalHandlers();
    }
#endif

319
    /* stop the ticker */
sof's avatar
sof committed
320
    stopTimer();
321
    exitTimer(wait_foreign);
322

Simon Marlow's avatar
Simon Marlow committed
323 324 325
    // set the terminal settings back to what they were
#if !defined(mingw32_HOST_OS)    
    resetTerminalSettings();
326 327
#endif

Simon Marlow's avatar
Simon Marlow committed
328 329 330
    // uninstall signal handlers
    resetDefaultHandlers();

331 332 333
    /* stop timing the shutdown, we're about to print stats */
    stat_endExit();
    
andy@galois.com's avatar
andy@galois.com committed
334 335 336
    /* shutdown the hpc support (if needed) */
    exitHpc();

Simon Marlow's avatar
Simon Marlow committed
337 338
    // clean up things from the storage manager's point of view.
    // also outputs the stats (+RTS -s) info.
339 340
    exitStorage();
    
341 342 343
    /* free the tasks */
    freeScheduler();

ei@vuokko.info's avatar
ei@vuokko.info committed
344
    /* free shared Typeable store */
345
    exitGlobalStore();
ei@vuokko.info's avatar
ei@vuokko.info committed
346

347 348 349
    /* free linker data */
    exitLinker();

350 351 352 353 354
    /* free file locking tables, if necessary */
#if !defined(mingw32_HOST_OS)    
    freeFileLocking();
#endif

Ian Lynagh's avatar
Ian Lynagh committed
355
    /* free the stable pointer table */
356 357
    exitStablePtrTable();

Ian Lynagh's avatar
Ian Lynagh committed
358 359 360 361 362
#if defined(DEBUG)
    /* free the thread label table */
    freeThreadLabelTable();
#endif

363 364 365 366 367 368
#ifdef RTS_GTK_FRONTPANEL
    if (RtsFlags.GcFlags.frontpanel) {
	stopFrontPanel();
    }
#endif

369
#if defined(PROFILING) 
370
    reportCCSProfiling();
371 372
#endif

373
    endProfiling();
374
    freeProfiling();
375

376
#ifdef PROFILING
377 378 379
    // Originally, this was in report_ccs_profiling().  Now, retainer
    // profiling might tack some extra stuff on to the end of this file
    // during endProfiling().
380
    if (prof_file != NULL) fclose(prof_file);
381
#endif
Simon Marlow's avatar
Simon Marlow committed
382

383 384 385
#ifdef TRACING
    endTracing();
    freeTracing();
Simon Marlow's avatar
Simon Marlow committed
386 387
#endif

388
#if defined(TICKY_TICKY)
389 390
    if (RtsFlags.TickyFlags.showTickyStats) PrintTickyInfo();
#endif
sof's avatar
sof committed
391

392
#if defined(mingw32_HOST_OS) && !defined(THREADED_RTS)
Simon Marlow's avatar
Simon Marlow committed
393
    shutdownAsyncIO(wait_foreign);
sof's avatar
sof committed
394
#endif
Simon Marlow's avatar
Simon Marlow committed
395

396 397 398
    /* free hash table storage */
    exitHashTable();

399 400 401 402 403
    // 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);
404

405 406
}

407 408 409 410 411 412 413 414
// The real hs_exit():
void
hs_exit(void)
{
    hs_exit_(rtsTrue);
    // be safe; this might be a DLL
}

415 416 417 418 419 420 421 422 423 424
// Compatibility interfaces
void
shutdownHaskell(void)
{
    hs_exit();
}

void
shutdownHaskellAndExit(int n)
{
Simon Marlow's avatar
Simon Marlow committed
425 426 427 428
    // we're about to exit(), no need to wait for foreign calls to return.
    hs_exit_(rtsFalse);

    if (hs_init_count == 0) {
429 430
	stg_exit(n);
    }
431
}
432

Simon Marlow's avatar
Simon Marlow committed
433 434 435 436 437 438 439 440 441
#ifndef mingw32_HOST_OS
void
shutdownHaskellAndSignal(int sig)
{
    hs_exit_(rtsFalse);
    kill(getpid(),sig);
}
#endif

442
/* 
443
 * called from STG-land to exit the program
444 445
 */

446 447
void (*exitFn)(int) = 0;

448
void  
449
stg_exit(int n)
450
{ 
451 452
  if (exitFn)
    (*exitFn)(n);
453
  exit(n);
454
}