xref: /freebsd/usr.sbin/btxld/btxld.c (revision 23f282aa31e9b6fceacd449020e936e98d6f2298)
1 /*
2  * Copyright (c) 1998 Robert Nordier
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  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
18  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
19  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
20  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
21  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
22  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
23  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
24  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #ifndef lint
28 static const char rcsid[] =
29   "$FreeBSD$";
30 #endif /* not lint */
31 
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/mman.h>
35 
36 #include <err.h>
37 #include <errno.h>
38 #include <fcntl.h>
39 #include <stdarg.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 
45 #include <a.out.h>
46 
47 #include "btx.h"
48 #include "elfh.h"
49 
50 #define BTX_PATH		"/sys/boot/i386/btx"
51 
52 #define I_LDR	0		/* BTX loader */
53 #define I_BTX	1		/* BTX kernel */
54 #define I_CLNT	2		/* Client program */
55 
56 #define F_BIN	0		/* Binary */
57 #define F_AOUT	1		/* ZMAGIC a.out */
58 #define F_ELF	2		/* 32-bit ELF */
59 #define F_CNT	3		/* Number of formats */
60 
61 #define IMPURE	1		/* Writable text */
62 #define MAXU32	0xffffffff	/* Maximum unsigned 32-bit quantity */
63 
64 #define align(x, y) (((x) + (y) - 1) & ~((y) - 1))
65 
66 struct hdr {
67     uint32_t fmt;		/* Format */
68     uint32_t flags;		/* Bit flags */
69     uint32_t size;		/* Size of file */
70     uint32_t text;		/* Size of text segment */
71     uint32_t data;		/* Size of data segment */
72     uint32_t bss;		/* Size of bss segment */
73     uint32_t org;		/* Program origin */
74     uint32_t entry;		/* Program entry point */
75 };
76 
77 static const char *const fmtlist[] = {"bin", "aout", "elf"};
78 
79 static const char binfo[] =
80     "kernel: ver=%u.%02u size=%x load=%x entry=%x map=%uM "
81     "pgctl=%x:%x\n";
82 static const char cinfo[] =
83     "client: fmt=%s size=%x text=%x data=%x bss=%x entry=%x\n";
84 static const char oinfo[] =
85     "output: fmt=%s size=%x text=%x data=%x org=%x entry=%x\n";
86 
87 static const char *lname =
88     BTX_PATH "/btxldr/btxldr";	/* BTX loader */
89 static const char *bname =
90     BTX_PATH "/btx/btx";	/* BTX kernel */
91 static const char *oname =
92     "a.out";			/* Output filename */
93 
94 static int ppage = -1;		/* First page present */
95 static int wpage = -1;		/* First page writable */
96 
97 static unsigned int format; 	/* Output format */
98 
99 static uint32_t centry; 	/* Client entry address */
100 static uint32_t lentry; 	/* Loader entry address */
101 
102 static int Eflag;		/* Client entry option */
103 
104 static int quiet;		/* Inhibit warnings */
105 static int verbose;		/* Display information */
106 
107 static const char *tname;	/* Temporary output file */
108 static const char *fname;	/* Current input file */
109 
110 static void cleanup(void);
111 static void btxld(const char *);
112 static void getbtx(int, struct btx_hdr *);
113 static void gethdr(int, struct hdr *);
114 static void puthdr(int, struct hdr *);
115 static void copy(int, int, size_t, off_t);
116 static size_t readx(int, void *, size_t, off_t);
117 static void writex(int, const void *, size_t);
118 static void seekx(int, off_t);
119 static unsigned int optfmt(const char *);
120 static uint32_t optaddr(const char *);
121 static int optpage(const char *, int);
122 static void Warn(const char *, const char *, ...);
123 static void usage(void);
124 
125 /*
126  * A link editor for BTX clients.
127  */
128 int
129 main(int argc, char *argv[])
130 {
131     int c;
132 
133     while ((c = getopt(argc, argv, "qvb:E:e:f:l:o:P:W:")) != -1)
134 	switch (c) {
135 	case 'q':
136 	    quiet = 1;
137 	    break;
138 	case 'v':
139 	    verbose = 1;
140 	    break;
141 	case 'b':
142 	    bname = optarg;
143 	    break;
144 	case 'E':
145 	    centry = optaddr(optarg);
146 	    Eflag = 1;
147 	    break;
148 	case 'e':
149 	    lentry = optaddr(optarg);
150 	    break;
151 	case 'f':
152 	    format = optfmt(optarg);
153 	    break;
154 	case 'l':
155 	    lname = optarg;
156 	    break;
157 	case 'o':
158 	    oname = optarg;
159 	    break;
160 	case 'P':
161 	    ppage = optpage(optarg, 1);
162 	    break;
163 	case 'W':
164 	    wpage = optpage(optarg, BTX_MAXCWR);
165 	    break;
166 	default:
167 	    usage();
168 	}
169     argc -= optind;
170     argv += optind;
171     if (argc != 1)
172 	usage();
173     atexit(cleanup);
174     btxld(*argv);
175     return 0;
176 }
177 
178 /*
179  * Clean up after errors.
180  */
181 static void
182 cleanup(void)
183 {
184     if (tname)
185 	remove(tname);
186 }
187 
188 /*
189  * Read the input files; write the output file; display information.
190  */
191 static void
192 btxld(const char *iname)
193 {
194     char name[FILENAME_MAX];
195     struct btx_hdr btx;
196     struct hdr ihdr, ohdr;
197     unsigned int ldr_size, cwr;
198     int fdi[3], fdo, i;
199 
200     ldr_size = 0;
201 
202     for (i = I_LDR; i <= I_CLNT; i++) {
203 	fname = i == I_LDR ? lname : i == I_BTX ? bname : iname;
204 	if ((fdi[i] = open(fname, O_RDONLY)) == -1)
205 	    err(2, "%s", fname);
206 	switch (i) {
207 	case I_LDR:
208 	    gethdr(fdi[i], &ihdr);
209 	    if (ihdr.fmt != F_BIN)
210 		Warn(fname, "Loader format is %s; processing as %s",
211 		     fmtlist[ihdr.fmt], fmtlist[F_BIN]);
212 	    ldr_size = ihdr.size;
213 	    break;
214 	case I_BTX:
215 	    getbtx(fdi[i], &btx);
216 	    break;
217 	case I_CLNT:
218 	    gethdr(fdi[i], &ihdr);
219 	    if (ihdr.org && ihdr.org != BTX_PGSIZE)
220 		Warn(fname,
221 		     "Client origin is 0x%x; expecting 0 or 0x%x",
222 		     ihdr.org, BTX_PGSIZE);
223 	}
224     }
225     memset(&ohdr, 0, sizeof(ohdr));
226     ohdr.fmt = format;
227     ohdr.text = ldr_size;
228     ohdr.data = btx.btx_textsz + ihdr.size;
229     ohdr.org = lentry;
230     ohdr.entry = lentry;
231     cwr = 0;
232     if (wpage > 0 || (wpage == -1 && !(ihdr.flags & IMPURE))) {
233 	if (wpage > 0)
234 	    cwr = wpage;
235 	else {
236 	    cwr = howmany(ihdr.text, BTX_PGSIZE);
237 	    if (cwr > BTX_MAXCWR)
238 		cwr = BTX_MAXCWR;
239 	}
240     }
241     if (ppage > 0 || (ppage && wpage && ihdr.org >= BTX_PGSIZE)) {
242 	btx.btx_flags |= BTX_MAPONE;
243 	if (!cwr)
244 	    cwr++;
245     }
246     btx.btx_pgctl -= cwr;
247     btx.btx_entry = Eflag ? centry : ihdr.entry;
248     if (snprintf(name, sizeof(name), "%s.tmp", oname) >= sizeof(name))
249 	errx(2, "%s: Filename too long", oname);
250     if ((fdo = open(name, O_CREAT | O_TRUNC | O_WRONLY, 0666)) == -1)
251 	err(2, "%s", name);
252     if (!(tname = strdup(name)))
253 	err(2, NULL);
254     puthdr(fdo, &ohdr);
255     for (i = I_LDR; i <= I_CLNT; i++) {
256 	fname = i == I_LDR ? lname : i == I_BTX ? bname : iname;
257 	switch (i) {
258 	case I_LDR:
259 	    copy(fdi[i], fdo, ldr_size, 0);
260 	    seekx(fdo, ohdr.size += ohdr.text);
261 	    break;
262 	case I_BTX:
263 	    writex(fdo, &btx, sizeof(btx));
264 	    copy(fdi[i], fdo, btx.btx_textsz - sizeof(btx),
265 		 sizeof(btx));
266 	    break;
267 	case I_CLNT:
268 	    copy(fdi[i], fdo, ihdr.size, 0);
269 	    if (ftruncate(fdo, ohdr.size += ohdr.data))
270 		err(2, "%s", tname);
271 	}
272 	if (close(fdi[i]))
273 	    err(2, "%s", fname);
274     }
275     if (close(fdo))
276 	err(2, "%s", tname);
277     if (rename(tname, oname))
278 	err(2, "%s: Can't rename to %s", tname, oname);
279     tname = NULL;
280     if (verbose) {
281 	printf(binfo, btx.btx_majver, btx.btx_minver, btx.btx_textsz,
282 	       BTX_ORIGIN(btx), BTX_ENTRY(btx), BTX_MAPPED(btx) *
283 	       BTX_PGSIZE / 0x100000, !!(btx.btx_flags & BTX_MAPONE),
284 	       BTX_MAPPED(btx) - btx.btx_pgctl - BTX_PGBASE /
285 	       BTX_PGSIZE - BTX_MAPPED(btx) * 4 / BTX_PGSIZE);
286 	printf(cinfo, fmtlist[ihdr.fmt], ihdr.size, ihdr.text,
287 	       ihdr.data, ihdr.bss, ihdr.entry);
288 	printf(oinfo, fmtlist[ohdr.fmt], ohdr.size, ohdr.text,
289 	       ohdr.data, ohdr.org, ohdr.entry);
290     }
291 }
292 
293 /*
294  * Read BTX file header.
295  */
296 static void
297 getbtx(int fd, struct btx_hdr * btx)
298 {
299     if (readx(fd, btx, sizeof(*btx), 0) != sizeof(*btx) ||
300 	btx->btx_magic[0] != BTX_MAG0 ||
301 	btx->btx_magic[1] != BTX_MAG1 ||
302 	btx->btx_magic[2] != BTX_MAG2)
303 	errx(1, "%s: Not a BTX kernel", fname);
304 }
305 
306 /*
307  * Get file size and read a.out or ELF header.
308  */
309 static void
310 gethdr(int fd, struct hdr *hdr)
311 {
312     struct stat sb;
313     const struct exec *ex;
314     const Elf32_Ehdr *ee;
315     const Elf32_Phdr *ep;
316     void *p;
317     unsigned int fmt, x, n, i;
318 
319     memset(hdr, 0, sizeof(*hdr));
320     if (fstat(fd, &sb))
321 	err(2, "%s", fname);
322     if (sb.st_size > MAXU32)
323 	errx(1, "%s: Too big", fname);
324     hdr->size = sb.st_size;
325     if ((p = mmap(NULL, hdr->size, PROT_READ, MAP_SHARED, fd,
326 		  0)) == MAP_FAILED)
327 	err(2, "%s", fname);
328     for (fmt = F_CNT - 1; !hdr->fmt && fmt; fmt--)
329 	switch (fmt) {
330 	case F_AOUT:
331 	    ex = p;
332 	    if (hdr->size >= sizeof(struct exec) && !N_BADMAG(*ex)) {
333 		hdr->fmt = fmt;
334 		x = N_GETMAGIC(*ex);
335 		if (x == OMAGIC || x == NMAGIC) {
336 		    if (x == NMAGIC)
337 			Warn(fname, "Treating %s NMAGIC as OMAGIC",
338 			     fmtlist[fmt]);
339 		    hdr->flags |= IMPURE;
340 		}
341 		hdr->text = ex->a_text;
342 		hdr->data = ex->a_data;
343 		hdr->bss = ex->a_bss;
344 		hdr->entry = ex->a_entry;
345 		if (ex->a_entry >= BTX_PGSIZE)
346 		    hdr->org = BTX_PGSIZE;
347 	    }
348 	    break;
349 	case F_ELF:
350 	    ee = p;
351 	    if (hdr->size >= sizeof(Elf32_Ehdr) && IS_ELF(*ee)) {
352 		hdr->fmt = fmt;
353 		for (n = i = 0; i < ee->e_phnum; i++) {
354 		    ep = (void *)((uint8_t *)p + ee->e_phoff +
355 				  ee->e_phentsize * i);
356 		    if (ep->p_type == PT_LOAD)
357 			switch (n++) {
358 			case 0:
359 			    hdr->text = ep->p_filesz;
360 			    hdr->org = ep->p_paddr;
361 			    if (ep->p_flags & PF_W)
362 				hdr->flags |= IMPURE;
363 			    break;
364 			case 1:
365 			    hdr->data = ep->p_filesz;
366 			    hdr->bss = ep->p_memsz - ep->p_filesz;
367 			    break;
368 			case 2:
369 			    Warn(fname,
370 				 "Ignoring extra %s PT_LOAD segments",
371 				 fmtlist[fmt]);
372 			}
373 		}
374 		hdr->entry = ee->e_entry;
375 	    }
376 	}
377     if (munmap(p, hdr->size))
378 	err(2, "%s", fname);
379 }
380 
381 /*
382  * Write a.out or ELF header.
383  */
384 static void
385 puthdr(int fd, struct hdr *hdr)
386 {
387     struct exec ex;
388     struct elfh eh;
389 
390     switch (hdr->fmt) {
391     case F_AOUT:
392 	memset(&ex, 0, sizeof(ex));
393 	N_SETMAGIC(ex, ZMAGIC, MID_ZERO, 0);
394 	hdr->text = N_ALIGN(ex, hdr->text);
395 	ex.a_text = hdr->text;
396 	hdr->data = N_ALIGN(ex, hdr->data);
397 	ex.a_data = hdr->data;
398 	ex.a_entry = hdr->entry;
399 	writex(fd, &ex, sizeof(ex));
400 	hdr->size = N_ALIGN(ex, sizeof(ex));
401 	seekx(fd, hdr->size);
402 	break;
403     case F_ELF:
404 	eh = elfhdr;
405 	eh.e.e_entry = hdr->entry;
406 	eh.p[0].p_vaddr = eh.p[0].p_paddr = hdr->org;
407 	eh.p[0].p_filesz = eh.p[0].p_memsz = hdr->text;
408 	eh.p[1].p_offset = eh.p[0].p_offset + eh.p[0].p_filesz;
409 	eh.p[1].p_vaddr = eh.p[1].p_paddr = align(eh.p[0].p_paddr +
410 						  eh.p[0].p_memsz, 4);
411 	eh.p[1].p_filesz = eh.p[1].p_memsz = hdr->data;
412 	eh.sh[2].sh_addr = eh.p[0].p_vaddr;
413 	eh.sh[2].sh_offset = eh.p[0].p_offset;
414 	eh.sh[2].sh_size = eh.p[0].p_filesz;
415 	eh.sh[3].sh_addr = eh.p[1].p_vaddr;
416 	eh.sh[3].sh_offset = eh.p[1].p_offset;
417 	eh.sh[3].sh_size = eh.p[1].p_filesz;
418 	writex(fd, &eh, sizeof(eh));
419 	hdr->size = sizeof(eh);
420     }
421 }
422 
423 /*
424  * Safe copy from input file to output file.
425  */
426 static void
427 copy(int fdi, int fdo, size_t nbyte, off_t offset)
428 {
429     char buf[8192];
430     size_t n;
431 
432     while (nbyte) {
433 	if ((n = sizeof(buf)) > nbyte)
434 	    n = nbyte;
435 	if (readx(fdi, buf, n, offset) != n)
436 	    errx(2, "%s: Short read", fname);
437 	writex(fdo, buf, n);
438 	nbyte -= n;
439 	offset = -1;
440     }
441 }
442 
443 /*
444  * Safe read from input file.
445  */
446 static size_t
447 readx(int fd, void *buf, size_t nbyte, off_t offset)
448 {
449     ssize_t n;
450 
451     if (offset != -1 && lseek(fd, offset, SEEK_SET) != offset)
452 	err(2, "%s", fname);
453     if ((n = read(fd, buf, nbyte)) == -1)
454 	err(2, "%s", fname);
455     return n;
456 }
457 
458 /*
459  * Safe write to output file.
460  */
461 static void
462 writex(int fd, const void *buf, size_t nbyte)
463 {
464     ssize_t n;
465 
466     if ((n = write(fd, buf, nbyte)) == -1)
467 	err(2, "%s", tname);
468     if (n != nbyte)
469 	errx(2, "%s: Short write", tname);
470 }
471 
472 /*
473  * Safe seek in output file.
474  */
475 static void
476 seekx(int fd, off_t offset)
477 {
478     if (lseek(fd, offset, SEEK_SET) != offset)
479 	err(2, "%s", tname);
480 }
481 
482 /*
483  * Convert an option argument to a format code.
484  */
485 static unsigned int
486 optfmt(const char *arg)
487 {
488     unsigned int i;
489 
490     for (i = 0; i < F_CNT && strcmp(arg, fmtlist[i]); i++);
491     if (i == F_CNT)
492 	errx(1, "%s: Unknown format", arg);
493     return i;
494 }
495 
496 /*
497  * Convert an option argument to an address.
498  */
499 static uint32_t
500 optaddr(const char *arg)
501 {
502     char *s;
503     unsigned long x;
504 
505     errno = 0;
506     x = strtoul(arg, &s, 0);
507     if (errno || !*arg || *s || x > MAXU32)
508 	errx(1, "%s: Illegal address", arg);
509     return x;
510 }
511 
512 /*
513  * Convert an option argument to a page number.
514  */
515 static int
516 optpage(const char *arg, int hi)
517 {
518     char *s;
519     long x;
520 
521     errno = 0;
522     x = strtol(arg, &s, 0);
523     if (errno || !*arg || *s || x < 0 || x > hi)
524 	errx(1, "%s: Illegal page number", arg);
525     return x;
526 }
527 
528 /*
529  * Display a warning.
530  */
531 static void
532 Warn(const char *locus, const char *fmt, ...)
533 {
534     va_list ap;
535     char *s;
536 
537     if (!quiet) {
538 	asprintf(&s, "%s: Warning: %s", locus, fmt);
539 	va_start(ap, fmt);
540 	vwarnx(s, ap);
541 	va_end(ap);
542 	free(s);
543     }
544 }
545 
546 /*
547  * Display usage information.
548  */
549 static void
550 usage(void)
551 {
552     fprintf(stderr, "%s\n%s\n",
553     "usage: btxld [-qv] [-b file] [-E address] [-e address] [-f format]",
554     "             [-l file] [-o filename] [-P page] [-W page] file");
555     exit(1);
556 }
557