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