blob: d6117f7fdf62f7725c21604e22aef5bbfce1e3c1 [file] [log] [blame]
David Brown4440af82017-01-09 12:15:05 -07001#[macro_use] extern crate log;
2extern crate env_logger;
David Brownde7729e2017-01-09 10:41:35 -07003extern crate docopt;
4extern crate libc;
5extern crate rand;
6extern crate rustc_serialize;
7
8#[macro_use]
9extern crate error_chain;
10
11use docopt::Docopt;
David Brown4cb26232017-04-11 08:15:18 -060012use rand::{Rng, SeedableRng, XorShiftRng};
Fabio Utzigbb5635e2017-04-10 09:07:02 -030013use rand::distributions::{IndependentSample, Range};
David Brownde7729e2017-01-09 10:41:35 -070014use rustc_serialize::{Decodable, Decoder};
David Browna3b93cf2017-03-29 12:41:26 -060015use std::fmt;
David Brownde7729e2017-01-09 10:41:35 -070016use std::mem;
David Brown361be7a2017-03-29 12:28:47 -060017use std::process;
David Brownde7729e2017-01-09 10:41:35 -070018use std::slice;
19
20mod area;
21mod c;
22mod flash;
23pub mod api;
24mod pdump;
25
26use flash::Flash;
27use area::{AreaDesc, FlashId};
28
29const USAGE: &'static str = "
30Mcuboot simulator
31
32Usage:
33 bootsim sizes
34 bootsim run --device TYPE [--align SIZE]
David Browna3b93cf2017-03-29 12:41:26 -060035 bootsim runall
David Brownde7729e2017-01-09 10:41:35 -070036 bootsim (--help | --version)
37
38Options:
39 -h, --help Show this message
40 --version Version
41 --device TYPE MCU to simulate
42 Valid values: stm32f4, k64f
43 --align SIZE Flash write alignment
44";
45
46#[derive(Debug, RustcDecodable)]
47struct Args {
48 flag_help: bool,
49 flag_version: bool,
50 flag_device: Option<DeviceName>,
51 flag_align: Option<AlignArg>,
52 cmd_sizes: bool,
53 cmd_run: bool,
David Browna3b93cf2017-03-29 12:41:26 -060054 cmd_runall: bool,
David Brownde7729e2017-01-09 10:41:35 -070055}
56
David Browna3b93cf2017-03-29 12:41:26 -060057#[derive(Copy, Clone, Debug, RustcDecodable)]
David Brown07fb8fa2017-03-20 12:40:57 -060058enum DeviceName { Stm32f4, K64f, K64fBig, Nrf52840 }
David Brownde7729e2017-01-09 10:41:35 -070059
David Browna3b93cf2017-03-29 12:41:26 -060060static ALL_DEVICES: &'static [DeviceName] = &[
61 DeviceName::Stm32f4,
62 DeviceName::K64f,
63 DeviceName::K64fBig,
64 DeviceName::Nrf52840,
65];
66
67impl fmt::Display for DeviceName {
68 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69 let name = match *self {
70 DeviceName::Stm32f4 => "stm32f4",
71 DeviceName::K64f => "k64f",
72 DeviceName::K64fBig => "k64fbig",
73 DeviceName::Nrf52840 => "nrf52840",
74 };
75 f.write_str(name)
76 }
77}
78
David Brownde7729e2017-01-09 10:41:35 -070079#[derive(Debug)]
80struct AlignArg(u8);
81
82impl Decodable for AlignArg {
83 // Decode the alignment ourselves, to restrict it to the valid possible alignments.
84 fn decode<D: Decoder>(d: &mut D) -> Result<AlignArg, D::Error> {
85 let m = d.read_u8()?;
86 match m {
87 1 | 2 | 4 | 8 => Ok(AlignArg(m)),
88 _ => Err(d.error("Invalid alignment")),
89 }
90 }
91}
92
93fn main() {
David Brown4440af82017-01-09 12:15:05 -070094 env_logger::init().unwrap();
95
David Brownde7729e2017-01-09 10:41:35 -070096 let args: Args = Docopt::new(USAGE)
97 .and_then(|d| d.decode())
98 .unwrap_or_else(|e| e.exit());
99 // println!("args: {:#?}", args);
100
101 if args.cmd_sizes {
102 show_sizes();
103 return;
104 }
105
David Brown361be7a2017-03-29 12:28:47 -0600106 let mut status = RunStatus::new();
David Browna3b93cf2017-03-29 12:41:26 -0600107 if args.cmd_run {
David Brown361be7a2017-03-29 12:28:47 -0600108
David Browna3b93cf2017-03-29 12:41:26 -0600109 let align = args.flag_align.map(|x| x.0).unwrap_or(1);
David Brown562a7a02017-01-23 11:19:03 -0700110
David Browna3b93cf2017-03-29 12:41:26 -0600111 let device = match args.flag_device {
112 None => panic!("Missing mandatory device argument"),
113 Some(dev) => dev,
114 };
David Brownde7729e2017-01-09 10:41:35 -0700115
David Browna3b93cf2017-03-29 12:41:26 -0600116 status.run_single(device, align);
117 }
118
119 if args.cmd_runall {
120 for &dev in ALL_DEVICES {
121 for &align in &[1, 2, 4, 8] {
122 status.run_single(dev, align);
123 }
124 }
125 }
David Brown5c6b6792017-03-20 12:51:28 -0600126
David Brown361be7a2017-03-29 12:28:47 -0600127 if status.failures > 0 {
128 warn!("{} Tests ran with {} failures", status.failures + status.passes, status.failures);
129 process::exit(1);
130 } else {
131 warn!("{} Tests ran successfully", status.passes);
132 process::exit(0);
133 }
134}
David Brown5c6b6792017-03-20 12:51:28 -0600135
David Brown361be7a2017-03-29 12:28:47 -0600136struct RunStatus {
137 failures: usize,
138 passes: usize,
139}
David Brownde7729e2017-01-09 10:41:35 -0700140
David Brown361be7a2017-03-29 12:28:47 -0600141impl RunStatus {
142 fn new() -> RunStatus {
143 RunStatus {
144 failures: 0,
145 passes: 0,
David Brownde7729e2017-01-09 10:41:35 -0700146 }
147 }
David Brownde7729e2017-01-09 10:41:35 -0700148
David Brown361be7a2017-03-29 12:28:47 -0600149 fn run_single(&mut self, device: DeviceName, align: u8) {
150 let mut failed = false;
151
David Browna3b93cf2017-03-29 12:41:26 -0600152 warn!("Running on device {} with alignment {}", device, align);
153
David Brown361be7a2017-03-29 12:28:47 -0600154 let (mut flash, areadesc) = match device {
155 DeviceName::Stm32f4 => {
156 // STM style flash. Large sectors, with a large scratch area.
157 let flash = Flash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
158 64 * 1024,
159 128 * 1024, 128 * 1024, 128 * 1024],
160 align as usize);
161 let mut areadesc = AreaDesc::new(&flash);
162 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
163 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
164 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch);
165 (flash, areadesc)
166 }
167 DeviceName::K64f => {
168 // NXP style flash. Small sectors, one small sector for scratch.
169 let flash = Flash::new(vec![4096; 128], align as usize);
170
171 let mut areadesc = AreaDesc::new(&flash);
172 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
173 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
174 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch);
175 (flash, areadesc)
176 }
177 DeviceName::K64fBig => {
178 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
179 // uses small sectors, but we tell the bootloader they are large.
180 let flash = Flash::new(vec![4096; 128], align as usize);
181
182 let mut areadesc = AreaDesc::new(&flash);
183 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0);
184 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1);
185 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch);
186 (flash, areadesc)
187 }
188 DeviceName::Nrf52840 => {
189 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
190 // does not divide into the image size.
191 let flash = Flash::new(vec![4096; 128], align as usize);
192
193 let mut areadesc = AreaDesc::new(&flash);
194 areadesc.add_image(0x008000, 0x034000, FlashId::Image0);
195 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1);
196 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch);
197 (flash, areadesc)
198 }
199 };
200
201 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
202 let (slot1_base, slot1_len) = areadesc.find(FlashId::Image1);
203 let (scratch_base, _) = areadesc.find(FlashId::ImageScratch);
204
205 // Code below assumes that the slots are consecutive.
206 assert_eq!(slot1_base, slot0_base + slot0_len);
207 assert_eq!(scratch_base, slot1_base + slot1_len);
208
209 // println!("Areas: {:#?}", areadesc.get_c());
210
211 // Install the boot trailer signature, so that the code will start an upgrade.
212 // TODO: This must be a multiple of flash alignment, add support for an image that is smaller,
213 // and just gets padded.
214 let primary = install_image(&mut flash, slot0_base, 32784);
215
216 // Install an upgrade image.
217 let upgrade = install_image(&mut flash, slot1_base, 41928);
218
219 // Set an alignment, and position the magic value.
220 c::set_sim_flash_align(align);
221 let trailer_size = c::boot_trailer_sz();
222
223 // Mark the upgrade as ready to install. (This looks like it might be a bug in the code,
224 // however.)
225 mark_upgrade(&mut flash, scratch_base - trailer_size as usize);
226
227 let (fl2, total_count) = try_upgrade(&flash, &areadesc, None);
228 info!("First boot, count={}", total_count);
229 if !verify_image(&fl2, slot0_base, &upgrade) {
230 error!("Image mismatch after first boot");
231 // This isn't really recoverable, and more tests aren't likely to reveal much.
232 self.failures += 1;
233 return;
234 }
235
236 let mut bad = 0;
David Brown4cb26232017-04-11 08:15:18 -0600237 // Let's try an image halfway through.
238 for i in 1 .. total_count {
David Brown361be7a2017-03-29 12:28:47 -0600239 info!("Try interruption at {}", i);
240 let (fl3, total_count) = try_upgrade(&flash, &areadesc, Some(i));
241 info!("Second boot, count={}", total_count);
242 if !verify_image(&fl3, slot0_base, &upgrade) {
243 warn!("FAIL at step {} of {}", i, total_count);
244 bad += 1;
245 }
246 if !verify_image(&fl3, slot1_base, &primary) {
247 warn!("Slot 1 FAIL at step {} of {}", i, total_count);
248 bad += 1;
249 }
250 }
251 error!("{} out of {} failed {:.2}%",
252 bad, total_count,
253 bad as f32 * 100.0 / total_count as f32);
254 if bad > 0 {
255 failed = true;
256 }
257
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300258 let (fl4, total_counts) = try_random_fails(&flash, &areadesc, 5);
259 info!("Random fails at counts={:?}", total_counts);
260 if !verify_image(&fl4, slot0_base, &upgrade) {
261 error!("Image mismatch after random fails");
262 self.failures += 1;
263 return;
264 }
265
David Brown361be7a2017-03-29 12:28:47 -0600266 for count in 2 .. 5 {
267 info!("Try revert: {}", count);
268 let fl2 = try_revert(&flash, &areadesc, count);
269 if !verify_image(&fl2, slot0_base, &primary) {
270 warn!("Revert failure on count {}", count);
271 failed = true;
272 }
273 }
274
275 info!("Try norevert");
276 let fl2 = try_norevert(&flash, &areadesc);
277 if !verify_image(&fl2, slot0_base, &upgrade) {
278 warn!("No revert failed");
279 failed = true;
280 }
281
282 /*
283 // show_flash(&flash);
284
285 println!("First boot for upgrade");
286 // c::set_flash_counter(570);
287 c::boot_go(&mut flash, &areadesc);
288 // println!("{} flash ops", c::get_flash_counter());
289
290 verify_image(&flash, slot0_base, &upgrade);
291
292 println!("\n------------------\nSecond boot");
293 c::boot_go(&mut flash, &areadesc);
294 */
295 if failed {
296 self.failures += 1;
297 } else {
298 self.passes += 1;
299 }
David Brownc638f792017-01-10 12:34:33 -0700300 }
David Brownde7729e2017-01-09 10:41:35 -0700301}
302
303/// Test a boot, optionally stopping after 'n' flash options. Returns a count of the number of
304/// flash operations done total.
305fn try_upgrade(flash: &Flash, areadesc: &AreaDesc, stop: Option<i32>) -> (Flash, i32) {
306 // Clone the flash to have a new copy.
307 let mut fl = flash.clone();
308
309 c::set_flash_counter(stop.unwrap_or(0));
310 let (first_interrupted, cnt1) = match c::boot_go(&mut fl, &areadesc) {
311 -0x13579 => (true, stop.unwrap()),
312 0 => (false, -c::get_flash_counter()),
313 x => panic!("Unknown return: {}", x),
314 };
315 c::set_flash_counter(0);
316
317 if first_interrupted {
318 // fl.dump();
319 match c::boot_go(&mut fl, &areadesc) {
320 -0x13579 => panic!("Shouldn't stop again"),
321 0 => (),
322 x => panic!("Unknown return: {}", x),
323 }
324 }
325
326 let cnt2 = cnt1 - c::get_flash_counter();
327
328 (fl, cnt2)
329}
330
David Brownc638f792017-01-10 12:34:33 -0700331fn try_revert(flash: &Flash, areadesc: &AreaDesc, count: usize) -> Flash {
David Brownde7729e2017-01-09 10:41:35 -0700332 let mut fl = flash.clone();
333 c::set_flash_counter(0);
334
David Brown163ab232017-01-23 15:48:35 -0700335 // fl.write_file("image0.bin").unwrap();
336 for i in 0 .. count {
337 info!("Running boot pass {}", i + 1);
David Brownc638f792017-01-10 12:34:33 -0700338 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
339 }
David Brownde7729e2017-01-09 10:41:35 -0700340 fl
341}
342
343fn try_norevert(flash: &Flash, areadesc: &AreaDesc) -> Flash {
344 let mut fl = flash.clone();
345 c::set_flash_counter(0);
346 let align = c::get_sim_flash_align() as usize;
347
348 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
349 // Write boot_ok
David Brown75e16d62017-01-23 15:47:59 -0700350 let ok = [1u8, 0, 0, 0, 0, 0, 0, 0];
David Brown5c6b6792017-03-20 12:51:28 -0600351 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
352 fl.write(slot0_base + slot0_len - align, &ok[..align]).unwrap();
David Brownde7729e2017-01-09 10:41:35 -0700353 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
354 fl
355}
356
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300357fn try_random_fails(flash: &Flash, areadesc: &AreaDesc, count: usize) -> (Flash, Vec<i32>) {
358 // Clone the flash to have a new copy.
359 let mut fl = flash.clone();
360
361 c::set_flash_counter(0);
362 let (_, total_ops) = match c::boot_go(&mut fl, &areadesc) {
363 -0x13579 => panic!("Should not be have been interrupted!"),
364 0 => (false, -c::get_flash_counter()),
365 x => panic!("Unknown return: {}", x),
366 };
367
368 let mut rng = rand::thread_rng();
369 let ops = Range::new(1, total_ops);
370 let mut stops = vec![0i32; count];
371 for i in 0 .. count {
372 let reset_counter = ops.ind_sample(&mut rng);
373 c::set_flash_counter(reset_counter);
374 match c::boot_go(&mut fl, &areadesc) {
375 0 | -0x13579 => (),
376 x => panic!("Unknown return: {}", x),
377 }
378 stops[i] = reset_counter;
379 }
380
381 c::set_flash_counter(0);
382 match c::boot_go(&mut fl, &areadesc) {
383 -0x13579 => panic!("Should not be have been interrupted!"),
384 0 => (),
385 x => panic!("Unknown return: {}", x),
386 }
387
388 (fl, stops)
389}
390
David Brownde7729e2017-01-09 10:41:35 -0700391/// Show the flash layout.
392#[allow(dead_code)]
393fn show_flash(flash: &Flash) {
394 println!("---- Flash configuration ----");
395 for sector in flash.sector_iter() {
396 println!(" {:2}: 0x{:08x}, 0x{:08x}",
397 sector.num, sector.base, sector.size);
398 }
399 println!("");
400}
401
402/// Install a "program" into the given image. This fakes the image header, or at least all of the
403/// fields used by the given code. Returns a copy of the image that was written.
404fn install_image(flash: &mut Flash, offset: usize, len: usize) -> Vec<u8> {
405 let offset0 = offset;
406
407 // Generate a boot header. Note that the size doesn't include the header.
408 let header = ImageHeader {
409 magic: 0x96f3b83c,
410 tlv_size: 0,
411 _pad1: 0,
412 hdr_size: 32,
413 key_id: 0,
414 _pad2: 0,
415 img_size: len as u32,
416 flags: 0,
417 ver: ImageVersion {
David Browne380fa62017-01-23 15:49:09 -0700418 major: (offset / (128 * 1024)) as u8,
David Brownde7729e2017-01-09 10:41:35 -0700419 minor: 0,
420 revision: 1,
David Browne380fa62017-01-23 15:49:09 -0700421 build_num: offset as u32,
David Brownde7729e2017-01-09 10:41:35 -0700422 },
423 _pad3: 0,
424 };
425
426 let b_header = header.as_raw();
427 /*
428 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
429 mem::size_of::<ImageHeader>()) };
430 */
431 assert_eq!(b_header.len(), 32);
432 flash.write(offset, &b_header).unwrap();
433 let offset = offset + b_header.len();
434
435 // The core of the image itself is just pseudorandom data.
436 let mut buf = vec![0; len];
437 splat(&mut buf, offset);
438 flash.write(offset, &buf).unwrap();
439 let offset = offset + buf.len();
440
441 // Copy out the image so that we can verify that the image was installed correctly later.
442 let mut copy = vec![0u8; offset - offset0];
443 flash.read(offset0, &mut copy).unwrap();
444
445 copy
446}
447
448/// Verify that given image is present in the flash at the given offset.
449fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
450 let mut copy = vec![0u8; buf.len()];
451 flash.read(offset, &mut copy).unwrap();
452
453 if buf != &copy[..] {
454 for i in 0 .. buf.len() {
455 if buf[i] != copy[i] {
David Brown4440af82017-01-09 12:15:05 -0700456 info!("First failure at {:#x}", offset + i);
David Brownde7729e2017-01-09 10:41:35 -0700457 break;
458 }
459 }
460 false
461 } else {
462 true
463 }
464}
465
466/// The image header
467#[repr(C)]
468pub struct ImageHeader {
469 magic: u32,
470 tlv_size: u16,
471 key_id: u8,
472 _pad1: u8,
473 hdr_size: u16,
474 _pad2: u16,
475 img_size: u32,
476 flags: u32,
477 ver: ImageVersion,
478 _pad3: u32,
479}
480
481impl AsRaw for ImageHeader {}
482
483#[repr(C)]
484pub struct ImageVersion {
485 major: u8,
486 minor: u8,
487 revision: u16,
488 build_num: u32,
489}
490
491/// Write out the magic so that the loader tries doing an upgrade.
492fn mark_upgrade(flash: &mut Flash, offset: usize) {
493 let magic = vec![0x77, 0xc2, 0x95, 0xf3,
494 0x60, 0xd2, 0xef, 0x7f,
495 0x35, 0x52, 0x50, 0x0f,
496 0x2c, 0xb6, 0x79, 0x80];
497 flash.write(offset, &magic).unwrap();
498}
499
500// Drop some pseudo-random gibberish onto the data.
501fn splat(data: &mut [u8], seed: usize) {
502 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
503 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
504 rng.fill_bytes(data);
505}
506
507/// Return a read-only view into the raw bytes of this object
508trait AsRaw : Sized {
509 fn as_raw<'a>(&'a self) -> &'a [u8] {
510 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
511 mem::size_of::<Self>()) }
512 }
513}
514
515fn show_sizes() {
516 // This isn't panic safe.
517 let old_align = c::get_sim_flash_align();
518 for min in &[1, 2, 4, 8] {
519 c::set_sim_flash_align(*min);
520 let msize = c::boot_trailer_sz();
521 println!("{:2}: {} (0x{:x})", min, msize, msize);
522 }
523 c::set_sim_flash_align(old_align);
524}