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