1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
//! Sections, fragments and fixups.
//!
//! Output is built as a list of *fragments* per section. A fragment whose size
//! is not yet known (an alignment, or a branch that may need a longer
//! displacement) keeps enough information for the layout loop to re-decide its
//! size until everything is stable.
use crate::expr::ExprRef;
use crate::intern::Name;
use crate::source::Span;
use crate::symbol::SymbolId;
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct SectionId(pub u32);
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum SectionKind {
/// Occupies space in the output file.
Progbits,
/// Zero-filled at load time (`.bss`).
Nobits,
Note,
}
#[derive(Copy, Clone, PartialEq, Eq, Default, Debug)]
pub struct SectionFlags {
pub alloc: bool,
pub write: bool,
pub exec: bool,
pub merge: bool,
pub strings: bool,
pub tls: bool,
pub group: bool,
}
impl SectionFlags {
pub fn text() -> SectionFlags {
SectionFlags {
alloc: true,
exec: true,
..Default::default()
}
}
pub fn data() -> SectionFlags {
SectionFlags {
alloc: true,
write: true,
..Default::default()
}
}
pub fn rodata() -> SectionFlags {
SectionFlags {
alloc: true,
..Default::default()
}
}
pub fn bss() -> SectionFlags {
SectionFlags {
alloc: true,
write: true,
..Default::default()
}
}
}
/// How a fixup's value is written into the output.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct FixupKind {
/// Field width in bytes: 1, 2, 4 or 8.
pub size: u8,
/// The value is relative to the address of the fixup itself (plus
/// `adjust`), rather than absolute.
pub pcrel: bool,
/// Range-check the result as signed rather than allowing either sign.
pub signed: bool,
/// Added to the fixup's own address before subtracting, for PC-relative
/// fields that are not at the end of their instruction. For x86 a `rel32`
/// four bytes before the end of the instruction uses `adjust = 4`.
pub adjust: i8,
/// Relocation to emit if the value cannot be resolved at assembly time.
/// `0` means "no relocation available"; an unresolved fixup is then an
/// error.
pub reloc: u32,
}
impl FixupKind {
pub fn data(size: u8) -> FixupKind {
FixupKind {
size,
pcrel: false,
signed: false,
adjust: 0,
reloc: 0,
}
}
pub fn pcrel(size: u8, adjust: i8) -> FixupKind {
FixupKind {
size,
pcrel: true,
signed: true,
adjust,
reloc: 0,
}
}
pub fn with_reloc(mut self, reloc: u32) -> FixupKind {
self.reloc = reloc;
self
}
pub fn signed(mut self) -> FixupKind {
self.signed = true;
self
}
/// Inclusive range of values this field can hold.
pub fn range(&self) -> (i128, i128) {
let bits = self.size as u32 * 8;
if self.signed {
(-(1i128 << (bits - 1)), (1i128 << (bits - 1)) - 1)
} else {
// Accept both the unsigned and the sign-extended reading, which is
// what assemblers do for `.byte -1` as well as `.byte 255`.
(-(1i128 << (bits - 1)), (1i128 << bits) - 1)
}
}
pub fn fits(&self, v: i128) -> bool {
if self.size >= 8 {
return true;
}
let (lo, hi) = self.range();
v >= lo && v <= hi
}
}
#[derive(Clone, Debug)]
pub struct Fixup {
/// Byte offset within the fragment's bytes.
pub offset: u32,
pub expr: ExprRef,
pub kind: FixupKind,
pub span: Span,
}
/// One possible encoding of a fragment.
#[derive(Clone, Debug, Default)]
pub struct Variant {
pub bytes: Vec<u8>,
pub fixups: Vec<Fixup>,
}
impl Variant {
pub fn new(bytes: Vec<u8>) -> Variant {
Variant {
bytes,
fixups: Vec::new(),
}
}
}
#[derive(Clone, Debug)]
pub enum FragKind {
/// Literal bytes. Instructions that can be encoded several ways list all
/// candidates smallest-first; layout raises `chosen` until every fixup
/// fits, and never lowers it, so the loop terminates.
Bytes {
variants: Vec<Variant>,
chosen: usize,
},
/// Pad to a multiple of `align`, at most `max_skip` bytes.
Align {
align: u64,
fill: Vec<u8>,
max_skip: Option<u64>,
/* filled by layout */ pad: u64,
},
/// Advance the location counter to an absolute offset within the section.
Org {
target: ExprRef,
fill: u8,
size: u64,
},
/// `.space` / `.skip`: `size` bytes of `fill`.
Space {
size: ExprRef,
fill: ExprRef,
resolved: u64,
},
/// A variable-length integer whose width depends on its value.
Leb128 {
value: ExprRef,
signed: bool,
encoded: Vec<u8>,
},
}
#[derive(Clone, Debug)]
pub struct Fragment {
pub kind: FragKind,
pub span: Span,
/// Offset from the start of the section, assigned by layout.
pub offset: u64,
}
impl Fragment {
pub fn new(kind: FragKind, span: Span) -> Fragment {
Fragment {
kind,
span,
offset: 0,
}
}
/// Current size in bytes, based on the last layout decision.
pub fn size(&self) -> u64 {
match &self.kind {
FragKind::Bytes { variants, chosen } => {
variants.get(*chosen).map_or(0, |v| v.bytes.len() as u64)
}
FragKind::Align { pad, .. } => *pad,
FragKind::Org { size, .. } => *size,
FragKind::Space { resolved, .. } => *resolved,
FragKind::Leb128 { encoded, .. } => encoded.len() as u64,
}
}
pub fn is_plain_data(&self) -> bool {
matches!(&self.kind, FragKind::Bytes { variants, .. } if variants.len() == 1)
}
}
pub struct Section {
pub id: SectionId,
pub name: Name,
pub kind: SectionKind,
pub flags: SectionFlags,
/// Required alignment of the section itself.
pub align: u64,
/// Entry size for mergeable sections; 0 otherwise.
pub entsize: u64,
pub frags: Vec<Fragment>,
/// Total size after the last layout pass.
pub size: u64,
/// Base address, for absolute output formats.
pub addr: u64,
/// The section symbol, created lazily when a relocation needs it.
pub sym: Option<SymbolId>,
/// Index of the trailing fragment that new data may be appended to, if
/// any. Cleared by anything that must not be merged across, such as a
/// label definition.
open_data: Option<usize>,
/// The `.subsection`-style saved location counter is not modelled yet;
/// this records the section's declared group name if it has one.
pub group: Option<Name>,
}
impl Section {
pub fn new(id: SectionId, name: Name, kind: SectionKind, flags: SectionFlags) -> Section {
Section {
id,
name,
kind,
flags,
align: 1,
entsize: 0,
frags: Vec::new(),
size: 0,
addr: 0,
sym: None,
open_data: None,
group: None,
}
}
/// Index the next fragment will get. Labels record this to name a position.
pub fn next_frag_index(&self) -> u32 {
self.frags.len() as u32
}
/// Prevents further merging into the current data fragment, so that the
/// next fragment index refers to a real position.
pub fn seal(&mut self) {
self.open_data = None;
}
pub fn push(&mut self, frag: Fragment) -> u32 {
self.open_data = None;
let idx = self.frags.len() as u32;
self.frags.push(frag);
idx
}
/// Appends raw bytes, merging into the previous data fragment when that is
/// safe. Merging keeps fragment counts (and therefore layout cost) low for
/// data-heavy files.
pub fn emit_bytes(&mut self, bytes: &[u8], span: Span) {
if let Some(i) = self.open_data
&& let FragKind::Bytes { variants, .. } = &mut self.frags[i].kind
{
variants[0].bytes.extend_from_slice(bytes);
self.frags[i].span = self.frags[i].span.to(span);
return;
}
let idx = self.frags.len();
self.frags.push(Fragment::new(
FragKind::Bytes {
variants: vec![Variant::new(bytes.to_vec())],
chosen: 0,
},
span,
));
self.open_data = Some(idx);
}
/// Appends `size` bytes to be filled in later from `expr`.
pub fn emit_fixup(&mut self, size: u8, expr: ExprRef, kind: FixupKind, span: Span) {
let placeholder = vec![0u8; size as usize];
let (idx, base) = match self.open_data {
Some(i) => {
let FragKind::Bytes { variants, .. } = &self.frags[i].kind else {
unreachable!("open_data always points at a Bytes fragment")
};
(i, variants[0].bytes.len() as u32)
}
None => {
let i = self.frags.len();
self.frags.push(Fragment::new(
FragKind::Bytes {
variants: vec![Variant::default()],
chosen: 0,
},
span,
));
self.open_data = Some(i);
(i, 0)
}
};
let FragKind::Bytes { variants, .. } = &mut self.frags[idx].kind else {
unreachable!()
};
variants[0].bytes.extend_from_slice(&placeholder);
variants[0].fixups.push(Fixup {
offset: base,
expr,
kind,
span,
});
self.frags[idx].span = self.frags[idx].span.to(span);
}
/// Appends a pre-encoded instruction with one or more size variants.
pub fn emit_variants(&mut self, variants: Vec<Variant>, span: Span) -> u32 {
debug_assert!(
!variants.is_empty(),
"an instruction needs at least one encoding"
);
self.push(Fragment::new(
FragKind::Bytes {
variants,
chosen: 0,
},
span,
))
}
pub fn is_empty(&self) -> bool {
self.frags.iter().all(|f| f.size() == 0)
}
}