xref: /freebsd/usr.sbin/btxld/btxld.c (revision 729362425c09cf6b362366aabc6fb547eee8035a)
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/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 "btx.h"
46 #include "elfh.h"
47 #include "endian.h"
48 #include "i386_a.out.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, btxle;
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 	    btxle = btx;
264 	    btxle.btx_pgctl = HTOLE16(btxle.btx_pgctl);
265 	    btxle.btx_textsz = HTOLE16(btxle.btx_textsz);
266 	    btxle.btx_entry = HTOLE32(btxle.btx_entry);
267 	    writex(fdo, &btxle, sizeof(btxle));
268 	    copy(fdi[i], fdo, btx.btx_textsz - sizeof(btx),
269 		 sizeof(btx));
270 	    break;
271 	case I_CLNT:
272 	    copy(fdi[i], fdo, ihdr.size, 0);
273 	    if (ftruncate(fdo, ohdr.size += ohdr.data))
274 		err(2, "%s", tname);
275 	}
276 	if (close(fdi[i]))
277 	    err(2, "%s", fname);
278     }
279     if (close(fdo))
280 	err(2, "%s", tname);
281     if (rename(tname, oname))
282 	err(2, "%s: Can't rename to %s", tname, oname);
283     tname = NULL;
284     if (verbose) {
285 	printf(binfo, btx.btx_majver, btx.btx_minver, btx.btx_textsz,
286 	       BTX_ORIGIN(btx), BTX_ENTRY(btx), BTX_MAPPED(btx) *
287 	       BTX_PGSIZE / 0x100000, !!(btx.btx_flags & BTX_MAPONE),
288 	       BTX_MAPPED(btx) - btx.btx_pgctl - BTX_PGBASE /
289 	       BTX_PGSIZE - BTX_MAPPED(btx) * 4 / BTX_PGSIZE);
290 	printf(cinfo, fmtlist[ihdr.fmt], ihdr.size, ihdr.text,
291 	       ihdr.data, ihdr.bss, ihdr.entry);
292 	printf(oinfo, fmtlist[ohdr.fmt], ohdr.size, ohdr.text,
293 	       ohdr.data, ohdr.org, ohdr.entry);
294     }
295 }
296 
297 /*
298  * Read BTX file header.
299  */
300 static void
301 getbtx(int fd, struct btx_hdr * btx)
302 {
303     if (readx(fd, btx, sizeof(*btx), 0) != sizeof(*btx) ||
304 	btx->btx_magic[0] != BTX_MAG0 ||
305 	btx->btx_magic[1] != BTX_MAG1 ||
306 	btx->btx_magic[2] != BTX_MAG2)
307 	errx(1, "%s: Not a BTX kernel", fname);
308     btx->btx_pgctl = LE16TOH(btx->btx_pgctl);
309     btx->btx_textsz = LE16TOH(btx->btx_textsz);
310     btx->btx_entry = LE32TOH(btx->btx_entry);
311 }
312 
313 /*
314  * Get file size and read a.out or ELF header.
315  */
316 static void
317 gethdr(int fd, struct hdr *hdr)
318 {
319     struct stat sb;
320     const struct i386_exec *ex;
321     const Elf32_Ehdr *ee;
322     const Elf32_Phdr *ep;
323     void *p;
324     unsigned int fmt, x, n, i;
325 
326     memset(hdr, 0, sizeof(*hdr));
327     if (fstat(fd, &sb))
328 	err(2, "%s", fname);
329     if (sb.st_size > MAXU32)
330 	errx(1, "%s: Too big", fname);
331     hdr->size = sb.st_size;
332     if ((p = mmap(NULL, hdr->size, PROT_READ, MAP_SHARED, fd,
333 		  0)) == MAP_FAILED)
334 	err(2, "%s", fname);
335     for (fmt = F_CNT - 1; !hdr->fmt && fmt; fmt--)
336 	switch (fmt) {
337 	case F_AOUT:
338 	    ex = p;
339 	    if (hdr->size >= sizeof(struct i386_exec) && !I386_N_BADMAG(*ex)) {
340 		hdr->fmt = fmt;
341 		x = I386_N_GETMAGIC(*ex);
342 		if (x == OMAGIC || x == NMAGIC) {
343 		    if (x == NMAGIC)
344 			Warn(fname, "Treating %s NMAGIC as OMAGIC",
345 			     fmtlist[fmt]);
346 		    hdr->flags |= IMPURE;
347 		}
348 		hdr->text = LE32TOH(ex->a_text);
349 		hdr->data = LE32TOH(ex->a_data);
350 		hdr->bss = LE32TOH(ex->a_bss);
351 		hdr->entry = LE32TOH(ex->a_entry);
352 		if (LE32TOH(ex->a_entry) >= BTX_PGSIZE)
353 		    hdr->org = BTX_PGSIZE;
354 	    }
355 	    break;
356 	case F_ELF:
357 	    ee = p;
358 	    if (hdr->size >= sizeof(Elf32_Ehdr) && IS_ELF(*ee)) {
359 		hdr->fmt = fmt;
360 		for (n = i = 0; i < LE16TOH(ee->e_phnum); i++) {
361 		    ep = (void *)((uint8_t *)p + LE32TOH(ee->e_phoff) +
362 				  LE16TOH(ee->e_phentsize) * i);
363 		    if (LE32TOH(ep->p_type) == PT_LOAD)
364 			switch (n++) {
365 			case 0:
366 			    hdr->text = LE32TOH(ep->p_filesz);
367 			    hdr->org = LE32TOH(ep->p_paddr);
368 			    if (LE32TOH(ep->p_flags) & PF_W)
369 				hdr->flags |= IMPURE;
370 			    break;
371 			case 1:
372 			    hdr->data = LE32TOH(ep->p_filesz);
373 			    hdr->bss = LE32TOH(ep->p_memsz) -
374 				LE32TOH(ep->p_filesz);
375 			    break;
376 			case 2:
377 			    Warn(fname,
378 				 "Ignoring extra %s PT_LOAD segments",
379 				 fmtlist[fmt]);
380 			}
381 		}
382 		hdr->entry = LE32TOH(ee->e_entry);
383 	    }
384 	}
385     if (munmap(p, hdr->size))
386 	err(2, "%s", fname);
387 }
388 
389 /*
390  * Write a.out or ELF header.
391  */
392 static void
393 puthdr(int fd, struct hdr *hdr)
394 {
395     struct i386_exec ex;
396     struct elfh eh;
397 
398     switch (hdr->fmt) {
399     case F_AOUT:
400 	memset(&ex, 0, sizeof(ex));
401 	I386_N_SETMAGIC(ex, ZMAGIC, MID_ZERO, 0);
402 	hdr->text = I386_N_ALIGN(ex, hdr->text);
403 	ex.a_text = HTOLE32(hdr->text);
404 	hdr->data = I386_N_ALIGN(ex, hdr->data);
405 	ex.a_data = HTOLE32(hdr->data);
406 	ex.a_entry = HTOLE32(hdr->entry);
407 	writex(fd, &ex, sizeof(ex));
408 	hdr->size = I386_N_ALIGN(ex, sizeof(ex));
409 	seekx(fd, hdr->size);
410 	break;
411     case F_ELF:
412 	eh = elfhdr;
413 	eh.e.e_entry = HTOLE32(hdr->entry);
414 	eh.p[0].p_vaddr = eh.p[0].p_paddr = HTOLE32(hdr->org);
415 	eh.p[0].p_filesz = eh.p[0].p_memsz = HTOLE32(hdr->text);
416 	eh.p[1].p_offset = HTOLE32(LE32TOH(eh.p[0].p_offset) +
417 	    LE32TOH(eh.p[0].p_filesz));
418 	eh.p[1].p_vaddr = eh.p[1].p_paddr =
419 	    HTOLE32(align(LE32TOH(eh.p[0].p_paddr) + LE32TOH(eh.p[0].p_memsz),
420 	    4));
421 	eh.p[1].p_filesz = eh.p[1].p_memsz = HTOLE32(hdr->data);
422 	eh.sh[2].sh_addr = eh.p[0].p_vaddr;
423 	eh.sh[2].sh_offset = eh.p[0].p_offset;
424 	eh.sh[2].sh_size = eh.p[0].p_filesz;
425 	eh.sh[3].sh_addr = eh.p[1].p_vaddr;
426 	eh.sh[3].sh_offset = eh.p[1].p_offset;
427 	eh.sh[3].sh_size = eh.p[1].p_filesz;
428 	writex(fd, &eh, sizeof(eh));
429 	hdr->size = sizeof(eh);
430     }
431 }
432 
433 /*
434  * Safe copy from input file to output file.
435  */
436 static void
437 copy(int fdi, int fdo, size_t nbyte, off_t offset)
438 {
439     char buf[8192];
440     size_t n;
441 
442     while (nbyte) {
443 	if ((n = sizeof(buf)) > nbyte)
444 	    n = nbyte;
445 	if (readx(fdi, buf, n, offset) != n)
446 	    errx(2, "%s: Short read", fname);
447 	writex(fdo, buf, n);
448 	nbyte -= n;
449 	offset = -1;
450     }
451 }
452 
453 /*
454  * Safe read from input file.
455  */
456 static size_t
457 readx(int fd, void *buf, size_t nbyte, off_t offset)
458 {
459     ssize_t n;
460 
461     if (offset != -1 && lseek(fd, offset, SEEK_SET) != offset)
462 	err(2, "%s", fname);
463     if ((n = read(fd, buf, nbyte)) == -1)
464 	err(2, "%s", fname);
465     return n;
466 }
467 
468 /*
469  * Safe write to output file.
470  */
471 static void
472 writex(int fd, const void *buf, size_t nbyte)
473 {
474     ssize_t n;
475 
476     if ((n = write(fd, buf, nbyte)) == -1)
477 	err(2, "%s", tname);
478     if (n != nbyte)
479 	errx(2, "%s: Short write", tname);
480 }
481 
482 /*
483  * Safe seek in output file.
484  */
485 static void
486 seekx(int fd, off_t offset)
487 {
488     if (lseek(fd, offset, SEEK_SET) != offset)
489 	err(2, "%s", tname);
490 }
491 
492 /*
493  * Convert an option argument to a format code.
494  */
495 static unsigned int
496 optfmt(const char *arg)
497 {
498     unsigned int i;
499 
500     for (i = 0; i < F_CNT && strcmp(arg, fmtlist[i]); i++);
501     if (i == F_CNT)
502 	errx(1, "%s: Unknown format", arg);
503     return i;
504 }
505 
506 /*
507  * Convert an option argument to an address.
508  */
509 static uint32_t
510 optaddr(const char *arg)
511 {
512     char *s;
513     unsigned long x;
514 
515     errno = 0;
516     x = strtoul(arg, &s, 0);
517     if (errno || !*arg || *s || x > MAXU32)
518 	errx(1, "%s: Illegal address", arg);
519     return x;
520 }
521 
522 /*
523  * Convert an option argument to a page number.
524  */
525 static int
526 optpage(const char *arg, int hi)
527 {
528     char *s;
529     long x;
530 
531     errno = 0;
532     x = strtol(arg, &s, 0);
533     if (errno || !*arg || *s || x < 0 || x > hi)
534 	errx(1, "%s: Illegal page number", arg);
535     return x;
536 }
537 
538 /*
539  * Display a warning.
540  */
541 static void
542 Warn(const char *locus, const char *fmt, ...)
543 {
544     va_list ap;
545     char *s;
546 
547     if (!quiet) {
548 	asprintf(&s, "%s: Warning: %s", locus, fmt);
549 	va_start(ap, fmt);
550 	vwarnx(s, ap);
551 	va_end(ap);
552 	free(s);
553     }
554 }
555 
556 /*
557  * Display usage information.
558  */
559 static void
560 usage(void)
561 {
562     fprintf(stderr, "%s\n%s\n",
563     "usage: btxld [-qv] [-b file] [-E address] [-e address] [-f format]",
564     "             [-l file] [-o filename] [-P page] [-W page] file");
565     exit(1);
566 }
567