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