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