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
#![warn(missing_docs)]
#![warn(clippy::unwrap_used, clippy::panic, clippy::expect_used)]
pub mod debug_info;
pub mod debug_step;
pub mod function_die;
pub mod registers;
pub(crate) mod source_statement;
pub mod stack_frame;
pub mod unit_info;
pub mod variable;
pub mod variable_cache;
pub use self::{
debug_info::*, debug_step::SteppingMode, registers::*, stack_frame::StackFrame, variable::*,
variable_cache::VariableCache,
};
use crate::{core::Core, MemoryInterface};
use gimli::DebuggingInformationEntry;
use std::{
io,
path::PathBuf,
str::Utf8Error,
sync::atomic::{AtomicI64, Ordering},
vec,
};
#[derive(Debug, thiserror::Error)]
pub enum DebugError {
#[error("IO Error while accessing debug data")]
Io(#[from] io::Error),
#[error("Error accessing debug data")]
DebugData(#[from] object::read::Error),
#[error("Error parsing debug data")]
Parse(#[from] gimli::read::Error),
#[error("Non-UTF8 data found in debug data")]
NonUtf8(#[from] Utf8Error),
#[error("Error using the probe")]
Probe(#[from] crate::Error),
#[error(transparent)]
CharConversion(#[from] std::char::CharTryFromError),
#[error(transparent)]
IntConversion(#[from] std::num::TryFromIntError),
#[error("{message} @program_counter={:#010X}.", pc_at_error)]
NoValidHaltLocation {
message: String,
pc_at_error: u64,
},
#[error("{message}")]
UnwindIncompleteResults {
message: String,
},
#[error(transparent)]
Other(#[from] anyhow::Error),
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ColumnType {
LeftEdge,
Column(u64),
}
impl From<gimli::ColumnType> for ColumnType {
fn from(column: gimli::ColumnType) -> Self {
match column {
gimli::ColumnType::LeftEdge => ColumnType::LeftEdge,
gimli::ColumnType::Column(c) => ColumnType::Column(c.get()),
}
}
}
static CACHE_KEY: AtomicI64 = AtomicI64::new(1);
pub fn get_sequential_key() -> i64 {
CACHE_KEY.fetch_add(1, Ordering::SeqCst)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SourceLocation {
pub line: Option<u64>,
pub column: Option<ColumnType>,
pub file: Option<String>,
pub directory: Option<PathBuf>,
pub low_pc: Option<u32>,
pub high_pc: Option<u32>,
}
fn extract_file(
debug_info: &DebugInfo,
unit: &gimli::Unit<GimliReader>,
attribute_value: gimli::AttributeValue<GimliReader>,
) -> Option<(PathBuf, String)> {
match attribute_value {
gimli::AttributeValue::FileIndex(index) => unit.line_program.as_ref().and_then(|ilnp| {
let header = ilnp.header();
if let Some(file_entry) = header.file(index) {
if let Some((Some(path), Some(file))) = debug_info
.find_file_and_directory(unit, header, file_entry)
.map(|(file, path)| (path, file))
{
Some((path, file))
} else {
tracing::warn!("Unable to extract file or path from {:?}.", attribute_value);
None
}
} else {
tracing::warn!("Unable to extract file entry for {:?}.", attribute_value);
None
}
}),
other => {
tracing::warn!(
"Unable to extract file information from attribute value {:?}: Not implemented.",
other
);
None
}
}
}
fn extract_byte_size(
_debug_info: &DebugInfo,
di_entry: &DebuggingInformationEntry<GimliReader>,
) -> u64 {
match di_entry.attr(gimli::DW_AT_byte_size) {
Ok(optional_byte_size_attr) => match optional_byte_size_attr {
Some(byte_size_attr) => match byte_size_attr.value() {
gimli::AttributeValue::Udata(byte_size) => byte_size,
other => {
tracing::warn!("Unimplemented: DW_AT_byte_size value: {:?} ", other);
0
}
},
None => 0,
},
Err(error) => {
tracing::warn!(
"Failed to extract byte_size: {:?} for debug_entry {:?}",
error,
di_entry.tag().static_string()
);
0
}
}
}
fn extract_line(attribute_value: gimli::AttributeValue<GimliReader>) -> Option<u64> {
match attribute_value {
gimli::AttributeValue::Udata(line) => Some(line),
_ => None,
}
}
fn extract_name(
debug_info: &DebugInfo,
attribute_value: gimli::AttributeValue<GimliReader>,
) -> String {
match attribute_value {
gimli::AttributeValue::DebugStrRef(name_ref) => {
if let Ok(name_raw) = debug_info.dwarf.string(name_ref) {
String::from_utf8_lossy(&name_raw).to_string()
} else {
"Invalid DW_AT_name value".to_string()
}
}
gimli::AttributeValue::String(name) => String::from_utf8_lossy(&name).to_string(),
other => format!("Unimplemented: Evaluate name from {other:?}"),
}
}
#[allow(clippy::unwrap_used, clippy::expect_used)]
pub(crate) fn _print_all_attributes(
core: &mut Core<'_>,
stackframe_cfa: Option<u64>,
dwarf: &gimli::Dwarf<DwarfReader>,
unit: &gimli::Unit<DwarfReader>,
tag: &gimli::DebuggingInformationEntry<DwarfReader>,
print_depth: usize,
) {
let mut attrs = tag.attrs();
while let Some(attr) = attrs.next().unwrap() {
for _ in 0..(print_depth) {
print!("\t");
}
print!("{}: ", attr.name());
use gimli::AttributeValue::*;
match attr.value() {
Addr(a) => println!("{a:#010x}"),
DebugStrRef(_) => {
let val = dwarf.attr_string(unit, attr.value()).unwrap();
println!("{}", std::str::from_utf8(&val).unwrap());
}
Exprloc(e) => {
let mut evaluation = e.evaluation(unit.encoding());
let mut result = evaluation.evaluate().unwrap();
loop {
use gimli::EvaluationResult::*;
result = match result {
Complete => break,
RequiresMemory { address, size, .. } => {
let mut buff = vec![0u8; size as usize];
core.read(address, &mut buff)
.expect("Failed to read memory");
match size {
1 => evaluation
.resume_with_memory(gimli::Value::U8(buff[0]))
.unwrap(),
2 => {
let val = u16::from(buff[0]) << 8 | u16::from(buff[1]);
evaluation
.resume_with_memory(gimli::Value::U16(val))
.unwrap()
}
4 => {
let val = u32::from(buff[0]) << 24
| u32::from(buff[1]) << 16
| u32::from(buff[2]) << 8
| u32::from(buff[3]);
evaluation
.resume_with_memory(gimli::Value::U32(val))
.unwrap()
}
x => {
tracing::error!(
"Requested memory with size {}, which is not supported yet.",
x
);
unimplemented!();
}
}
}
RequiresFrameBase => evaluation
.resume_with_frame_base(stackframe_cfa.unwrap())
.unwrap(),
RequiresRegister {
register,
base_type,
} => {
let raw_value: u64 = core
.read_core_reg(register.0)
.expect("Failed to read memory");
if base_type != gimli::UnitOffset(0) {
unimplemented!(
"Support for units in RequiresRegister request is not yet implemented."
)
}
evaluation
.resume_with_register(gimli::Value::Generic(raw_value))
.unwrap()
}
RequiresRelocatedAddress(address_index) => {
evaluation
.resume_with_relocated_address(address_index)
.unwrap()
}
x => {
println!("print_all_attributes {x:?}");
todo!()
}
}
}
let result = evaluation.result();
println!("Expression: {:x?}", &result[0]);
}
LocationListsRef(_) => {
println!("LocationList");
}
DebugLocListsBase(_) => {
println!(" LocationList");
}
DebugLocListsIndex(_) => {
println!(" LocationList");
}
_ => {
println!("print_all_attributes {:?}", attr.value());
}
}
}
}