summaryrefslogtreecommitdiffstats
path: root/private/crt32/startup/crt0.c
blob: bc0e4f75dd72060acb71087da92656d4e13f356b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
/***
*crt0.c - C runtime initialization routine
*
*	Copyright (c) 1989-1993, Microsoft Corporation. All rights reserved.
*
*Purpose:
*       This the main startup routine. It is called upon program
*       startup by a very small assembler stub.
*
*Revision History:
*       06-27-89  PHG   Module created, based on asm version
*       11-02-89  JCR   Added DOS32QUERYSYSINFO to get osversion
*       04-09-90  GJF   Added #include <cruntime.h>. Put in explicit calling
*                       types (_CALLTYPE1 or _CALLTYPE4) for __crt0(),
*                       inherit(), __amsg_exit() and _cintDIV(). Also, fixed
*                       the copyright and cleaned up the formatting a bit.
*       04-10-90  GJF   Fixed compiler warnings (-W3).
*       08-08-90  GJF   Added exception handling stuff (needed to support
*                       runtime errors and signal()).
*       08-31-90  GJF   Removed 32 from API names.
*       10-08-90  GJF   New-style function declarators.
*       12-05-90  GJF   Fixed off-by-one error in inherit().
*       12-06-90  GJF   Win32 version of inherit().
*       12-06-90  SRW   Added _osfile back for win32.  Changed _osfinfo from
*                       an array of structures to an array of 32-bit handles
*                       (_osfhnd)
*       01-21-91  GJF   ANSI naming.
*       01-25-91  SRW   Changed Win32 Process Startup [_WIN32_]
*       02-01-91  SRW   Removed usage of PPEB type [_WIN32_]
*       02-05-91  SRW   Changed to pass _osfile and _osfhnd arrays as binary
*                       data to child process.  [_WIN32_]
*       04-02-91  GJF   Need to get version number sooner so it can be used in
*                       _heap_init. Prefixed an '_' onto BaseProcessStartup.
*                       Version info now stored in _os[version|major|minor] and
*                       _base[version|major|minor] (_WIN32_).
*       04-10-91  PNT   Added _MAC_ conditional
*       04-26-91  SRW   Removed level 3 warnings
*       05-14-91  GJF   Turn on exception handling for Dosx32.
*       05-22-91  GJF   Fixed careless errors.
*       07-12-91  GJF   Fixed one more careless error.
*       08-13-91  GJF   Removed definitions of _confh and _coninpfh.
*       09-13-91  GJF   Incorporated Stevewo's startup variations.
*       11-07-91  GJF   Revised try-except, fixed outdated comments on file
*                       handle inheritance [_WIN32_].
*       12-02-91  SRW   Fixed WinMain startup code to skip over first token
*                       plus delimiters for the lpszCommandLine parameter.
*       01-17-92  GJF   Merge of NT and CRT version. Restored Stevewo's scheme
*                       for unhandled exceptions.
*       02-13-92  GJF   For Win32, moved file inheritance stuff to ioinit.c.
*                       Call to inherit() is replace by call to _ioinit().
*       04-16-92  DJM   POSIX support
*       08-26-92  SKS   Add _osver, _winver, _winmajor, _winminor
*       08-26-92  GJF   Deleted version number(s) fetch from POSIX startup (it
*                       involved a Win32 API call).
*	09-30-92  SRW	Call _heap_init before _mtinit
*	04-26-93  GJF	Made lpszCommandLine (unsigned char *) to deal with
*			chars > 127 in the command line.
*	04-27-93  GJF	Removed support for _RT_STACK, _RT_INTDIV,
*			_RT_INVALDISP and _RT_NONCONT.
*	05-11-93  SKS	Remove obsolete variable _atopsp
*			Change _mtinit to return failure
*	05-14-93  GJF	Added support for quoted program names.
*
*******************************************************************************/

#include <cruntime.h>
#include <dos.h>
#include <internal.h>
#include <stdlib.h>
#include <string.h>
#ifndef _POSIX_
#include <rterr.h>
#else
#include <posix/sys/types.h>
#include <posix/unistd.h>
#include <posix/signal.h>
#endif
#include <oscalls.h>

#ifdef  _CRUISER_
/*
 * C file info string
 */
char _acfinfo[] = "_C_FILE_INFO=";
#endif  /* _CRUISER_ */

/*
 * command line, environment, and a few other globals
 */
char *_acmdln;          /* points to command line */
char *_aenvptr;         /* points to environment block */

#ifdef _POSIX_
char *_cmdlin;
#endif

void (_CRTAPI1 * _aexit_rtn)(int) = _exit;   /* RT message return procedure */

#ifdef  _CRUISER_
static void _CRTAPI3 inherit(void);  /* local function */
#endif  /* _CRUISER_ */

#ifndef _MAC_

#ifdef _POSIX_

/***
*mainCRTStartup(PVOID Peb)
*
*Purpose:
*       This routine does the C runtime initialization, calls main(), and
*       then exits.  It never returns.
*
*Entry:
*       PVOID Peb - pointer to Win32 Process Environment Block (not used)
*
*Exit:
*       This function never returns.
*
*******************************************************************************/

void
mainCRTStartup(
        void
        )
{
        int mainret;
        char **ppch;

        extern char **environ;
	extern char * __PdxGetCmdLine(void);  /* a hacked API in the Posix SS */
	extern main(int,char**);

	_cmdlin = __PdxGetCmdLine();
        ppch = (char **)_cmdlin;
        __argv = ppch;

        // normalize argv pointers

        __argc = 0;
        while (NULL != *ppch) {
                *ppch += (int)_cmdlin;
                ++__argc;
                ++ppch;
        }
        // normalize environ pointers

        ++ppch;
        environ = ppch;

        while (NULL != *ppch) {
                *ppch = *ppch + (int)_cmdlin;
                ++ppch;
        }

        /*
         * If POSIX runtime needs to fetch and store POSIX verion info,
         * it should be done here.
         *
         *      Get_and_save_version_info;
         */

        _heap_init();                           /* initialize heap */
        _cinit();                               /* do C data initialize */

	try {
        	mainret = main(__argc, __argv);
	} except (EXCEPTION_EXECUTE_HANDLER) {
		switch (GetExceptionCode()) {
		case STATUS_ACCESS_VIOLATION:
			kill(getpid(), SIGSEGV);
			break;
		case STATUS_ILLEGAL_INSTRUCTION:
		case STATUS_PRIVILEGED_INSTRUCTION:
			kill(getpid(), SIGILL);
			break;
		case STATUS_FLOAT_DENORMAL_OPERAND:
		case STATUS_FLOAT_DIVIDE_BY_ZERO:
		case STATUS_FLOAT_INEXACT_RESULT:
		case STATUS_FLOAT_OVERFLOW:
		case STATUS_FLOAT_STACK_CHECK:
		case STATUS_FLOAT_UNDERFLOW:
			kill(getpid(), SIGFPE);
			break;
		default:
			kill(getpid(), SIGKILL);
		}

		mainret = -1;
	}
        exit(mainret);
}
#else   /* ndef _POSIX_ */

#ifdef  _CRUISER_

/***
*__crt0(cmdline, envptr)
*
*Purpose:
*       This routine does the C runtime initialization, calls main(), and
*       then exits.  It never returns.
*
*Entry:
*       char *cmdline - pointer to OS/2 command line
*       char *envptr - pointer to OS/2 environment block
*
*Exit:
*       This function never returns.
*
*******************************************************************************/

void _CRTAPI1 __crt0 (
        char *cmdline,
        char *envptr
        )
{
        int mainret;

        /* initialize pointers to command line and environment */
        _acmdln = cmdline;
        _aenvptr = envptr;

        /* Get the OS/2 version */

        /* make sure our assumptions are correct */

#if  (_QSV_VERSION_MAJOR+1 != _QSV_VERSION_MINOR)
#error Invalid DosQuerySysInfo parameters
#endif

        DOSQUERYSYSINFO(_QSV_VERSION_MAJOR, _QSV_VERSION_MINOR,
        (unsigned char *)&_osmajor, (2*sizeof(int)) );

#else   /* ndef _CRUISER_ */

#ifdef  _WIN32_

/***
*BaseProcessStartup(PVOID Peb)
*
*Purpose:
*       This routine does the C runtime initialization, calls main(), and
*       then exits.  It never returns.
*
*Entry:
*       PVOID Peb - pointer to Win32 Process Environment Block (not used)
*
*Exit:
*       This function never returns.
*
*******************************************************************************/

#ifdef  _DOSX32_

void _BaseProcessStartup (

#else

#ifdef _WINMAIN_
void WinMainCRTStartup(
#else
void mainCRTStartup(
#endif

#endif
        void
        )

{
        int mainret;

#ifdef _WINMAIN_
	unsigned char *lpszCommandLine;
        STARTUPINFOA StartupInfo;
#endif
        _acmdln = (char *)GetCommandLine();
        _aenvptr = (char *)GetEnvironmentStrings();

        /*
         * Get the full Win32 version
         */
        _osversion =                            /* OBSOLETE */
        _osver = GetVersion();

        _winminor = (_osver >> 8) & 0x00FF ;
        _winmajor = _osver & 0x00FF ;
        _winver = (_winmajor << 8) + _winminor;
        _osver = (_osver >> 16) & 0x00FFFF ;

        /* --------- The following block is OBSOLETE --------- */

        /*
         * unpack base version info
         */
        _baseversion = (_osversion & 0xFFFF0000) >> 16;
        _baseminor = _baseversion & 0x00FF;
        _basemajor = (_baseversion & 0xFF00) >> 8;

        /*
         * unpack top-level version info (Windows version)
         */
        _osversion &= 0x0000FFFF;
        _osmajor = _osversion & 0x00FF;
        _osminor = (_osversion & 0xFF00) >> 8;

        /* --------- The preceding block is OBSOLETE --------- */

#else   /* ndef _WIN32_ */

#error ERROR - ONLY CRUISER OR WIN32 TARGET SUPPORTED!

#endif  /* _WIN32_ */

#endif  /* _CRUISER_ */

        _heap_init();                           /* initialize heap */
#ifdef MTHREAD
        if(!_mtinit())				/* initialize multi-thread */
		_amsg_exit(_RT_THREAD); 	/* write message and die */
#endif
#ifdef  _WIN32_
        _ioinit();                              /* initialize lowio */
#else   /* ndef _WIN32_ */
#ifdef  _CRUISER_
        inherit();                              /* inherit file info */
#endif  /* _CRUISER_ */
#endif  /* _WIN32_ */
        _setargv();                             /* get cmd line info */
        _setenvp();                             /* get environ info */

        _cinit();                               /* do C data initialize */

        /* now call the main program, and then exit with the return value
           we get back */

        /*
         * NOTE: THERE MUST BE NO PROTOTYPE FOR THE main() FUNCTION IF THIS
         * IS BUILT FOR THE 386 WITH _stdcall AS THE DEFAULT CALLING TYPE!
         * OTHERWISE, THE STACK WILL NOT BE PROPERLY RESTORED AFTER THE CALL
         * BELOW. WE MIGHT GET AWAY WITH THIS, SINCE WE EXIT RIGHT AWAY, BUT
         * THERE IS NO POINT IN ASKING FOR TROUBLE.
         */

#ifdef  _CRUISER_

        _try {
                mainret = main(__argc, __argv, _environ);
        }
        _except ( _XcptFilter(_exception_code(), _exception_info()) )
        {
                switch( _exception_code() ) {

                        case _XCPT_UNABLE_TO_GROW_STACK :
                                _amsg_exit(_RT_STACK);

                        case _XCPT_INTEGER_DIVIDE_BY_ZERO :
                                /*
                                 * NOTE: THIS IS WHERE cintDIV WENT!
                                 *
                                 * exit via high-level exit function
                                 */
                                _aexit_rtn = exit;
                                _amsg_exit(_RT_INTDIV);

                        case _XCPT_INVALID_DISPOSITION :
                                /*
                                 * this exception should never occur. if it
                                 * does, it would have to be a bug in the
                                 * runtime support for signal() or SEH.
                                 */
                                _amsg_exit(_RT_INVALDISP);

                        case _XCPT_NONCONTINUABLE_EXCEPTION :
                                /*
                                 * this exception could possibly occur as the
                                 * result of a bad user exception filter or
                                 * an error in _XcptFilter().
                                 */
                                _amsg_exit(_RT_NONCONT);

                        case _XCPT_SIGABRT :
                                /*
                                 * no message is printed unless abort() was
                                 * called in which case, abort() prints out
                                 * the termination message before raising the
                                 * signal
                                 */
                                _exit(3);

                        default :
                                /*
                                 * no default action, should never get here
                                 */
                                ;
                } /* end of switch */

        } /* end of _try - _except */

#else   /* ndef _CRUISER_ */

#ifdef  _WIN32_

        try {
#ifdef _WINMAIN_
                /*
		 * Skip past program name (first token in command line).
		 * Check for and handle quoted program name.
                 */
		lpszCommandLine = (unsigned char *)_acmdln;

		if ( *lpszCommandLine == '\"' ) {
		    /*
		     * Scan, and skip over, subsequent characters until
		     * another double-quote or a null is encountered.
		     */
		    while ( *++lpszCommandLine && (*lpszCommandLine
			     != '\"') );
		    /*
		     * If we stopped on a double-quote (usual case), skip
		     * over it.
		     */
		    if ( *lpszCommandLine == '\"' )
			lpszCommandLine++;
		}
		else {
		    while (*lpszCommandLine > ' ')
			lpszCommandLine++;
                }

                /*
                 * Skip past any white space preceeding the second token.
                 */
                while (*lpszCommandLine && (*lpszCommandLine <= ' ')) {
                    lpszCommandLine++;
                }

                StartupInfo.dwFlags = 0;
                GetStartupInfoA( &StartupInfo );

                mainret = WinMain( GetModuleHandle(NULL),
                                   NULL,
                                   lpszCommandLine,
                                   StartupInfo.dwFlags & STARTF_USESHOWWINDOW
                                        ? StartupInfo.wShowWindow
                                        : SW_SHOWDEFAULT
                                 );
#else
                mainret = main(__argc, __argv, _environ);
#endif
                exit(mainret);
        }
        except ( _XcptFilter(GetExceptionCode(), GetExceptionInformation()) )
	{
		/*
		 * Should never reach here
		 */
		_exit( GetExceptionCode() );

        } /* end of try - except */

#else   /* ndef _WIN32_ */

#error ERROR - ONLY CRUISER, WIN32, MAC, OR POSIX TARGET SUPPORTED!

#endif  /* _WIN32_ */

#endif  /* _CRUISER_ */

}

#endif  /* _POSIX_ */

#endif  /* ndef _MAC_ */


#ifdef  _CRUISER_

/***
*inherit() - obtain and process info on inherited file handles.
*
*Purpose:
*
*       Locates and interprets the C_FILE_INFO environment variable.
*
*       The value of the variable is written into the "_osfile" array.
*
*       Format:  _C_FILE_INFO=<AA><BB><CC><DD>...
*
*       This variable is a environment variable where each pair of
*       successive letters from one byte in _osfile.  The letters are
*       in the reange "A" through "P" representing the 0 though 15.
*       The first letter of each pair is the more significant 4 bits
*       of the result.
*
*Entry:
*       No parameters: reads the environment.
*
*Exit:
*       No return value.
*
*Exceptions:
*
*******************************************************************************/

static void _CRTAPI3 inherit (
        void
        )
{
        char *p;                        /* pointer to environment strings */
        unsigned char byte;             /* byte we build up */
        int fh;                         /* handle we're on */

        p = _aenvptr;
        while (*p != '\0') {
                if (strncmp(p, _acfinfo, CFI_LENGTH + 1) == 0) {
                        /* found the _C_FILE_INFO string, now parse it */
                        p += CFI_LENGTH + 1;            /* point to value */
                        fh = 0;
                        do
                        {
                                byte = (*p++ - 'A') << 4;
                                byte += *p++ - 'A';     /* read byte */
                                _osfile[fh++] = byte;
                        }
                        while(byte);

                        break;
                }
                else
                        p += strlen(p) + 1;     /* advance to next string */
        }
}

#endif  /* _CRUISER_ */


/***
*_amsg_exit(rterrnum) - Fast exit fatal errors
*
*Purpose:
*       Exit the program with error code of 255 and appropriate error
*       message.
*
*Entry:
*       int rterrnum - error message number (amsg_exit only).
*
*Exit:
*       Calls exit() (for integer divide-by-0) or _exit() indirectly
*       through _aexit_rtn [amsg_exit].
*       For multi-thread: calls _exit() function
*
*Exceptions:
*
*******************************************************************************/

void _CRTAPI1 _amsg_exit (
        int rterrnum
        )
{
        _FF_MSGBANNER();                        /* write run-time error banner */
        _NMSG_WRITE(rterrnum);                  /* write message */

        _aexit_rtn(255);                        /* normally _exit(255) */
}

#ifdef _POSIX_

/***
*RaiseException() - stub for posix FP routines
*
*Purpose:
*       Stub of a Win32 API that posix can't call
*
*Entry:
*
*Exit:
*
*Exceptions:
*
*******************************************************************************/

VOID
WINAPI
RaiseException(
    DWORD dwExceptionCode,
    DWORD dwExceptionFlags,
    DWORD nNumberOfArguments,
    LPDWORD lpArguments
    )
{
}

#endif  /* _POSIX_ */