nabla-decompiler 0.1.2

Binary decompilation engine with CFG analysis and pseudocode generation
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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
//! Pseudocode generation and lifting from assembly

use anyhow::Result;
use std::collections::HashMap;

use crate::types::{
    Address, Disassembly, Function, InstructionGroup, PseudoCode, 
    Variable, VariableScope, VariableType
};

/// Generate pseudocode for all functions
pub fn generate_pseudocode(functions: &[Function], disasm: &Disassembly) -> Result<HashMap<Address, PseudoCode>> {
    let mut pseudocode_map = HashMap::new();
    
    for function in functions {
        let pseudocode = lift_function_to_pseudocode(function, disasm)?;
        pseudocode_map.insert(function.address, pseudocode);
    }
    
    Ok(pseudocode_map)
}

/// Generate pseudocode for a single function
pub fn lift_function_to_pseudocode(function: &Function, disasm: &Disassembly) -> Result<PseudoCode> {
    let mut code_lines = Vec::new();
    let mut variables = Vec::new();
    let mut comments = HashMap::new();
    let mut register_map = HashMap::new();
    
    // Initialize register mapping
    for i in 0..8 {
        register_map.insert(format!("r{}", i), format!("var_{}", i));
    }
    register_map.insert("sp".to_string(), "stack_ptr".to_string());
    register_map.insert("lr".to_string(), "return_addr".to_string());
    register_map.insert("pc".to_string(), "program_counter".to_string());
    
    // Generate function signature
    let default_name = format!("func_{:x}", function.address);
    let func_name = function.name.as_deref().unwrap_or(&default_name);
    code_lines.push(format!("int {}() {{", func_name));
    
    // Declare local variables
    for i in 0..8 {
        let var_name = format!("var_{}", i);
        variables.push(Variable {
            name: var_name.clone(),
            var_type: VariableType::Integer(32),
            first_use: function.address,
            scope: VariableScope::Local,
        });
        code_lines.push(format!("    int {};", var_name));
    }
    
    code_lines.push("".to_string());
    
    // Process instructions in order
    for &addr in &function.instructions {
        if let Some(instruction) = disasm.instructions.iter().find(|i| i.address == addr) {
            let pseudocode_line = lift_instruction_to_pseudocode(instruction, &register_map);
            
            // Add address comment
            comments.insert(addr, format!("0x{:x}: {} {}", addr, instruction.mnemonic, instruction.operands));
            
            // Add indented pseudocode
            if !pseudocode_line.is_empty() {
                code_lines.push(format!("    {}; // 0x{:x}", pseudocode_line, addr));
            }
            
            // Add control flow comments
            match instruction.group {
                InstructionGroup::Jump => {
                    if is_conditional_jump(instruction) {
                        code_lines.push("    // Conditional branch".to_string());
                    } else {
                        code_lines.push("    goto label; // Unconditional jump".to_string());
                    }
                }
                InstructionGroup::Call => {
                    code_lines.push("    // Function call".to_string());
                }
                InstructionGroup::Return => {
                    code_lines.push("    return var_0; // Return statement".to_string());
                }
                _ => {}
            }
        }
    }
    
    code_lines.push("}".to_string());
    
    let confidence = calculate_confidence(&function.instructions, disasm);
    
    Ok(PseudoCode {
        function_address: function.address,
        function_name: function.name.clone(),
        code: code_lines.join("\n"),
        variables,
        comments,
        confidence,
    })
}

/// Lift a single instruction to pseudocode
fn lift_instruction_to_pseudocode(instruction: &crate::types::Instruction, register_map: &HashMap<String, String>) -> String {
    let mnemonic = instruction.mnemonic.to_lowercase();
    let operands = &instruction.operands;
    
    match mnemonic.as_str() {
        // Move operations
        "mov" => lift_move_instruction(operands, register_map),
        "ldr" => lift_load_instruction(operands, register_map),
        "str" => lift_store_instruction(operands, register_map),
        
        // Arithmetic operations
        "add" => lift_arithmetic_instruction("add", operands, register_map),
        "sub" => lift_arithmetic_instruction("sub", operands, register_map),
        "mul" => lift_arithmetic_instruction("mul", operands, register_map),
        
        // Logical operations
        "and" => lift_logical_instruction("and", operands, register_map),
        "orr" => lift_logical_instruction("or", operands, register_map),
        "eor" => lift_logical_instruction("xor", operands, register_map),
        
        // Compare operations
        "cmp" => lift_compare_instruction(operands, register_map),
        "tst" => lift_test_instruction(operands, register_map),
        
        // Branch operations
        "b" | "bl" => lift_branch_instruction(&mnemonic, operands),
        
        // Stack operations
        "push" => lift_push_instruction(operands, register_map),
        "pop" => lift_pop_instruction(operands, register_map),
        
        // No-op
        "nop" => "/* no operation */".to_string(),
        
        _ => format!("/* {} {} */", mnemonic, operands),
    }
}

/// Lift move instruction
fn lift_move_instruction(operands: &str, register_map: &HashMap<String, String>) -> String {
    let parts: Vec<&str> = operands.split(',').map(|s| s.trim()).collect();
    if parts.len() == 2 {
        let dest = translate_operand(parts[0], register_map);
        let src = translate_operand(parts[1], register_map);
        format!("{} = {}", dest, src)
    } else {
        format!("/* mov {} */", operands)
    }
}

/// Lift load instruction
fn lift_load_instruction(operands: &str, register_map: &HashMap<String, String>) -> String {
    let parts: Vec<&str> = operands.split(',').map(|s| s.trim()).collect();
    if parts.len() == 2 {
        let dest = translate_operand(parts[0], register_map);
        let src = translate_memory_operand(parts[1], register_map);
        format!("{} = {}", dest, src)
    } else {
        format!("/* ldr {} */", operands)
    }
}

/// Lift store instruction
fn lift_store_instruction(operands: &str, register_map: &HashMap<String, String>) -> String {
    let parts: Vec<&str> = operands.split(',').map(|s| s.trim()).collect();
    if parts.len() == 2 {
        let src = translate_operand(parts[0], register_map);
        let dest = translate_memory_operand(parts[1], register_map);
        format!("{} = {}", dest, src)
    } else {
        format!("/* str {} */", operands)
    }
}

/// Lift arithmetic instruction
fn lift_arithmetic_instruction(op: &str, operands: &str, register_map: &HashMap<String, String>) -> String {
    let parts: Vec<&str> = operands.split(',').map(|s| s.trim()).collect();
    
    match parts.len() {
        2 => {
            // Two operand form: add r0, r1
            let dest = translate_operand(parts[0], register_map);
            let src = translate_operand(parts[1], register_map);
            format!("{} {}= {}", dest, op_to_assignment(op), src)
        }
        3 => {
            // Three operand form: add r0, r1, r2
            let dest = translate_operand(parts[0], register_map);
            let src1 = translate_operand(parts[1], register_map);
            let src2 = translate_operand(parts[2], register_map);
            format!("{} = {} {} {}", dest, src1, op_to_operator(op), src2)
        }
        _ => format!("/* {} {} */", op, operands),
    }
}

/// Lift logical instruction
fn lift_logical_instruction(op: &str, operands: &str, register_map: &HashMap<String, String>) -> String {
    let parts: Vec<&str> = operands.split(',').map(|s| s.trim()).collect();
    
    if parts.len() >= 2 {
        let dest = translate_operand(parts[0], register_map);
        let src1 = translate_operand(parts[1], register_map);
        
        if parts.len() == 3 {
            let src2 = translate_operand(parts[2], register_map);
            format!("{} = {} {} {}", dest, src1, op, src2)
        } else {
            format!("{} {}= {}", dest, op, src1)
        }
    } else {
        format!("/* {} {} */", op, operands)
    }
}

/// Lift compare instruction
fn lift_compare_instruction(operands: &str, register_map: &HashMap<String, String>) -> String {
    let parts: Vec<&str> = operands.split(',').map(|s| s.trim()).collect();
    if parts.len() == 2 {
        let op1 = translate_operand(parts[0], register_map);
        let op2 = translate_operand(parts[1], register_map);
        format!("flags = compare({}, {})", op1, op2)
    } else {
        format!("/* cmp {} */", operands)
    }
}

/// Lift test instruction
fn lift_test_instruction(operands: &str, register_map: &HashMap<String, String>) -> String {
    let parts: Vec<&str> = operands.split(',').map(|s| s.trim()).collect();
    if parts.len() == 2 {
        let op1 = translate_operand(parts[0], register_map);
        let op2 = translate_operand(parts[1], register_map);
        format!("flags = test({} & {})", op1, op2)
    } else {
        format!("/* tst {} */", operands)
    }
}

/// Lift branch instruction
fn lift_branch_instruction(mnemonic: &str, operands: &str) -> String {
    if mnemonic == "bl" {
        format!("call({})", operands.trim())
    } else if mnemonic.len() > 1 {
        // Conditional branch
        let condition = &mnemonic[1..];
        format!("if (condition_{}) goto {}", condition, operands.trim())
    } else {
        format!("goto {}", operands.trim())
    }
}

/// Lift push instruction
fn lift_push_instruction(operands: &str, register_map: &HashMap<String, String>) -> String {
    let regs = parse_register_list(operands);
    let translated_regs: Vec<String> = regs.iter()
        .map(|reg| translate_operand(reg, register_map))
        .collect();
    format!("push({})", translated_regs.join(", "))
}

/// Lift pop instruction
fn lift_pop_instruction(operands: &str, register_map: &HashMap<String, String>) -> String {
    let regs = parse_register_list(operands);
    let translated_regs: Vec<String> = regs.iter()
        .map(|reg| translate_operand(reg, register_map))
        .collect();
    format!("pop({})", translated_regs.join(", "))
}

/// Translate operand to pseudocode variable
fn translate_operand(operand: &str, register_map: &HashMap<String, String>) -> String {
    let operand = operand.trim();
    
    // Immediate values
    if operand.starts_with('#') {
        return operand[1..].to_string();
    }
    
    // Hex values
    if operand.starts_with("0x") {
        return operand.to_string();
    }
    
    // Register names
    if let Some(var_name) = register_map.get(operand) {
        return var_name.clone();
    }
    
    // Default case
    operand.to_string()
}

/// Translate memory operand
fn translate_memory_operand(operand: &str, register_map: &HashMap<String, String>) -> String {
    let operand = operand.trim();
    
    // Simple [reg] format
    if operand.starts_with('[') && operand.ends_with(']') {
        let inner = &operand[1..operand.len()-1];
        let base_reg = translate_operand(inner, register_map);
        format!("*{}", base_reg)
    } else {
        translate_operand(operand, register_map)
    }
}

/// Parse register list like {r0, r1, r2, lr}
fn parse_register_list(operands: &str) -> Vec<String> {
    if operands.starts_with('{') && operands.ends_with('}') {
        let inner = &operands[1..operands.len()-1];
        inner.split(',').map(|s| s.trim().to_string()).collect()
    } else {
        vec![operands.trim().to_string()]
    }
}

/// Convert operation to assignment operator
fn op_to_assignment(op: &str) -> &str {
    match op {
        "add" => "+",
        "sub" => "-",
        "mul" => "*",
        _ => "=",
    }
}

/// Convert operation to binary operator
fn op_to_operator(op: &str) -> &str {
    match op {
        "add" => "+",
        "sub" => "-",
        "mul" => "*",
        _ => op,
    }
}

/// Check if instruction is a conditional jump
fn is_conditional_jump(instruction: &crate::types::Instruction) -> bool {
    let mnemonic = instruction.mnemonic.to_lowercase();
    mnemonic.starts_with("b") && mnemonic.len() > 1 && mnemonic != "bl" && mnemonic != "blx"
}

/// Calculate confidence score for pseudocode generation
fn calculate_confidence(instructions: &[Address], disasm: &Disassembly) -> f32 {
    if instructions.is_empty() {
        return 0.0;
    }
    
    let mut confidence_factors = ConfidenceFactors::new();
    
    // Analyze instruction coverage and complexity
    analyze_instruction_coverage(instructions, disasm, &mut confidence_factors);
    
    // Analyze control flow patterns
    analyze_control_flow_patterns(instructions, disasm, &mut confidence_factors);
    
    // Analyze data flow patterns
    analyze_data_flow_patterns(instructions, disasm, &mut confidence_factors);
    
    // Analyze architecture-specific factors
    analyze_architecture_support(instructions, disasm, &mut confidence_factors);
    
    // Perform semantic validation
    analyze_semantic_validity(instructions, disasm, &mut confidence_factors);
    
    // Calculate weighted confidence score
    confidence_factors.calculate_final_score()
}

/// Factors that contribute to pseudocode confidence
#[derive(Debug)]
struct ConfidenceFactors {
    instruction_coverage: f32,      // 0.0-1.0: How many instructions we can lift
    instruction_complexity: f32,    // 0.0-1.0: Complexity of instruction patterns
    control_flow_clarity: f32,      // 0.0-1.0: How clear the control flow is
    data_flow_consistency: f32,     // 0.0-1.0: Consistency of data usage
    architecture_support: f32,      // 0.0-1.0: How well we support the architecture
    semantic_validity: f32,         // 0.0-1.0: Semantic correctness of generated code
}

impl ConfidenceFactors {
    fn new() -> Self {
        Self {
            instruction_coverage: 0.0,
            instruction_complexity: 0.5, // Default to medium complexity
            control_flow_clarity: 0.5,
            data_flow_consistency: 0.5,
            architecture_support: 0.7,   // Default to good support
            semantic_validity: 0.5,
        }
    }
    
    fn calculate_final_score(&self) -> f32 {
        // Weighted average of confidence factors
        let weights = [
            (self.instruction_coverage, 0.25),      // 25% - Most important
            (self.instruction_complexity, 0.15),    // 15%
            (self.control_flow_clarity, 0.20),      // 20%
            (self.data_flow_consistency, 0.15),     // 15%
            (self.architecture_support, 0.10),      // 10%
            (self.semantic_validity, 0.15),         // 15%
        ];
        
        let weighted_sum: f32 = weights.iter().map(|(score, weight)| score * weight).sum();
        weighted_sum.min(1.0).max(0.0)
    }
}

/// Analyze how well we can lift the instructions
fn analyze_instruction_coverage(instructions: &[Address], disasm: &Disassembly, factors: &mut ConfidenceFactors) {
    let mut known_instructions = 0;
    let mut complex_instructions = 0;
    let total_instructions = instructions.len();
    
    for &addr in instructions {
        if let Some(instruction) = disasm.instructions.iter().find(|i| i.address == addr) {
            let mnemonic = instruction.mnemonic.to_lowercase();
            
            // Categorize instruction support levels
            let support_level = get_instruction_support_level(&mnemonic);
            match support_level {
                InstructionSupport::FullSupport => {
                    known_instructions += 1;
                }
                InstructionSupport::PartialSupport => {
                    known_instructions += 1;
                    complex_instructions += 1;
                }
                InstructionSupport::BasicSupport => {
                    // Count as half-known
                }
                InstructionSupport::NoSupport => {
                    // Reduces confidence
                }
            }
        }
    }
    
    factors.instruction_coverage = known_instructions as f32 / total_instructions as f32;
    
    // Adjust for instruction complexity
    if complex_instructions > 0 {
        let complexity_ratio = complex_instructions as f32 / total_instructions as f32;
        factors.instruction_complexity = 1.0 - (complexity_ratio * 0.5); // Reduce confidence for complex instructions
    }
}

/// Analyze control flow patterns for clarity
fn analyze_control_flow_patterns(instructions: &[Address], disasm: &Disassembly, factors: &mut ConfidenceFactors) {
    let mut jump_count = 0;
    let mut _conditional_jumps = 0;
    let mut call_count = 0;
    let mut return_count = 0;
    let mut unclear_branches = 0;
    
    for &addr in instructions {
        if let Some(instruction) = disasm.instructions.iter().find(|i| i.address == addr) {
            match instruction.group {
                InstructionGroup::Jump => {
                    jump_count += 1;
                    if is_conditional_jump(instruction) {
                        _conditional_jumps += 1;
                        
                        // Check if we can determine the condition clearly
                        if !has_clear_condition(instruction) {
                            unclear_branches += 1;
                        }
                    }
                }
                InstructionGroup::Call => call_count += 1,
                InstructionGroup::Return => return_count += 1,
                _ => {}
            }
        }
    }
    
    let total_control_flow = jump_count + call_count + return_count;
    if total_control_flow == 0 {
        factors.control_flow_clarity = 1.0; // Simple linear flow
    } else {
        // Calculate clarity based on control flow complexity
        let complexity_penalty = (unclear_branches as f32 / total_control_flow as f32) * 0.5;
        let branch_density = total_control_flow as f32 / instructions.len() as f32;
        
        // High branch density reduces clarity
        let density_penalty = if branch_density > 0.3 { 0.2 } else { 0.0 };
        
        factors.control_flow_clarity = (1.0 - complexity_penalty - density_penalty).max(0.1);
    }
}

/// Analyze data flow patterns for consistency
fn analyze_data_flow_patterns(instructions: &[Address], disasm: &Disassembly, factors: &mut ConfidenceFactors) {
    let mut register_usage = HashMap::new();
    let mut _memory_accesses = 0;
    let mut undefined_operations = 0;
    
    for &addr in instructions {
        if let Some(instruction) = disasm.instructions.iter().find(|i| i.address == addr) {
            // Track register usage patterns
            let registers = extract_registers_from_operands(&instruction.operands);
            for reg in registers {
                *register_usage.entry(reg).or_insert(0) += 1;
            }
            
            // Count memory operations
            if matches!(instruction.group, InstructionGroup::Load | InstructionGroup::Store) {
                _memory_accesses += 1;
            }
            
            // Check for operations we can't translate well
            if instruction.group == InstructionGroup::Other {
                undefined_operations += 1;
            }
        }
    }
    
    // Calculate data flow consistency
    let total_ops = instructions.len();
    let undefined_ratio = undefined_operations as f32 / total_ops as f32;
    
    // Penalize high undefined operation ratio
    factors.data_flow_consistency = (1.0 - undefined_ratio).max(0.0);
    
    // Bonus for consistent register usage patterns
    if !register_usage.is_empty() {
        let avg_usage = register_usage.values().sum::<usize>() as f32 / register_usage.len() as f32;
        let usage_variance = register_usage.values()
            .map(|&count| (count as f32 - avg_usage).powi(2))
            .sum::<f32>() / register_usage.len() as f32;
        
        // Lower variance indicates more consistent usage
        let consistency_bonus = if usage_variance < avg_usage { 0.1 } else { 0.0 };
        factors.data_flow_consistency = (factors.data_flow_consistency + consistency_bonus).min(1.0);
    }
}

/// Determine support level for an instruction
#[derive(Debug, PartialEq)]
enum InstructionSupport {
    FullSupport,    // We can lift this perfectly
    PartialSupport, // We can lift this but may lose some semantics
    BasicSupport,   // We can represent this as a comment
    NoSupport,      // We can't handle this at all
}

fn get_instruction_support_level(mnemonic: &str) -> InstructionSupport {
    match mnemonic {
        // Full support - common operations we handle well
        "mov" | "ldr" | "str" | "add" | "sub" | "mul" | "div" |
        "and" | "orr" | "eor" | "cmp" | "tst" | "push" | "pop" |
        "nop" => InstructionSupport::FullSupport,
        
        // Partial support - we can handle but may lose nuance
        "b" | "bl" | "bx" | "blx" | "beq" | "bne" | "blt" | "bgt" |
        "ble" | "bge" | "bhi" | "bls" | "bcc" | "bcs" |
        "lsl" | "lsr" | "asr" | "ror" | "rrx" |
        "adc" | "sbc" | "rsb" | "rsc" |
        "ldm" | "stm" | "ldmia" | "stmia" | "ldmdb" | "stmdb" => InstructionSupport::PartialSupport,
        
        // Basic support - architecture-specific or complex instructions
        "swi" | "svc" | "bkpt" | "wfi" | "wfe" | "sev" |
        "msr" | "mrs" | "mcr" | "mrc" | "cdp" |
        "vmov" | "vadd" | "vsub" | "vmul" | "vdiv" |
        "ldrex" | "strex" | "clrex" | "dmb" | "dsb" | "isb" => InstructionSupport::BasicSupport,
        
        // No support - unrecognized or very specialized
        _ => InstructionSupport::NoSupport,
    }
}

/// Check if a conditional jump has a clear condition we can represent
fn has_clear_condition(instruction: &crate::types::Instruction) -> bool {
    let mnemonic = instruction.mnemonic.to_lowercase();
    
    // Standard ARM conditional suffixes we can handle well
    matches!(mnemonic.as_str(), 
        "beq" | "bne" | "blt" | "bgt" | "ble" | "bge" |
        "bhi" | "bls" | "bcc" | "bcs" | "bmi" | "bpl" |
        "bvs" | "bvc" | "bal"
    )
}

/// Extract register names from instruction operands
fn extract_registers_from_operands(operands: &str) -> Vec<String> {
    let mut registers = Vec::new();
    
    // Simple regex-like parsing for common register patterns
    for part in operands.split(&[',', ' ', '[', ']', '{', '}']) {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }
        
        // ARM register patterns
        if part.starts_with('r') && part.len() <= 3 {
            if let Ok(_) = part[1..].parse::<u8>() {
                registers.push(part.to_string());
            }
        } else if matches!(part, "sp" | "lr" | "pc" | "fp") {
            registers.push(part.to_string());
        }
        // x86 register patterns
        else if matches!(part, "eax" | "ebx" | "ecx" | "edx" | "esi" | "edi" | "esp" | "ebp" |
                              "rax" | "rbx" | "rcx" | "rdx" | "rsi" | "rdi" | "rsp" | "rbp" |
                              "r8" | "r9" | "r10" | "r11" | "r12" | "r13" | "r14" | "r15") {
            registers.push(part.to_string());
        }
    }
    
    registers
}

/// Analyze architecture-specific support factors
fn analyze_architecture_support(instructions: &[Address], disasm: &Disassembly, factors: &mut ConfidenceFactors) {
    let mut arch_indicators = HashMap::new();
    
    // Count architecture-specific instruction patterns
    for &addr in instructions {
        if let Some(instruction) = disasm.instructions.iter().find(|i| i.address == addr) {
            let mnemonic = instruction.mnemonic.to_lowercase();
            
            // Detect architecture from instruction patterns
            if matches!(mnemonic.as_str(), "mov" | "ldr" | "str" | "add" | "sub" | "b" | "bl" | "push" | "pop") {
                *arch_indicators.entry("arm").or_insert(0) += 1;
            } else if matches!(mnemonic.as_str(), "mov" | "add" | "sub" | "jmp" | "call" | "ret" | "push" | "pop") {
                *arch_indicators.entry("x86").or_insert(0) += 1;
            } else if mnemonic.starts_with("v") {
                *arch_indicators.entry("vector").or_insert(0) += 1;
            }
        }
    }
    
    // Calculate architecture support based on dominant architecture
    if let Some((dominant_arch, count)) = arch_indicators.iter().max_by_key(|(_, &count)| count) {
        let total_instructions = instructions.len();
        let coverage_ratio = *count as f32 / total_instructions as f32;
        
        // Adjust support based on architecture and coverage
        factors.architecture_support = match *dominant_arch {
            "arm" => (0.9 * coverage_ratio).min(0.9),      // Excellent ARM support
            "x86" => (0.8 * coverage_ratio).min(0.8),      // Good x86 support
            "vector" => (0.6 * coverage_ratio).min(0.6),   // Limited vector support
            _ => 0.5,
        };
    }
}

/// Analyze semantic validity of generated pseudocode
fn analyze_semantic_validity(instructions: &[Address], disasm: &Disassembly, factors: &mut ConfidenceFactors) {
    let mut semantic_issues = 0;
    let mut valid_patterns = 0;
    
    // Look for common semantic patterns and issues
    for window in instructions.windows(2) {
        if let (Some(instr1), Some(instr2)) = (
            disasm.instructions.iter().find(|i| i.address == window[0]),
            disasm.instructions.iter().find(|i| i.address == window[1])
        ) {
            // Check for valid instruction sequences
            if is_valid_instruction_sequence(instr1, instr2) {
                valid_patterns += 1;
            } else if is_problematic_sequence(instr1, instr2) {
                semantic_issues += 1;
            }
        }
    }
    
    // Check for function prologue/epilogue patterns
    if has_valid_function_structure(instructions, disasm) {
        valid_patterns += 2; // Bonus for good function structure
    }
    
    // Calculate semantic validity
    let total_patterns = valid_patterns + semantic_issues;
    if total_patterns > 0 {
        factors.semantic_validity = valid_patterns as f32 / total_patterns as f32;
    } else {
        factors.semantic_validity = 0.7; // Default for functions without clear patterns
    }
}

/// Check if two consecutive instructions form a valid semantic sequence
fn is_valid_instruction_sequence(instr1: &crate::types::Instruction, instr2: &crate::types::Instruction) -> bool {
    let mnemonic1 = instr1.mnemonic.to_lowercase();
    let mnemonic2 = instr2.mnemonic.to_lowercase();
    
    // Check for compare followed by conditional branch
    if mnemonic1 == "cmp" && mnemonic2.starts_with("b") && mnemonic2.len() > 1 {
        return true;
    }
    
    // Common valid patterns
    matches!(
        (mnemonic1.as_str(), mnemonic2.as_str()),
        // Load followed by use
        ("ldr", "add") | ("ldr", "sub") | ("ldr", "cmp") | ("ldr", "str") |
        // Push followed by function setup
        ("push", "mov") | ("push", "sub") |
        // Function call patterns
        ("bl", "cmp") | ("bl", "mov") |
        // Stack operations
        ("sub", "str")
    )
}

/// Check if two consecutive instructions form a problematic sequence
fn is_problematic_sequence(instr1: &crate::types::Instruction, instr2: &crate::types::Instruction) -> bool {
    let mnemonic1 = instr1.mnemonic.to_lowercase();
    let mnemonic2 = instr2.mnemonic.to_lowercase();
    let mnemonics = (mnemonic1.as_str(), mnemonic2.as_str());

    // Redundant operations
    if mnemonics == ("mov", "mov") && instr1.operands == instr2.operands {
        return true;
    }
    // Conflicting operations
    if mnemonics == ("push", "pop") && instr1.operands == instr2.operands {
        return true;
    }
    // Unusual control flow
    if mnemonics.0 == "ret" && mnemonics.1 != "nop" { // Instructions after return
        return true;
    }

    false
}

/// Check if the function has a valid structure (prologue/epilogue)
fn has_valid_function_structure(instructions: &[Address], disasm: &Disassembly) -> bool {
    if instructions.len() < 3 {
        return false;
    }
    
    // Check for function prologue (first few instructions)
    let has_prologue = instructions.iter().take(3).any(|&addr| {
        if let Some(instruction) = disasm.instructions.iter().find(|i| i.address == addr) {
            let mnemonic = instruction.mnemonic.to_lowercase();
            matches!(mnemonic.as_str(), "push" | "sub" | "mov") && 
            (instruction.operands.contains("sp") || instruction.operands.contains("lr"))
        } else {
            false
        }
    });
    
    // Check for function epilogue (last few instructions)
    let has_epilogue = instructions.iter().rev().take(3).any(|&addr| {
        if let Some(instruction) = disasm.instructions.iter().find(|i| i.address == addr) {
            let mnemonic = instruction.mnemonic.to_lowercase();
            matches!(mnemonic.as_str(), "pop" | "add" | "bx" | "ret") &&
            (instruction.operands.contains("sp") || instruction.operands.contains("lr") || instruction.operands.contains("pc"))
        } else {
            false
        }
    });
    
    has_prologue && has_epilogue
}