alaz 0.1.1

AArch64 汇编语言分析工具 - 支持237条指令、多优化级别对比、智能语义解释
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
//! 汇编指令语义解释器
//! 
//! 将汇编指令转换为人类可读的语义描述
//! 
//! V2: 基于 JSON 数据库的解耦设计

use crate::instruction::{Instruction, InstructionType, Operand};
use crate::instruction_db::{InstructionDatabase, InstructionDef};
use std::sync::OnceLock;

// 全局指令数据库(延迟初始化)
static INSTRUCTION_DB: OnceLock<InstructionDatabase> = OnceLock::new();

/// 获取指令数据库
fn get_instruction_db() -> &'static InstructionDatabase {
    INSTRUCTION_DB.get_or_init(|| {
        InstructionDatabase::load_embedded()
            .expect("Failed to load instruction database")
    })
}

/// 指令语义解释器
pub struct SemanticInterpreter;

impl SemanticInterpreter {
    /// 解释单条指令(新版:优先使用数据库)
    pub fn interpret(instruction: &Instruction) -> String {
        // 首先尝试从数据库获取指令定义
        let inst_type_str = format!("{:?}", instruction.instruction_type).to_lowercase();
        if let Some(def) = get_instruction_db().find_instruction(&inst_type_str) {
            return Self::interpret_from_db(&def, instruction);
        }
        
        // 回退到旧的硬编码解释(保持向后兼容)
        Self::interpret_legacy(instruction)
    }

    /// 从数据库定义生成语义解释
    fn interpret_from_db(def: &InstructionDef, instruction: &Instruction) -> String {
        // 使用数据库中的描述作为基础
        let base_desc = &def.description;
        
        // 如果有操作数,尝试生成更详细的解释
        if !instruction.operands.is_empty() {
            match def.mnemonic.as_str() {
                // 三操作数算术/逻辑指令
                "add" | "sub" | "mul" | "and" | "orr" | "eor" | "bic" => {
                    if instruction.operands.len() >= 3 {
                        let dest = Self::operand_name(&instruction.operands[0]);
                        let src1 = Self::operand_name(&instruction.operands[1]);
                        let src2 = Self::operand_name(&instruction.operands[2]);
                        let op = match def.mnemonic.as_str() {
                            "add" => "+",
                            "sub" => "-",
                            "mul" => "×",
                            "and" => "&",
                            "orr" => "|",
                            "eor" => "^",
                            "bic" => "& ~",
                            _ => "",
                        };
                        return format!("{} = {} {} {}", dest, src1, op, src2);
                    }
                }
                // 加载/存储指令
                "ldr" | "str" | "ldrb" | "strb" | "ldrh" | "strh" => {
                    if instruction.operands.len() >= 2 {
                        let reg = Self::operand_name(&instruction.operands[0]);
                        let mem = Self::operand_name(&instruction.operands[1]);
                        let action = if def.mnemonic.starts_with("ld") { "加载" } else { "存储" };
                        return format!("{} {} {}", action, reg, mem);
                    }
                }
                _ => {}
            }
        }
        
        // 默认返回数据库中的描述
        base_desc.clone()
    }

    /// 旧版硬编码解释(保持向后兼容)
    fn interpret_legacy(instruction: &Instruction) -> String {
        match instruction.instruction_type {
            InstructionType::ADD => Self::interpret_add(instruction),
            InstructionType::SUB => Self::interpret_sub(instruction),
            InstructionType::MUL => Self::interpret_mul(instruction),
            InstructionType::AND => Self::interpret_and(instruction),
            InstructionType::ORR => Self::interpret_orr(instruction),
            InstructionType::EOR => Self::interpret_eor(instruction),
            InstructionType::LSL => Self::interpret_lsl(instruction),
            InstructionType::LSR => Self::interpret_lsr(instruction),
            InstructionType::ASR => Self::interpret_asr(instruction),
            InstructionType::LDR => Self::interpret_ldr(instruction),
            InstructionType::LDRB => Self::interpret_ldrb(instruction),
            InstructionType::LDRH => Self::interpret_ldrh(instruction),
            InstructionType::LDP => Self::interpret_ldp(instruction),
            InstructionType::STR => Self::interpret_str(instruction),
            InstructionType::STRB => Self::interpret_strb(instruction),
            InstructionType::STRH => Self::interpret_strh(instruction),
            InstructionType::STP => Self::interpret_stp(instruction),
            InstructionType::MOV => Self::interpret_mov(instruction),
            InstructionType::MOVZ => Self::interpret_movz(instruction),
            InstructionType::MOVK => Self::interpret_movk(instruction),
            InstructionType::CMP => Self::interpret_cmp(instruction),
            InstructionType::B => Self::interpret_b(instruction),
            InstructionType::BL => Self::interpret_bl(instruction),
            InstructionType::BR => Self::interpret_br(instruction),
            InstructionType::RET => String::from("从子程序返回"),
            InstructionType::BEQ => String::from("如果相等则跳转 (Z=1)"),
            InstructionType::BNE => String::from("如果不相等则跳转 (Z=0)"),
            InstructionType::BHI => String::from("如果无符号大于则跳转 (C=1且Z=0)"),
            InstructionType::BLS => String::from("如果无符号小于等于则跳转 (C=0或Z=1)"),
            InstructionType::BCC => String::from("如果无进位则跳转 (C=0)"),
            InstructionType::BGE => String::from("如果有符号大于等于则跳转 (N=V)"),
            InstructionType::BLT => String::from("如果有符号小于则跳转 (N≠V)"),
            InstructionType::BGT => String::from("如果有符号大于则跳转 (Z=0且N=V)"),
            InstructionType::BLE => String::from("如果有符号小于等于则跳转 (Z=1或N≠V)"),
            InstructionType::CBZ => Self::interpret_cbz(instruction),
            InstructionType::CBNZ => Self::interpret_cbnz(instruction),
            InstructionType::NOP => String::from("空操作"),
            _ => format!("{:?} 指令", instruction.instruction_type),
        }
    }

    // 各指令的解释函数
    fn interpret_add(inst: &Instruction) -> String {
        if inst.operands.len() >= 3 {
            let dest = Self::operand_name(&inst.operands[0]);
            let src1 = Self::operand_name(&inst.operands[1]);
            let src2 = Self::operand_name(&inst.operands[2]);
            format!("{} = {} + {}", dest, src1, src2)
        } else {
            String::from("加法运算")
        }
    }

    fn interpret_sub(inst: &Instruction) -> String {
        if inst.operands.len() >= 3 {
            let dest = Self::operand_name(&inst.operands[0]);
            let src1 = Self::operand_name(&inst.operands[1]);
            let src2 = Self::operand_name(&inst.operands[2]);
            format!("{} = {} - {}", dest, src1, src2)
        } else {
            String::from("减法运算")
        }
    }

    fn interpret_mul(inst: &Instruction) -> String {
        if inst.operands.len() >= 3 {
            let dest = Self::operand_name(&inst.operands[0]);
            let src1 = Self::operand_name(&inst.operands[1]);
            let src2 = Self::operand_name(&inst.operands[2]);
            format!("{} = {} × {}", dest, src1, src2)
        } else {
            String::from("乘法运算")
        }
    }

    fn interpret_and(inst: &Instruction) -> String {
        if inst.operands.len() >= 3 {
            let dest = Self::operand_name(&inst.operands[0]);
            let src1 = Self::operand_name(&inst.operands[1]);
            let src2 = Self::operand_name(&inst.operands[2]);
            format!("{} = {} & {}", dest, src1, src2)
        } else {
            String::from("按位与")
        }
    }

    fn interpret_orr(inst: &Instruction) -> String {
        if inst.operands.len() >= 3 {
            let dest = Self::operand_name(&inst.operands[0]);
            let src1 = Self::operand_name(&inst.operands[1]);
            let src2 = Self::operand_name(&inst.operands[2]);
            format!("{} = {} | {}", dest, src1, src2)
        } else {
            String::from("按位或")
        }
    }

    fn interpret_eor(inst: &Instruction) -> String {
        if inst.operands.len() >= 3 {
            let dest = Self::operand_name(&inst.operands[0]);
            let src1 = Self::operand_name(&inst.operands[1]);
            let src2 = Self::operand_name(&inst.operands[2]);
            format!("{} = {} ^ {}", dest, src1, src2)
        } else {
            String::from("按位异或")
        }
    }

    fn interpret_lsl(inst: &Instruction) -> String {
        if inst.operands.len() >= 3 {
            let dest = Self::operand_name(&inst.operands[0]);
            let src = Self::operand_name(&inst.operands[1]);
            let shift = Self::operand_name(&inst.operands[2]);
            format!("{} = {} << {}", dest, src, shift)
        } else {
            String::from("逻辑左移")
        }
    }

    fn interpret_lsr(inst: &Instruction) -> String {
        if inst.operands.len() >= 3 {
            let dest = Self::operand_name(&inst.operands[0]);
            let src = Self::operand_name(&inst.operands[1]);
            let shift = Self::operand_name(&inst.operands[2]);
            format!("{} = {} >> {}", dest, src, shift)
        } else {
            String::from("逻辑右移")
        }
    }

    fn interpret_asr(inst: &Instruction) -> String {
        if inst.operands.len() >= 3 {
            let dest = Self::operand_name(&inst.operands[0]);
            let src = Self::operand_name(&inst.operands[1]);
            let shift = Self::operand_name(&inst.operands[2]);
            format!("{} = {} >> {} (算术)", dest, src, shift)
        } else {
            String::from("算术右移")
        }
    }

    fn interpret_ldr(inst: &Instruction) -> String {
        if inst.operands.len() >= 2 {
            let dest = Self::operand_name(&inst.operands[0]);
            let mem = Self::memory_operand_desc(&inst.operands[1]);
            format!("{} 加载到 {}", mem, dest)
        } else {
            String::from("从内存加载")
        }
    }

    fn interpret_ldrb(inst: &Instruction) -> String {
        if inst.operands.len() >= 2 {
            let dest = Self::operand_name(&inst.operands[0]);
            let mem = Self::memory_operand_desc(&inst.operands[1]);
            format!("{} 加载字节到 {}", mem, dest)
        } else {
            String::from("从内存加载字节")
        }
    }

    fn interpret_ldrh(inst: &Instruction) -> String {
        if inst.operands.len() >= 2 {
            let dest = Self::operand_name(&inst.operands[0]);
            let mem = Self::memory_operand_desc(&inst.operands[1]);
            format!("{} 加载半字到 {}", mem, dest)
        } else {
            String::from("从内存加载半字")
        }
    }

    fn interpret_ldp(inst: &Instruction) -> String {
        if inst.operands.len() >= 3 {
            let dest1 = Self::operand_name(&inst.operands[0]);
            let dest2 = Self::operand_name(&inst.operands[1]);
            let mem = Self::memory_operand_desc(&inst.operands[2]);
            format!("{} 加载 {}{}", mem, dest1, dest2)
        } else {
            String::from("从内存加载一对寄存器")
        }
    }

    fn interpret_str(inst: &Instruction) -> String {
        if inst.operands.len() >= 2 {
            let src = Self::operand_name(&inst.operands[0]);
            let mem = Self::memory_operand_desc(&inst.operands[1]);
            format!("{} 存储到 {}", src, mem)
        } else {
            String::from("存储到内存")
        }
    }

    fn interpret_strb(inst: &Instruction) -> String {
        if inst.operands.len() >= 2 {
            let src = Self::operand_name(&inst.operands[0]);
            let mem = Self::memory_operand_desc(&inst.operands[1]);
            format!("{} (字节) 存储到 {}", src, mem)
        } else {
            String::from("存储字节到内存")
        }
    }

    fn interpret_strh(inst: &Instruction) -> String {
        if inst.operands.len() >= 2 {
            let src = Self::operand_name(&inst.operands[0]);
            let mem = Self::memory_operand_desc(&inst.operands[1]);
            format!("{} (半字) 存储到 {}", src, mem)
        } else {
            String::from("存储半字到内存")
        }
    }

    fn interpret_stp(inst: &Instruction) -> String {
        if inst.operands.len() >= 3 {
            let src1 = Self::operand_name(&inst.operands[0]);
            let src2 = Self::operand_name(&inst.operands[1]);
            let mem = Self::memory_operand_desc(&inst.operands[2]);
            format!("{}{} 存储到 {}", src1, src2, mem)
        } else {
            String::from("存储一对寄存器到内存")
        }
    }

    fn interpret_mov(inst: &Instruction) -> String {
        if inst.operands.len() >= 2 {
            let dest = Self::operand_name(&inst.operands[0]);
            let src = Self::operand_name(&inst.operands[1]);
            format!("{} = {}", dest, src)
        } else {
            String::from("数据移动")
        }
    }

    fn interpret_movz(inst: &Instruction) -> String {
        if inst.operands.len() >= 2 {
            let dest = Self::operand_name(&inst.operands[0]);
            let src = Self::operand_name(&inst.operands[1]);
            format!("{} = {} (其他位清零)", dest, src)
        } else {
            String::from("移动立即数并清零")
        }
    }

    fn interpret_movk(inst: &Instruction) -> String {
        if inst.operands.len() >= 2 {
            let dest = Self::operand_name(&inst.operands[0]);
            let src = Self::operand_name(&inst.operands[1]);
            format!("{} 的部分位 = {} (保持其他位)", dest, src)
        } else {
            String::from("移动立即数并保持")
        }
    }

    fn interpret_cmp(inst: &Instruction) -> String {
        if inst.operands.len() >= 2 {
            let src1 = Self::operand_name(&inst.operands[0]);
            let src2 = Self::operand_name(&inst.operands[1]);
            format!("比较 {}{} (设置标志位)", src1, src2)
        } else {
            String::from("比较")
        }
    }

    fn interpret_b(inst: &Instruction) -> String {
        if !inst.operands.is_empty() {
            let target = Self::operand_name(&inst.operands[0]);
            format!("无条件跳转到 {}", target)
        } else {
            String::from("无条件跳转")
        }
    }

    fn interpret_bl(inst: &Instruction) -> String {
        if !inst.operands.is_empty() {
            let target = Self::operand_name(&inst.operands[0]);
            format!("调用函数 {} (保存返回地址)", target)
        } else {
            String::from("调用函数")
        }
    }

    fn interpret_br(inst: &Instruction) -> String {
        if !inst.operands.is_empty() {
            let target = Self::operand_name(&inst.operands[0]);
            format!("跳转到寄存器 {} 中的地址", target)
        } else {
            String::from("跳转到寄存器地址")
        }
    }

    fn interpret_cbz(inst: &Instruction) -> String {
        if inst.operands.len() >= 2 {
            let reg = Self::operand_name(&inst.operands[0]);
            let target = Self::operand_name(&inst.operands[1]);
            format!("如果 {} == 0 则跳转到 {}", reg, target)
        } else {
            String::from("比较为零则跳转")
        }
    }

    fn interpret_cbnz(inst: &Instruction) -> String {
        if inst.operands.len() >= 2 {
            let reg = Self::operand_name(&inst.operands[0]);
            let target = Self::operand_name(&inst.operands[1]);
            format!("如果 {} ≠ 0 则跳转到 {}", reg, target)
        } else {
            String::from("比较非零则跳转")
        }
    }

    // 辅助函数

    fn operand_name(operand: &Operand) -> String {
        match operand {
            Operand::Register(reg) => format!("{:?}", reg),
            Operand::Immediate(imm) => {
                if *imm < 0 {
                    format!("{}", imm)
                } else {
                    format!("0x{:x}", imm)
                }
            }
            Operand::Label(label) => label.clone(),
            Operand::Memory { base, offset, .. } => {
                if let Some(off) = offset {
                    if *off >= 0 {
                        format!("[{:?}+0x{:x}]", base, off)
                    } else {
                        format!("[{:?}-0x{:x}]", base, -off)
                    }
                } else {
                    format!("[{:?}]", base)
                }
            }
        }
    }

    fn memory_operand_desc(operand: &Operand) -> String {
        match operand {
            Operand::Memory { base, offset, index, .. } => {
                let mut desc = format!("({:?}", base);
                if let Some(off) = offset {
                    if *off >= 0 {
                        desc.push_str(&format!(" + 0x{:x}", off));
                    } else {
                        desc.push_str(&format!(" - 0x{:x}", -off));
                    }
                }
                if let Some(idx) = index {
                    desc.push_str(&format!(" + {:?}", idx));
                }
                desc.push(')');
                desc
            }
            _ => Self::operand_name(operand),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::register::Register;

    #[test]
    fn test_interpret_add() {
        let inst = Instruction::new(
            InstructionType::ADD,
            vec![
                Operand::Register(Register::X0),
                Operand::Register(Register::X1),
                Operand::Register(Register::X2),
            ],
            0,
        );
        let interpretation = SemanticInterpreter::interpret(&inst);
        assert_eq!(interpretation, "X0 = X1 + X2");
    }

    #[test]
    fn test_interpret_ldr() {
        let inst = Instruction::new(
            InstructionType::LDR,
            vec![
                Operand::Register(Register::X0),
                Operand::Memory {
                    base: Register::SP,
                    offset: Some(8),
                    index: None,
                    pre_indexed: false,
                    post_indexed: false,
                },
            ],
            0,
        );
        let interpretation = SemanticInterpreter::interpret(&inst);
        assert!(interpretation.contains("X0"));
        assert!(interpretation.contains("SP"));
    }
}