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