1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 :(before "End Main")
20 if (is_equal(argv[1], "translate")) {
21 START_TRACING_UNTIL_END_OF_SCOPE;
22 assert(argc > 3);
23 program p;
24 ifstream fin(argv[2]);
25 if (!fin) {
26 cerr << "could not open " << argv[2] << '\n';
27 return 1;
28 }
29 parse(fin, p);
30 if (trace_contains_errors()) return 1;
31 transform(p);
32 if (trace_contains_errors()) return 1;
33 save_elf(p, argv[3]);
34 if (trace_contains_errors()) unlink(argv[3]);
35 return 0;
36 }
37
38 :(code)
39
40 void save_elf(const program& p, const char* filename) {
41 ofstream out(filename, ios::binary);
42 write_elf_header(out, p);
43 for (size_t i = 0; i < p.segments.size(); ++i)
44 write_segment(p.segments.at(i), out);
45 out.close();
46 }
47
48 void write_elf_header(ostream& out, const program& p) {
49 char c = '\0';
50
51
52
53
54
55 O(0x7f); O(0x45); O(0x4c); O(0x46);
56 O(0x1);
57 O(0x1);
58 O(0x1); O(0x0);
59 for (size_t i = 0; i < 8; ++i) { O(0x0); }
60
61 O(0x02); O(0x00);
62
63 O(0x03); O(0x00);
64
65 O(0x01); O(0x00); O(0x00); O(0x00);
66
67 int e_entry = p.segments.at(0).start;
68 emit(e_entry);
69
70 int e_phoff = 0x34;
71 emit(e_phoff);
72
73 int dummy32 = 0;
74 emit(dummy32);
75
76 emit(dummy32);
77
78 uint16_t e_ehsize = 0x34;
79 emit(e_ehsize);
80
81 uint16_t e_phentsize = 0x20;
82 emit(e_phentsize);
83
84 uint16_t e_phnum = SIZE(p.segments);
85 emit(e_phnum);
86
87 uint16_t dummy16 = 0x0;
88 emit(dummy16);
89
90 emit(dummy16);
91
92 emit(dummy16);
93
94 uint32_t p_offset = 0x34 + SIZE(p.segments)*0x20;
95 for (int i = 0; i < SIZE(p.segments); ++i) {
96
97
98 uint32_t p_type = 0x1;
99 emit(p_type);
100
101 emit(p_offset);
102
103 emit(p.segments.at(i).start);
104
105 emit(p.segments.at(i).start);
106
107 uint32_t size = size_of(p.segments.at(i));
108 assert(size < SEGMENT_SIZE);
109 emit(size);
110
111 emit(size);
112
113 uint32_t p_flags = (i == 0) ? 0x5 : 0x6;
114 emit(p_flags);
115
116
117
118
119
120
121
122
123
124
125
126
127 uint32_t p_align = 0x1000;
128 emit(p_align);
129 if (p_offset % p_align != p.segments.at(i).start % p_align) {
130 raise << "segment starting at 0x" << HEXWORD << p.segments.at(i).start << " is improperly aligned; alignment for p_offset " << p_offset << " should be " << (p_offset % p_align) << " but is " << (p.segments.at(i).start % p_align) << '\n' << end();
131 return;
132 }
133
134
135 p_offset += size;
136 }
137
138
139 }
140
141 void write_segment(const segment& s, ostream& out) {
142 for (int i = 0; i < SIZE(s.lines); ++i) {
143 const vector<word>& w = s.lines.at(i).words;
144 for (int j = 0; j < SIZE(w); ++j) {
145 uint8_t x = hex_byte(w.at(j).data);
146 out.write(reinterpret_cast<const char*>(&x), 1);
147 }
148 }
149 }
150
151 uint32_t size_of(const segment& s) {
152 uint32_t sum = 0;
153 for (int i = 0; i < SIZE(s.lines); ++i)
154 sum += SIZE(s.lines.at(i).words);
155 return sum;
156 }
157
158 :(before "End Includes")
159 using std::ios;