blob: b75b1d782f7edafe865bb49dbd72108ff5419cbf [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
David Brown2639e072017-10-11 11:18:44 -0600201 let mut failed = false;
202
203 // Creates a badly signed image in slot1 to check that it is not
204 // upgraded to
205 let mut bad_flash = flash.clone();
206 let bad_slot1_image = Images {
David Brownd5e632c2017-10-19 10:49:46 -0600207 slot0: slot0.clone(),
208 slot1: slot1.clone(),
David Brown2639e072017-10-11 11:18:44 -0600209 primary: install_image(&mut bad_flash, slot0_base, 32784, false),
210 upgrade: install_image(&mut bad_flash, slot1_base, 41928, true),
David Brown541860c2017-11-06 11:25:42 -0700211 align: align,
David Brown2639e072017-10-11 11:18:44 -0600212 };
213
214 failed |= run_signfail_upgrade(&bad_flash, &areadesc, &bad_slot1_image);
215
216 let images = Images {
David Brownd5e632c2017-10-19 10:49:46 -0600217 slot0: slot0.clone(),
218 slot1: slot1.clone(),
David Brown2639e072017-10-11 11:18:44 -0600219 primary: install_image(&mut flash, slot0_base, 32784, false),
220 upgrade: install_image(&mut flash, slot1_base, 41928, false),
David Brown541860c2017-11-06 11:25:42 -0700221 align: align,
David Brown2639e072017-10-11 11:18:44 -0600222 };
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);
David Brown541860c2017-11-06 11:25:42 -0700339 let fl = try_revert(&flash, &areadesc, count, images.align);
David Brown2639e072017-10-11 11:18:44 -0600340 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");
David Brown2639e072017-10-11 11:18:44 -0600467
468 // First do a normal upgrade...
David Brown541860c2017-11-06 11:25:42 -0700469 if c::boot_go(&mut fl, &areadesc, None, images.align) != 0 {
David Brown2639e072017-10-11 11:18:44 -0600470 warn!("Failed first boot");
471 fails += 1;
472 }
473
474 //FIXME: copy_done is written by boot_go, is it ok if no copy
475 // was ever done?
476
477 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
478 warn!("Slot 0 image verification FAIL");
479 fails += 1;
480 }
481 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
482 COPY_DONE) {
483 warn!("Mismatched trailer for Slot 0");
484 fails += 1;
485 }
486 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
487 UNSET) {
488 warn!("Mismatched trailer for Slot 1");
489 fails += 1;
490 }
491
492 // Marks image in slot0 as permanent, no revert should happen...
David Brown541860c2017-11-06 11:25:42 -0700493 mark_permanent_upgrade(&mut fl, &images.slot0, images.align);
David Brown2639e072017-10-11 11:18:44 -0600494
495 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
496 COPY_DONE) {
497 warn!("Mismatched trailer for Slot 0");
498 fails += 1;
499 }
500
David Brown541860c2017-11-06 11:25:42 -0700501 if c::boot_go(&mut fl, &areadesc, None, images.align) != 0 {
David Brown2639e072017-10-11 11:18:44 -0600502 warn!("Failed second boot");
503 fails += 1;
504 }
505
506 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
507 COPY_DONE) {
508 warn!("Mismatched trailer for Slot 0");
509 fails += 1;
510 }
511 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
512 warn!("Failed image verification");
513 fails += 1;
514 }
515
516 if fails > 0 {
517 error!("Error running upgrade without revert");
518 }
519
520 fails > 0
521}
522
523// Tests a new image written to slot0 that already has magic and image_ok set
524// while there is no image on slot1, so no revert should ever happen...
525fn run_norevert_newimage(flash: &SimFlash, areadesc: &AreaDesc,
526 images: &Images) -> bool {
527 let mut fl = flash.clone();
528 let mut fails = 0;
529
530 info!("Try non-revert on imgtool generated image");
David Brown2639e072017-10-11 11:18:44 -0600531
532 mark_upgrade(&mut fl, &images.slot0);
533
534 // This simulates writing an image created by imgtool to Slot 0
535 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET, UNSET) {
536 warn!("Mismatched trailer for Slot 0");
537 fails += 1;
538 }
539
540 // Run the bootloader...
David Brown541860c2017-11-06 11:25:42 -0700541 if c::boot_go(&mut fl, &areadesc, None, images.align) != 0 {
David Brown2639e072017-10-11 11:18:44 -0600542 warn!("Failed first boot");
543 fails += 1;
544 }
545
546 // State should not have changed
547 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
548 warn!("Failed image verification");
549 fails += 1;
550 }
551 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
552 UNSET) {
553 warn!("Mismatched trailer for Slot 0");
554 fails += 1;
555 }
556 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
557 UNSET) {
558 warn!("Mismatched trailer for Slot 1");
559 fails += 1;
560 }
561
562 if fails > 0 {
563 error!("Expected a non revert with new image");
564 }
565
566 fails > 0
567}
568
569// Tests a new image written to slot0 that already has magic and image_ok set
570// while there is no image on slot1, so no revert should ever happen...
571fn run_signfail_upgrade(flash: &SimFlash, areadesc: &AreaDesc,
572 images: &Images) -> bool {
573 let mut fl = flash.clone();
574 let mut fails = 0;
575
576 info!("Try upgrade image with bad signature");
David Brown2639e072017-10-11 11:18:44 -0600577
578 mark_upgrade(&mut fl, &images.slot0);
David Brown541860c2017-11-06 11:25:42 -0700579 mark_permanent_upgrade(&mut fl, &images.slot0, images.align);
David Brown2639e072017-10-11 11:18:44 -0600580 mark_upgrade(&mut fl, &images.slot1);
581
582 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
583 UNSET) {
584 warn!("Mismatched trailer for Slot 0");
585 fails += 1;
586 }
587
588 // Run the bootloader...
David Brown541860c2017-11-06 11:25:42 -0700589 if c::boot_go(&mut fl, &areadesc, None, images.align) != 0 {
David Brown2639e072017-10-11 11:18:44 -0600590 warn!("Failed first boot");
591 fails += 1;
592 }
593
594 // State should not have changed
595 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
596 warn!("Failed image verification");
597 fails += 1;
598 }
599 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
600 UNSET) {
601 warn!("Mismatched trailer for Slot 0");
602 fails += 1;
603 }
604
605 if fails > 0 {
606 error!("Expected an upgrade failure when image has bad signature");
607 }
608
609 fails > 0
610}
611
612/// Test a boot, optionally stopping after 'n' flash options. Returns a count
613/// of the number of flash operations done total.
614fn try_upgrade(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
615 stop: Option<i32>) -> (SimFlash, i32) {
616 // Clone the flash to have a new copy.
617 let mut fl = flash.clone();
618
David Brown541860c2017-11-06 11:25:42 -0700619 mark_permanent_upgrade(&mut fl, &images.slot1, images.align);
David Brown2639e072017-10-11 11:18:44 -0600620
David Brownee61c832017-11-06 11:13:25 -0700621 let mut counter = stop.unwrap_or(0);
622
David Brown541860c2017-11-06 11:25:42 -0700623 let (first_interrupted, count) = match c::boot_go(&mut fl, &areadesc, Some(&mut counter), images.align) {
David Brown2639e072017-10-11 11:18:44 -0600624 -0x13579 => (true, stop.unwrap()),
David Brownee61c832017-11-06 11:13:25 -0700625 0 => (false, -counter),
David Brown2639e072017-10-11 11:18:44 -0600626 x => panic!("Unknown return: {}", x),
627 };
David Brown2639e072017-10-11 11:18:44 -0600628
David Brownee61c832017-11-06 11:13:25 -0700629 counter = 0;
David Brown2639e072017-10-11 11:18:44 -0600630 if first_interrupted {
631 // fl.dump();
David Brown541860c2017-11-06 11:25:42 -0700632 match c::boot_go(&mut fl, &areadesc, Some(&mut counter), images.align) {
David Brown2639e072017-10-11 11:18:44 -0600633 -0x13579 => panic!("Shouldn't stop again"),
634 0 => (),
635 x => panic!("Unknown return: {}", x),
636 }
637 }
638
David Brownee61c832017-11-06 11:13:25 -0700639 (fl, count - counter)
David Brown2639e072017-10-11 11:18:44 -0600640}
641
642#[cfg(not(feature = "overwrite-only"))]
David Brown541860c2017-11-06 11:25:42 -0700643fn try_revert(flash: &SimFlash, areadesc: &AreaDesc, count: usize, align: u8) -> SimFlash {
David Brown2639e072017-10-11 11:18:44 -0600644 let mut fl = flash.clone();
David Brown2639e072017-10-11 11:18:44 -0600645
646 // fl.write_file("image0.bin").unwrap();
647 for i in 0 .. count {
648 info!("Running boot pass {}", i + 1);
David Brown541860c2017-11-06 11:25:42 -0700649 assert_eq!(c::boot_go(&mut fl, &areadesc, None, align), 0);
David Brown2639e072017-10-11 11:18:44 -0600650 }
651 fl
652}
653
654#[cfg(not(feature = "overwrite-only"))]
655fn try_revert_with_fail_at(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
656 stop: i32) -> bool {
657 let mut fl = flash.clone();
658 let mut x: i32;
659 let mut fails = 0;
660
David Brownee61c832017-11-06 11:13:25 -0700661 let mut counter = stop;
David Brown541860c2017-11-06 11:25:42 -0700662 x = c::boot_go(&mut fl, &areadesc, Some(&mut counter), images.align);
David Brown2639e072017-10-11 11:18:44 -0600663 if x != -0x13579 {
664 warn!("Should have stopped at interruption point");
665 fails += 1;
666 }
667
668 if !verify_trailer(&fl, images.slot0.trailer_off, None, None, UNSET) {
669 warn!("copy_done should be unset");
670 fails += 1;
671 }
672
David Brown541860c2017-11-06 11:25:42 -0700673 x = c::boot_go(&mut fl, &areadesc, None, images.align);
David Brown2639e072017-10-11 11:18:44 -0600674 if x != 0 {
675 warn!("Should have finished upgrade");
676 fails += 1;
677 }
678
679 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
680 warn!("Image in slot 0 before revert is invalid at stop={}", stop);
681 fails += 1;
682 }
683 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
684 warn!("Image in slot 1 before revert is invalid at stop={}", stop);
685 fails += 1;
686 }
687 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
688 COPY_DONE) {
689 warn!("Mismatched trailer for Slot 0 before revert");
690 fails += 1;
691 }
692 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
693 UNSET) {
694 warn!("Mismatched trailer for Slot 1 before revert");
695 fails += 1;
696 }
697
698 // Do Revert
David Brown541860c2017-11-06 11:25:42 -0700699 x = c::boot_go(&mut fl, &areadesc, None, images.align);
David Brown2639e072017-10-11 11:18:44 -0600700 if x != 0 {
701 warn!("Should have finished a revert");
702 fails += 1;
703 }
704
705 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
706 warn!("Image in slot 0 after revert is invalid at stop={}", stop);
707 fails += 1;
708 }
709 if !verify_image(&fl, images.slot1.base_off, &images.upgrade) {
710 warn!("Image in slot 1 after revert is invalid at stop={}", stop);
711 fails += 1;
712 }
713 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
714 COPY_DONE) {
715 warn!("Mismatched trailer for Slot 1 after revert");
716 fails += 1;
717 }
718 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
719 UNSET) {
720 warn!("Mismatched trailer for Slot 1 after revert");
721 fails += 1;
722 }
723
724 fails > 0
725}
726
727fn try_random_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
728 total_ops: i32, count: usize) -> (SimFlash, Vec<i32>) {
729 let mut fl = flash.clone();
730
David Brown541860c2017-11-06 11:25:42 -0700731 mark_permanent_upgrade(&mut fl, &images.slot1, images.align);
David Brown2639e072017-10-11 11:18:44 -0600732
733 let mut rng = rand::thread_rng();
734 let mut resets = vec![0i32; count];
735 let mut remaining_ops = total_ops;
736 for i in 0 .. count {
737 let ops = Range::new(1, remaining_ops / 2);
738 let reset_counter = ops.ind_sample(&mut rng);
David Brownee61c832017-11-06 11:13:25 -0700739 let mut counter = reset_counter;
David Brown541860c2017-11-06 11:25:42 -0700740 match c::boot_go(&mut fl, &areadesc, Some(&mut counter), images.align) {
David Brown2639e072017-10-11 11:18:44 -0600741 0 | -0x13579 => (),
742 x => panic!("Unknown return: {}", x),
743 }
744 remaining_ops -= reset_counter;
745 resets[i] = reset_counter;
746 }
747
David Brown541860c2017-11-06 11:25:42 -0700748 match c::boot_go(&mut fl, &areadesc, None, images.align) {
David Brown2639e072017-10-11 11:18:44 -0600749 -0x13579 => panic!("Should not be have been interrupted!"),
750 0 => (),
751 x => panic!("Unknown return: {}", x),
752 }
753
754 (fl, resets)
755}
756
757/// Show the flash layout.
758#[allow(dead_code)]
759fn show_flash(flash: &Flash) {
760 println!("---- Flash configuration ----");
761 for sector in flash.sector_iter() {
762 println!(" {:3}: 0x{:08x}, 0x{:08x}",
763 sector.num, sector.base, sector.size);
764 }
765 println!("");
766}
767
768/// Install a "program" into the given image. This fakes the image header, or at least all of the
769/// fields used by the given code. Returns a copy of the image that was written.
770fn install_image(flash: &mut Flash, offset: usize, len: usize,
771 bad_sig: bool) -> Vec<u8> {
772 let offset0 = offset;
773
774 let mut tlv = make_tlv();
775
776 // Generate a boot header. Note that the size doesn't include the header.
777 let header = ImageHeader {
778 magic: 0x96f3b83d,
779 tlv_size: tlv.get_size(),
780 _pad1: 0,
781 hdr_size: 32,
782 key_id: 0,
783 _pad2: 0,
784 img_size: len as u32,
785 flags: tlv.get_flags(),
786 ver: ImageVersion {
787 major: (offset / (128 * 1024)) as u8,
788 minor: 0,
789 revision: 1,
790 build_num: offset as u32,
791 },
792 _pad3: 0,
793 };
794
795 let b_header = header.as_raw();
796 tlv.add_bytes(&b_header);
797 /*
798 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
799 mem::size_of::<ImageHeader>()) };
800 */
801 assert_eq!(b_header.len(), 32);
802 flash.write(offset, &b_header).unwrap();
803 let offset = offset + b_header.len();
804
805 // The core of the image itself is just pseudorandom data.
806 let mut buf = vec![0; len];
807 splat(&mut buf, offset);
808 tlv.add_bytes(&buf);
809
810 // Get and append the TLV itself.
811 if bad_sig {
812 let good_sig = &mut tlv.make_tlv();
813 buf.append(&mut vec![0; good_sig.len()]);
814 } else {
815 buf.append(&mut tlv.make_tlv());
816 }
817
818 // Pad the block to a flash alignment (8 bytes).
819 while buf.len() % 8 != 0 {
820 buf.push(0xFF);
821 }
822
823 flash.write(offset, &buf).unwrap();
824 let offset = offset + buf.len();
825
826 // Copy out the image so that we can verify that the image was installed correctly later.
827 let mut copy = vec![0u8; offset - offset0];
828 flash.read(offset0, &mut copy).unwrap();
829
830 copy
831}
832
833// The TLV in use depends on what kind of signature we are verifying.
834#[cfg(feature = "sig-rsa")]
835fn make_tlv() -> TlvGen {
836 TlvGen::new_rsa_pss()
837}
838
839#[cfg(not(feature = "sig-rsa"))]
840fn make_tlv() -> TlvGen {
841 TlvGen::new_hash_only()
842}
843
844/// Verify that given image is present in the flash at the given offset.
845fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
846 let mut copy = vec![0u8; buf.len()];
847 flash.read(offset, &mut copy).unwrap();
848
849 if buf != &copy[..] {
850 for i in 0 .. buf.len() {
851 if buf[i] != copy[i] {
852 info!("First failure at {:#x}", offset + i);
853 break;
854 }
855 }
856 false
857 } else {
858 true
859 }
860}
861
862#[cfg(feature = "overwrite-only")]
863#[allow(unused_variables)]
864// overwrite-only doesn't employ trailer management
865fn verify_trailer(flash: &Flash, offset: usize,
866 magic: Option<&[u8]>, image_ok: Option<u8>,
867 copy_done: Option<u8>) -> bool {
868 true
869}
870
871#[cfg(not(feature = "overwrite-only"))]
872fn verify_trailer(flash: &Flash, offset: usize,
873 magic: Option<&[u8]>, image_ok: Option<u8>,
874 copy_done: Option<u8>) -> bool {
875 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 2];
876 let mut failed = false;
877
878 flash.read(offset, &mut copy).unwrap();
879
880 failed |= match magic {
881 Some(v) => {
882 if &copy[16..] != v {
883 warn!("\"magic\" mismatch at {:#x}", offset);
884 true
885 } else {
886 false
887 }
888 },
889 None => false,
890 };
891
892 failed |= match image_ok {
893 Some(v) => {
894 if copy[8] != v {
895 warn!("\"image_ok\" mismatch at {:#x}", offset);
896 true
897 } else {
898 false
899 }
900 },
901 None => false,
902 };
903
904 failed |= match copy_done {
905 Some(v) => {
906 if copy[0] != v {
907 warn!("\"copy_done\" mismatch at {:#x}", offset);
908 true
909 } else {
910 false
911 }
912 },
913 None => false,
914 };
915
916 !failed
917}
918
919/// The image header
920#[repr(C)]
921pub struct ImageHeader {
922 magic: u32,
923 tlv_size: u16,
924 key_id: u8,
925 _pad1: u8,
926 hdr_size: u16,
927 _pad2: u16,
928 img_size: u32,
929 flags: u32,
930 ver: ImageVersion,
931 _pad3: u32,
932}
933
934impl AsRaw for ImageHeader {}
935
936#[repr(C)]
937pub struct ImageVersion {
938 major: u8,
939 minor: u8,
940 revision: u16,
941 build_num: u32,
942}
943
David Brownd5e632c2017-10-19 10:49:46 -0600944#[derive(Clone)]
David Brown2639e072017-10-11 11:18:44 -0600945struct SlotInfo {
946 base_off: usize,
947 trailer_off: usize,
948}
949
David Brownd5e632c2017-10-19 10:49:46 -0600950struct Images {
951 slot0: SlotInfo,
952 slot1: SlotInfo,
David Brown2639e072017-10-11 11:18:44 -0600953 primary: Vec<u8>,
954 upgrade: Vec<u8>,
David Brown541860c2017-11-06 11:25:42 -0700955 align: u8,
David Brown2639e072017-10-11 11:18:44 -0600956}
957
958const MAGIC_VALID: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3,
959 0x60, 0xd2, 0xef, 0x7f,
960 0x35, 0x52, 0x50, 0x0f,
961 0x2c, 0xb6, 0x79, 0x80]);
962const MAGIC_UNSET: Option<&[u8]> = Some(&[0xff; 16]);
963
964const COPY_DONE: Option<u8> = Some(1);
965const IMAGE_OK: Option<u8> = Some(1);
966const UNSET: Option<u8> = Some(0xff);
967
968/// Write out the magic so that the loader tries doing an upgrade.
969fn mark_upgrade(flash: &mut Flash, slot: &SlotInfo) {
970 let offset = slot.trailer_off + c::boot_max_align() * 2;
971 flash.write(offset, MAGIC_VALID.unwrap()).unwrap();
972}
973
974/// Writes the image_ok flag which, guess what, tells the bootloader
975/// the this image is ok (not a test, and no revert is to be performed).
David Brown541860c2017-11-06 11:25:42 -0700976fn mark_permanent_upgrade(flash: &mut Flash, slot: &SlotInfo, align: u8) {
David Brown2639e072017-10-11 11:18:44 -0600977 let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
David Brown2639e072017-10-11 11:18:44 -0600978 let off = slot.trailer_off + c::boot_max_align();
David Brown541860c2017-11-06 11:25:42 -0700979 flash.write(off, &ok[..align as usize]).unwrap();
David Brown2639e072017-10-11 11:18:44 -0600980}
981
982// Drop some pseudo-random gibberish onto the data.
983fn splat(data: &mut [u8], seed: usize) {
984 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
985 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
986 rng.fill_bytes(data);
987}
988
989/// Return a read-only view into the raw bytes of this object
990trait AsRaw : Sized {
991 fn as_raw<'a>(&'a self) -> &'a [u8] {
992 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
993 mem::size_of::<Self>()) }
994 }
995}
996
997fn show_sizes() {
998 // This isn't panic safe.
David Brown2639e072017-10-11 11:18:44 -0600999 for min in &[1, 2, 4, 8] {
David Brown541860c2017-11-06 11:25:42 -07001000 let msize = c::boot_trailer_sz(*min);
David Brown2639e072017-10-11 11:18:44 -06001001 println!("{:2}: {} (0x{:x})", min, msize, msize);
1002 }
David Brown2639e072017-10-11 11:18:44 -06001003}