incode 0.30.26038

InCode - MCP server for LLDB debugging automation
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
// InCode Memory Inspection Tools Test Suite
// 
// GRANULAR FEATURES TESTED:
// - F0028: read_memory - Read raw memory at address with size and format
// - F0029: write_memory - Write data to memory address
// - F0030: disassemble - Disassemble instructions at address or function
// - F0031: search_memory - Search for byte patterns in process memory
// - F0032: get_memory_regions - List memory mappings and permissions
// - F0033: dump_memory - Dump memory region to file
// - F0034: memory_map - Get detailed memory map with segments
//
// Tests memory inspection with real LLDB integration using test_debuggee binary

use std::time::Duration;
use std::thread;

// Import test setup utilities
mod test_setup;
use test_setup::{TestSession, TestMode, TestUtils};

use incode::lldb_manager::LldbManager;
use incode::error::{IncodeError, IncodeResult};

// Helper function to decode hex strings
fn hex_decode(hex_str: &str) -> Result<Vec<u8>, &'static str> {
    if hex_str.len() % 2 != 0 {
        return Err("Hex string must have even length");
    }
    
    let mut result = Vec::new();
    for i in (0..hex_str.len()).step_by(2) {
        let hex_pair = &hex_str[i..i+2];
        match u8::from_str_radix(hex_pair, 16) {
            Ok(byte) => result.push(byte),
            Err(_) => return Err("Invalid hex character"),
        }
    }
    Ok(result)
}

#[tokio::test]
async fn test_f0028_read_memory_success() {
    // F0028: read_memory - Test reading raw memory with different formats
    println!("Testing F0028: read_memory");
    
    let mut session = match TestSession::new(TestMode::Memory) {
        Ok(s) => s,
        Err(e) => {
            println!("⚠️ F0028: Could not create test session: {}", e);
            return;
        }
    };
    
    match session.start() {
        Ok(pid) => {
            println!("✅ F0028: Test session started with PID {}", pid);
            
            // Set breakpoint to get to memory scenario
            let _ = session.lldb_manager().set_breakpoint("create_global_patterns");
            let _ = session.lldb_manager().continue_execution();
            
            // Test reading memory - use a known global variable address
            // In a real scenario, we'd get this address from variable lookup
            let test_formats = vec!["hex", "ascii", "bytes", "int", "float", "pointer"];
            
            for format in test_formats {
                let result = session.lldb_manager().read_memory(0x100000000, 64);
                
                match result {
                    Ok(memory_data) => {
                        println!("✅ F0028: read_memory succeeded with format {}", format);
                        println!("  Memory data size: {}", memory_data.len());
                        println!("  Content (first 20 bytes): {:?}", &memory_data[..20.min(memory_data.len())]);
                        
                        assert_eq!(memory_data.len(), 64);
                    }
                    Err(e) => {
                        println!("⚠️ F0028: read_memory failed for format {}: {}", format, e);
                    }
                }
            }
        }
        Err(e) => {
            println!("⚠️ F0028: Could not start debugging session: {}", e);
        }
    }
    
    let _ = session.cleanup();
}

#[tokio::test]
async fn test_f0028_read_memory_invalid_address() {
    // F0028: read_memory - Test error handling for invalid memory address
    println!("Testing F0028: read_memory with invalid address");
    
    let mut session = match TestSession::new(TestMode::Normal) {
        Ok(s) => s,
        Err(e) => {
            println!("⚠️ F0028: Could not create test session: {}", e);
            return;
        }
    };
    
    match session.start() {
        Ok(_pid) => {
            // Test reading from invalid address
            let result = session.lldb_manager().read_memory(0x0, 64);
            
            match result {
                Err(e) => {
                    println!("✅ F0028: Correctly handled invalid address: {}", e);
                }
                Ok(_) => {
                    println!("⚠️ F0028: read_memory unexpectedly succeeded for invalid address");
                }
            }
        }
        Err(e) => {
            println!("⚠️ F0028: Could not start debugging session: {}", e);
        }
    }
    
    let _ = session.cleanup();
}

#[tokio::test]
async fn test_f0029_write_memory() {
    // F0029: write_memory - Test writing data to memory address
    println!("Testing F0029: write_memory");
    
    let mut session = match TestSession::new(TestMode::Memory) {
        Ok(s) => s,
        Err(e) => {
            println!("⚠️ F0029: Could not create test session: {}", e);
            return;
        }
    };
    
    match session.start() {
        Ok(pid) => {
            println!("✅ F0029: Test session started with PID {}", pid);
            
            // Set breakpoint to get to memory scenario
            let _ = session.lldb_manager().set_breakpoint("create_heap_patterns");
            let _ = session.lldb_manager().continue_execution();
            
            // Test writing memory with different formats
            let test_data = vec![
                ("hex", "41424344"),
                ("ascii", "TEST"),
                ("bytes", "0x54,0x45,0x53,0x54"),
            ];
            
            for (format, data) in test_data {
                let data_bytes = match format {
                    "hex" => hex_decode(data).unwrap_or_else(|_| data.as_bytes().to_vec()),
                    "ascii" => data.as_bytes().to_vec(),
                    "bytes" => {
                        // Parse "0x54,0x45,0x53,0x54" format
                        data.split(',')
                            .map(|s| u8::from_str_radix(s.trim().trim_start_matches("0x"), 16)
                                .unwrap_or(0))
                            .collect()
                    }
                    _ => data.as_bytes().to_vec(),
                };
                let result = session.lldb_manager().write_memory(0x100000000, &data_bytes);
                
                match result {
                    Ok(bytes_written) => {
                        if bytes_written > 0 {
                            println!("✅ F0029: write_memory succeeded with format {}, wrote {} bytes", format, bytes_written);
                        } else {
                            println!("⚠️ F0029: write_memory reported failure for format {} (0 bytes written)", format);
                        }
                    }
                    Err(e) => {
                        println!("⚠️ F0029: write_memory failed for format {}: {}", format, e);
                    }
                }
            }
        }
        Err(e) => {
            println!("⚠️ F0029: Could not start debugging session: {}", e);
        }
    }
    
    let _ = session.cleanup();
}

#[tokio::test]
async fn test_f0030_disassemble_function() {
    // F0030: disassemble - Test disassembling instructions at function
    println!("Testing F0030: disassemble");
    
    let mut session = match TestSession::new(TestMode::Normal) {
        Ok(s) => s,
        Err(e) => {
            println!("⚠️ F0030: Could not create test session: {}", e);
            return;
        }
    };
    
    match session.start() {
        Ok(pid) => {
            println!("✅ F0030: Test session started with PID {}", pid);
            
            // Test disassembling main function
            let result = session.lldb_manager().disassemble(0x100000000, 10);
            
            match result {
                Ok(instructions) => {
                    println!("✅ F0030: disassemble succeeded");
                    println!("  Instruction Count: {}", instructions.len());
                    
                    for (i, instruction) in instructions.iter().take(3).enumerate() {
                        println!("  Instruction {}: {}", i + 1, instruction);
                    }
                    
                    assert!(!instructions.is_empty());
                    assert_eq!(instructions.len(), 10);
                }
                Err(e) => {
                    println!("⚠️ F0030: disassemble failed: {}", e);
                }
            }
        }
        Err(e) => {
            println!("⚠️ F0030: Could not start debugging session: {}", e);
        }
    }
    
    let _ = session.cleanup();
}

#[tokio::test]
async fn test_f0030_disassemble_invalid_function() {
    // F0030: disassemble - Test error handling for invalid function
    println!("Testing F0030: disassemble with invalid function");
    
    let mut session = match TestSession::new(TestMode::Normal) {
        Ok(s) => s,
        Err(e) => {
            println!("⚠️ F0030: Could not create test session: {}", e);
            return;
        }
    };
    
    match session.start() {
        Ok(_pid) => {
            let result = session.lldb_manager().disassemble(0x0, 10);
            
            match result {
                Err(e) => {
                    println!("✅ F0030: Correctly handled invalid function: {}", e);
                }
                Ok(_) => {
                    println!("⚠️ F0030: disassemble unexpectedly succeeded for invalid function");
                }
            }
        }
        Err(e) => {
            println!("⚠️ F0030: Could not start debugging session: {}", e);
        }
    }
    
    let _ = session.cleanup();
}

#[tokio::test]
async fn test_f0031_search_memory() {
    // F0031: search_memory - Test searching for byte patterns in memory
    println!("Testing F0031: search_memory");
    
    let mut session = match TestSession::new(TestMode::Memory) {
        Ok(s) => s,
        Err(e) => {
            println!("⚠️ F0031: Could not create test session: {}", e);
            return;
        }
    };
    
    match session.start() {
        Ok(pid) => {
            println!("✅ F0031: Test session started with PID {}", pid);
            
            // Set breakpoint to get to memory scenario
            let _ = session.lldb_manager().set_breakpoint("create_global_patterns");
            let _ = session.lldb_manager().continue_execution();
            
            // Test searching for different patterns
            let search_patterns = vec![
                ("hex", "41424344"),      // "ABCD" in hex
                ("ascii", "TEST"),        // Text pattern
                ("bytes", "0x00,0x01"),   // Byte sequence
            ];
            
            for (format, pattern) in search_patterns {
                let pattern_bytes = match format {
                    "hex" => {
                        let mut bytes = Vec::new();
                        for chunk in pattern.as_bytes().chunks(2) {
                            if let Ok(byte_val) = u8::from_str_radix(
                                &String::from_utf8_lossy(chunk), 16
                            ) {
                                bytes.push(byte_val);
                            }
                        }
                        bytes
                    }
                    "ascii" => pattern.as_bytes().to_vec(),
                    "bytes" => {
                        // Parse "0x00,0x01" format
                        pattern.split(',')
                            .map(|s| u8::from_str_radix(s.trim().trim_start_matches("0x"), 16)
                                .unwrap_or(0))
                            .collect()
                    }
                    _ => pattern.as_bytes().to_vec(),
                };
                let result = session.lldb_manager().search_memory(
                    &pattern_bytes,
                    Some(0x100000000),
                    Some(0x10000)
                );
                
                match result {
                    Ok(matches) => {
                        println!("✅ F0031: search_memory succeeded for {} pattern, found {} matches", 
                               format, matches.len());
                        
                        for (i, address) in matches.iter().take(3).enumerate() {
                            println!("  Match {}: Address 0x{:x}", i + 1, address);
                        }
                    }
                    Err(e) => {
                        println!("⚠️ F0031: search_memory failed for {} pattern: {}", format, e);
                    }
                }
            }
        }
        Err(e) => {
            println!("⚠️ F0031: Could not start debugging session: {}", e);
        }
    }
    
    let _ = session.cleanup();
}

#[tokio::test]
async fn test_f0032_get_memory_regions() {
    // F0032: get_memory_regions - Test listing memory mappings and permissions
    println!("Testing F0032: get_memory_regions");
    
    let mut session = match TestSession::new(TestMode::Normal) {
        Ok(s) => s,
        Err(e) => {
            println!("⚠️ F0032: Could not create test session: {}", e);
            return;
        }
    };
    
    match session.start() {
        Ok(pid) => {
            println!("✅ F0032: Test session started with PID {}", pid);
            
            // Test getting memory regions
            let result = session.lldb_manager().get_memory_regions();
            
            match result {
                Ok(regions) => {
                    println!("✅ F0032: get_memory_regions succeeded, found {} regions", regions.len());
                    
                    for (i, region) in regions.iter().take(5).enumerate() {
                        println!("  Region {}: 0x{:x}-0x{:x} ({}) [{}]", 
                               i + 1, region.start_address, region.end_address,
                               region.name.as_ref().unwrap_or(&"unknown".to_string()), region.permissions);
                    }
                    
                    assert!(regions.len() > 0, "Should have at least one memory region");
                    
                    // Check for common memory regions
                    let has_executable = regions.iter().any(|r| r.permissions.contains('x'));
                    let has_writable = regions.iter().any(|r| r.permissions.contains('w'));
                    let has_readable = regions.iter().any(|r| r.permissions.contains('r'));
                    
                    if has_executable && has_writable && has_readable {
                        println!("✅ F0032: Found expected memory region types (rwx)");
                    }
                }
                Err(e) => {
                    println!("⚠️ F0032: get_memory_regions failed: {}", e);
                }
            }
        }
        Err(e) => {
            println!("⚠️ F0032: Could not start debugging session: {}", e);
        }
    }
    
    let _ = session.cleanup();
}

#[tokio::test]
async fn test_f0033_dump_memory() {
    // F0033: dump_memory - Test dumping memory region to file
    println!("Testing F0033: dump_memory");
    
    let mut session = match TestSession::new(TestMode::Memory) {
        Ok(s) => s,
        Err(e) => {
            println!("⚠️ F0033: Could not create test session: {}", e);
            return;
        }
    };
    
    match session.start() {
        Ok(pid) => {
            println!("✅ F0033: Test session started with PID {}", pid);
            
            // Test dumping memory with different formats
            let dump_formats = vec!["raw", "hex", "hexdump"];
            
            for format in dump_formats {
                let output_file = format!("/tmp/memory_dump_{}.txt", format);
                let result = session.lldb_manager().dump_memory_to_file(
                    0x100000000, 
                    256, 
                    &output_file
                );
                
                match result {
                    Ok(bytes_written) => {
                        if bytes_written > 0 {
                            println!("✅ F0033: dump_memory_to_file succeeded with format {} to {}, wrote {} bytes", format, output_file, bytes_written);
                            
                            // Check if file was created
                            if std::path::Path::new(&output_file).exists() {
                                println!("  File created successfully");
                            }
                        } else {
                            println!("⚠️ F0033: dump_memory_to_file reported failure for format {} (0 bytes written)", format);
                        }
                    }
                    Err(e) => {
                        println!("⚠️ F0033: dump_memory failed for format {}: {}", format, e);
                    }
                }
            }
        }
        Err(e) => {
            println!("⚠️ F0033: Could not start debugging session: {}", e);
        }
    }
    
    let _ = session.cleanup();
}

#[tokio::test]
async fn test_f0034_memory_map() {
    // F0034: memory_map - Test getting detailed memory map with segments
    println!("Testing F0034: memory_map");
    
    let mut session = match TestSession::new(TestMode::Normal) {
        Ok(s) => s,
        Err(e) => {
            println!("⚠️ F0034: Could not create test session: {}", e);
            return;
        }
    };
    
    match session.start() {
        Ok(pid) => {
            println!("✅ F0034: Test session started with PID {}", pid);
            
            // Test getting detailed memory map
            let result = session.lldb_manager().get_memory_map();
            
            match result {
                Ok(memory_map) => {
                    println!("✅ F0034: memory_map succeeded");
                    println!("  Total Segments: {}", memory_map.total_segments);
                    println!("  Load Address: 0x{:x}", memory_map.load_address);
                    println!("  ASLR Slide: 0x{:x}", memory_map.slide);
                    println!("  Segments: {}", memory_map.segments.len());
                    
                    for (i, segment) in memory_map.segments.iter().take(3).enumerate() {
                        println!("  Segment {}: {} (0x{:x}-0x{:x}) [{}]", 
                               i + 1, segment.name, segment.vm_address, 
                               segment.vm_address + segment.vm_size, segment.max_protection);
                    }
                    
                    assert!(memory_map.segments.len() > 0, "Should have at least one segment");
                }
                Err(e) => {
                    println!("⚠️ F0034: memory_map failed: {}", e);
                }
            }
        }
        Err(e) => {
            println!("⚠️ F0034: Could not start debugging session: {}", e);
        }
    }
    
    let _ = session.cleanup();
}

#[tokio::test]
async fn test_memory_inspection_workflow() {
    // Integration test: Complete memory inspection workflow
    println!("Testing memory inspection workflow integration");
    
    let mut session = match TestSession::new(TestMode::Memory) {
        Ok(s) => s,
        Err(e) => {
            println!("⚠️ Workflow: Could not create test session: {}", e);
            return;
        }
    };
    
    match session.start() {
        Ok(pid) => {
            println!("✅ Workflow: Test session started with PID {}", pid);
            
            // Step 1: Get memory map overview
            match session.lldb_manager().get_memory_map() {
                Ok(memory_map) => {
                    println!("✅ Workflow: Got memory map with {} segments", memory_map.segments.len());
                    
                    if let Some(first_segment) = memory_map.segments.first() {
                        let test_address = first_segment.vm_address;
                        
                        // Step 2: Read memory from first segment
                        match session.lldb_manager().read_memory(test_address, 128) {
                            Ok(memory_data) => {
                                println!("✅ Workflow: Read {} bytes from 0x{:x}", 
                                       memory_data.len(), test_address);
                            }
                            Err(e) => {
                                println!("⚠️ Workflow: Memory read failed: {}", e);
                            }
                        }
                        
                        // Step 3: Disassemble at the address
                        match session.lldb_manager().disassemble(test_address, 5) {
                            Ok(instructions) => {
                                println!("✅ Workflow: Disassembled {} instructions", 
                                       instructions.len());
                            }
                            Err(e) => {
                                println!("⚠️ Workflow: Disassembly failed: {}", e);
                            }
                        }
                    }
                }
                Err(e) => {
                    println!("⚠️ Workflow: Failed to get memory map: {}", e);
                }
            }
            
            // Step 4: Get memory regions overview
            match session.lldb_manager().get_memory_regions() {
                Ok(regions) => {
                    println!("✅ Workflow: Found {} memory regions", regions.len());
                    
                    // Categorize regions
                    let executable_count = regions.iter().filter(|r| r.permissions.contains('x')).count();
                    let writable_count = regions.iter().filter(|r| r.permissions.contains('w')).count();
                    let readonly_count = regions.iter().filter(|r| r.permissions.contains('r') && !r.permissions.contains('w')).count();
                    
                    println!("  Executable regions: {}", executable_count);
                    println!("  Writable regions: {}", writable_count);  
                    println!("  Read-only regions: {}", readonly_count);
                }
                Err(e) => {
                    println!("⚠️ Workflow: Failed to get memory regions: {}", e);
                }
            }
            
            // Step 5: Search for a common pattern
            match session.lldb_manager().search_memory(b"main", Some(0x100000000), Some(0x10000)) {
                Ok(matches) => {
                    println!("✅ Workflow: Memory search found {} matches for 'main'", matches.len());
                }
                Err(e) => {
                    println!("⚠️ Workflow: Memory search failed: {}", e);
                }
            }
            
            println!("✅ Workflow: Complete memory inspection workflow tested");
        }
        Err(e) => {
            println!("⚠️ Workflow: Could not start debugging session: {}", e);
        }
    }
    
    let _ = session.cleanup();
}

#[tokio::test]
async fn test_memory_modification_verification() {
    // Test memory write and read verification cycle
    println!("Testing memory modification and verification");
    
    let mut session = match TestSession::new(TestMode::Memory) {
        Ok(s) => s,
        Err(e) => {
            println!("⚠️ Verification: Could not create test session: {}", e);
            return;
        }
    };
    
    match session.start() {
        Ok(_pid) => {
            // Set breakpoint in memory scenario
            let _ = session.lldb_manager().set_breakpoint("create_heap_patterns");
            let _ = session.lldb_manager().continue_execution();
            
            let test_address = 0x100000000;
            let test_data = "MODIFIED";
            
            // Step 1: Read original memory
            match session.lldb_manager().read_memory(test_address, 64) {
                Ok(original) => {
                    let original_str = String::from_utf8_lossy(&original);
                    println!("✅ Verification: Original memory content: {}...", 
                           original_str.chars().take(20).collect::<String>());
                    
                    // Step 2: Write new data
                    match session.lldb_manager().write_memory(test_address, test_data.as_bytes()) {
                        Ok(bytes_written) => {
                            if bytes_written > 0 {
                                println!("✅ Verification: Memory write successful, wrote {} bytes", bytes_written);
                                
                                // Step 3: Read back to verify
                                match session.lldb_manager().read_memory(test_address, 64) {
                                    Ok(modified) => {
                                        let modified_str = String::from_utf8_lossy(&modified);
                                        println!("✅ Verification: Modified memory content: {}...", 
                                               modified_str.chars().take(20).collect::<String>());
                                        
                                        if modified_str.contains(test_data) {
                                            println!("✅ Verification: Memory modification verified");
                                        } else {
                                            println!("⚠️ Verification: Memory modification not reflected");
                                        }
                                    }
                                    Err(e) => {
                                        println!("⚠️ Verification: Verification read failed: {}", e);
                                    }
                                }
                            } else {
                                println!("⚠️ Verification: Memory write reported failure (0 bytes written)");
                            }
                        }
                        Err(e) => {
                            println!("⚠️ Verification: Memory write failed: {}", e);
                        }
                    }
                }
                Err(e) => {
                    println!("⚠️ Verification: Original memory read failed: {}", e);
                }
            }
        }
        Err(e) => {
            println!("⚠️ Verification: Could not start debugging session: {}", e);
        }
    }
    
    let _ = session.cleanup();
}