1 /*
2  * hack-coff.c - hack the header of an xcoff file to fill in
3  * a few fields needed by the Open Firmware xcoff loader on
4  * Power Macs but not initialized by objcopy.
5  *
6  * Copyright (C) Paul Mackerras 1997.
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version
11  * 2 of the License, or (at your option) any later version.
12  */
13 #include <stdio.h>
14 #include <unistd.h>
15 #include <fcntl.h>
16 #include "rs6000.h"
17 
18 #define AOUT_MAGIC	0x010b
19 
20 #define get_16be(x)	((((unsigned char *)(x))[0] << 8) \
21 			 + ((unsigned char *)(x))[1])
22 #define put_16be(x, v)	(((unsigned char *)(x))[0] = (v) >> 8, \
23 			 ((unsigned char *)(x))[1] = (v) & 0xff)
24 #define get_32be(x)	((((unsigned char *)(x))[0] << 24) \
25 			 + (((unsigned char *)(x))[1] << 16) \
26 			 + (((unsigned char *)(x))[2] << 8) \
27 			 + ((unsigned char *)(x))[3])
28 
29 int
main(int ac,char ** av)30 main(int ac, char **av)
31 {
32     int fd;
33     int i, nsect;
34     int aoutsz;
35     struct external_filehdr fhdr;
36     AOUTHDR aout;
37     struct external_scnhdr shdr;
38 
39     if (ac != 2) {
40 	fprintf(stderr, "Usage: hack-coff coff-file\n");
41 	exit(1);
42     }
43     if ((fd = open(av[1], 2)) == -1) {
44 	perror(av[2]);
45 	exit(1);
46     }
47     if (read(fd, &fhdr, sizeof(fhdr)) != sizeof(fhdr))
48 	goto readerr;
49     i = get_16be(fhdr.f_magic);
50     if (i != U802TOCMAGIC && i != U802WRMAGIC && i != U802ROMAGIC) {
51 	fprintf(stderr, "%s: not an xcoff file\n", av[1]);
52 	exit(1);
53     }
54     aoutsz = get_16be(fhdr.f_opthdr);
55     if (read(fd, &aout, aoutsz) != aoutsz)
56 	goto readerr;
57     nsect = get_16be(fhdr.f_nscns);
58     for (i = 0; i < nsect; ++i) {
59 	if (read(fd, &shdr, sizeof(shdr)) != sizeof(shdr))
60 	    goto readerr;
61 	if (strcmp(shdr.s_name, ".text") == 0) {
62 	    put_16be(aout.o_snentry, i+1);
63 	    put_16be(aout.o_sntext, i+1);
64 	} else if (strcmp(shdr.s_name, ".data") == 0) {
65 	    put_16be(aout.o_sndata, i+1);
66 	} else if (strcmp(shdr.s_name, ".bss") == 0) {
67 	    put_16be(aout.o_snbss, i+1);
68 	}
69     }
70     put_16be(aout.magic, AOUT_MAGIC);
71     if (lseek(fd, (long) sizeof(struct external_filehdr), 0) == -1
72 	|| write(fd, &aout, aoutsz) != aoutsz) {
73 	fprintf(stderr, "%s: write error\n", av[1]);
74 	exit(1);
75     }
76     close(fd);
77     exit(0);
78 
79 readerr:
80     fprintf(stderr, "%s: read error or file too short\n", av[1]);
81     exit(1);
82 }
83