BSD 3 development
[unix-history] / usr / src / cmd / 1kfix.c
CommitLineData
52319808
BJ
1#include <stdio.h>
2#include <a.out.h>
3#include <sys/param.h>
4#include <sys/vm.h>
5char *malloc();
6
7#define round(a,b) (((a)+((b)-1))&~(b-1))
8
9main(argc, argv)
10 int argc;
11 char *argv[];
12{
13 char *tp, *dp, *sp;
14 struct exec x, y;
15 int io;
16 char zeroes[NBPG];
17
18 --argc;
19 ++argv;
20 if (argc == 0) {
21 fprintf(stderr, "usage: 1kfix file ...\n");
22 exit(1);
23 }
24 do {
25 io = open(argv[0], 2);
26 if (io < 0) {
27 perror(argv[0]);
28 argc--, argv++;
29 continue;
30 }
31 if (read(io, &x, sizeof x) != sizeof x)
32 goto format;
33
34 switch (x.a_magic) {
35
36 case 0407:
37 case 0410:
38 if ((round(x.a_text,NBPG) & CLOFSET) == 0) {
39 fprintf(stderr, "%s: wins as is\n", argv[0]);
40 goto skip;
41 }
42 break;
43
44 case 0413:
45 lseek(io, NBPG, 0);
46 break;
47
48 default:
49format:
50 printf("%s: not object file\n", argv[0]);
51 goto skip;
52 }
53
54 tp = malloc(x.a_text);
55 dp = malloc(x.a_data);
56 sp = malloc(x.a_syms);
57 if (read(io, tp, x.a_text) != x.a_text ||
58 read(io, dp, x.a_data) != x.a_data ||
59 read(io, sp, x.a_syms) != x.a_syms) {
60 fprintf(stderr, "%s: short read\n", argv[0]);
61 goto skip;
62 }
63 close(io);
64 io = creat(argv[0], 0755);
65 if (io < 0) {
66 perror(argv[0]);
67 goto skip;
68 }
69
70 y = x;
71 switch (x.a_magic) {
72
73 case 0413: {
74 int i;
75 for (i = 0; i < 512; i++)
76 if (tp[i] != 0)
77 break;
78 if (i == 512)
79 printf("%s: already fixed\n", argv[0]);
80 if (x.a_text & CLOFSET) {
81 y.a_text -= NBPG;
82 y.a_data += NBPG;
83 }
84 }
85 break;
86
87 case 0407:
88 case 0410:
89 y.a_text = round(x.a_text, NBPG) - NBPG;
90 y.a_data += NBPG;
91 if (y.a_text == 0) {
92 fprintf(stderr, "%s: text size would be 0\n", argv[0]);
93 goto skip;
94 }
95 }
96 y.a_trsize = y.a_drsize = 0;
97 write(io, (char *)&y, sizeof y);
98 if (x.a_magic == 0413)
99 lseek(io, BSIZE, 0);
100 write(io, tp, x.a_text);
101 if (x.a_magic != 0413)
102 write(io, zeroes, round(x.a_text, NBPG) - x.a_text);
103 write(io, dp, x.a_data);
104 write(io, sp, x.a_syms);
105 free(tp);
106 free(dp);
107 free(sp);
108skip:
109 argc--, argv++;
110 close(io);
111 } while (argc > 0);
112 exit(0);
113}