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
#![allow(clippy::arithmetic_side_effects)]
// Copyright 2017 Rich Lane <lanerl@gmail.com>
//
// Licensed under the Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0> or
// the MIT license <http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

//! This module translates eBPF assembly language to binary.

use self::InstructionType::{
    AluBinary, AluUnary, CallImm, CallReg, Endian, JumpConditional, JumpUnconditional, LoadAbs,
    LoadDwImm, LoadInd, LoadReg, NoOperand, StoreImm, StoreReg, Syscall,
};
use crate::{
    asm_parser::{
        parse,
        Operand::{Integer, Label, Memory, Register},
        Statement,
    },
    ebpf::{self, Insn},
    elf::Executable,
    program::{BuiltinProgram, FunctionRegistry, SBPFVersion},
    vm::ContextObject,
};
use std::{collections::HashMap, sync::Arc};

#[derive(Clone, Copy, Debug, PartialEq)]
enum InstructionType {
    AluBinary,
    AluUnary,
    LoadDwImm,
    LoadAbs,
    LoadInd,
    LoadReg,
    StoreImm,
    StoreReg,
    JumpUnconditional,
    JumpConditional,
    Syscall,
    CallImm,
    CallReg,
    Endian(i64),
    NoOperand,
}

fn make_instruction_map() -> HashMap<String, (InstructionType, u8)> {
    let mut result = HashMap::new();

    let alu_binary_ops = [
        ("add", ebpf::BPF_ADD),
        ("sub", ebpf::BPF_SUB),
        ("mul", ebpf::BPF_MUL),
        ("div", ebpf::BPF_DIV),
        ("or", ebpf::BPF_OR),
        ("and", ebpf::BPF_AND),
        ("lsh", ebpf::BPF_LSH),
        ("rsh", ebpf::BPF_RSH),
        ("mod", ebpf::BPF_MOD),
        ("xor", ebpf::BPF_XOR),
        ("mov", ebpf::BPF_MOV),
        ("arsh", ebpf::BPF_ARSH),
        ("hor", ebpf::BPF_HOR),
    ];

    let mem_sizes = [
        ("w", ebpf::BPF_W),
        ("h", ebpf::BPF_H),
        ("b", ebpf::BPF_B),
        ("dw", ebpf::BPF_DW),
    ];

    let jump_conditions = [
        ("jeq", ebpf::BPF_JEQ),
        ("jgt", ebpf::BPF_JGT),
        ("jge", ebpf::BPF_JGE),
        ("jlt", ebpf::BPF_JLT),
        ("jle", ebpf::BPF_JLE),
        ("jset", ebpf::BPF_JSET),
        ("jne", ebpf::BPF_JNE),
        ("jsgt", ebpf::BPF_JSGT),
        ("jsge", ebpf::BPF_JSGE),
        ("jslt", ebpf::BPF_JSLT),
        ("jsle", ebpf::BPF_JSLE),
    ];

    {
        let mut entry = |name: &str, inst_type: InstructionType, opc: u8| {
            result.insert(name.to_string(), (inst_type, opc))
        };

        // Miscellaneous.
        entry("exit", NoOperand, ebpf::EXIT);
        entry("ja", JumpUnconditional, ebpf::JA);
        entry("syscall", Syscall, ebpf::CALL_IMM);
        entry("call", CallImm, ebpf::CALL_IMM);
        entry("callx", CallReg, ebpf::CALL_REG);
        entry("lddw", LoadDwImm, ebpf::LD_DW_IMM);

        // AluUnary.
        entry("neg", AluUnary, ebpf::NEG64);
        entry("neg32", AluUnary, ebpf::NEG32);
        entry("neg64", AluUnary, ebpf::NEG64);

        // AluBinary.
        for &(name, opc) in &alu_binary_ops {
            entry(name, AluBinary, ebpf::BPF_ALU64 | opc);
            entry(&format!("{name}32"), AluBinary, ebpf::BPF_ALU | opc);
            entry(&format!("{name}64"), AluBinary, ebpf::BPF_ALU64 | opc);
        }

        // Product Quotient Remainder.
        entry(
            "lmul",
            AluBinary,
            ebpf::BPF_PQR | ebpf::BPF_B | ebpf::BPF_LMUL,
        );
        entry(
            "lmul64",
            AluBinary,
            ebpf::BPF_PQR | ebpf::BPF_B | ebpf::BPF_LMUL,
        );
        entry("lmul32", AluBinary, ebpf::BPF_PQR | ebpf::BPF_LMUL);
        entry(
            "uhmul",
            AluBinary,
            ebpf::BPF_PQR | ebpf::BPF_B | ebpf::BPF_UHMUL,
        );
        entry(
            "uhmul64",
            AluBinary,
            ebpf::BPF_PQR | ebpf::BPF_B | ebpf::BPF_UHMUL,
        );
        entry("uhmul32", AluBinary, ebpf::BPF_PQR | ebpf::BPF_UHMUL);
        entry(
            "shmul",
            AluBinary,
            ebpf::BPF_PQR | ebpf::BPF_B | ebpf::BPF_SHMUL,
        );
        entry(
            "shmul64",
            AluBinary,
            ebpf::BPF_PQR | ebpf::BPF_B | ebpf::BPF_SHMUL,
        );
        entry("shmul32", AluBinary, ebpf::BPF_PQR | ebpf::BPF_SHMUL);
        entry(
            "udiv",
            AluBinary,
            ebpf::BPF_PQR | ebpf::BPF_B | ebpf::BPF_UDIV,
        );
        entry(
            "udiv64",
            AluBinary,
            ebpf::BPF_PQR | ebpf::BPF_B | ebpf::BPF_UDIV,
        );
        entry("udiv32", AluBinary, ebpf::BPF_PQR | ebpf::BPF_UDIV);
        entry(
            "urem",
            AluBinary,
            ebpf::BPF_PQR | ebpf::BPF_B | ebpf::BPF_UREM,
        );
        entry(
            "urem64",
            AluBinary,
            ebpf::BPF_PQR | ebpf::BPF_B | ebpf::BPF_UREM,
        );
        entry("urem32", AluBinary, ebpf::BPF_PQR | ebpf::BPF_UREM);
        entry(
            "sdiv",
            AluBinary,
            ebpf::BPF_PQR | ebpf::BPF_B | ebpf::BPF_SDIV,
        );
        entry(
            "sdiv64",
            AluBinary,
            ebpf::BPF_PQR | ebpf::BPF_B | ebpf::BPF_SDIV,
        );
        entry("sdiv32", AluBinary, ebpf::BPF_PQR | ebpf::BPF_SDIV);
        entry(
            "srem",
            AluBinary,
            ebpf::BPF_PQR | ebpf::BPF_B | ebpf::BPF_SREM,
        );
        entry(
            "srem64",
            AluBinary,
            ebpf::BPF_PQR | ebpf::BPF_B | ebpf::BPF_SREM,
        );
        entry("srem32", AluBinary, ebpf::BPF_PQR | ebpf::BPF_SREM);

        // LoadAbs, LoadInd, LoadReg, StoreImm, and StoreReg.
        for &(suffix, size) in &mem_sizes {
            entry(
                &format!("ldabs{suffix}"),
                LoadAbs,
                ebpf::BPF_ABS | ebpf::BPF_LD | size,
            );
            entry(
                &format!("ldind{suffix}"),
                LoadInd,
                ebpf::BPF_IND | ebpf::BPF_LD | size,
            );
            entry(
                &format!("ldx{suffix}"),
                LoadReg,
                ebpf::BPF_MEM | ebpf::BPF_LDX | size,
            );
            entry(
                &format!("st{suffix}"),
                StoreImm,
                ebpf::BPF_MEM | ebpf::BPF_ST | size,
            );
            entry(
                &format!("stx{suffix}"),
                StoreReg,
                ebpf::BPF_MEM | ebpf::BPF_STX | size,
            );
        }

        // JumpConditional.
        for &(name, condition) in &jump_conditions {
            entry(name, JumpConditional, ebpf::BPF_JMP | condition);
        }

        // Endian.
        for &size in &[16, 32, 64] {
            entry(&format!("be{size}"), Endian(size), ebpf::BE);
            entry(&format!("le{size}"), Endian(size), ebpf::LE);
        }
    }

    result
}

fn insn(opc: u8, dst: i64, src: i64, off: i64, imm: i64) -> Result<Insn, String> {
    if !(0..16).contains(&dst) {
        return Err(format!("Invalid destination register {dst}"));
    }
    if !(0..16).contains(&src) {
        return Err(format!("Invalid source register {src}"));
    }
    if off < i16::MIN as i64 || off > i16::MAX as i64 {
        return Err(format!("Invalid offset {off}"));
    }
    if imm < i32::MIN as i64 || imm > i32::MAX as i64 {
        return Err(format!("Invalid immediate {imm}"));
    }
    Ok(Insn {
        ptr: 0,
        opc,
        dst: dst as u8,
        src: src as u8,
        off: off as i16,
        imm,
    })
}

fn resolve_label(
    insn_ptr: usize,
    labels: &HashMap<&str, usize>,
    label: &str,
) -> Result<i64, String> {
    labels
        .get(label)
        .map(|target_pc| *target_pc as i64 - insn_ptr as i64 - 1)
        .ok_or_else(|| format!("Label not found {label}"))
}

/// Parse assembly source and translate to binary.
///
/// # Examples
///
/// ```
/// use solana_rbpf::{assembler::assemble, program::BuiltinProgram, vm::{Config, TestContextObject}};
/// let executable = assemble::<TestContextObject>(
///    "add64 r1, 0x605
///     mov64 r2, 0x32
///     mov64 r1, r0
///     be16 r0
///     neg64 r2
///     exit",
///     std::sync::Arc::new(BuiltinProgram::new_mock()),
/// ).unwrap();
/// let program = executable.get_text_bytes().1;
/// println!("{:?}", program);
/// # assert_eq!(program,
/// #            &[0x07, 0x01, 0x00, 0x00, 0x05, 0x06, 0x00, 0x00,
/// #              0xb7, 0x02, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00,
/// #              0xbf, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/// #              0xdc, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
/// #              0x87, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/// #              0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
/// ```
///
/// This will produce the following output:
///
/// ```test
/// [0x07, 0x01, 0x00, 0x00, 0x05, 0x06, 0x00, 0x00,
///  0xb7, 0x02, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00,
///  0xbf, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
///  0xdc, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
///  0x87, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
///  0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
/// ```
pub fn assemble<C: ContextObject>(
    src: &str,
    loader: Arc<BuiltinProgram<C>>,
) -> Result<Executable<C>, String> {
    let sbpf_version = if loader.get_config().enable_sbpf_v2 {
        SBPFVersion::V2
    } else {
        SBPFVersion::V1
    };

    let statements = parse(src)?;
    let instruction_map = make_instruction_map();
    let mut insn_ptr = 0;
    let mut function_registry = FunctionRegistry::default();
    let mut labels = HashMap::new();
    labels.insert("entrypoint", 0);
    for statement in statements.iter() {
        match statement {
            Statement::Label { name } => {
                if name.starts_with("function_") || name == "entrypoint" {
                    function_registry
                        .register_function(insn_ptr as u32, name.as_bytes(), insn_ptr)
                        .map_err(|_| format!("Label hash collision {name}"))?;
                }
                labels.insert(name.as_str(), insn_ptr);
            }
            Statement::Directive { name, operands } =>
            {
                #[allow(clippy::single_match)]
                match (name.as_str(), operands.as_slice()) {
                    ("fill", [Integer(repeat), Integer(_value)]) => {
                        insn_ptr += *repeat as usize;
                    }
                    _ => {}
                }
            }
            Statement::Instruction { name, .. } => {
                insn_ptr += if name == "lddw" { 2 } else { 1 };
            }
        }
    }
    insn_ptr = 0;
    let mut instructions: Vec<Insn> = Vec::new();
    for statement in statements.iter() {
        match statement {
            Statement::Label { .. } => {}
            Statement::Directive { name, operands } =>
            {
                #[allow(clippy::single_match)]
                match (name.as_str(), operands.as_slice()) {
                    ("fill", [Integer(repeat), Integer(value)]) => {
                        for _ in 0..*repeat {
                            instructions.push(Insn {
                                ptr: insn_ptr,
                                opc: *value as u8,
                                dst: (*value >> 8) as u8 & 0xF,
                                src: (*value >> 12) as u8 & 0xF,
                                off: (*value >> 16) as u16 as i16,
                                imm: (*value >> 32) as u32 as i64,
                            });
                            insn_ptr += 1;
                        }
                    }
                    _ => return Err(format!("Invalid directive {name:?}")),
                }
            }
            Statement::Instruction { name, operands } => {
                let name = name.as_str();
                match instruction_map.get(name) {
                    Some(&(inst_type, opc)) => {
                        let mut insn = match (inst_type, operands.as_slice()) {
                            (AluBinary, [Register(dst), Register(src)]) => {
                                insn(opc | ebpf::BPF_X, *dst, *src, 0, 0)
                            }
                            (AluBinary, [Register(dst), Integer(imm)]) => {
                                insn(opc | ebpf::BPF_K, *dst, 0, 0, *imm)
                            }
                            (AluUnary, [Register(dst)]) => insn(opc, *dst, 0, 0, 0),
                            (LoadAbs, [Integer(imm)]) => insn(opc, 0, 0, 0, *imm),
                            (LoadInd, [Register(src), Integer(imm)]) => insn(opc, 0, *src, 0, *imm),
                            (LoadReg, [Register(dst), Memory(src, off)])
                            | (StoreReg, [Memory(dst, off), Register(src)]) => {
                                insn(opc, *dst, *src, *off, 0)
                            }
                            (StoreImm, [Memory(dst, off), Integer(imm)]) => {
                                insn(opc, *dst, 0, *off, *imm)
                            }
                            (NoOperand, []) => insn(opc, 0, 0, 0, 0),
                            (JumpUnconditional, [Integer(off)]) => insn(opc, 0, 0, *off, 0),
                            (JumpConditional, [Register(dst), Register(src), Integer(off)]) => {
                                insn(opc | ebpf::BPF_X, *dst, *src, *off, 0)
                            }
                            (JumpConditional, [Register(dst), Integer(imm), Integer(off)]) => {
                                insn(opc | ebpf::BPF_K, *dst, 0, *off, *imm)
                            }
                            (JumpUnconditional, [Label(label)]) => {
                                insn(opc, 0, 0, resolve_label(insn_ptr, &labels, label)?, 0)
                            }
                            (CallImm, [Integer(imm)]) => {
                                let target_pc = *imm + insn_ptr as i64 + 1;
                                let label = format!("function_{}", target_pc as usize);
                                function_registry
                                    .register_function(
                                        target_pc as u32,
                                        label.as_bytes(),
                                        target_pc as usize,
                                    )
                                    .map_err(|_| format!("Label hash collision {name}"))?;
                                insn(opc, 0, 1, 0, target_pc)
                            }
                            (CallReg, [Register(dst)]) => {
                                if sbpf_version.callx_uses_src_reg() {
                                    insn(opc, 0, *dst, 0, 0)
                                } else {
                                    insn(opc, 0, 0, 0, *dst)
                                }
                            }
                            (JumpConditional, [Register(dst), Register(src), Label(label)]) => {
                                insn(
                                    opc | ebpf::BPF_X,
                                    *dst,
                                    *src,
                                    resolve_label(insn_ptr, &labels, label)?,
                                    0,
                                )
                            }
                            (JumpConditional, [Register(dst), Integer(imm), Label(label)]) => insn(
                                opc | ebpf::BPF_K,
                                *dst,
                                0,
                                resolve_label(insn_ptr, &labels, label)?,
                                *imm,
                            ),
                            (Syscall, [Label(label)]) => insn(
                                opc,
                                0,
                                0,
                                0,
                                ebpf::hash_symbol_name(label.as_bytes()) as i32 as i64,
                            ),
                            (CallImm, [Label(label)]) => {
                                let label: &str = label;
                                let target_pc = *labels
                                    .get(label)
                                    .ok_or_else(|| format!("Label not found {label}"))?;
                                insn(opc, 0, 1, 0, target_pc as i64)
                            }
                            (Endian(size), [Register(dst)]) => insn(opc, *dst, 0, 0, size),
                            (LoadDwImm, [Register(dst), Integer(imm)]) => {
                                insn(opc, *dst, 0, 0, (*imm << 32) >> 32)
                            }
                            _ => Err(format!("Unexpected operands: {operands:?}")),
                        }?;
                        insn.ptr = insn_ptr;
                        instructions.push(insn);
                        insn_ptr += 1;
                        if let LoadDwImm = inst_type {
                            if let Integer(imm) = operands[1] {
                                instructions.push(Insn {
                                    ptr: insn_ptr,
                                    imm: imm >> 32,
                                    ..Insn::default()
                                });
                                insn_ptr += 1;
                            }
                        }
                    }
                    None => return Err(format!("Invalid instruction {name:?}")),
                }
            }
        }
    }
    let program = instructions
        .iter()
        .flat_map(|insn| insn.to_vec())
        .collect::<Vec<_>>();
    Executable::<C>::from_text_bytes(&program, loader, sbpf_version, function_registry)
        .map_err(|err| format!("Executable constructor {err:?}"))
}