sbpf-linker 0.2.0

Upstream BPF linker for SBPF V0/V3 programs
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
use crate::{ProgramOptions, SbpfLinkerError};

use sbpf_assembler::ast::{AST, build_program};
use sbpf_assembler::astnode::{ASTNode, GlobalDecl, Label, ROData};
use sbpf_assembler::section::DebugSection;
use sbpf_assembler::{ProgramLayout, SbpfArch, Token};
use sbpf_common::{
    inst_param::Number, instruction::Instruction, opcode::Opcode,
};

use either::Either;
use object::RelocationTarget::Symbol;
use object::{
    File, Object as _, ObjectSection as _, ObjectSymbol as _, SectionIndex,
};

use std::collections::HashMap;

use crate::fuse_args_stack::{
    FunctionRange, diagnose_stack_arg_overlaps, rewrite_r11_stack_args,
};

fn decode_instruction_for_arch(
    data: &[u8],
    arch: SbpfArch,
) -> Result<Instruction, sbpf_common::errors::SBPFError> {
    if arch.is_v3() {
        Instruction::from_bytes_sbpf_v3(data)
    } else {
        Instruction::from_bytes(data)
    }
}

// Staged rodata region. We collect these before emitting so we can sort by
// address and fill anonymous gaps before the AST is built.
struct RodataEntry {
    section_index: SectionIndex,
    address: u64,
    size: u64,
    name: String,
    bytes: Vec<Number>,
}

pub fn parse_bytecode(
    bytes: &[u8],
    options: ProgramOptions,
) -> Result<ProgramLayout, SbpfLinkerError> {
    let ProgramOptions { optimization, arch, stack_frame_size } = options;
    let mut ast = AST::new();

    let obj = File::parse(bytes)?;

    // Track all read-only sections including .rodata* and .data.rel.ro* sections.
    // .data.rel.ro* is read-only after load-time pointer patching and can be
    // an lddw relocation target just like .rodata*.
    let mut ro_sections = HashMap::new();
    for section in obj.sections().filter(|section| {
        section
            .name()
            .map(|name| {
                name.starts_with(".rodata") || name.starts_with(".data.rel.ro")
            })
            .unwrap_or(false)
    }) {
        ro_sections.insert(section.index(), section);
    }

    let mut text_section_bases = HashMap::new();
    let mut text_size = 0u64;
    for section in obj.sections().filter(|section| {
        section.name().map(|name| name.starts_with(".text")).unwrap_or(false)
    }) {
        text_section_bases.insert(section.index(), text_size);
        text_size += section.size();
    }
    let mut pending_rodata: Vec<RodataEntry> = Vec::new();
    let mut rodata_table: HashMap<(Option<SectionIndex>, u64), String> =
        HashMap::new();

    let mut function_starts = Vec::new();
    for symbol in obj.symbols() {
        if let Some(ro_section) = symbol
            .section_index()
            .and_then(|section_index| ro_sections.get(&section_index))
        {
            // STT_SECTION symbols have size == 0; anonymous gaps they cover
            // are handled by the gap-fill pass below.
            if symbol.kind() == object::SymbolKind::Section {
                continue;
            }
            assert!(
                symbol.size() > 0,
                "non-STT_SECTION rodata symbol has size 0"
            );

            let bytes: Vec<Number> = (0..symbol.size())
                .map(|i| {
                    Number::Int(i64::from(
                        ro_section.data().unwrap()
                            [(symbol.address() + i) as usize],
                    ))
                })
                .collect();
            pending_rodata.push(RodataEntry {
                section_index: ro_section.index(),
                address: symbol.address(),
                size: symbol.size(),
                name: symbol.name().unwrap().to_owned(),
                bytes,
            });
        } else if let Some(section_index) = symbol.section_index()
            && let Some(section_base) = text_section_bases.get(&section_index)
        {
            let sym_name = symbol.name().unwrap_or("");
            if sym_name.is_empty() {
                continue;
            }
            ast.nodes.push(ASTNode::Label {
                label: Label { name: sym_name.to_owned(), span: 0..1 },
                offset: section_base + symbol.address(),
            });
            if symbol.kind() == object::SymbolKind::Text {
                ast.add_function_entry(sym_name.to_owned());
                function_starts.push((
                    section_base + symbol.address(),
                    sym_name.to_owned(),
                ));
            }
            if sym_name == "entrypoint" {
                ast.nodes.push(ASTNode::GlobalDecl {
                    global_decl: GlobalDecl {
                        entry_label: sym_name.to_owned(),
                        span: 0..1,
                    },
                });
            }
        }
    }

    // Mapping from offset to known labels
    let mut labels_by_offset: HashMap<u64, String> = HashMap::new();
    for node in &ast.nodes {
        if let ASTNode::Label { label, offset } = node {
            labels_by_offset
                .entry(*offset)
                .or_insert_with(|| label.name.clone());
        }
    }
    // Mapping from offset to synthetic labels
    let mut synthetic_labels_by_offset: HashMap<u64, String> = HashMap::new();

    // Gap-fill pass: synthesize rodata entries for byte ranges not covered by
    // any named symbol (e.g. compiler-generated lookup tables).
    let mut synthetic_rodata: Vec<RodataEntry> = Vec::new();
    for (section_index, ro_section) in &ro_sections {
        let section_data = ro_section.data().unwrap();
        let section_size = section_data.len() as u64;

        let mut section_entries: Vec<&RodataEntry> = pending_rodata
            .iter()
            .filter(|e| &e.section_index == section_index)
            .collect();
        section_entries.sort_by_key(|e| e.address);

        let mut cursor = 0u64;
        for entry in &section_entries {
            if cursor < entry.address {
                let gap_bytes: Vec<Number> = section_data
                    [cursor as usize..entry.address as usize]
                    .iter()
                    .map(|&b| Number::Int(i64::from(b)))
                    .collect();
                synthetic_rodata.push(RodataEntry {
                    section_index: *section_index,
                    address: cursor,
                    size: entry.address - cursor,
                    name: format!(
                        ".rodata.__anon_{:#x}_{:#x}",
                        section_index.0, cursor
                    ),
                    bytes: gap_bytes,
                });
            }
            cursor = cursor.max(entry.address + entry.size);
        }

        if cursor < section_size {
            let gap_bytes: Vec<Number> = section_data[cursor as usize..]
                .iter()
                .map(|&b| Number::Int(i64::from(b)))
                .collect();
            synthetic_rodata.push(RodataEntry {
                section_index: *section_index,
                address: cursor,
                size: section_size - cursor,
                name: format!(
                    ".rodata.__anon_{:#x}_{:#x}",
                    section_index.0, cursor
                ),
                bytes: gap_bytes,
            });
        }
    }

    pending_rodata.extend(synthetic_rodata);
    pending_rodata.sort_by_key(|e| (e.section_index.0, e.address));

    let mut rodata_offset = 0u64;
    for entry in pending_rodata {
        ast.rodata_nodes.push(ASTNode::ROData {
            rodata: ROData {
                name: entry.name.clone(),
                args: vec![
                    Token::Directive(String::from("byte"), 0..1),
                    Token::VectorLiteral(entry.bytes, 0..1),
                ],
                span: 0..1,
            },
            offset: rodata_offset,
        });
        rodata_table
            .insert((Some(entry.section_index), entry.address), entry.name);
        rodata_offset += entry.size;
    }

    let mut debug_sections = Vec::default();
    ast.set_rodata_size(rodata_offset);

    for section in obj.sections() {
        if let Some(section_base) = text_section_bases.get(&section.index()) {
            let section_base = *section_base;
            let section_data = section.data().unwrap();
            // parse text section and build instruction nodes
            // lddw takes 16 bytes, other instructions take 8 bytes
            let mut offset = 0;
            while offset < section_data.len() {
                let data = &section_data[offset..];
                let instruction = decode_instruction_for_arch(data, arch);
                if let Err(error) = instruction {
                    return Err(SbpfLinkerError::InstructionParseError(
                        error.to_string(),
                    ));
                }
                let node_len = match instruction.as_ref().unwrap().opcode {
                    Opcode::Lddw => 16,
                    _ => 8,
                };
                ast.nodes.push(ASTNode::Instruction {
                    instruction: instruction.unwrap(),
                    offset: section_base + offset as u64,
                });
                offset += node_len;
            }

            // handle relocations
            let section_name =
                section.name().unwrap_or("<invalid>").to_owned();
            for rel in section.relocations() {
                let rel_target = rel.1.target();
                let rel_addend = rel.1.addend();
                let rel_has_implicit_addend = rel.1.has_implicit_addend();

                // handle relocations for call targets and rodata referenced by lddw
                let symbol = match rel_target {
                    Symbol(sym) => obj.symbol_by_index(sym).unwrap(),
                    _ => continue,
                };

                let node: &mut Instruction = ast
                    .get_instruction_at_offset(section_base + rel.0)
                    .unwrap();

                if node.opcode == Opcode::Lddw {
                    // addend is not explicit in the relocation entry, but implicitly
                    // encoded as the immediate value of the instruction
                    let addend = match node.imm {
                        Some(Either::Right(Number::Int(val))) => val,
                        _ => 0,
                    };

                    let key = (symbol.section_index(), addend as u64);
                    if rodata_table.contains_key(&key) {
                        // Replace the immediate value with the rodata label
                        let ro_label = rodata_table[&key].clone();
                        node.imm = Some(Either::Left(ro_label));
                    } else {
                        panic!("relocation in lddw is not in .rodata");
                    }
                } else if node.opcode == Opcode::Call {
                    if symbol.kind() == object::SymbolKind::Section {
                        let addend_i64 = if rel_has_implicit_addend {
                            // If relocation uses implicit addend, use `node.imm`
                            match &node.imm {
                                Some(Either::Right(
                                    Number::Int(val) | Number::Addr(val),
                                )) => *val,
                                _ => rel_addend,
                            }
                        } else {
                            // Otherwise use explicit relocation addend
                            rel_addend
                        };

                        let target_section_base =
                            symbol.section_index().and_then(|idx| {
                                text_section_bases.get(&idx).copied()
                            });

                        let resolved_target_offset = target_section_base
                            .zip(addend_i64.checked_add(1))
                            .and_then(|(section_base, slots)| {
                                let slots = u64::try_from(slots).ok()?;
                                let local = slots
                                    .checked_mul(8)?
                                    .checked_add(symbol.address())?;
                                section_base.checked_add(local)
                            })
                            .filter(|target| *target < text_size);

                        let target_name = if let Some(target_offset) =
                            resolved_target_offset
                        {
                            if let Some(existing_name) =
                                labels_by_offset.get(&target_offset)
                            {
                                // Use known label
                                existing_name.clone()
                            } else {
                                // If label is not known, create and use a synthetic label
                                let synthetic_name =
                                    synthetic_labels_by_offset
                                        .entry(target_offset)
                                        .or_insert_with(|| {
                                            format!(
                                                ".__sbpf_section_call_{target_offset:x}"
                                            )
                                        })
                                        .clone();
                                labels_by_offset.insert(
                                    target_offset,
                                    synthetic_name.clone(),
                                );
                                synthetic_name
                            }
                        } else {
                            return Err(
                                SbpfLinkerError::UnresolvedSectionCallRelocation {
                                    section: section_name.clone(),
                                    abs_off: section_base + rel.0,
                                    addend: addend_i64,
                                },
                            );
                        };

                        node.imm = Some(Either::Left(target_name));
                    } else {
                        let name = symbol.name().unwrap_or("");
                        assert!(
                            !name.is_empty(),
                            "non-STT_SECTION call target has empty name"
                        );
                        node.imm = Some(Either::Left(name.to_owned()));
                    }
                }
            }
        } else if let Ok(section_name) = section.name()
            && section_name.starts_with(".debug_")
        {
            // So we have debug sections, keep them around.
            debug_sections.push(DebugSection::new(
                section_name,
                0, // will compute during emitting
                section.data().unwrap().to_vec(),
            ));
        }
    }

    if !synthetic_labels_by_offset.is_empty() {
        // Add synthetic labels to AST
        let mut synthetic_labels =
            synthetic_labels_by_offset.into_iter().collect::<Vec<_>>();
        synthetic_labels.sort_by_key(|(offset, _)| *offset);
        for (offset, name) in synthetic_labels {
            ast.nodes.push(ASTNode::Label {
                label: Label { name, span: 0..1 },
                offset,
            });
        }
    }

    ast.set_text_size(text_size);

    // Sort ast.nodes in source order: each label immediately before the
    // instruction at the same byte offset. The CFG builder expects source-order
    // input and no longer sorts internally. Non-label/instruction nodes
    // (GlobalDecl, etc.) are kept at the front in their original order.
    {
        let (mut metadata, mut text): (Vec<ASTNode>, Vec<ASTNode>) =
            std::mem::take(&mut ast.nodes).into_iter().partition(|n| {
                !matches!(
                    n,
                    ASTNode::Label { .. } | ASTNode::Instruction { .. }
                )
            });
        text.sort_by_key(|node| match node {
            ASTNode::Label { offset, .. } => (*offset, 0u8),
            ASTNode::Instruction { offset, .. } => (*offset, 1u8),
            _ => unreachable!(),
        });
        metadata.append(&mut text);
        ast.nodes = metadata;
    }

    function_starts.sort_by_key(|(start, _)| *start);
    // Function aliases can produce multiple STT_FUNC symbols at the same
    // address. Keep one entry per address when constructing function ranges.
    function_starts.dedup_by_key(|(start, _)| *start);
    let functions = function_starts
        .iter()
        .enumerate()
        .map(|(index, (start, name))| FunctionRange {
            name: name.clone(),
            start: *start,
            end: function_starts
                .get(index + 1)
                .map_or(text_size, |(next_start, _)| *next_start),
        })
        .collect::<Vec<_>>();

    for overlap in
        diagnose_stack_arg_overlaps(&ast, stack_frame_size, &functions)
    {
        tracing::error!(
            function = %overlap.function,
            local_start = overlap.local_stack.start,
            local_end = overlap.local_stack.end,
            argument_start = overlap.incoming_args.start,
            argument_end = overlap.incoming_args.end,
            "local stack variable overlaps incoming spilled-argument region"
        );
    }

    rewrite_r11_stack_args(&mut ast, stack_frame_size)
        .map_err(|errors| SbpfLinkerError::BuildProgramError { errors })?;

    let mut parse_result = build_program(ast, arch, optimization)
        .map_err(|errors| SbpfLinkerError::BuildProgramError { errors })?;

    parse_result.debug_sections = debug_sections;

    Ok(parse_result)
}