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