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