embedded-debugger-mcp 0.1.0

A Model Context Protocol server for embedded debugging with probe-rs - supports ARM Cortex-M, RISC-V debugging via J-Link, ST-Link, and more
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
//! RTT manager implementation using probe-rs RTT API

use crate::error::{DebugError, Result};
use std::collections::HashMap;
use std::sync::Arc;
use std::path::Path;
use tokio::sync::Mutex;
use tracing::{debug, info, error, warn};
use probe_rs::{Session, rtt::{Rtt, ScanRegion}, MemoryInterface};

/// RTT manager for hardware communication with embedded targets  
#[derive(Debug)]
pub struct RttManager {
    /// RTT attachment status
    attached: bool,
    /// Real RTT instance from probe-rs
    rtt: Option<Rtt>,
    /// Session reference for RTT operations
    session: Option<Arc<Mutex<Session>>>,
    /// Cached channel information from RTT
    channels: HashMap<u32, ChannelInfo>,
    /// Number of up channels discovered
    up_channel_count: usize,
    /// Number of down channels discovered
    down_channel_count: usize,
}

#[derive(Debug, Clone)]
pub struct ChannelInfo {
    pub id: u32,
    pub name: String,
    pub direction: ChannelDirection,
    pub mode: String,
    pub buffer_size: usize,
}

#[derive(Debug, Clone)]
pub enum ChannelDirection {
    Up,   // Target to Host
    Down, // Host to Target
}

impl Default for RttManager {
    fn default() -> Self {
        Self::new()
    }
}

impl RttManager {
    /// Create a new RTT manager
    pub fn new() -> Self {
        Self {
            attached: false,
            rtt: None,
            session: None,
            channels: HashMap::new(),
            up_channel_count: 0,
            down_channel_count: 0,
        }
    }

    /// Enhanced attach method with ELF symbol detection first (probe-rs style)
    /// This is the recommended method that follows probe-rs best practices
    pub async fn attach_with_elf(
        &mut self,
        session: Arc<Mutex<Session>>,
        firmware_path: &Path,
    ) -> Result<()> {
        info!("Starting enhanced RTT attachment with ELF symbol detection first");
        debug!("Firmware path: {}", firmware_path.display());

        // Phase 1: Try ELF symbol detection (primary method)
        match crate::rtt::elf_parser::get_rtt_symbol_from_elf(firmware_path) {
            Ok(symbol_addr) => {
                info!("✅ Found _SEGGER_RTT symbol at 0x{:08X}, attempting direct connection", symbol_addr);
                
                // Try direct connection at symbol address
                match self.try_rtt_at_address(session.clone(), symbol_addr).await {
                    Ok(_) => {
                        info!("🎯 RTT connected successfully using ELF symbol address!");
                        return Ok(());
                    }
                    Err(e) => {
                        warn!("RTT connection failed at symbol address 0x{:08X}: {}", symbol_addr, e);
                        info!("Falling back to memory scanning...");
                    }
                }
            }
            Err(e) => {
                info!("ELF symbol detection failed: {}", e);
                info!("Proceeding with memory scanning fallback...");
            }
        }

        // Phase 2: Memory scanning fallback (original method)
        info!("Using memory scanning fallback approach");
        self.attach(session, None, None).await
    }

    /// Try RTT connection at specific address (used for ELF symbol detection)
    async fn try_rtt_at_address(
        &mut self,
        session: Arc<Mutex<Session>>,
        address: u64,
    ) -> Result<()> {
        debug!("Attempting RTT connection at specific address: 0x{:08X}", address);

        // Store session reference
        self.session = Some(session.clone());

        let mut session_guard = session.lock().await;
        let mut core = session_guard.core(0).map_err(|e| {
            error!("Failed to get core for RTT attachment: {}", e);
            DebugError::RttError(format!("Failed to get core: {}", e))
        })?;

        // Validate control block at address first
        let is_valid = self.validate_rtt_control_block_sync(&mut core, address)?;
        if !is_valid {
            return Err(DebugError::RttError(format!(
                "Invalid RTT control block at address 0x{:08X} (magic identifier not found)",
                address
            )));
        }
        debug!("✅ RTT control block validated at 0x{:08X}", address);

        // CRITICAL FIX: Use ScanRegion::Exact for direct address connection
        debug!("Using ScanRegion::Exact for direct address connection...");
        
        let scan_region = ScanRegion::Exact(address);
        let rtt_result = Rtt::attach_region(&mut core, &scan_region);

        match rtt_result {
            Ok(rtt) => {
                info!("Successfully attached RTT at ELF symbol address 0x{:08X}!", address);
                self.complete_attachment_sync(rtt)
            }
            Err(e) => {
                error!("RTT attachment failed at address 0x{:08X}: {}", address, e);
                Err(DebugError::RttError(format!(
                    "RTT attachment failed at symbol address 0x{:08X}: {}",
                    address, e
                )))
            }
        }
    }

    /// Validate RTT control block at given address (probe-rs style validation)
    fn validate_rtt_control_block_sync(
        &self,
        core: &mut probe_rs::Core<'_>,
        address: u64,
    ) -> Result<bool> {
        debug!("Validating RTT control block at address 0x{:08X}", address);

        // Read 16 bytes for RTT magic identifier
        let mut id_buffer = [0u8; 16];
        core.read(address, &mut id_buffer).map_err(|e| {
            DebugError::RttError(format!("Failed to read RTT control block at 0x{:08X}: {}", address, e))
        })?;

        // Check for "SEGGER RTT" magic identifier
        const RTT_ID: &[u8] = b"SEGGER RTT\0\0\0\0\0\0";
        let is_valid = id_buffer == RTT_ID;

        if is_valid {
            debug!("✅ Valid RTT control block found at 0x{:08X}", address);
        } else {
            debug!("❌ Invalid RTT control block at 0x{:08X}, found: {:02X?}", address, &id_buffer[..10]);
        }

        Ok(is_valid)
    }

    /// Attach to RTT on target using probe-rs RTT API with enhanced detection
    /// Priority: ELF symbol detection first, then memory scanning fallback
    pub async fn attach(
        &mut self, 
        session: Arc<Mutex<Session>>,
        control_block_address: Option<u64>,
        memory_ranges: Option<Vec<(u64, u64)>>
    ) -> Result<()> {
        debug!("Attaching to RTT using probe-rs integration with enhanced detection");
        
        // Store session reference
        self.session = Some(session.clone());
        
        // Note: memory_map not needed for probe-rs 0.25 attach_region API
        
        // Get the session and core to perform RTT attachment
        let mut session_guard = session.lock().await;
        let mut core = session_guard.core(0).map_err(|e| {
            error!("Failed to get core for RTT attachment: {}", e);
            DebugError::RttError(format!("Failed to get core: {}", e))
        })?;
        
        // Check if target is running (important for RTT initialization)
        let core_status = core.status().map_err(|e| {
            error!("Failed to get core status: {}", e);
            DebugError::RttError(format!("Failed to get core status: {}", e))
        })?;
        debug!("Core status before RTT attach: {:?}", core_status);
        
        // Build ScanRegion based on parameters
        let scan_region = if let Some(cb_addr) = control_block_address {
            info!("RTT scan: Using exact address: 0x{:08X}", cb_addr);
            ScanRegion::Exact(cb_addr)
        } else if let Some(ranges) = memory_ranges {
            info!("RTT scan: Using custom memory ranges: {:?}", ranges);
            let ranges = ranges.into_iter()
                .map(|(start, end)| start..end)
                .collect();
            ScanRegion::Ranges(ranges)
        } else {
            info!("RTT scan: Using RAM scan (probe-rs default)");
            ScanRegion::Ram
        };
        
        // Try RTT attachment with appropriate scan region
        debug!("Attempting RTT attach with scan region: {:?}", scan_region);
        let rtt_result = Rtt::attach_region(&mut core, &scan_region);
        
        match rtt_result {
            Ok(rtt) => {
                info!("Successfully attached to RTT control block!");
                self.complete_attachment_sync(rtt)
            }
            Err(e) => {
                error!("RTT attachment failed: {}", e);
                
                // Provide detailed debugging information
                let detailed_error = format!(
                    "RTT attachment failed: {}\n\n\
                    Debug Information:\n\
                    - Core Status: {:?}\n\
                    - Scan Region: {:?}\n\
                    - Control Block Address: {:?}\n\n\
                    Common Solutions:\n\
                    - Make sure RTT is initialized on the target (defmt-rtt or rtt-target)\n\
                    - Ensure target is running (not halted) during RTT initialization\n\
                    - Check that firmware has sufficient time to initialize RTT\n\
                    - Verify memory regions contain RTT control block\n\
                    - For defmt: ensure defmt-rtt feature is enabled in firmware", 
                    e, 
                    core_status,
                    scan_region,
                    control_block_address
                );
                
                Err(DebugError::RttError(detailed_error))
            }
        }
    }
    
    /// Complete RTT attachment by discovering channels (synchronous version)
    fn complete_attachment_sync(&mut self, mut rtt: Rtt) -> Result<()> {
        // Clear any previous state
        self.channels.clear();
        
        // Discover up channels (target to host)
        let up_channels = rtt.up_channels();
        self.up_channel_count = up_channels.len();
        for i in 0..up_channels.len() {
            if let Some(up_channel) = up_channels.get(i) {
                let channel_info = ChannelInfo {
                    id: i as u32,
                    name: up_channel.name().unwrap_or(&format!("Up{}", i)).to_string(),
                    direction: ChannelDirection::Up,
                    mode: "RTT".to_string(), // Simplified as mode() requires &mut Core
                    buffer_size: up_channel.buffer_size(),
                };
                self.channels.insert(i as u32, channel_info);
                debug!("Discovered up channel {}: {} (size: {} bytes)", 
                       i, up_channel.name().unwrap_or("unnamed"), up_channel.buffer_size());
            }
        }
        
        // Discover down channels (host to target)
        let down_channels = rtt.down_channels();
        self.down_channel_count = down_channels.len();
        for i in 0..down_channels.len() {
            if let Some(down_channel) = down_channels.get(i) {
                let channel_info = ChannelInfo {
                    id: i as u32,
                    name: down_channel.name().unwrap_or(&format!("Down{}", i)).to_string(),
                    direction: ChannelDirection::Down,
                    mode: "RTT".to_string(), // Simplified as mode() requires &mut Core
                    buffer_size: down_channel.buffer_size(),
                };
                // Use offset for down channels to avoid ID conflicts
                self.channels.insert(1000 + i as u32, channel_info);
                debug!("Discovered down channel {}: {} (size: {} bytes)", 
                       i, down_channel.name().unwrap_or("unnamed"), down_channel.buffer_size());
            }
        }
        
        // Store the RTT instance
        self.rtt = Some(rtt);
        self.attached = true;
        
        info!("RTT attachment completed: {} up channels, {} down channels", 
              self.up_channel_count, self.down_channel_count);
        Ok(())
    }

    /// Detach from RTT
    pub async fn detach(&mut self) -> Result<()> {
        debug!("Detaching from RTT");
        
        self.attached = false;
        self.rtt = None;
        self.session = None;
        self.channels.clear();
        self.up_channel_count = 0;
        self.down_channel_count = 0;
        
        info!("RTT detached successfully");
        Ok(())
    }

    /// Read from RTT up channel using probe-rs RTT API
    pub async fn read_channel(&mut self, channel: u32) -> Result<Vec<u8>> {
        if !self.attached {
            return Err(DebugError::RttError("RTT not attached".to_string()));
        }

        let session = self.session.as_ref()
            .ok_or_else(|| DebugError::RttError("No session available".to_string()))?;
        
        let rtt = self.rtt.as_mut()
            .ok_or_else(|| DebugError::RttError("No RTT instance available".to_string()))?;
        
        // Lock session and get core
        let mut session_guard = session.lock().await;
        let mut core = session_guard.core(0).map_err(|e| {
            DebugError::RttError(format!("Failed to get core: {}", e))
        })?;
        
        // Get the up channel (mutable reference)
        let up_channels = rtt.up_channels();
        let up_channel = up_channels.get_mut(channel as usize)
            .ok_or_else(|| DebugError::RttError(format!("Up channel {} not found", channel)))?;
        
        // Read from RTT channel
        let mut buffer = vec![0u8; 1024]; // Buffer for reading
        match up_channel.read(&mut core, &mut buffer) {
            Ok(bytes_read) => {
                buffer.truncate(bytes_read);
                if bytes_read > 0 {
                    debug!("Read {} bytes from RTT up channel {}", bytes_read, channel);
                }
                Ok(buffer)
            }
            Err(e) => {
                error!("Failed to read from RTT up channel {}: {}", channel, e);
                Err(DebugError::RttError(format!("RTT read failed: {}", e)))
            }
        }
    }

    /// Write to RTT down channel using probe-rs RTT API
    pub async fn write_channel(&mut self, channel: u32, data: &[u8]) -> Result<usize> {
        if !self.attached {
            return Err(DebugError::RttError("RTT not attached".to_string()));
        }

        let session = self.session.as_ref()
            .ok_or_else(|| DebugError::RttError("No session available".to_string()))?;
        
        let rtt = self.rtt.as_mut()
            .ok_or_else(|| DebugError::RttError("No RTT instance available".to_string()))?;
        
        // Lock session and get core
        let mut session_guard = session.lock().await;
        let mut core = session_guard.core(0).map_err(|e| {
            DebugError::RttError(format!("Failed to get core: {}", e))
        })?;
        
        // Get the down channel (mutable reference)
        let down_channels = rtt.down_channels();
        let down_channel = down_channels.get_mut(channel as usize)
            .ok_or_else(|| DebugError::RttError(format!("Down channel {} not found", channel)))?;
        
        // Write to RTT channel
        match down_channel.write(&mut core, data) {
            Ok(bytes_written) => {
                debug!("Wrote {} bytes to RTT down channel {}", bytes_written, channel);
                info!("RTT Write Channel {}: {:?}", channel, String::from_utf8_lossy(&data[..bytes_written]));
                Ok(bytes_written)
            }
            Err(e) => {
                error!("Failed to write to RTT down channel {}: {}", channel, e);
                Err(DebugError::RttError(format!("RTT write failed: {}", e)))
            }
        }
    }

    /// Get information about all RTT channels
    pub fn get_channels(&self) -> Vec<&ChannelInfo> {
        self.channels.values().collect()
    }

    /// Check if RTT is attached
    pub fn is_attached(&self) -> bool {
        self.attached
    }

    /// Get the number of available up channels
    pub fn up_channel_count(&self) -> usize {
        self.up_channel_count
    }

    /// Get the number of available down channels
    pub fn down_channel_count(&self) -> usize {
        self.down_channel_count
    }
}