sbpf-assembler 0.2.4

Assembler for SBPF (Solana BPF) assembly language
Documentation
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
use {
    crate::{
        CompileError, SbpfArch,
        astnode::{ASTNode, ROData},
        dynsym::{DynamicSymbolMap, RelDynMap, RelocationType},
        header::ProgramHeader,
        optimizer,
        parser::ProgramLayout,
        section::{CodeSection, DataSection},
    },
    either::Either,
    sbpf_common::{
        inst_param::{Number, Register},
        instruction::Instruction,
        opcode::Opcode,
    },
    std::{
        collections::{HashMap, HashSet},
        path::PathBuf,
    },
    syscall_map::murmur3_32,
};

type LabelOffsetMap = HashMap<String, u64>;
type NumericLabel = (String, u64, usize);

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OptimizationConfig {
    Disabled,
    Enabled { cfg_dump_dir: Option<PathBuf> },
}

impl Default for OptimizationConfig {
    fn default() -> Self {
        Self::disabled()
    }
}

impl OptimizationConfig {
    pub fn disabled() -> Self {
        Self::Disabled
    }

    pub fn enabled() -> Self {
        Self::Enabled { cfg_dump_dir: None }
    }

    pub fn with_cfg_dump_dir(self, path: impl Into<PathBuf>) -> Self {
        match self {
            Self::Enabled { .. } => Self::Enabled {
                cfg_dump_dir: Some(path.into()),
            },
            Self::Disabled => Self::Disabled,
        }
    }
}

#[derive(Default, Debug)]
pub struct AST {
    pub nodes: Vec<ASTNode>,
    pub rodata_nodes: Vec<ASTNode>,

    function_entries: HashSet<String>,
    text_size: u64,
    rodata_size: u64,
}

impl AST {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn add_function_entry(&mut self, name: String) {
        self.function_entries.insert(name);
    }

    pub(crate) fn function_entries(&self) -> &HashSet<String> {
        &self.function_entries
    }

    //
    pub fn set_text_size(&mut self, text_size: u64) {
        self.text_size = text_size;
    }

    //
    pub fn set_rodata_size(&mut self, rodata_size: u64) {
        self.rodata_size = rodata_size;
    }

    //
    pub fn get_instruction_at_offset(&mut self, offset: u64) -> Option<&mut Instruction> {
        self.nodes
            .iter_mut()
            .find(|node| match node {
                ASTNode::Instruction {
                    instruction: _,
                    offset: inst_offset,
                    ..
                } => offset == *inst_offset,
                _ => false,
            })
            .map(|node| match node {
                ASTNode::Instruction { instruction, .. } => instruction,
                _ => panic!("Expected Instruction node"),
            })
    }

    //
    pub fn get_rodata_at_offset(&self, offset: u64) -> Option<&ROData> {
        self.rodata_nodes
            .iter()
            .find(|node| match node {
                ASTNode::ROData {
                    rodata: _,
                    offset: rodata_offset,
                    ..
                } => offset == *rodata_offset,
                _ => false,
            })
            .map(|node| match node {
                ASTNode::ROData { rodata, .. } => rodata,
                _ => panic!("Expected ROData node"),
            })
    }

    /// Resolve numeric label references (like "2f" or "1b")
    pub(crate) fn resolve_numeric_label(
        label_ref: &str,
        current_idx: usize,
        numeric_labels: &[NumericLabel],
    ) -> Option<u64> {
        if let Some(direction) = label_ref.chars().last()
            && (direction == 'f' || direction == 'b')
        {
            let label_num = &label_ref[..label_ref.len() - 1];

            if direction == 'f' {
                // search forward from current position
                for (name, offset, node_idx) in numeric_labels {
                    if name == label_num && *node_idx > current_idx {
                        return Some(*offset);
                    }
                }
            } else {
                // search backward from current position
                for (name, offset, node_idx) in numeric_labels.iter().rev() {
                    if name == label_num && *node_idx < current_idx {
                        return Some(*offset);
                    }
                }
            }
        }
        None
    }
}

pub fn build_program(
    mut ast: AST,
    arch: SbpfArch,
    optimization: OptimizationConfig,
) -> Result<ProgramLayout, Vec<CompileError>> {
    let optimization = run_optimizations(&mut ast, &optimization);
    let mut errors = optimization.errors;

    let (label_offset_map, numeric_labels) = label_offset_map(&ast);
    let program_is_static = arch.is_v3()
        || !ast.nodes.iter().any(|node| {
            matches!(node, ASTNode::Instruction { instruction: inst, .. }
                if inst.is_syscall()
                || (inst.opcode == Opcode::Lddw && matches!(&inst.imm, Some(Either::Left(_)))))
        });

    let label_resolution = resolve_label_references(
        &mut ast,
        arch,
        program_is_static,
        &label_offset_map,
        &numeric_labels,
    );
    errors.extend(label_resolution.errors);

    optimizer::remove_temp_control_flow_target_labels(
        &mut ast.nodes,
        &optimization.labels_to_remove,
    );

    if !errors.is_empty() {
        Err(errors)
    } else {
        Ok(ProgramLayout {
            code_section: CodeSection::new(std::mem::take(&mut ast.nodes), ast.text_size),
            data_section: DataSection::new(std::mem::take(&mut ast.rodata_nodes), ast.rodata_size),
            dynamic_symbols: label_resolution.dynamic_symbols,
            relocation_data: label_resolution.relocations,
            prog_is_static: program_is_static,
            arch,
            debug_sections: Vec::default(),
        })
    }
}

#[derive(Default)]
struct OptimizationOutcome {
    labels_to_remove: HashSet<String>,
    errors: Vec<CompileError>,
}

fn run_optimizations(ast: &mut AST, config: &OptimizationConfig) -> OptimizationOutcome {
    let OptimizationConfig::Enabled { cfg_dump_dir } = config else {
        return OptimizationOutcome::default();
    };

    // Normalize numeric and relative control-flow targets to labels before running
    // CFG-based optimizations. Synthetic labels are tracked so they can be removed
    // after optimization, and the pass is skipped if normalization fails.
    let canonicalized_targets = optimizer::canonicalize_control_flow_targets(&mut ast.nodes);
    let labels_to_remove = canonicalized_targets.labels_to_remove;
    let mut errors = Vec::new();

    if canonicalized_targets.errors.is_empty() {
        if let Some(dump_dir) = cfg_dump_dir.as_deref() {
            let mut dump_errors = Vec::new();
            if let Err(error) = std::fs::create_dir_all(dump_dir) {
                dump_errors.push((dump_dir.to_path_buf(), error));
                optimizer::eliminate_unreachable_functions(ast);
            } else {
                optimizer::eliminate_unreachable_functions_with_observer(ast, |stage, cfg| {
                    let path = dump_dir.join(stage.file_name());
                    if let Err(error) = std::fs::write(&path, sbpf_analyze::dump_cfg(cfg)) {
                        dump_errors.push((path, error));
                    }
                });
            }
            for (path, error) in dump_errors {
                errors.push(CompileError::BytecodeError {
                    error: format!("failed to write CFG dump '{}': {error}", path.display()),
                    span: 0..0,
                    custom_label: None,
                });
            }
        } else {
            optimizer::eliminate_unreachable_functions(ast);
        }
    }

    OptimizationOutcome {
        labels_to_remove,
        errors,
    }
}

#[derive(Default)]
struct LabelResolution {
    dynamic_symbols: DynamicSymbolMap,
    relocations: RelDynMap,
    errors: Vec<CompileError>,
}

fn resolve_label_references(
    ast: &mut AST,
    arch: SbpfArch,
    program_is_static: bool,
    label_offset_map: &LabelOffsetMap,
    numeric_labels: &[NumericLabel],
) -> LabelResolution {
    let mut relocations = RelDynMap::new();
    let mut dynamic_symbols = DynamicSymbolMap::new();
    let mut errors = Vec::new();

    // Resolve both static and dynamic syscalls.
    for node in ast.nodes.iter_mut() {
        if let ASTNode::Instruction {
            instruction: inst,
            offset,
        } = node
            && inst.is_syscall()
            && let Some(Either::Left(syscall_name)) = &inst.imm
        {
            let syscall_name = syscall_name.clone();
            if arch.is_v3() {
                // Static syscall: src = 0, imm = hash
                inst.src = Some(Register { n: 0 });
                inst.imm = Some(Either::Right(Number::Int(murmur3_32(&syscall_name) as i64)));
            } else {
                // Dynamic syscall: src = 1, imm = -1
                inst.src = Some(Register { n: 1 });
                inst.imm = Some(Either::Right(Number::Int(-1)));

                // Add relocation for dynamic syscall
                relocations.add_rel_dyn(*offset, RelocationType::RSbfSyscall, syscall_name.clone());
                dynamic_symbols.add_call_target(syscall_name.clone(), *offset);
            }
        }
    }

    for (idx, node) in ast.nodes.iter_mut().enumerate() {
        if let ASTNode::Instruction {
            instruction: inst,
            offset,
            ..
        } = node
        {
            // For jump/call instructions, replace label with relative offsets
            if inst.is_jump()
                && let Some(Either::Left(label)) = &inst.off
            {
                let target_offset = if let Some(offset) = label_offset_map.get(label) {
                    Some(*offset)
                } else {
                    // Handle numeric label references
                    AST::resolve_numeric_label(label, idx, numeric_labels)
                };

                if let Some(target_offset) = target_offset {
                    let rel_offset = (target_offset as i64 - *offset as i64) / 8 - 1;
                    inst.off = Some(Either::Right(rel_offset as i16));
                } else {
                    errors.push(CompileError::UndefinedLabel {
                        label: label.clone(),
                        span: inst.span.clone(),
                        custom_label: None,
                    });
                }
            } else if inst.opcode == Opcode::Call
                && let Some(Either::Left(label)) = &inst.imm
                && let Some(target_offset) = label_offset_map.get(label)
            {
                let rel_offset = (*target_offset as i64 - *offset as i64) / 8 - 1;
                inst.src = Some(Register { n: 1 });
                inst.imm = Some(Either::Right(Number::Int(rel_offset)));
            }

            if inst.opcode == Opcode::Lddw
                && let Some(Either::Left(name)) = &inst.imm
            {
                let label = name.clone();
                // Add relocation for lddw (only for v0)
                if !arch.is_v3() {
                    relocations.add_rel_dyn(*offset, RelocationType::RSbf64Relative, label.clone());
                }

                if let Some(target_offset) = label_offset_map.get(&label) {
                    let abs_offset = if arch.is_v3() {
                        if *target_offset >= ast.text_size {
                            (ProgramHeader::V3_RODATA_VADDR + *target_offset - ast.text_size) as i64
                        } else {
                            (ProgramHeader::V3_BYTECODE_VADDR + *target_offset) as i64
                        }
                    } else {
                        let ph_count = if program_is_static { 1 } else { 3 };
                        let ph_offset = 64 + (ph_count as u64 * 56) as i64;
                        *target_offset as i64 + ph_offset
                    };
                    // Replace label with immediate value
                    inst.imm = Some(Either::Right(Number::Addr(abs_offset)));
                } else {
                    errors.push(CompileError::UndefinedLabel {
                        label: name.clone(),
                        span: inst.span.clone(),
                        custom_label: None,
                    });
                }
            }
        }
    }

    // Set entry point offset if a GlobalDecl was specified
    let entry_label = ast.nodes.iter().find_map(|node| {
        if let ASTNode::GlobalDecl { global_decl } = node {
            Some(global_decl.entry_label.clone())
        } else {
            None
        }
    });
    if let Some(entry_label) = entry_label
        && let Some(offset) = label_offset_map.get(&entry_label)
    {
        dynamic_symbols.add_entry_point(entry_label, *offset);
    }

    LabelResolution {
        dynamic_symbols,
        relocations,
        errors,
    }
}

fn label_offset_map(ast: &AST) -> (LabelOffsetMap, Vec<NumericLabel>) {
    let mut label_offset_map = HashMap::new();
    let mut numeric_labels = Vec::new();

    for (idx, node) in ast.nodes.iter().enumerate() {
        if let ASTNode::Label { label, offset } = node {
            label_offset_map.insert(label.name.clone(), *offset);
            numeric_labels.push((label.name.clone(), *offset, idx));
        }
    }

    for node in &ast.rodata_nodes {
        if let ASTNode::ROData { rodata, offset } = node {
            label_offset_map.insert(rodata.name.clone(), *offset + ast.text_size);
        }
    }

    (label_offset_map, numeric_labels)
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        crate::{astnode::Label, parser::Token},
    };

    #[test]
    fn test_ast_new() {
        let ast = AST::new();
        assert!(ast.nodes.is_empty());
        assert!(ast.rodata_nodes.is_empty());
        assert_eq!(ast.text_size, 0);
        assert_eq!(ast.rodata_size, 0);
    }

    #[test]
    fn test_ast_set_sizes() {
        let mut ast = AST::new();
        ast.set_text_size(100);
        ast.set_rodata_size(50);
        assert_eq!(ast.text_size, 100);
        assert_eq!(ast.rodata_size, 50);
    }

    #[test]
    fn test_get_instruction_at_offset() {
        let mut ast = AST::new();
        ast.nodes
            .push(instruction_node(Opcode::Exit, 0, None, None));

        let found = ast.get_instruction_at_offset(0);
        assert!(found.is_some());
        assert_eq!(found.unwrap().opcode, Opcode::Exit);

        let not_found = ast.get_instruction_at_offset(8);
        assert!(not_found.is_none());
    }

    #[test]
    fn test_get_rodata_at_offset() {
        let mut ast = AST::new();
        let rodata = ROData {
            name: "data".to_string(),
            args: vec![
                Token::Directive("ascii".to_string(), 0..5),
                Token::StringLiteral("test".to_string(), 6..12),
            ],
            span: 0..12,
        };
        ast.rodata_nodes.push(ASTNode::ROData {
            rodata: rodata.clone(),
            offset: 0,
        });

        let found = ast.get_rodata_at_offset(0);
        assert!(found.is_some());
        assert_eq!(found.unwrap().name, "data");
    }

    #[test]
    fn test_resolve_numeric_label_forward() {
        let numeric_labels = vec![("1".to_string(), 16, 2), ("2".to_string(), 32, 4)];

        let result = AST::resolve_numeric_label("1f", 0, &numeric_labels);
        assert_eq!(result, Some(16));

        let result = AST::resolve_numeric_label("2f", 3, &numeric_labels);
        assert_eq!(result, Some(32));
    }

    #[test]
    fn test_resolve_numeric_label_backward() {
        let numeric_labels = vec![("1".to_string(), 16, 2), ("2".to_string(), 32, 4)];

        let result = AST::resolve_numeric_label("1b", 3, &numeric_labels);
        assert_eq!(result, Some(16));

        let result = AST::resolve_numeric_label("2b", 5, &numeric_labels);
        assert_eq!(result, Some(32));
    }

    #[test]
    fn test_canonicalize_numeric_jump_target_to_label() {
        let mut nodes = vec![
            instruction_node(Opcode::Ja, 0, Some(Either::Left("1f".to_string())), None),
            label_node("1", 8),
            instruction_node(Opcode::Exit, 8, None, None),
        ];

        let canonicalized = optimizer::canonicalize_control_flow_targets(&mut nodes);

        assert!(canonicalized.errors.is_empty());
        assert!(canonicalized.labels_to_remove.is_empty());
        let ASTNode::Instruction { instruction, .. } = &nodes[0] else {
            panic!("expected instruction");
        };
        assert_eq!(instruction.off, Some(Either::Left("1".to_string())));
    }

    #[test]
    fn test_canonicalize_relative_jump_target_to_synthetic_label() {
        let mut nodes = vec![
            instruction_node(Opcode::Ja, 0, Some(Either::Right(1)), None),
            instruction_node(Opcode::Exit, 8, None, None),
            instruction_node(Opcode::Exit, 16, None, None),
        ];

        let canonicalized = optimizer::canonicalize_control_flow_targets(&mut nodes);

        assert!(canonicalized.errors.is_empty());
        assert_eq!(canonicalized.labels_to_remove.len(), 1);

        let ASTNode::Instruction { instruction, .. } = &nodes[0] else {
            panic!("expected instruction");
        };
        let Some(Either::Left(label)) = &instruction.off else {
            panic!("expected canonical label target");
        };
        assert!(label.starts_with("temp_"));
        assert!(canonicalized.labels_to_remove.contains(label));
        assert!(
            matches!(&nodes[2], ASTNode::Label { label: target_label, offset }
                if target_label.name == *label && *offset == 16)
        );
    }

    #[test]
    fn test_canonicalize_rejects_invalid_relative_jump_target() {
        let mut nodes = vec![
            instruction_node(Opcode::Ja, 0, Some(Either::Right(1)), None),
            instruction_node(Opcode::Exit, 8, None, None),
        ];

        let canonicalized = optimizer::canonicalize_control_flow_targets(&mut nodes);

        assert_eq!(canonicalized.errors.len(), 1);
        assert!(canonicalized.labels_to_remove.is_empty());
        assert_eq!(nodes.len(), 2);
        let ASTNode::Instruction { instruction, .. } = &nodes[0] else {
            panic!("expected instruction");
        };
        assert_eq!(instruction.off, Some(Either::Right(1)));
    }

    #[test]
    fn test_dce_recomputes_relative_call_target_after_removing_code() {
        let mut ast = AST::new();
        ast.add_function_entry("entrypoint".to_string());
        ast.add_function_entry("dead".to_string());
        ast.add_function_entry("target".to_string());
        ast.nodes = vec![
            label_node("entrypoint", 0),
            internal_call_node(0, 2),
            instruction_node(Opcode::Exit, 8, None, None),
            label_node("dead", 16),
            instruction_node(Opcode::Exit, 16, None, None),
            label_node("target", 24),
            instruction_node(Opcode::Exit, 24, None, None),
        ];
        ast.set_text_size(32);

        let program_layout =
            build_program(ast, SbpfArch::V0, OptimizationConfig::enabled()).unwrap();
        let nodes = program_layout.code_section.get_nodes();

        assert_eq!(
            nodes
                .iter()
                .filter(|node| matches!(node, ASTNode::Instruction { .. }))
                .count(),
            3
        );
        assert!(matches!(
            &nodes[1],
            ASTNode::Instruction { instruction, offset }
                if instruction.opcode == Opcode::Call
                    && instruction.src == Some(Register { n: 1 })
                    && instruction.imm == Some(Either::Right(Number::Int(1)))
                    && *offset == 0
        ));
        assert!(matches!(
            &nodes[3],
            ASTNode::Label { label, offset } if label.name == "target" && *offset == 16
        ));
    }

    #[test]
    fn test_optimize_ast_removes_temp_jump_target_labels() {
        let mut ast = AST::new();
        ast.nodes = vec![
            instruction_node(Opcode::Ja, 0, Some(Either::Right(1)), None),
            instruction_node(Opcode::Exit, 8, None, None),
            instruction_node(Opcode::Exit, 16, None, None),
        ];
        ast.set_text_size(24);
        ast.set_rodata_size(0);

        let result = build_program(ast, SbpfArch::V0, OptimizationConfig::enabled());

        assert!(result.is_ok());
        let program_layout = result.unwrap();
        assert!(!program_layout.code_section.get_nodes().iter().any(|node| {
            matches!(node, ASTNode::Label { label, .. }
                if label
                    .name
                    .starts_with("temp_"))
        }));
        let ASTNode::Instruction { instruction, .. } = &program_layout.code_section.get_nodes()[0]
        else {
            panic!("expected instruction");
        };
        assert_eq!(instruction.off, Some(Either::Right(1)));
    }

    #[test]
    fn test_build_program_simple() {
        for arch in [SbpfArch::V0, SbpfArch::V3] {
            let mut ast = AST::new();
            ast.nodes
                .push(instruction_node(Opcode::Exit, 0, None, None));
            ast.set_text_size(8);
            ast.set_rodata_size(0);

            let result = build_program(ast, arch, OptimizationConfig::default());
            assert!(result.is_ok());
            let parse_result = result.unwrap();
            assert!(parse_result.prog_is_static);
        }
    }

    #[test]
    fn test_build_program_undefined_label_error() {
        for arch in [SbpfArch::V0, SbpfArch::V3] {
            let mut ast = AST::new();
            ast.nodes.push(instruction_node(
                Opcode::Ja,
                0,
                Some(Either::Left("undefined_label".to_string())),
                None,
            ));
            ast.set_text_size(8);

            let result = build_program(ast, arch, OptimizationConfig::default());
            assert!(result.is_err());
        }
    }

    #[test]
    fn test_build_program_static_syscalls_no_relocation() {
        let mut ast = AST::new();

        ast.nodes.push(instruction_node(
            Opcode::Call,
            0,
            None,
            Some(Either::Left("sol_log_".to_string())),
        ));
        ast.nodes
            .push(instruction_node(Opcode::Exit, 8, None, None));

        ast.set_text_size(16);
        ast.set_rodata_size(0);

        let result = build_program(ast, SbpfArch::V3, OptimizationConfig::default());
        assert!(result.is_ok());
        let parse_result = result.unwrap();

        assert!(parse_result.prog_is_static);
        assert!(parse_result.relocation_data.get_rel_dyns().is_empty());
    }

    #[test]
    fn test_build_program_dynamic_syscalls_with_relocation() {
        let mut ast = AST::new();

        ast.nodes.push(instruction_node(
            Opcode::Call,
            0,
            None,
            Some(Either::Left("sol_log_".to_string())),
        ));
        ast.nodes
            .push(instruction_node(Opcode::Exit, 8, None, None));

        ast.set_text_size(16);
        ast.set_rodata_size(0);

        let result = build_program(ast, SbpfArch::V0, OptimizationConfig::default());
        assert!(result.is_ok());
        let parse_result = result.unwrap();

        assert!(!parse_result.prog_is_static);
        assert!(!parse_result.relocation_data.get_rel_dyns().is_empty());
    }

    fn label_node(name: &str, offset: u64) -> ASTNode {
        ASTNode::Label {
            label: Label {
                name: name.to_string(),
                span: 0..0,
            },
            offset,
        }
    }

    fn instruction_node(
        opcode: Opcode,
        offset: u64,
        off: Option<Either<String, i16>>,
        imm: Option<Either<String, Number>>,
    ) -> ASTNode {
        ASTNode::Instruction {
            instruction: Instruction {
                opcode,
                dst: None,
                src: None,
                off,
                imm,
                span: 0..0,
            },
            offset,
        }
    }

    fn internal_call_node(offset: u64, relative_offset: i64) -> ASTNode {
        ASTNode::Instruction {
            instruction: Instruction {
                opcode: Opcode::Call,
                dst: None,
                src: Some(Register { n: 1 }),
                off: None,
                imm: Some(Either::Right(Number::Int(relative_offset))),
                span: 0..0,
            },
            offset,
        }
    }
}