Initial import from FreeBSD RELENG_4:
[dragonfly.git] / lib / csu / i386 / crt0.c
1 /*
2  * Copyright (c) 1993 Paul Kranenburg
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by Paul Kranenburg.
16  * 4. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  * $FreeBSD: src/lib/csu/i386/crt0.c,v 1.36 1999/08/27 23:57:55 peter Exp $
31  */
32
33 #include <sys/param.h>
34
35 #include <stdlib.h>
36
37 #ifdef DYNAMIC
38 #include <sys/types.h>
39 #include <sys/syscall.h>
40 #include <a.out.h>
41 #include <string.h>
42 #include <sys/mman.h>
43 #include <link.h>
44
45 /* !!!
46  * This is gross, ld.so is a ZMAGIC a.out, but has `sizeof(hdr)' for
47  * an entry point and not at PAGSIZ as the N_*ADDR macros assume.
48  */
49 #undef N_DATADDR
50 #define N_DATADDR(x)    ((x).a_text)
51
52 #undef N_BSSADDR
53 #define N_BSSADDR(x)    ((x).a_text + (x).a_data)
54
55 #ifndef N_GETMAGIC
56 #define N_GETMAGIC(x)   ((x).a_magic)
57 #endif /* N_GETMAGIC */
58
59 #ifndef MAP_PRIVATE
60 #define MAP_PRIVATE     MAP_COPY
61 #endif /* MAP_PRIVATE */
62
63 #ifndef MAP_FILE
64 #define MAP_FILE        0
65 #endif /* MAP_FILE */
66
67 #ifndef MAP_ANON
68 #define MAP_ANON        0
69 #endif /* MAP_ANON */
70
71 #ifdef DEBUG 
72 /*
73  * We need these two because we are going to call them before the ld.so is
74  * finished (as a matter of fact before we know if it exists !) so we must
75  * provide these versions for them
76  */
77 static char             *_getenv();
78 static int              _strncmp();
79 #endif /* DEBUG */
80
81 #ifndef LDSO
82 #define LDSO            "/usr/libexec/ld.so"
83 #endif /* LDSO */
84
85 extern struct _dynamic  _DYNAMIC;
86 static void             __do_dynamic_link(char **argv);
87 #endif /* DYNAMIC */
88
89 int                     _callmain();
90 int                     errno;
91 static char             empty[1];
92 char                    *__progname = empty;
93 char                    **environ;
94
95 /* Globals used by dlopen() and related functions in libc */
96 struct ld_entry         *__ldso_entry;
97 int                     __ldso_version;
98
99 extern  unsigned char   etext;
100 extern  unsigned char   eprol asm ("eprol");
101 extern                  start() asm("start");
102 extern                  mcount() asm ("mcount");
103 extern  int             main(int argc, char **argv, char **envp);
104 int                     __syscall(int syscall,...);
105 #ifdef MCRT0
106 void                    monstartup(void *low, void *high);
107 #endif /* MCRT0 */
108
109
110 /*
111  * We need these system calls, but can't use library stubs because the are
112  * not accessible until we have done the ld.so stunt.
113  */
114
115 #define _exit(v) \
116         __syscall(SYS_exit, (int)(v))
117 #define _open(name, f, m) \
118         __syscall(SYS_open, (const char *)(name), (int)(f), (int)(m))
119 #define _read(fd, s, n) \
120         __syscall(SYS_read, (int)(fd), (void *)(s), (size_t)(n))
121 #define _write(fd, s, n) \
122         __syscall(SYS_write, (int)(fd), (const void *)(s), (size_t)(n))
123 #define _mmap(addr, len, prot, flags, fd, off)  \
124         (void *) __syscall(SYS_mmap, (void *)(addr), (size_t)(len), \
125                 (int)(prot), (int)(flags), (int)(fd), 0, (off_t)(off))
126
127 #define _PUTNMSG(str, len)      _write(2, (str), (len))
128 #define _PUTMSG(str)            _PUTNMSG((str), sizeof (str) - 1)
129 #define _FATAL(str)             ( _PUTMSG(str), _exit(1) )
130
131
132 int
133 start()
134 {
135         struct kframe {
136                 int     kargc;
137                 char    *kargv[1];      /* size depends on kargc */
138                 char    kargstr[1];     /* size varies */
139                 char    kenvstr[1];     /* size varies */
140         };
141         /*
142          *      ALL REGISTER VARIABLES!!!
143          */
144         register struct kframe *kfp;
145         register char **targv;
146         register char **argv;
147         extern void _mcleanup();
148 #ifdef DYNAMIC
149         volatile caddr_t x;
150 #endif
151
152 #ifdef lint
153         kfp = 0;
154 #else /* not lint */
155         /* just above the saved frame pointer */
156         asm ("lea 4(%%ebp), %0" : "=r" (kfp) );
157 #endif /* not lint */
158         for (argv = targv = &kfp->kargv[0]; *targv++; /* void */)
159                 /* void */ ;
160         if (targv >= (char **)(*argv))
161                 --targv;
162         environ = targv;
163
164         if (argv[0]) {
165                 register char *s;
166                 __progname = argv[0];
167                 for (s=__progname; *s != '\0'; s++)
168                         if (*s == '/')
169                                 __progname = s+1;
170         }
171
172 #ifdef DYNAMIC
173         /* ld(1) convention: if DYNAMIC = 0 then statically linked */
174         /* sometimes GCC is too smart/stupid for its own good */
175         x = (caddr_t)&_DYNAMIC;
176         if (x)
177                 __do_dynamic_link(argv);
178 #endif /* DYNAMIC */
179
180 asm("eprol:");
181
182 #ifdef MCRT0
183         atexit(_mcleanup);
184         monstartup(&eprol, &etext);
185 #endif /* MCRT0 */
186
187 asm ("__callmain:");            /* Defined for the benefit of debuggers */
188         exit(main(kfp->kargc, argv, environ));
189 }
190
191 #ifdef DYNAMIC
192 static void
193 __do_dynamic_link(argv)
194         char    **argv;
195 {
196         struct crt_ldso crt;
197         struct exec     hdr;
198         char            *ldso;
199         int             (*entry)();
200
201 #ifdef DEBUG
202         /* Provision for alternate ld.so - security risk! */
203         if (!(ldso = _getenv("LDSO")))
204 #endif
205                 ldso = LDSO;
206
207         crt.crt_ldfd = _open(ldso, 0, 0);
208         if (crt.crt_ldfd == -1) {
209                 _PUTMSG("Couldn't open ");
210                 _PUTMSG(LDSO);
211                 _FATAL(".\n");
212         }
213
214         /* Read LDSO exec header */
215         if (_read(crt.crt_ldfd, &hdr, sizeof hdr) < sizeof hdr) {
216                 _FATAL("Failure reading ld.so\n");
217         }
218         if ((N_GETMAGIC_NET(hdr) != ZMAGIC) && (N_GETMAGIC(hdr) != QMAGIC)) {
219                 _FATAL("Bad magic: ld.so\n");
220         }
221
222         /* We use MAP_ANON */
223         crt.crt_dzfd = -1;
224
225         /* Map in ld.so */
226         crt.crt_ba = (int)_mmap(0, hdr.a_text,
227                         PROT_READ|PROT_EXEC,
228                         MAP_FILE|MAP_PRIVATE,
229                         crt.crt_ldfd, N_TXTOFF(hdr));
230         if (crt.crt_ba == -1) {
231                 _FATAL("Cannot map ld.so (text)\n");
232         }
233
234         /* Map in data segment of ld.so writable */
235         if ((int)_mmap((caddr_t)(crt.crt_ba+N_DATADDR(hdr)), hdr.a_data,
236                         PROT_READ|PROT_WRITE,
237                         MAP_FIXED|MAP_FILE|MAP_PRIVATE,
238                         crt.crt_ldfd, N_DATOFF(hdr)) == -1) {
239                 _FATAL("Cannot map ld.so (data)\n");
240         }
241
242         /* Map bss segment of ld.so zero */
243         if (hdr.a_bss && (int)_mmap((caddr_t)(crt.crt_ba+N_BSSADDR(hdr)),
244                         hdr.a_bss,
245                         PROT_READ|PROT_WRITE,
246                         MAP_FIXED|MAP_ANON|MAP_PRIVATE,
247                         crt.crt_dzfd, 0) == -1) {
248                 _FATAL("Cannot map ld.so (bss)\n");
249         }
250
251         crt.crt_dp = &_DYNAMIC;
252         crt.crt_ep = environ;
253         crt.crt_bp = (caddr_t)_callmain;
254         crt.crt_prog = __progname;
255         crt.crt_ldso = ldso;
256         crt.crt_ldentry = NULL;
257         crt.crt_argv = argv;
258
259         entry = (int (*)())(crt.crt_ba + sizeof hdr);
260         __ldso_version = (*entry)(CRT_VERSION_BSD_5, &crt);
261         __ldso_entry = crt.crt_ldentry;
262         if (__ldso_version == -1 && __ldso_entry == NULL) {
263                 /* If version 5 not recognised, try version 4 */
264                 __ldso_version = (*entry)(CRT_VERSION_BSD_4, &crt);
265                 __ldso_entry = crt.crt_ldentry;
266                 if (__ldso_version == -1 && __ldso_entry == NULL) {
267                         /* if version 4 not recognised, try version 3 */
268                         __ldso_version = (*entry)(CRT_VERSION_BSD_3, &crt);
269                         __ldso_entry = _DYNAMIC.d_entry;
270                 }
271         }
272         if (__ldso_version == -1) {
273                 _PUTMSG("ld.so failed");
274                 if (__ldso_entry != NULL) {
275                         const char *msg = (__ldso_entry->dlerror)();
276                         if(msg != NULL) {
277                                 const char *endp;
278                                 _PUTMSG(": ");
279                                 for(endp = msg;  *endp != '\0';  ++endp)
280                                         ;       /* Find the end */
281                                 _PUTNMSG(msg, endp - msg);
282                         }
283                 }
284                 _FATAL("\n");
285         }
286
287
288         if (__ldso_version >= LDSO_VERSION_HAS_DLEXIT)
289                 atexit(__ldso_entry->dlexit);
290
291         return;
292 }
293
294 /*
295  * Support routines
296  */
297
298 #ifdef DEBUG
299 static int
300 _strncmp(s1, s2, n)
301         register char *s1, *s2;
302         register n;
303 {
304
305         if (n == 0)
306                 return (0);
307         do {
308                 if (*s1 != *s2++)
309                         return (*(unsigned char *)s1 - *(unsigned char *)--s2);
310                 if (*s1++ == 0)
311                         break;
312         } while (--n != 0);
313         return (0);
314 }
315
316 static char *
317 _getenv(name)
318         register char *name;
319 {
320         extern char **environ;
321         register int len;
322         register char **P, *C;
323
324         for (C = name, len = 0; *C && *C != '='; ++C, ++len);
325         for (P = environ; *P; ++P)
326                 if (!_strncmp(*P, name, len))
327                         if (*(C = *P + len) == '=') {
328                                 return(++C);
329                         }
330         return (char *)0;
331 }
332
333 #endif /* DEBUG */
334
335         asm("   ___syscall:");
336         asm("           popl %ecx");
337         asm("           popl %eax");
338         asm("           pushl %ecx");
339         asm("           .byte 0x9a");
340         asm("           .long 0");
341         asm("           .word 7");
342         asm("           pushl %ecx");
343         asm("           jc 1f");
344         asm("           ret");
345         asm("   1:");
346         asm("           movl    $-1,%eax");
347         asm("           ret");
348
349 #endif /* DYNAMIC */
350
351
352 /*
353  * Support routines
354  */
355
356 #ifdef MCRT0
357 asm ("  .text");
358 asm ("_eprol:");
359 #endif