blob: d42a7b7454d87dce8c0aa9f86154259bd8429242 [file] [log] [blame]
David Brown2639e072017-10-11 11:18:44 -06001#[macro_use] extern crate log;
2extern crate ring;
3extern crate env_logger;
4extern crate docopt;
5extern crate libc;
6extern crate pem;
7extern crate rand;
8#[macro_use] extern crate serde_derive;
9extern crate serde;
10extern crate simflash;
11extern crate untrusted;
12extern crate mcuboot_sys;
13
14use docopt::Docopt;
15use rand::{Rng, SeedableRng, XorShiftRng};
16use rand::distributions::{IndependentSample, Range};
17use std::fmt;
18use std::mem;
19use std::process;
20use std::slice;
21
22mod caps;
23mod tlv;
David Brownca7b5d32017-11-03 08:37:38 -060024pub mod testlog;
David Brown2639e072017-10-11 11:18:44 -060025
26use simflash::{Flash, SimFlash};
27use mcuboot_sys::{c, AreaDesc, FlashId};
28use caps::Caps;
29use tlv::TlvGen;
30
31const USAGE: &'static str = "
32Mcuboot simulator
33
34Usage:
35 bootsim sizes
36 bootsim run --device TYPE [--align SIZE]
37 bootsim runall
38 bootsim (--help | --version)
39
40Options:
41 -h, --help Show this message
42 --version Version
43 --device TYPE MCU to simulate
44 Valid values: stm32f4, k64f
45 --align SIZE Flash write alignment
46";
47
48#[derive(Debug, Deserialize)]
49struct Args {
50 flag_help: bool,
51 flag_version: bool,
52 flag_device: Option<DeviceName>,
53 flag_align: Option<AlignArg>,
54 cmd_sizes: bool,
55 cmd_run: bool,
56 cmd_runall: bool,
57}
58
59#[derive(Copy, Clone, Debug, Deserialize)]
David Browndecbd042017-10-19 10:43:17 -060060pub enum DeviceName { Stm32f4, K64f, K64fBig, Nrf52840 }
David Brown2639e072017-10-11 11:18:44 -060061
David Browndd2b1182017-11-02 15:39:21 -060062pub static ALL_DEVICES: &'static [DeviceName] = &[
David Brown2639e072017-10-11 11:18:44 -060063 DeviceName::Stm32f4,
64 DeviceName::K64f,
65 DeviceName::K64fBig,
66 DeviceName::Nrf52840,
67];
68
69impl fmt::Display for DeviceName {
70 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
71 let name = match *self {
72 DeviceName::Stm32f4 => "stm32f4",
73 DeviceName::K64f => "k64f",
74 DeviceName::K64fBig => "k64fbig",
75 DeviceName::Nrf52840 => "nrf52840",
76 };
77 f.write_str(name)
78 }
79}
80
81#[derive(Debug)]
82struct AlignArg(u8);
83
84struct AlignArgVisitor;
85
86impl<'de> serde::de::Visitor<'de> for AlignArgVisitor {
87 type Value = AlignArg;
88
89 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
90 formatter.write_str("1, 2, 4 or 8")
91 }
92
93 fn visit_u8<E>(self, n: u8) -> Result<Self::Value, E>
94 where E: serde::de::Error
95 {
96 Ok(match n {
97 1 | 2 | 4 | 8 => AlignArg(n),
98 n => {
99 let err = format!("Could not deserialize '{}' as alignment", n);
100 return Err(E::custom(err));
101 }
102 })
103 }
104}
105
106impl<'de> serde::de::Deserialize<'de> for AlignArg {
107 fn deserialize<D>(d: D) -> Result<AlignArg, D::Error>
108 where D: serde::de::Deserializer<'de>
109 {
110 d.deserialize_u8(AlignArgVisitor)
111 }
112}
113
114pub fn main() {
115 let args: Args = Docopt::new(USAGE)
116 .and_then(|d| d.deserialize())
117 .unwrap_or_else(|e| e.exit());
118 // println!("args: {:#?}", args);
119
120 if args.cmd_sizes {
121 show_sizes();
122 return;
123 }
124
125 let mut status = RunStatus::new();
126 if args.cmd_run {
127
128 let align = args.flag_align.map(|x| x.0).unwrap_or(1);
129
130
131 let device = match args.flag_device {
132 None => panic!("Missing mandatory device argument"),
133 Some(dev) => dev,
134 };
135
136 status.run_single(device, align);
137 }
138
139 if args.cmd_runall {
140 for &dev in ALL_DEVICES {
141 for &align in &[1, 2, 4, 8] {
142 status.run_single(dev, align);
143 }
144 }
145 }
146
147 if status.failures > 0 {
148 error!("{} Tests ran with {} failures", status.failures + status.passes, status.failures);
149 process::exit(1);
150 } else {
151 error!("{} Tests ran successfully", status.passes);
152 process::exit(0);
153 }
154}
155
David Browndd2b1182017-11-02 15:39:21 -0600156pub struct RunStatus {
David Brown2639e072017-10-11 11:18:44 -0600157 failures: usize,
158 passes: usize,
159}
160
161impl RunStatus {
David Browndd2b1182017-11-02 15:39:21 -0600162 pub fn new() -> RunStatus {
David Brown2639e072017-10-11 11:18:44 -0600163 RunStatus {
164 failures: 0,
165 passes: 0,
166 }
167 }
168
David Browndd2b1182017-11-02 15:39:21 -0600169 pub fn run_single(&mut self, device: DeviceName, align: u8) {
David Brown2639e072017-10-11 11:18:44 -0600170 warn!("Running on device {} with alignment {}", device, align);
171
David Browndecbd042017-10-19 10:43:17 -0600172 let (mut flash, areadesc) = make_device(device, align);
David Brown2639e072017-10-11 11:18:44 -0600173
174 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
175 let (slot1_base, slot1_len) = areadesc.find(FlashId::Image1);
176 let (scratch_base, _) = areadesc.find(FlashId::ImageScratch);
177
178 // Code below assumes that the slots are consecutive.
179 assert_eq!(slot1_base, slot0_base + slot0_len);
180 assert_eq!(scratch_base, slot1_base + slot1_len);
181
182 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 2;
183
184 // println!("Areas: {:#?}", areadesc.get_c());
185
186 // Install the boot trailer signature, so that the code will start an upgrade.
187 // TODO: This must be a multiple of flash alignment, add support for an image that is smaller,
188 // and just gets padded.
189
190 // Create original and upgrade images
191 let slot0 = SlotInfo {
192 base_off: slot0_base as usize,
193 trailer_off: slot1_base - offset_from_end,
194 };
195
196 let slot1 = SlotInfo {
197 base_off: slot1_base as usize,
198 trailer_off: scratch_base - offset_from_end,
199 };
200
201 // Set an alignment, and position the magic value.
202 c::set_sim_flash_align(align);
203
204 let mut failed = false;
205
206 // Creates a badly signed image in slot1 to check that it is not
207 // upgraded to
208 let mut bad_flash = flash.clone();
209 let bad_slot1_image = Images {
David Brownd5e632c2017-10-19 10:49:46 -0600210 slot0: slot0.clone(),
211 slot1: slot1.clone(),
David Brown2639e072017-10-11 11:18:44 -0600212 primary: install_image(&mut bad_flash, slot0_base, 32784, false),
213 upgrade: install_image(&mut bad_flash, slot1_base, 41928, true),
214 };
215
216 failed |= run_signfail_upgrade(&bad_flash, &areadesc, &bad_slot1_image);
217
218 let images = Images {
David Brownd5e632c2017-10-19 10:49:46 -0600219 slot0: slot0.clone(),
220 slot1: slot1.clone(),
David Brown2639e072017-10-11 11:18:44 -0600221 primary: install_image(&mut flash, slot0_base, 32784, false),
222 upgrade: install_image(&mut flash, slot1_base, 41928, false),
223 };
224
225 failed |= run_norevert_newimage(&flash, &areadesc, &images);
226
227 mark_upgrade(&mut flash, &images.slot1);
228
229 // upgrades without fails, counts number of flash operations
230 let total_count = match run_basic_upgrade(&flash, &areadesc, &images) {
231 Ok(v) => v,
232 Err(_) => {
233 self.failures += 1;
234 return;
235 },
236 };
237
238 failed |= run_basic_revert(&flash, &areadesc, &images);
239 failed |= run_revert_with_fails(&flash, &areadesc, &images, total_count);
240 failed |= run_perm_with_fails(&flash, &areadesc, &images, total_count);
241 failed |= run_perm_with_random_fails(&flash, &areadesc, &images,
242 total_count, 5);
243 failed |= run_norevert(&flash, &areadesc, &images);
244
245 //show_flash(&flash);
246
247 if failed {
248 self.failures += 1;
249 } else {
250 self.passes += 1;
251 }
252 }
David Browndd2b1182017-11-02 15:39:21 -0600253
254 pub fn failures(&self) -> usize {
255 self.failures
256 }
David Brown2639e072017-10-11 11:18:44 -0600257}
258
David Browndecbd042017-10-19 10:43:17 -0600259/// Build the Flash and area descriptor for a given device.
260pub fn make_device(device: DeviceName, align: u8) -> (SimFlash, AreaDesc) {
261 match device {
262 DeviceName::Stm32f4 => {
263 // STM style flash. Large sectors, with a large scratch area.
264 let flash = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
265 64 * 1024,
266 128 * 1024, 128 * 1024, 128 * 1024],
267 align as usize);
268 let mut areadesc = AreaDesc::new(&flash);
269 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
270 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
271 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch);
272 (flash, areadesc)
273 }
274 DeviceName::K64f => {
275 // NXP style flash. Small sectors, one small sector for scratch.
276 let flash = SimFlash::new(vec![4096; 128], align as usize);
277
278 let mut areadesc = AreaDesc::new(&flash);
279 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
280 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
281 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch);
282 (flash, areadesc)
283 }
284 DeviceName::K64fBig => {
285 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
286 // uses small sectors, but we tell the bootloader they are large.
287 let flash = SimFlash::new(vec![4096; 128], align as usize);
288
289 let mut areadesc = AreaDesc::new(&flash);
290 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0);
291 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1);
292 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch);
293 (flash, areadesc)
294 }
295 DeviceName::Nrf52840 => {
296 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
297 // does not divide into the image size.
298 let flash = SimFlash::new(vec![4096; 128], align as usize);
299
300 let mut areadesc = AreaDesc::new(&flash);
301 areadesc.add_image(0x008000, 0x034000, FlashId::Image0);
302 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1);
303 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch);
304 (flash, areadesc)
305 }
306 }
307}
308
David Brown2639e072017-10-11 11:18:44 -0600309/// A simple upgrade without forced failures.
310///
311/// Returns the number of flash operations which can later be used to
312/// inject failures at chosen steps.
313fn run_basic_upgrade(flash: &SimFlash, areadesc: &AreaDesc, images: &Images)
314 -> Result<i32, ()> {
315 let (fl, total_count) = try_upgrade(&flash, &areadesc, &images, None);
316 info!("Total flash operation count={}", total_count);
317
318 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
319 warn!("Image mismatch after first boot");
320 Err(())
321 } else {
322 Ok(total_count)
323 }
324}
325
326#[cfg(feature = "overwrite-only")]
327#[allow(unused_variables)]
328fn run_basic_revert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool {
329 false
330}
331
332#[cfg(not(feature = "overwrite-only"))]
333fn run_basic_revert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool {
334 let mut fails = 0;
335
336 // FIXME: this test would also pass if no swap is ever performed???
337 if Caps::SwapUpgrade.present() {
338 for count in 2 .. 5 {
339 info!("Try revert: {}", count);
340 let fl = try_revert(&flash, &areadesc, count);
341 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
342 error!("Revert failure on count {}", count);
343 fails += 1;
344 }
345 }
346 }
347
348 fails > 0
349}
350
351fn run_perm_with_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
352 total_flash_ops: i32) -> bool {
353 let mut fails = 0;
354
355 // Let's try an image halfway through.
356 for i in 1 .. total_flash_ops {
357 info!("Try interruption at {}", i);
358 let (fl, count) = try_upgrade(&flash, &areadesc, &images, Some(i));
359 info!("Second boot, count={}", count);
360 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
361 warn!("FAIL at step {} of {}", i, total_flash_ops);
362 fails += 1;
363 }
364
365 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
366 COPY_DONE) {
367 warn!("Mismatched trailer for Slot 0");
368 fails += 1;
369 }
370
371 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
372 UNSET) {
373 warn!("Mismatched trailer for Slot 1");
374 fails += 1;
375 }
376
377 if Caps::SwapUpgrade.present() {
378 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
379 warn!("Slot 1 FAIL at step {} of {}", i, total_flash_ops);
380 fails += 1;
381 }
382 }
383 }
384
385 if fails > 0 {
386 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
387 fails as f32 * 100.0 / total_flash_ops as f32);
388 }
389
390 fails > 0
391}
392
393fn run_perm_with_random_fails(flash: &SimFlash, areadesc: &AreaDesc,
394 images: &Images, total_flash_ops: i32,
395 total_fails: usize) -> bool {
396 let mut fails = 0;
397 let (fl, total_counts) = try_random_fails(&flash, &areadesc, &images,
398 total_flash_ops, total_fails);
399 info!("Random interruptions at reset points={:?}", total_counts);
400
401 let slot0_ok = verify_image(&fl, images.slot0.base_off, &images.upgrade);
402 let slot1_ok = if Caps::SwapUpgrade.present() {
403 verify_image(&fl, images.slot1.base_off, &images.primary)
404 } else {
405 true
406 };
407 if !slot0_ok || !slot1_ok {
408 error!("Image mismatch after random interrupts: slot0={} slot1={}",
409 if slot0_ok { "ok" } else { "fail" },
410 if slot1_ok { "ok" } else { "fail" });
411 fails += 1;
412 }
413 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
414 COPY_DONE) {
415 error!("Mismatched trailer for Slot 0");
416 fails += 1;
417 }
418 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
419 UNSET) {
420 error!("Mismatched trailer for Slot 1");
421 fails += 1;
422 }
423
424 if fails > 0 {
425 error!("Error testing perm upgrade with {} fails", total_fails);
426 }
427
428 fails > 0
429}
430
431#[cfg(feature = "overwrite-only")]
432#[allow(unused_variables)]
433fn run_revert_with_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
434 total_count: i32) -> bool {
435 false
436}
437
438#[cfg(not(feature = "overwrite-only"))]
439fn run_revert_with_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
440 total_count: i32) -> bool {
441 let mut fails = 0;
442
443 if Caps::SwapUpgrade.present() {
444 for i in 1 .. (total_count - 1) {
445 info!("Try interruption at {}", i);
446 if try_revert_with_fail_at(&flash, &areadesc, &images, i) {
447 error!("Revert failed at interruption {}", i);
448 fails += 1;
449 }
450 }
451 }
452
453 fails > 0
454}
455
456#[cfg(feature = "overwrite-only")]
457#[allow(unused_variables)]
458fn run_norevert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool {
459 false
460}
461
462#[cfg(not(feature = "overwrite-only"))]
463fn run_norevert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool {
464 let mut fl = flash.clone();
465 let mut fails = 0;
466
467 info!("Try norevert");
468 c::set_flash_counter(0);
469
470 // First do a normal upgrade...
471 if c::boot_go(&mut fl, &areadesc) != 0 {
472 warn!("Failed first boot");
473 fails += 1;
474 }
475
476 //FIXME: copy_done is written by boot_go, is it ok if no copy
477 // was ever done?
478
479 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
480 warn!("Slot 0 image verification FAIL");
481 fails += 1;
482 }
483 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
484 COPY_DONE) {
485 warn!("Mismatched trailer for Slot 0");
486 fails += 1;
487 }
488 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
489 UNSET) {
490 warn!("Mismatched trailer for Slot 1");
491 fails += 1;
492 }
493
494 // Marks image in slot0 as permanent, no revert should happen...
495 mark_permanent_upgrade(&mut fl, &images.slot0);
496
497 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
498 COPY_DONE) {
499 warn!("Mismatched trailer for Slot 0");
500 fails += 1;
501 }
502
503 if c::boot_go(&mut fl, &areadesc) != 0 {
504 warn!("Failed second boot");
505 fails += 1;
506 }
507
508 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
509 COPY_DONE) {
510 warn!("Mismatched trailer for Slot 0");
511 fails += 1;
512 }
513 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
514 warn!("Failed image verification");
515 fails += 1;
516 }
517
518 if fails > 0 {
519 error!("Error running upgrade without revert");
520 }
521
522 fails > 0
523}
524
525// Tests a new image written to slot0 that already has magic and image_ok set
526// while there is no image on slot1, so no revert should ever happen...
527fn run_norevert_newimage(flash: &SimFlash, areadesc: &AreaDesc,
528 images: &Images) -> bool {
529 let mut fl = flash.clone();
530 let mut fails = 0;
531
532 info!("Try non-revert on imgtool generated image");
533 c::set_flash_counter(0);
534
535 mark_upgrade(&mut fl, &images.slot0);
536
537 // This simulates writing an image created by imgtool to Slot 0
538 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET, UNSET) {
539 warn!("Mismatched trailer for Slot 0");
540 fails += 1;
541 }
542
543 // Run the bootloader...
544 if c::boot_go(&mut fl, &areadesc) != 0 {
545 warn!("Failed first boot");
546 fails += 1;
547 }
548
549 // State should not have changed
550 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
551 warn!("Failed image verification");
552 fails += 1;
553 }
554 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
555 UNSET) {
556 warn!("Mismatched trailer for Slot 0");
557 fails += 1;
558 }
559 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
560 UNSET) {
561 warn!("Mismatched trailer for Slot 1");
562 fails += 1;
563 }
564
565 if fails > 0 {
566 error!("Expected a non revert with new image");
567 }
568
569 fails > 0
570}
571
572// Tests a new image written to slot0 that already has magic and image_ok set
573// while there is no image on slot1, so no revert should ever happen...
574fn run_signfail_upgrade(flash: &SimFlash, areadesc: &AreaDesc,
575 images: &Images) -> bool {
576 let mut fl = flash.clone();
577 let mut fails = 0;
578
579 info!("Try upgrade image with bad signature");
580 c::set_flash_counter(0);
581
582 mark_upgrade(&mut fl, &images.slot0);
583 mark_permanent_upgrade(&mut fl, &images.slot0);
584 mark_upgrade(&mut fl, &images.slot1);
585
586 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
587 UNSET) {
588 warn!("Mismatched trailer for Slot 0");
589 fails += 1;
590 }
591
592 // Run the bootloader...
593 if c::boot_go(&mut fl, &areadesc) != 0 {
594 warn!("Failed first boot");
595 fails += 1;
596 }
597
598 // State should not have changed
599 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
600 warn!("Failed image verification");
601 fails += 1;
602 }
603 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
604 UNSET) {
605 warn!("Mismatched trailer for Slot 0");
606 fails += 1;
607 }
608
609 if fails > 0 {
610 error!("Expected an upgrade failure when image has bad signature");
611 }
612
613 fails > 0
614}
615
616/// Test a boot, optionally stopping after 'n' flash options. Returns a count
617/// of the number of flash operations done total.
618fn try_upgrade(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
619 stop: Option<i32>) -> (SimFlash, i32) {
620 // Clone the flash to have a new copy.
621 let mut fl = flash.clone();
622
623 mark_permanent_upgrade(&mut fl, &images.slot1);
624
625 c::set_flash_counter(stop.unwrap_or(0));
626 let (first_interrupted, count) = match c::boot_go(&mut fl, &areadesc) {
627 -0x13579 => (true, stop.unwrap()),
628 0 => (false, -c::get_flash_counter()),
629 x => panic!("Unknown return: {}", x),
630 };
631 c::set_flash_counter(0);
632
633 if first_interrupted {
634 // fl.dump();
635 match c::boot_go(&mut fl, &areadesc) {
636 -0x13579 => panic!("Shouldn't stop again"),
637 0 => (),
638 x => panic!("Unknown return: {}", x),
639 }
640 }
641
642 (fl, count - c::get_flash_counter())
643}
644
645#[cfg(not(feature = "overwrite-only"))]
646fn try_revert(flash: &SimFlash, areadesc: &AreaDesc, count: usize) -> SimFlash {
647 let mut fl = flash.clone();
648 c::set_flash_counter(0);
649
650 // fl.write_file("image0.bin").unwrap();
651 for i in 0 .. count {
652 info!("Running boot pass {}", i + 1);
653 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
654 }
655 fl
656}
657
658#[cfg(not(feature = "overwrite-only"))]
659fn try_revert_with_fail_at(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
660 stop: i32) -> bool {
661 let mut fl = flash.clone();
662 let mut x: i32;
663 let mut fails = 0;
664
665 c::set_flash_counter(stop);
666 x = c::boot_go(&mut fl, &areadesc);
667 if x != -0x13579 {
668 warn!("Should have stopped at interruption point");
669 fails += 1;
670 }
671
672 if !verify_trailer(&fl, images.slot0.trailer_off, None, None, UNSET) {
673 warn!("copy_done should be unset");
674 fails += 1;
675 }
676
677 c::set_flash_counter(0);
678 x = c::boot_go(&mut fl, &areadesc);
679 if x != 0 {
680 warn!("Should have finished upgrade");
681 fails += 1;
682 }
683
684 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
685 warn!("Image in slot 0 before revert is invalid at stop={}", stop);
686 fails += 1;
687 }
688 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
689 warn!("Image in slot 1 before revert is invalid at stop={}", stop);
690 fails += 1;
691 }
692 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
693 COPY_DONE) {
694 warn!("Mismatched trailer for Slot 0 before revert");
695 fails += 1;
696 }
697 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
698 UNSET) {
699 warn!("Mismatched trailer for Slot 1 before revert");
700 fails += 1;
701 }
702
703 // Do Revert
704 c::set_flash_counter(0);
705 x = c::boot_go(&mut fl, &areadesc);
706 if x != 0 {
707 warn!("Should have finished a revert");
708 fails += 1;
709 }
710
711 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
712 warn!("Image in slot 0 after revert is invalid at stop={}", stop);
713 fails += 1;
714 }
715 if !verify_image(&fl, images.slot1.base_off, &images.upgrade) {
716 warn!("Image in slot 1 after revert is invalid at stop={}", stop);
717 fails += 1;
718 }
719 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
720 COPY_DONE) {
721 warn!("Mismatched trailer for Slot 1 after revert");
722 fails += 1;
723 }
724 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
725 UNSET) {
726 warn!("Mismatched trailer for Slot 1 after revert");
727 fails += 1;
728 }
729
730 fails > 0
731}
732
733fn try_random_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
734 total_ops: i32, count: usize) -> (SimFlash, Vec<i32>) {
735 let mut fl = flash.clone();
736
737 mark_permanent_upgrade(&mut fl, &images.slot1);
738
739 let mut rng = rand::thread_rng();
740 let mut resets = vec![0i32; count];
741 let mut remaining_ops = total_ops;
742 for i in 0 .. count {
743 let ops = Range::new(1, remaining_ops / 2);
744 let reset_counter = ops.ind_sample(&mut rng);
745 c::set_flash_counter(reset_counter);
746 match c::boot_go(&mut fl, &areadesc) {
747 0 | -0x13579 => (),
748 x => panic!("Unknown return: {}", x),
749 }
750 remaining_ops -= reset_counter;
751 resets[i] = reset_counter;
752 }
753
754 c::set_flash_counter(0);
755 match c::boot_go(&mut fl, &areadesc) {
756 -0x13579 => panic!("Should not be have been interrupted!"),
757 0 => (),
758 x => panic!("Unknown return: {}", x),
759 }
760
761 (fl, resets)
762}
763
764/// Show the flash layout.
765#[allow(dead_code)]
766fn show_flash(flash: &Flash) {
767 println!("---- Flash configuration ----");
768 for sector in flash.sector_iter() {
769 println!(" {:3}: 0x{:08x}, 0x{:08x}",
770 sector.num, sector.base, sector.size);
771 }
772 println!("");
773}
774
775/// Install a "program" into the given image. This fakes the image header, or at least all of the
776/// fields used by the given code. Returns a copy of the image that was written.
777fn install_image(flash: &mut Flash, offset: usize, len: usize,
778 bad_sig: bool) -> Vec<u8> {
779 let offset0 = offset;
780
781 let mut tlv = make_tlv();
782
783 // Generate a boot header. Note that the size doesn't include the header.
784 let header = ImageHeader {
785 magic: 0x96f3b83d,
786 tlv_size: tlv.get_size(),
787 _pad1: 0,
788 hdr_size: 32,
789 key_id: 0,
790 _pad2: 0,
791 img_size: len as u32,
792 flags: tlv.get_flags(),
793 ver: ImageVersion {
794 major: (offset / (128 * 1024)) as u8,
795 minor: 0,
796 revision: 1,
797 build_num: offset as u32,
798 },
799 _pad3: 0,
800 };
801
802 let b_header = header.as_raw();
803 tlv.add_bytes(&b_header);
804 /*
805 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
806 mem::size_of::<ImageHeader>()) };
807 */
808 assert_eq!(b_header.len(), 32);
809 flash.write(offset, &b_header).unwrap();
810 let offset = offset + b_header.len();
811
812 // The core of the image itself is just pseudorandom data.
813 let mut buf = vec![0; len];
814 splat(&mut buf, offset);
815 tlv.add_bytes(&buf);
816
817 // Get and append the TLV itself.
818 if bad_sig {
819 let good_sig = &mut tlv.make_tlv();
820 buf.append(&mut vec![0; good_sig.len()]);
821 } else {
822 buf.append(&mut tlv.make_tlv());
823 }
824
825 // Pad the block to a flash alignment (8 bytes).
826 while buf.len() % 8 != 0 {
827 buf.push(0xFF);
828 }
829
830 flash.write(offset, &buf).unwrap();
831 let offset = offset + buf.len();
832
833 // Copy out the image so that we can verify that the image was installed correctly later.
834 let mut copy = vec![0u8; offset - offset0];
835 flash.read(offset0, &mut copy).unwrap();
836
837 copy
838}
839
840// The TLV in use depends on what kind of signature we are verifying.
841#[cfg(feature = "sig-rsa")]
842fn make_tlv() -> TlvGen {
843 TlvGen::new_rsa_pss()
844}
845
846#[cfg(not(feature = "sig-rsa"))]
847fn make_tlv() -> TlvGen {
848 TlvGen::new_hash_only()
849}
850
851/// Verify that given image is present in the flash at the given offset.
852fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
853 let mut copy = vec![0u8; buf.len()];
854 flash.read(offset, &mut copy).unwrap();
855
856 if buf != &copy[..] {
857 for i in 0 .. buf.len() {
858 if buf[i] != copy[i] {
859 info!("First failure at {:#x}", offset + i);
860 break;
861 }
862 }
863 false
864 } else {
865 true
866 }
867}
868
869#[cfg(feature = "overwrite-only")]
870#[allow(unused_variables)]
871// overwrite-only doesn't employ trailer management
872fn verify_trailer(flash: &Flash, offset: usize,
873 magic: Option<&[u8]>, image_ok: Option<u8>,
874 copy_done: Option<u8>) -> bool {
875 true
876}
877
878#[cfg(not(feature = "overwrite-only"))]
879fn verify_trailer(flash: &Flash, offset: usize,
880 magic: Option<&[u8]>, image_ok: Option<u8>,
881 copy_done: Option<u8>) -> bool {
882 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 2];
883 let mut failed = false;
884
885 flash.read(offset, &mut copy).unwrap();
886
887 failed |= match magic {
888 Some(v) => {
889 if &copy[16..] != v {
890 warn!("\"magic\" mismatch at {:#x}", offset);
891 true
892 } else {
893 false
894 }
895 },
896 None => false,
897 };
898
899 failed |= match image_ok {
900 Some(v) => {
901 if copy[8] != v {
902 warn!("\"image_ok\" mismatch at {:#x}", offset);
903 true
904 } else {
905 false
906 }
907 },
908 None => false,
909 };
910
911 failed |= match copy_done {
912 Some(v) => {
913 if copy[0] != v {
914 warn!("\"copy_done\" mismatch at {:#x}", offset);
915 true
916 } else {
917 false
918 }
919 },
920 None => false,
921 };
922
923 !failed
924}
925
926/// The image header
927#[repr(C)]
928pub struct ImageHeader {
929 magic: u32,
930 tlv_size: u16,
931 key_id: u8,
932 _pad1: u8,
933 hdr_size: u16,
934 _pad2: u16,
935 img_size: u32,
936 flags: u32,
937 ver: ImageVersion,
938 _pad3: u32,
939}
940
941impl AsRaw for ImageHeader {}
942
943#[repr(C)]
944pub struct ImageVersion {
945 major: u8,
946 minor: u8,
947 revision: u16,
948 build_num: u32,
949}
950
David Brownd5e632c2017-10-19 10:49:46 -0600951#[derive(Clone)]
David Brown2639e072017-10-11 11:18:44 -0600952struct SlotInfo {
953 base_off: usize,
954 trailer_off: usize,
955}
956
David Brownd5e632c2017-10-19 10:49:46 -0600957struct Images {
958 slot0: SlotInfo,
959 slot1: SlotInfo,
David Brown2639e072017-10-11 11:18:44 -0600960 primary: Vec<u8>,
961 upgrade: Vec<u8>,
962}
963
964const MAGIC_VALID: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3,
965 0x60, 0xd2, 0xef, 0x7f,
966 0x35, 0x52, 0x50, 0x0f,
967 0x2c, 0xb6, 0x79, 0x80]);
968const MAGIC_UNSET: Option<&[u8]> = Some(&[0xff; 16]);
969
970const COPY_DONE: Option<u8> = Some(1);
971const IMAGE_OK: Option<u8> = Some(1);
972const UNSET: Option<u8> = Some(0xff);
973
974/// Write out the magic so that the loader tries doing an upgrade.
975fn mark_upgrade(flash: &mut Flash, slot: &SlotInfo) {
976 let offset = slot.trailer_off + c::boot_max_align() * 2;
977 flash.write(offset, MAGIC_VALID.unwrap()).unwrap();
978}
979
980/// Writes the image_ok flag which, guess what, tells the bootloader
981/// the this image is ok (not a test, and no revert is to be performed).
982fn mark_permanent_upgrade(flash: &mut Flash, slot: &SlotInfo) {
983 let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
984 let align = c::get_sim_flash_align() as usize;
985 let off = slot.trailer_off + c::boot_max_align();
986 flash.write(off, &ok[..align]).unwrap();
987}
988
989// Drop some pseudo-random gibberish onto the data.
990fn splat(data: &mut [u8], seed: usize) {
991 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
992 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
993 rng.fill_bytes(data);
994}
995
996/// Return a read-only view into the raw bytes of this object
997trait AsRaw : Sized {
998 fn as_raw<'a>(&'a self) -> &'a [u8] {
999 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1000 mem::size_of::<Self>()) }
1001 }
1002}
1003
1004fn show_sizes() {
1005 // This isn't panic safe.
1006 let old_align = c::get_sim_flash_align();
1007 for min in &[1, 2, 4, 8] {
1008 c::set_sim_flash_align(*min);
1009 let msize = c::boot_trailer_sz();
1010 println!("{:2}: {} (0x{:x})", min, msize, msize);
1011 }
1012 c::set_sim_flash_align(old_align);
1013}