main.lc 11.5 KB
Newer Older
1
2
3
4
5
6
7
%/****************************************************************
%*								*
%*	This is where everything starts 			*
%*								*
%****************************************************************/

\begin{code}
8
#if defined(PROFILING) || defined(PAR) || defined(CONCURRENT)
9
#if !defined(_AIX)
10
11
#define NON_POSIX_SOURCE /* time things on Solaris -- sigh */
#endif
12
#endif
13
14
15
16

#include "rtsdefs.h"
#include <setjmp.h>

sof's avatar
sof committed
17
18
19
20
#if 1
#include <windows.h>
#endif

21
22
23
24
25
26
#if defined(STDC_HEADERS) || defined(HAVE_STRING_H)
# include <string.h>
/* An ANSI string.h and pre-ANSI memory.h might conflict.  */
# if !defined(STDC_HEADERS) && defined(HAVE_MEMORY_H)
#  include <memory.h>
# endif /* not STDC_HEADERS and HAVE_MEMORY_H */
27

28
29
30
31
32
#else /* not STDC_HEADERS and not HAVE_STRING_H */
# include <strings.h>
/* memory.h and strings.h conflict on some systems.  */
#endif /* not STDC_HEADERS and not HAVE_STRING_H */

33
#if defined(PROFILING) || defined(PAR) || defined(GRAN)
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/* need some "time" things */

/* ToDo: This is a mess! Improve ? */

# ifdef HAVE_SYS_TYPES_H
#  include <sys/types.h>
# endif

# ifdef HAVE_SYS_TIMES_H
#  include <sys/times.h>
# endif

# ifdef HAVE_SYS_TIME_H
#  include <sys/time.h>
# endif
49
#endif /* PROFILING || PAR */
50
51
52
53
54
55
56
57
58

#ifndef PAR
STGRegisterTable MainRegTable;
#endif

/* fwd decls */
void shutdownHaskell(STG_NO_ARGS);

EXTFUN(startStgWorld);
59
extern void PrintTickyInfo(STG_NO_ARGS);
60
61
62
63
extern void checkAStack(STG_NO_ARGS);

/* a real nasty Global Variable */
/* moved to main/TopClosure(13)?.lc -- *one* of them will get linked in
64
P_ TopClosure = GHCmain_mainPrimIO_closure;
65
66
67
68
69
70
 */

/* structure to carry around info about the storage manager */
smInfo StorageMgrInfo;

#ifdef PAR
71
72
73
extern I_ 	OkToGC, buckets;
extern rtsBool	TraceSparks, DelaySparks,
    	    	DeferGlobalUpdates;
74

75
76
77
void RunParallelSystem PROTO((P_));
void initParallelSystem(STG_NO_ARGS);
void SynchroniseSystem(STG_NO_ARGS);
78

79
void SetTrace PROTO((W_ address, I_ level/*?*/));
80
81
#endif

82
83
84
void *stgAllocForGMP   PROTO((size_t));
void *stgReallocForGMP PROTO ((void *, size_t, size_t));
void  stgDeallocForGMP PROTO ((void *, size_t));
85
86
87
88
89
90
91
92

/* NeXTs can't just reach out and touch "end", to use in
   distinguishing things in static vs dynamic (malloc'd) memory.
*/
#if nextstep2_TARGET_OS || nextstep3_TARGET_OS /* ToDo: use END_BY_FUNNY_MEANS or something */
void *get_end_result;
#endif

93
int   prog_argc; /* an "int" so as to match normal "argc" */
94
char  **prog_argv;
95
int   rts_argc;  /* ditto */
96
97
98
99
100
101
char *rts_argv[MAX_RTS_ARGS];

#ifndef PAR
jmp_buf restart_main;	    /* For restarting after a signal */
#endif

102
#if defined(PAR)
103
int nPEs = 0;		    /* Number of PEs */
104
105
#endif

sof's avatar
sof committed
106
107
108
109
110
111
112
113
114
\end{code}

Setting up and initialising the run-time system:
(used by main(), and people that don't allow Haskell
to stay in control.)

\begin{code}
void
initRTS(int argc, char *argv[])
115
{
116
117
118
#ifdef GRAN
 int i;
#endif
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
\end{code}

The very first thing we do is grab the start time...just in case we're
collecting timing statistics.

\begin{code}
    start_time();
\end{code}

The parallel system needs to be initialised and synchronised before
the program is run.  This is done {\em before} heap allocation, so we
can grab all remaining heap without needing to consider the System
Manager's requirements.

\begin{code}
#ifdef PAR
135
    if (*argv[0] == '-') {     /* Look to see whether we're the Main Thread */
136
	IAmMainThread = rtsTrue;
137
        argv++; argc--;			/* Strip off flag argument */
138
    }
139
    /* 
140
141
     * Grab the number of PEs out of the argument vector, and
     * eliminate it from further argument processing.
142
143
144
     */
    nPEs = atoi(argv[1]);
    argv[1] = argv[0];
145
    argv++; argc--;
146
    initEachPEHook();                  /* HWL: hook to be execed on each PE */
147
148
149
    SynchroniseSystem();
#endif

150
#if defined(PROFILING) || defined(PAR) || defined(GRAN)
151
152
153
154
155
156
157
158
159
    /* setup string indicating time of run -- only used for profiling */
    (void) time_str();
#endif

#if nextstep2_TARGET_OS || nextstep3_TARGET_OS /* ToDo: use END_BY_FUNNY_MEANS or something */
    get_end_result = get_end();
#endif

    /* 
160
161
162
       divide the command-line args between pgm and RTS; figure out
       what statsfile to use (if any); [if so, write the whole
       cmd-line into it]
163
164
       
    */
165
166
167
168
169
    initRtsFlagsDefaults();
    defaultsHook(); /* the one supplied does nothing;
		       the user may have supplied a more interesting one.
		    */

170
171
172
173
174
175
176
177
178
    setupRtsFlags(&argc, argv, &rts_argc, rts_argv);
    prog_argc = argc;
    prog_argv = argv;

#if defined(PAR)
   /* Initialise the parallel system -- before initHeap! */
   initParallelSystem();
#endif	/* PAR */

179
#if defined(PROFILING) || defined(PAR)
180
181
182
183
184
185
186
    if (init_cc_profiling(rts_argc, rts_argv, prog_argv) != 0) {
        fflush(stdout);
	fprintf(stderr, "init_cc_profiling failed!\n");
	EXIT(EXIT_FAILURE);
    }
#endif

187
188
#if defined(GRAN)
    if (!RTSflags.GranFlags.granSimStats_suppressed)
189
      if (init_gr_simulation(rts_argc, rts_argv, prog_argc, prog_argv) != 0) {
190
191
	  fprintf(stderr, "init_gr_simulation failed!\n"); 
	  EXIT(EXIT_FAILURE);
192
193
194
195
      }
#endif

#ifdef PAR
196
    if (RTSflags.ParFlags.granSimStats)
197
198
199
	init_gr_profiling(rts_argc, rts_argv, prog_argc, prog_argv);
#endif

200
201
    /* initialize the storage manager */
    initSM();
202
203

#ifndef PAR
204
    if (! initStacks( &StorageMgrInfo )) {
205
206
207
208
209
210
        fflush(stdout);
	fprintf(stderr, "initStacks failed!\n");
	EXIT(EXIT_FAILURE);
    }
#endif

211
    if (! initHeap( &StorageMgrInfo )) {
212
        fflush(stdout);
213
214
	fprintf(stderr, "initHeap failed!\n");
	EXIT(EXIT_FAILURE);
215
216
217
    }

#if defined(CONCURRENT) && !defined(GRAN)
218
    if (!initThreadPools()) {
219
220
221
222
223
224
        fflush(stdout);
	fprintf(stderr, "initThreadPools failed!\n"); 
        EXIT(EXIT_FAILURE);
    }
#endif

225
#if defined(PROFILING) || defined(PAR)
226
227
228
229
    /* call cost centre registering routine (after heap allocated) */
    cc_register();
#endif

230
#if defined(TICKY_TICKY)
231
232
233
234
235
236
237
238
239
240
    max_SpA = MAIN_SpA; /* initial high-water marks */
    max_SpB = MAIN_SpB;
#endif

    /* Tell GNU multi-precision pkg about our custom alloc functions */
    mp_set_memory_functions(stgAllocForGMP, stgReallocForGMP, stgDeallocForGMP);

    /* Record initialization times */
    end_init();

241
#if defined(PROFILING) || defined(CONCURRENT) 
242
243
244
245
246
247
248
249
250
    /* 
     * Both the context-switcher and the cost-center profiler use 
     * a virtual timer.
     */
    if (install_vtalrm_handler()) {
	fflush(stdout);
	fprintf(stderr, "Can't install VTALRM handler.\n");
	EXIT(EXIT_FAILURE);
    }
251
252
253
254
255
256
#if (defined(CONCURRENT) && defined(PROFILING)) || defined(PAR)
    if (! time_profiling)
	RTSflags.CcFlags.msecsPerTick = RTSflags.ConcFlags.ctxtSwitchTime;
    else {
	if (RTSflags.ConcFlags.ctxtSwitchTime % (1000/TICK_FREQUENCY) == 0)
	    RTSflags.CcFlags.msecsPerTick = TICK_MILLISECS;
257
	else
258
	    RTSflags.CcFlags.msecsPerTick = CS_MIN_MILLISECS;
259

260
261
262
	RTSflags.CcFlags.ctxtSwitchTicks = RTSflags.ConcFlags.ctxtSwitchTime / RTSflags.CcFlags.msecsPerTick;
	RTSflags.CcFlags.profilerTicks = TICK_MILLISECS / RTSflags.CcFlags.msecsPerTick;
    }
263
264
265
266
267
268
#endif

#ifndef CONCURRENT
    START_TIME_PROFILER;
#endif

269
#endif	/* PROFILING || CONCURRENT */
270
271
272
273
274
275

#ifndef PAR
    setjmp(restart_main);
    initUserSignals();
#endif

sof's avatar
sof committed
276
277
278
279
280
281
282
283

}

int /* return type of "main" is defined by the C standard */
main(int argc, char *argv[])
{
  initRTS(argc,argv);

284
#ifdef CONCURRENT
sof's avatar
sof committed
285
    AvailableStack = AvailableTSO = PrelBase_Z91Z93_closure;
286
# if defined(GRAN)                                                 /* HWL */
287
288
289
290
    /* Moved in here from ScheduleThreads, to handle a restart_main 
       (because of a signal) properly. */
    for (i=0; i<RTSflags.GranFlags.proc; i++) 
      {
sof's avatar
sof committed
291
292
        RunnableThreadsHd[i] = RunnableThreadsTl[i] = PrelBase_Z91Z93_closure;
	WaitThreadsHd[i] = WaitThreadsTl[i] = PrelBase_Z91Z93_closure;
293
294
295
296
297
        PendingSparksHd[i][REQUIRED_POOL] = PendingSparksHd[i][ADVISORY_POOL] = 
        PendingSparksTl[i][REQUIRED_POOL] = PendingSparksTl[i][ADVISORY_POOL] = 
            NULL; 
      }
# else
sof's avatar
sof committed
298
299
    RunnableThreadsHd = RunnableThreadsTl = PrelBase_Z91Z93_closure;
    WaitingThreadsHd = WaitingThreadsTl = PrelBase_Z91Z93_closure;
300
301
302
303
304
305
    PendingSparksHd[REQUIRED_POOL] = 
      PendingSparksTl[REQUIRED_POOL] = PendingSparksBase[REQUIRED_POOL];
    PendingSparksHd[ADVISORY_POOL] = 
      PendingSparksTl[ADVISORY_POOL] = PendingSparksBase[ADVISORY_POOL];
# endif

sof's avatar
sof committed
306
    CurrentTSO = PrelBase_Z91Z93_closure;
307
308
309
310

# ifdef PAR
    RunParallelSystem(TopClosure);
# else
sof's avatar
sof committed
311
    STKO_LINK(MainStkO) = PrelBase_Z91Z93_closure;
312
313
314
315
316
317
    ScheduleThreads(TopClosure);
# endif	/* PAR */

#else	/* not threaded (sequential) */

    miniInterpret((StgFunPtr)startStgWorld);
318

319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
#endif /* !CONCURRENT */

    shutdownHaskell();
    return(EXIT_SUCCESS);    /* don't use EXIT! :-) */
}
\end{code}

It should be possible to call @shutdownHaskell@ whenever you want to
shut a Haskell program down in an orderly way.

Note that some of this code probably depends on the integrity of
various internal data structures so this should not be called in
response to detecting a catastrophic error.

\begin{code}
void
shutdownHaskell(STG_NO_ARGS)
{
    STOP_TIME_PROFILER;

339
340
341
342
343
344
345
#if defined(GRAN)
    /* For some reason this must be before exitSM */
    if (!RTSflags.GranFlags.granSimStats_suppressed)
      end_gr_simulation();
#endif

    if (! exitSM(&StorageMgrInfo) ) {
346
347
348
349
350
	fflush(stdout);
	fprintf(stderr, "exitSM failed!\n");
	EXIT(EXIT_FAILURE);
    }

351
#if defined(PROFILING)
352
353
    heap_profile_finish();
#endif
354
#if defined(PROFILING) || defined(PAR)
355
356
357
    report_cc_profiling(1 /* final */ );
#endif

358
359
#if defined(TICKY_TICKY)
    if (RTSflags.TickyFlags.showTickyStats) PrintTickyInfo();
360
361
#endif

sof's avatar
sof committed
362
363
364
365
366
    /* Give the application a chance to do something sensible
       on-exit
    */
    OnExitHook();

367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
    fflush(stdout);
    /* This fflush is important, because: if "main" just returns,
       then we will end up in pre-supplied exit code that will close
       streams and flush buffers.  In particular we have seen: it
       will close fd 0 (stdin), then flush fd 1 (stdout), then <who
       cares>...

       But if you're playing with sockets, that "close fd 0" might
       suggest to the daemon that all is over, only to be presented
       with more stuff on "fd 1" at the flush.

       The fflush avoids this sad possibility.
    */
}
\end{code}

Sets up and returns a string indicating the date/time of the run.
Successive calls simply return the same string again. Initially
called by @main.lc@ to initialise the string at the start of the run.
Only used for profiling.

\begin{code}
389
#if defined(PROFILING) || defined(CONCURRENT) || defined(GRAN)
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# include <time.h>

char *
time_str(STG_NO_ARGS)
{
    static time_t now = 0;
    static char nowstr[26];

    if (now == 0) {
	time(&now);
	strcpy(nowstr, ctime(&now));
	strcpy(nowstr+16,nowstr+19);
	nowstr[21] = '\0';
    }
    return nowstr;
}
#endif /* profiling */
\end{code}

ToDo: Will this work under threads?

\begin{code}
412
StgStablePtr errorHandler = -1; /* NB: prone to magic-value-ery (WDP 95/12) */
413

414
415
StgInt
getErrorHandler(STG_NO_ARGS)
416
417
418
419
{
  return (StgInt) errorHandler;
}

420
#if !defined(PAR)
421

422
423
424
void
raiseError( handler )
  StgStablePtr handler;
425
{
426
  if (handler == -1) { /* beautiful magic value... (WDP 95/12) */
427
    shutdownHaskell();
428
    EXIT(EXIT_FAILURE);
429
430
431
432
433
434
435
436
437
438
  } else {
    TopClosure = deRefStablePointer( handler );
    longjmp(restart_main,1);
  }
}
\end{code}

\begin{code}
StgInt
catchError( newErrorHandler )
439
  StgStablePtr newErrorHandler;
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
{
  StgStablePtr oldErrorHandler = errorHandler;
  errorHandler = newErrorHandler;
  return oldErrorHandler;
}

#endif
\end{code}

If we have installed an error handler, we might want to
indicate that we have successfully recovered from an error by
decrementing the counter.

\begin{code}
void
decrementErrorCount()
{
  ErrorIO_call_count-=1;	
}

\end{code}