This repository has been archived by the owner on Jan 30, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
main.rs
383 lines (315 loc) · 12.1 KB
/
main.rs
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
mod backtrace;
mod canary;
mod cli;
mod cortexm;
mod dep;
mod elf;
mod probe;
mod registers;
mod stacked;
mod target_info;
use std::{
env, fs,
io::{self, Write as _},
path::Path,
process,
sync::atomic::{AtomicBool, Ordering},
sync::{Arc, Mutex},
time::Duration,
};
use anyhow::{anyhow, bail};
use colored::Colorize as _;
use defmt_decoder::Locations;
use probe_rs::{
flashing::{self, Format},
Core,
DebugProbeError::ProbeSpecific,
MemoryInterface as _, Session,
};
use probe_rs_rtt::{Rtt, ScanRegion, UpChannel};
use signal_hook::consts::signal;
use crate::{backtrace::Outcome, canary::Canary, elf::Elf, target_info::TargetInfo};
const TIMEOUT: Duration = Duration::from_secs(1);
fn main() -> anyhow::Result<()> {
cli::handle_arguments().map(|code| process::exit(code))
}
fn run_target_program(elf_path: &Path, chip_name: &str, opts: &cli::Opts) -> anyhow::Result<i32> {
if !elf_path.exists() {
bail!(
"can't find ELF file at `{}`; are you sure you got the right path?",
elf_path.display()
);
}
let elf_bytes = fs::read(elf_path)?;
let elf = &Elf::parse(&elf_bytes)?;
let target_info = TargetInfo::new(chip_name, elf)?;
let probe = probe::open(opts)?;
let probe_target = target_info.probe_target.clone();
let mut sess = if opts.connect_under_reset {
probe.attach_under_reset(probe_target)?
} else {
let probe_attach = probe.attach(probe_target);
if let Err(probe_rs::Error::Probe(ProbeSpecific(e))) = &probe_attach {
// FIXME Using `to_string().contains(...)` is a workaround as the concrete type
// of `e` is not public and therefore does not allow downcasting.
if e.to_string().contains("JtagNoDeviceConnected") {
eprintln!("Info: Jtag cannot find a connected device.");
eprintln!("Help:");
eprintln!(" Check that the debugger is connected to the chip, if so");
eprintln!(" try using probe-run with option `--connect-under-reset`");
eprintln!(" or, if using cargo:");
eprintln!(" cargo run -- --connect-under-reset");
eprintln!(" If using this flag fixed your issue, this error might");
eprintln!(" come from the program currently in the chip and using");
eprintln!(" `--connect-under-reset` is only a workaround.\n");
}
}
probe_attach?
};
log::debug!("started session");
if opts.no_flash {
log::info!("skipped flashing");
} else {
let size = elf.program_flash_size();
log::info!("flashing program ({:.02} KiB)", size as f64 / 1024.0);
flashing::download_file(&mut sess, elf_path, Format::Elf)?;
log::info!("success!");
}
let canary = Canary::install(&mut sess, &target_info, elf, opts.measure_stack)?;
if opts.measure_stack && canary.is_none() {
bail!("failed to set up stack measurement");
}
start_program(&mut sess, elf)?;
let sess = Arc::new(Mutex::new(sess));
let current_dir = &env::current_dir()?;
let halted_due_to_signal = extract_and_print_logs(elf, &sess, opts, current_dir)?;
print_separator();
let mut sess = sess.lock().unwrap();
let mut core = sess.core(0)?;
let canary_touched = canary
.map(|canary| canary.touched(&mut core, elf))
.transpose()?
.unwrap_or(false);
let panic_present = canary_touched || halted_due_to_signal;
let mut backtrace_settings = backtrace::Settings {
current_dir,
backtrace_limit: opts.backtrace_limit,
backtrace: (&opts.backtrace).into(),
panic_present,
shorten_paths: opts.shorten_paths,
};
let mut outcome = backtrace::print(
&mut core,
elf,
&target_info.active_ram_region,
&mut backtrace_settings,
)?;
// if general outcome was OK but the user ctrl-c'ed, that overrides our outcome
// (TODO refactor this to be less bumpy)
if halted_due_to_signal && outcome == Outcome::Ok {
outcome = Outcome::CtrlC
}
core.reset_and_halt(TIMEOUT)?;
outcome.log();
Ok(outcome.into())
}
fn start_program(sess: &mut Session, elf: &Elf) -> anyhow::Result<()> {
let mut core = sess.core(0)?;
log::debug!("starting device");
if core.get_available_breakpoint_units()? == 0 {
if elf.rtt_buffer_address().is_some() {
bail!("RTT not supported on device without HW breakpoints");
} else {
log::warn!("device doesn't support HW breakpoints; HardFault will NOT make `probe-run` exit with an error code");
}
}
if let Some(rtt_buffer_address) = elf.rtt_buffer_address() {
set_rtt_to_blocking(&mut core, elf.main_fn_address(), rtt_buffer_address)?
}
core.set_hw_breakpoint(cortexm::clear_thumb_bit(elf.vector_table.hard_fault))?;
core.run()?;
Ok(())
}
/// Set rtt to blocking mode
fn set_rtt_to_blocking(
core: &mut Core,
main_fn_address: u32,
rtt_buffer_address: u32,
) -> anyhow::Result<()> {
// set and wait for a hardware breakpoint at the beginning of `fn main()`
core.set_hw_breakpoint(main_fn_address)?;
core.run()?;
core.wait_for_core_halted(Duration::from_secs(5))?;
// calculate address of up-channel-flags inside the rtt control block
const OFFSET: u32 = 44;
let rtt_buffer_address = rtt_buffer_address + OFFSET;
// read flags
let channel_flags = &mut [0];
core.read_32(rtt_buffer_address, channel_flags)?;
// modify flags to blocking
const MODE_MASK: u32 = 0b11;
const MODE_BLOCK_IF_FULL: u32 = 0b10;
let modified_channel_flags = (channel_flags[0] & !MODE_MASK) | MODE_BLOCK_IF_FULL;
// write flags back
core.write_word_32(rtt_buffer_address, modified_channel_flags)?;
// clear the breakpoint we set before
core.clear_hw_breakpoint(main_fn_address)?;
Ok(())
}
fn extract_and_print_logs(
elf: &Elf,
sess: &Arc<Mutex<Session>>,
opts: &cli::Opts,
current_dir: &Path,
) -> anyhow::Result<bool> {
let exit = Arc::new(AtomicBool::new(false));
let sig_id = signal_hook::flag::register(signal::SIGINT, exit.clone())?;
let mut logging_channel = if let Some(address) = elf.rtt_buffer_address() {
Some(setup_logging_channel(address, sess.clone())?)
} else {
eprintln!("RTT logs not available; blocking until the device halts..");
None
};
let use_defmt = logging_channel
.as_ref()
.map_or(false, |channel| channel.name() == Some("defmt"));
if use_defmt && opts.no_flash {
bail!(
"attempted to use `--no-flash` and `defmt` logging -- this combination is not allowed. Remove the `--no-flash` flag"
);
} else if use_defmt && elf.defmt_table.is_none() {
bail!("\"defmt\" RTT channel is in use, but the firmware binary contains no defmt data");
}
print_separator();
let stdout = io::stdout();
let mut stdout = stdout.lock();
let mut read_buf = [0; 1024];
let mut defmt_buffer = vec![];
let mut was_halted = false;
while !exit.load(Ordering::Relaxed) {
if let Some(logging_channel) = &mut logging_channel {
let num_bytes_read = match logging_channel.read(&mut read_buf) {
Ok(n) => n,
Err(e) => {
eprintln!("RTT error: {}", e);
break;
}
};
if num_bytes_read != 0 {
match &elf.defmt_table {
Some(table) if use_defmt => {
defmt_buffer.extend_from_slice(&read_buf[..num_bytes_read]);
decode_and_print_defmt_logs(
&mut defmt_buffer,
table,
elf.defmt_locations.as_ref(),
current_dir,
opts,
)?;
}
_ => {
stdout.write_all(&read_buf[..num_bytes_read])?;
stdout.flush()?;
}
}
}
}
let mut sess = sess.lock().unwrap();
let mut core = sess.core(0)?;
let is_halted = core.core_halted()?;
if is_halted && was_halted {
break;
}
was_halted = is_halted;
}
drop(stdout);
signal_hook::low_level::unregister(sig_id);
signal_hook::flag::register_conditional_default(signal::SIGINT, exit.clone())?;
// TODO refactor: a printing fucntion shouldn't stop the MC as a side effect
// Ctrl-C was pressed; stop the microcontroller.
if exit.load(Ordering::Relaxed) {
let mut sess = sess.lock().unwrap();
let mut core = sess.core(0)?;
core.halt(TIMEOUT)?;
}
let halted_due_to_signal = exit.load(Ordering::Relaxed);
Ok(halted_due_to_signal)
}
fn decode_and_print_defmt_logs(
buffer: &mut Vec<u8>,
table: &defmt_decoder::Table,
locations: Option<&Locations>,
current_dir: &Path,
opts: &cli::Opts,
) -> anyhow::Result<()> {
loop {
match table.decode(buffer) {
Ok((frame, consumed)) => {
// NOTE(`[]` indexing) all indices in `table` have already been verified to exist in
// the `locations` map
let (file, line, mod_path) = locations
.map(|locations| &locations[&frame.index()])
.map(|location| {
let path = if let Ok(relpath) = location.file.strip_prefix(¤t_dir) {
relpath.display().to_string()
} else {
let dep_path = dep::Path::from_std_path(&location.file);
if opts.shorten_paths {
dep_path.format_short()
} else {
dep_path.format_highlight()
}
};
(
Some(path),
Some(location.line as u32),
Some(&*location.module),
)
})
.unwrap_or((None, None, None));
// Forward the defmt frame to our logger.
defmt_decoder::log::log_defmt(&frame, file.as_deref(), line, mod_path);
let num_bytes = buffer.len();
buffer.rotate_left(consumed);
buffer.truncate(num_bytes - consumed);
}
Err(defmt_decoder::DecodeError::UnexpectedEof) => break,
Err(defmt_decoder::DecodeError::Malformed) => {
log::error!("failed to decode defmt data: {:x?}", buffer);
return Err(defmt_decoder::DecodeError::Malformed.into());
}
}
}
Ok(())
}
fn setup_logging_channel(
rtt_buffer_address: u32,
sess: Arc<Mutex<Session>>,
) -> anyhow::Result<UpChannel> {
const NUM_RETRIES: usize = 10; // picked at random, increase if necessary
let scan_region = ScanRegion::Exact(rtt_buffer_address);
for _ in 0..NUM_RETRIES {
match Rtt::attach_region(sess.clone(), &scan_region) {
Ok(mut rtt) => {
log::debug!("Successfully attached RTT");
let channel = rtt
.up_channels()
.take(0)
.ok_or_else(|| anyhow!("RTT up channel 0 not found"))?;
return Ok(channel);
}
Err(probe_rs_rtt::Error::ControlBlockNotFound) => {
log::trace!("Could not attach because the target's RTT control block isn't initialized (yet). retrying");
}
Err(e) => {
return Err(anyhow!(e));
}
}
}
log::error!("Max number of RTT attach retries exceeded.");
Err(anyhow!(probe_rs_rtt::Error::ControlBlockNotFound))
}
/// Print a line to separate different execution stages.
fn print_separator() {
println!("{}", "─".repeat(80).dimmed());
}