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