blob: 9e630ba48a42ca796baa4256ccbd8540215c9499 [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 Browndb9a3952017-11-06 13:16:15 -0700156/// A test run, intended to be run from "cargo test", so panics on failure.
157pub struct Run {
158 flash: SimFlash,
159 areadesc: AreaDesc,
160 slots: [SlotInfo; 2],
161 align: u8,
162}
163
164impl Run {
165 pub fn new(device: DeviceName, align: u8) -> Run {
166 let (flash, areadesc) = make_device(device, align);
167
168 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
169 let (slot1_base, slot1_len) = areadesc.find(FlashId::Image1);
170 let (scratch_base, _) = areadesc.find(FlashId::ImageScratch);
171
172 // The code assumes that the slots are consecutive.
173 assert_eq!(slot1_base, slot0_base + slot0_len);
174 assert_eq!(scratch_base, slot1_base + slot1_len);
175
176 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 2;
177
178 // Construct a primary image.
179 let slot0 = SlotInfo {
180 base_off: slot0_base as usize,
181 trailer_off: slot1_base - offset_from_end,
182 };
183
184 // And an upgrade image.
185 let slot1 = SlotInfo {
186 base_off: slot1_base as usize,
187 trailer_off: scratch_base - offset_from_end,
188 };
189
190 Run {
191 flash: flash,
192 areadesc: areadesc,
193 slots: [slot0, slot1],
194 align: align,
195 }
196 }
197
198 pub fn each_device<F>(f: F)
199 where F: Fn(&mut Run)
200 {
201 for &dev in ALL_DEVICES {
202 for &align in &[1, 2, 4, 8] {
203 let mut run = Run::new(dev, align);
204 f(&mut run);
205 }
206 }
207 }
208}
209
David Browndd2b1182017-11-02 15:39:21 -0600210pub struct RunStatus {
David Brown2639e072017-10-11 11:18:44 -0600211 failures: usize,
212 passes: usize,
213}
214
215impl RunStatus {
David Browndd2b1182017-11-02 15:39:21 -0600216 pub fn new() -> RunStatus {
David Brown2639e072017-10-11 11:18:44 -0600217 RunStatus {
218 failures: 0,
219 passes: 0,
220 }
221 }
222
David Browndd2b1182017-11-02 15:39:21 -0600223 pub fn run_single(&mut self, device: DeviceName, align: u8) {
David Brown2639e072017-10-11 11:18:44 -0600224 warn!("Running on device {} with alignment {}", device, align);
225
David Browndc9cba12017-11-06 13:31:42 -0700226 let run = Run::new(device, align);
David Brown2639e072017-10-11 11:18:44 -0600227
David Brown2639e072017-10-11 11:18:44 -0600228 let mut failed = false;
229
230 // Creates a badly signed image in slot1 to check that it is not
231 // upgraded to
David Browndb9a3952017-11-06 13:16:15 -0700232 let mut bad_flash = run.flash.clone();
David Browndc9cba12017-11-06 13:31:42 -0700233 let primary = install_image(&mut bad_flash, run.slots[0].base_off, 32784, false);
234 let upgrade = install_image(&mut bad_flash, run.slots[1].base_off, 41928, true);
David Brown2639e072017-10-11 11:18:44 -0600235 let bad_slot1_image = Images {
David Browndc9cba12017-11-06 13:31:42 -0700236 flash: bad_flash,
David Brown3f687dc2017-11-06 13:41:18 -0700237 areadesc: run.areadesc.clone(),
David Browndb9a3952017-11-06 13:16:15 -0700238 slot0: run.slots[0].clone(),
239 slot1: run.slots[1].clone(),
David Browndc9cba12017-11-06 13:31:42 -0700240 primary: primary,
241 upgrade: upgrade,
David Brown541860c2017-11-06 11:25:42 -0700242 align: align,
David Brown2639e072017-10-11 11:18:44 -0600243 };
244
David Brown5f7ec2b2017-11-06 13:54:02 -0700245 failed |= bad_slot1_image.run_signfail_upgrade();
David Brown2639e072017-10-11 11:18:44 -0600246
David Browndc9cba12017-11-06 13:31:42 -0700247 let mut flash = run.flash.clone();
248 let primary = install_image(&mut flash, run.slots[0].base_off, 32784, false);
249 let upgrade = install_image(&mut flash, run.slots[1].base_off, 41928, false);
250 let mut images = Images {
251 flash: flash,
David Brown3f687dc2017-11-06 13:41:18 -0700252 areadesc: run.areadesc.clone(),
David Browndb9a3952017-11-06 13:16:15 -0700253 slot0: run.slots[0].clone(),
254 slot1: run.slots[1].clone(),
David Browndc9cba12017-11-06 13:31:42 -0700255 primary: primary,
256 upgrade: upgrade,
David Brown541860c2017-11-06 11:25:42 -0700257 align: align,
David Brown2639e072017-10-11 11:18:44 -0600258 };
259
David Brown5f7ec2b2017-11-06 13:54:02 -0700260 failed |= images.run_norevert_newimage();
David Brown2639e072017-10-11 11:18:44 -0600261
David Browndc9cba12017-11-06 13:31:42 -0700262 mark_upgrade(&mut images.flash, &images.slot1);
David Brown2639e072017-10-11 11:18:44 -0600263
264 // upgrades without fails, counts number of flash operations
David Brown5f7ec2b2017-11-06 13:54:02 -0700265 let total_count = match images.run_basic_upgrade() {
David Brown2639e072017-10-11 11:18:44 -0600266 Ok(v) => v,
267 Err(_) => {
268 self.failures += 1;
269 return;
270 },
271 };
272
David Brown5f7ec2b2017-11-06 13:54:02 -0700273 failed |= images.run_basic_revert();
274 failed |= images.run_revert_with_fails(total_count);
275 failed |= images.run_perm_with_fails(total_count);
276 failed |= images.run_perm_with_random_fails(total_count, 5);
277 failed |= images.run_norevert();
David Brown2639e072017-10-11 11:18:44 -0600278
279 //show_flash(&flash);
280
281 if failed {
282 self.failures += 1;
283 } else {
284 self.passes += 1;
285 }
286 }
David Browndd2b1182017-11-02 15:39:21 -0600287
288 pub fn failures(&self) -> usize {
289 self.failures
290 }
David Brown2639e072017-10-11 11:18:44 -0600291}
292
David Browndecbd042017-10-19 10:43:17 -0600293/// Build the Flash and area descriptor for a given device.
294pub fn make_device(device: DeviceName, align: u8) -> (SimFlash, AreaDesc) {
295 match device {
296 DeviceName::Stm32f4 => {
297 // STM style flash. Large sectors, with a large scratch area.
298 let flash = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
299 64 * 1024,
300 128 * 1024, 128 * 1024, 128 * 1024],
301 align as usize);
302 let mut areadesc = AreaDesc::new(&flash);
303 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
304 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
305 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch);
306 (flash, areadesc)
307 }
308 DeviceName::K64f => {
309 // NXP style flash. Small sectors, one small sector for scratch.
310 let flash = SimFlash::new(vec![4096; 128], align as usize);
311
312 let mut areadesc = AreaDesc::new(&flash);
313 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
314 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
315 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch);
316 (flash, areadesc)
317 }
318 DeviceName::K64fBig => {
319 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
320 // uses small sectors, but we tell the bootloader they are large.
321 let flash = SimFlash::new(vec![4096; 128], align as usize);
322
323 let mut areadesc = AreaDesc::new(&flash);
324 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0);
325 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1);
326 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch);
327 (flash, areadesc)
328 }
329 DeviceName::Nrf52840 => {
330 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
331 // does not divide into the image size.
332 let flash = SimFlash::new(vec![4096; 128], align as usize);
333
334 let mut areadesc = AreaDesc::new(&flash);
335 areadesc.add_image(0x008000, 0x034000, FlashId::Image0);
336 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1);
337 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch);
338 (flash, areadesc)
339 }
340 }
341}
342
David Brown5f7ec2b2017-11-06 13:54:02 -0700343impl Images {
344 /// A simple upgrade without forced failures.
345 ///
346 /// Returns the number of flash operations which can later be used to
347 /// inject failures at chosen steps.
348 fn run_basic_upgrade(&self) -> Result<i32, ()> {
349 let (fl, total_count) = try_upgrade(&self.flash, &self, None);
350 info!("Total flash operation count={}", total_count);
David Brown2639e072017-10-11 11:18:44 -0600351
David Brown5f7ec2b2017-11-06 13:54:02 -0700352 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
353 warn!("Image mismatch after first boot");
354 Err(())
355 } else {
356 Ok(total_count)
David Brown2639e072017-10-11 11:18:44 -0600357 }
358 }
359
David Brown5f7ec2b2017-11-06 13:54:02 -0700360 #[cfg(feature = "overwrite-only")]
361 fn run_basic_revert(&self) -> bool {
362 false
363 }
David Brown2639e072017-10-11 11:18:44 -0600364
David Brown5f7ec2b2017-11-06 13:54:02 -0700365 #[cfg(not(feature = "overwrite-only"))]
366 fn run_basic_revert(&self) -> bool {
367 let mut fails = 0;
David Brown2639e072017-10-11 11:18:44 -0600368
David Brown5f7ec2b2017-11-06 13:54:02 -0700369 // FIXME: this test would also pass if no swap is ever performed???
370 if Caps::SwapUpgrade.present() {
371 for count in 2 .. 5 {
372 info!("Try revert: {}", count);
373 let fl = try_revert(&self.flash, &self.areadesc, count, self.align);
374 if !verify_image(&fl, self.slot0.base_off, &self.primary) {
375 error!("Revert failure on count {}", count);
376 fails += 1;
377 }
378 }
379 }
380
381 fails > 0
382 }
383
384 fn run_perm_with_fails(&self, total_flash_ops: i32) -> bool {
385 let mut fails = 0;
386
387 // Let's try an image halfway through.
388 for i in 1 .. total_flash_ops {
389 info!("Try interruption at {}", i);
390 let (fl, count) = try_upgrade(&self.flash, &self, Some(i));
391 info!("Second boot, count={}", count);
392 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
393 warn!("FAIL at step {} of {}", i, total_flash_ops);
394 fails += 1;
395 }
396
397 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
398 COPY_DONE) {
399 warn!("Mismatched trailer for Slot 0");
400 fails += 1;
401 }
402
403 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
404 UNSET) {
405 warn!("Mismatched trailer for Slot 1");
406 fails += 1;
407 }
408
409 if Caps::SwapUpgrade.present() {
410 if !verify_image(&fl, self.slot1.base_off, &self.primary) {
411 warn!("Slot 1 FAIL at step {} of {}", i, total_flash_ops);
412 fails += 1;
413 }
414 }
415 }
416
417 if fails > 0 {
418 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
419 fails as f32 * 100.0 / total_flash_ops as f32);
420 }
421
422 fails > 0
423 }
424
425 fn run_perm_with_random_fails(&self, total_flash_ops: i32,
426 total_fails: usize) -> bool {
427 let mut fails = 0;
428 let (fl, total_counts) = try_random_fails(&self.flash, &self,
429 total_flash_ops, total_fails);
430 info!("Random interruptions at reset points={:?}", total_counts);
431
432 let slot0_ok = verify_image(&fl, self.slot0.base_off, &self.upgrade);
433 let slot1_ok = if Caps::SwapUpgrade.present() {
434 verify_image(&fl, self.slot1.base_off, &self.primary)
435 } else {
436 true
437 };
438 if !slot0_ok || !slot1_ok {
439 error!("Image mismatch after random interrupts: slot0={} slot1={}",
440 if slot0_ok { "ok" } else { "fail" },
441 if slot1_ok { "ok" } else { "fail" });
442 fails += 1;
443 }
444 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
445 COPY_DONE) {
446 error!("Mismatched trailer for Slot 0");
447 fails += 1;
448 }
449 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
450 UNSET) {
451 error!("Mismatched trailer for Slot 1");
David Brown2639e072017-10-11 11:18:44 -0600452 fails += 1;
453 }
454
David Brown5f7ec2b2017-11-06 13:54:02 -0700455 if fails > 0 {
456 error!("Error testing perm upgrade with {} fails", total_fails);
457 }
458
459 fails > 0
460 }
461
462 #[cfg(feature = "overwrite-only")]
463 #[allow(unused_variables)]
464 fn run_revert_with_fails(&self, total_count: i32) -> bool {
465 false
466 }
467
468 #[cfg(not(feature = "overwrite-only"))]
469 fn run_revert_with_fails(&self, total_count: i32) -> bool {
470 let mut fails = 0;
471
472 if Caps::SwapUpgrade.present() {
473 for i in 1 .. (total_count - 1) {
474 info!("Try interruption at {}", i);
475 if try_revert_with_fail_at(&self.flash, &self, i) {
476 error!("Revert failed at interruption {}", i);
477 fails += 1;
478 }
479 }
480 }
481
482 fails > 0
483 }
484
485 #[cfg(feature = "overwrite-only")]
486 fn run_norevert(&self) -> bool {
487 false
488 }
489
490 #[cfg(not(feature = "overwrite-only"))]
491 fn run_norevert(&self) -> bool {
492 let mut fl = self.flash.clone();
493 let mut fails = 0;
494
495 info!("Try norevert");
496
497 // First do a normal upgrade...
498 if c::boot_go(&mut fl, &self.areadesc, None, self.align) != 0 {
499 warn!("Failed first boot");
500 fails += 1;
501 }
502
503 //FIXME: copy_done is written by boot_go, is it ok if no copy
504 // was ever done?
505
506 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
507 warn!("Slot 0 image verification FAIL");
508 fails += 1;
509 }
510 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, UNSET,
David Brown2639e072017-10-11 11:18:44 -0600511 COPY_DONE) {
512 warn!("Mismatched trailer for Slot 0");
513 fails += 1;
514 }
David Brown5f7ec2b2017-11-06 13:54:02 -0700515 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
David Brown2639e072017-10-11 11:18:44 -0600516 UNSET) {
517 warn!("Mismatched trailer for Slot 1");
518 fails += 1;
519 }
520
David Brown5f7ec2b2017-11-06 13:54:02 -0700521 // Marks image in slot0 as permanent, no revert should happen...
522 mark_permanent_upgrade(&mut fl, &self.slot0, self.align);
523
524 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
525 COPY_DONE) {
526 warn!("Mismatched trailer for Slot 0");
527 fails += 1;
David Brown2639e072017-10-11 11:18:44 -0600528 }
David Brown2639e072017-10-11 11:18:44 -0600529
David Brown5f7ec2b2017-11-06 13:54:02 -0700530 if c::boot_go(&mut fl, &self.areadesc, None, self.align) != 0 {
531 warn!("Failed second boot");
532 fails += 1;
David Brown2639e072017-10-11 11:18:44 -0600533 }
David Brown5f7ec2b2017-11-06 13:54:02 -0700534
535 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
536 COPY_DONE) {
537 warn!("Mismatched trailer for Slot 0");
538 fails += 1;
539 }
540 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
541 warn!("Failed image verification");
542 fails += 1;
543 }
544
545 if fails > 0 {
546 error!("Error running upgrade without revert");
547 }
548
549 fails > 0
David Brown2639e072017-10-11 11:18:44 -0600550 }
551
David Brown5f7ec2b2017-11-06 13:54:02 -0700552 // Tests a new image written to slot0 that already has magic and image_ok set
553 // while there is no image on slot1, so no revert should ever happen...
554 fn run_norevert_newimage(&self) -> bool {
555 let mut fl = self.flash.clone();
556 let mut fails = 0;
David Brown2639e072017-10-11 11:18:44 -0600557
David Brown5f7ec2b2017-11-06 13:54:02 -0700558 info!("Try non-revert on imgtool generated image");
David Brown2639e072017-10-11 11:18:44 -0600559
David Brown5f7ec2b2017-11-06 13:54:02 -0700560 mark_upgrade(&mut fl, &self.slot0);
David Brown2639e072017-10-11 11:18:44 -0600561
David Brown5f7ec2b2017-11-06 13:54:02 -0700562 // This simulates writing an image created by imgtool to Slot 0
563 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, UNSET, UNSET) {
564 warn!("Mismatched trailer for Slot 0");
565 fails += 1;
566 }
David Brown2639e072017-10-11 11:18:44 -0600567
David Brown5f7ec2b2017-11-06 13:54:02 -0700568 // Run the bootloader...
569 if c::boot_go(&mut fl, &self.areadesc, None, self.align) != 0 {
570 warn!("Failed first boot");
571 fails += 1;
572 }
573
574 // State should not have changed
575 if !verify_image(&fl, self.slot0.base_off, &self.primary) {
576 warn!("Failed image verification");
577 fails += 1;
578 }
579 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, UNSET,
580 UNSET) {
581 warn!("Mismatched trailer for Slot 0");
582 fails += 1;
583 }
584 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
585 UNSET) {
586 warn!("Mismatched trailer for Slot 1");
587 fails += 1;
588 }
589
590 if fails > 0 {
591 error!("Expected a non revert with new image");
592 }
593
594 fails > 0
David Brown2639e072017-10-11 11:18:44 -0600595 }
596
David Brown5f7ec2b2017-11-06 13:54:02 -0700597 // Tests a new image written to slot0 that already has magic and image_ok set
598 // while there is no image on slot1, so no revert should ever happen...
599 fn run_signfail_upgrade(&self) -> bool {
600 let mut fl = self.flash.clone();
601 let mut fails = 0;
David Brown2639e072017-10-11 11:18:44 -0600602
David Brown5f7ec2b2017-11-06 13:54:02 -0700603 info!("Try upgrade image with bad signature");
604
605 mark_upgrade(&mut fl, &self.slot0);
606 mark_permanent_upgrade(&mut fl, &self.slot0, self.align);
607 mark_upgrade(&mut fl, &self.slot1);
608
609 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
610 UNSET) {
611 warn!("Mismatched trailer for Slot 0");
612 fails += 1;
613 }
614
615 // Run the bootloader...
616 if c::boot_go(&mut fl, &self.areadesc, None, self.align) != 0 {
617 warn!("Failed first boot");
618 fails += 1;
619 }
620
621 // State should not have changed
622 if !verify_image(&fl, self.slot0.base_off, &self.primary) {
623 warn!("Failed image verification");
624 fails += 1;
625 }
626 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
627 UNSET) {
628 warn!("Mismatched trailer for Slot 0");
629 fails += 1;
630 }
631
632 if fails > 0 {
633 error!("Expected an upgrade failure when image has bad signature");
634 }
635
636 fails > 0
David Brown2639e072017-10-11 11:18:44 -0600637 }
David Brown2639e072017-10-11 11:18:44 -0600638}
639
640/// Test a boot, optionally stopping after 'n' flash options. Returns a count
641/// of the number of flash operations done total.
David Brown3f687dc2017-11-06 13:41:18 -0700642fn try_upgrade(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600643 stop: Option<i32>) -> (SimFlash, i32) {
644 // Clone the flash to have a new copy.
645 let mut fl = flash.clone();
646
David Brown541860c2017-11-06 11:25:42 -0700647 mark_permanent_upgrade(&mut fl, &images.slot1, images.align);
David Brown2639e072017-10-11 11:18:44 -0600648
David Brownee61c832017-11-06 11:13:25 -0700649 let mut counter = stop.unwrap_or(0);
650
David Brown3f687dc2017-11-06 13:41:18 -0700651 let (first_interrupted, count) = match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align) {
David Brown2639e072017-10-11 11:18:44 -0600652 -0x13579 => (true, stop.unwrap()),
David Brownee61c832017-11-06 11:13:25 -0700653 0 => (false, -counter),
David Brown2639e072017-10-11 11:18:44 -0600654 x => panic!("Unknown return: {}", x),
655 };
David Brown2639e072017-10-11 11:18:44 -0600656
David Brownee61c832017-11-06 11:13:25 -0700657 counter = 0;
David Brown2639e072017-10-11 11:18:44 -0600658 if first_interrupted {
659 // fl.dump();
David Brown3f687dc2017-11-06 13:41:18 -0700660 match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align) {
David Brown2639e072017-10-11 11:18:44 -0600661 -0x13579 => panic!("Shouldn't stop again"),
662 0 => (),
663 x => panic!("Unknown return: {}", x),
664 }
665 }
666
David Brownee61c832017-11-06 11:13:25 -0700667 (fl, count - counter)
David Brown2639e072017-10-11 11:18:44 -0600668}
669
670#[cfg(not(feature = "overwrite-only"))]
David Brown541860c2017-11-06 11:25:42 -0700671fn try_revert(flash: &SimFlash, areadesc: &AreaDesc, count: usize, align: u8) -> SimFlash {
David Brown2639e072017-10-11 11:18:44 -0600672 let mut fl = flash.clone();
David Brown2639e072017-10-11 11:18:44 -0600673
674 // fl.write_file("image0.bin").unwrap();
675 for i in 0 .. count {
676 info!("Running boot pass {}", i + 1);
David Brown541860c2017-11-06 11:25:42 -0700677 assert_eq!(c::boot_go(&mut fl, &areadesc, None, align), 0);
David Brown2639e072017-10-11 11:18:44 -0600678 }
679 fl
680}
681
682#[cfg(not(feature = "overwrite-only"))]
David Brown3f687dc2017-11-06 13:41:18 -0700683fn try_revert_with_fail_at(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600684 stop: i32) -> bool {
685 let mut fl = flash.clone();
686 let mut x: i32;
687 let mut fails = 0;
688
David Brownee61c832017-11-06 11:13:25 -0700689 let mut counter = stop;
David Brown3f687dc2017-11-06 13:41:18 -0700690 x = c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align);
David Brown2639e072017-10-11 11:18:44 -0600691 if x != -0x13579 {
692 warn!("Should have stopped at interruption point");
693 fails += 1;
694 }
695
696 if !verify_trailer(&fl, images.slot0.trailer_off, None, None, UNSET) {
697 warn!("copy_done should be unset");
698 fails += 1;
699 }
700
David Brown3f687dc2017-11-06 13:41:18 -0700701 x = c::boot_go(&mut fl, &images.areadesc, None, images.align);
David Brown2639e072017-10-11 11:18:44 -0600702 if x != 0 {
703 warn!("Should have finished upgrade");
704 fails += 1;
705 }
706
707 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
708 warn!("Image in slot 0 before revert is invalid at stop={}", stop);
709 fails += 1;
710 }
711 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
712 warn!("Image in slot 1 before revert is invalid at stop={}", stop);
713 fails += 1;
714 }
715 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
716 COPY_DONE) {
717 warn!("Mismatched trailer for Slot 0 before revert");
718 fails += 1;
719 }
720 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
721 UNSET) {
722 warn!("Mismatched trailer for Slot 1 before revert");
723 fails += 1;
724 }
725
726 // Do Revert
David Brown3f687dc2017-11-06 13:41:18 -0700727 x = c::boot_go(&mut fl, &images.areadesc, None, images.align);
David Brown2639e072017-10-11 11:18:44 -0600728 if x != 0 {
729 warn!("Should have finished a revert");
730 fails += 1;
731 }
732
733 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
734 warn!("Image in slot 0 after revert is invalid at stop={}", stop);
735 fails += 1;
736 }
737 if !verify_image(&fl, images.slot1.base_off, &images.upgrade) {
738 warn!("Image in slot 1 after revert is invalid at stop={}", stop);
739 fails += 1;
740 }
741 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
742 COPY_DONE) {
743 warn!("Mismatched trailer for Slot 1 after revert");
744 fails += 1;
745 }
746 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
747 UNSET) {
748 warn!("Mismatched trailer for Slot 1 after revert");
749 fails += 1;
750 }
751
752 fails > 0
753}
754
David Brown3f687dc2017-11-06 13:41:18 -0700755fn try_random_fails(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600756 total_ops: i32, count: usize) -> (SimFlash, Vec<i32>) {
757 let mut fl = flash.clone();
758
David Brown541860c2017-11-06 11:25:42 -0700759 mark_permanent_upgrade(&mut fl, &images.slot1, images.align);
David Brown2639e072017-10-11 11:18:44 -0600760
761 let mut rng = rand::thread_rng();
762 let mut resets = vec![0i32; count];
763 let mut remaining_ops = total_ops;
764 for i in 0 .. count {
765 let ops = Range::new(1, remaining_ops / 2);
766 let reset_counter = ops.ind_sample(&mut rng);
David Brownee61c832017-11-06 11:13:25 -0700767 let mut counter = reset_counter;
David Brown3f687dc2017-11-06 13:41:18 -0700768 match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align) {
David Brown2639e072017-10-11 11:18:44 -0600769 0 | -0x13579 => (),
770 x => panic!("Unknown return: {}", x),
771 }
772 remaining_ops -= reset_counter;
773 resets[i] = reset_counter;
774 }
775
David Brown3f687dc2017-11-06 13:41:18 -0700776 match c::boot_go(&mut fl, &images.areadesc, None, images.align) {
David Brown2639e072017-10-11 11:18:44 -0600777 -0x13579 => panic!("Should not be have been interrupted!"),
778 0 => (),
779 x => panic!("Unknown return: {}", x),
780 }
781
782 (fl, resets)
783}
784
785/// Show the flash layout.
786#[allow(dead_code)]
787fn show_flash(flash: &Flash) {
788 println!("---- Flash configuration ----");
789 for sector in flash.sector_iter() {
790 println!(" {:3}: 0x{:08x}, 0x{:08x}",
791 sector.num, sector.base, sector.size);
792 }
793 println!("");
794}
795
796/// Install a "program" into the given image. This fakes the image header, or at least all of the
797/// fields used by the given code. Returns a copy of the image that was written.
798fn install_image(flash: &mut Flash, offset: usize, len: usize,
799 bad_sig: bool) -> Vec<u8> {
800 let offset0 = offset;
801
802 let mut tlv = make_tlv();
803
804 // Generate a boot header. Note that the size doesn't include the header.
805 let header = ImageHeader {
806 magic: 0x96f3b83d,
807 tlv_size: tlv.get_size(),
808 _pad1: 0,
809 hdr_size: 32,
810 key_id: 0,
811 _pad2: 0,
812 img_size: len as u32,
813 flags: tlv.get_flags(),
814 ver: ImageVersion {
815 major: (offset / (128 * 1024)) as u8,
816 minor: 0,
817 revision: 1,
818 build_num: offset as u32,
819 },
820 _pad3: 0,
821 };
822
823 let b_header = header.as_raw();
824 tlv.add_bytes(&b_header);
825 /*
826 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
827 mem::size_of::<ImageHeader>()) };
828 */
829 assert_eq!(b_header.len(), 32);
830 flash.write(offset, &b_header).unwrap();
831 let offset = offset + b_header.len();
832
833 // The core of the image itself is just pseudorandom data.
834 let mut buf = vec![0; len];
835 splat(&mut buf, offset);
836 tlv.add_bytes(&buf);
837
838 // Get and append the TLV itself.
839 if bad_sig {
840 let good_sig = &mut tlv.make_tlv();
841 buf.append(&mut vec![0; good_sig.len()]);
842 } else {
843 buf.append(&mut tlv.make_tlv());
844 }
845
846 // Pad the block to a flash alignment (8 bytes).
847 while buf.len() % 8 != 0 {
848 buf.push(0xFF);
849 }
850
851 flash.write(offset, &buf).unwrap();
852 let offset = offset + buf.len();
853
854 // Copy out the image so that we can verify that the image was installed correctly later.
855 let mut copy = vec![0u8; offset - offset0];
856 flash.read(offset0, &mut copy).unwrap();
857
858 copy
859}
860
861// The TLV in use depends on what kind of signature we are verifying.
862#[cfg(feature = "sig-rsa")]
863fn make_tlv() -> TlvGen {
864 TlvGen::new_rsa_pss()
865}
866
867#[cfg(not(feature = "sig-rsa"))]
868fn make_tlv() -> TlvGen {
869 TlvGen::new_hash_only()
870}
871
872/// Verify that given image is present in the flash at the given offset.
873fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
874 let mut copy = vec![0u8; buf.len()];
875 flash.read(offset, &mut copy).unwrap();
876
877 if buf != &copy[..] {
878 for i in 0 .. buf.len() {
879 if buf[i] != copy[i] {
880 info!("First failure at {:#x}", offset + i);
881 break;
882 }
883 }
884 false
885 } else {
886 true
887 }
888}
889
890#[cfg(feature = "overwrite-only")]
891#[allow(unused_variables)]
892// overwrite-only doesn't employ trailer management
893fn verify_trailer(flash: &Flash, offset: usize,
894 magic: Option<&[u8]>, image_ok: Option<u8>,
895 copy_done: Option<u8>) -> bool {
896 true
897}
898
899#[cfg(not(feature = "overwrite-only"))]
900fn verify_trailer(flash: &Flash, offset: usize,
901 magic: Option<&[u8]>, image_ok: Option<u8>,
902 copy_done: Option<u8>) -> bool {
903 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 2];
904 let mut failed = false;
905
906 flash.read(offset, &mut copy).unwrap();
907
908 failed |= match magic {
909 Some(v) => {
910 if &copy[16..] != v {
911 warn!("\"magic\" mismatch at {:#x}", offset);
912 true
913 } else {
914 false
915 }
916 },
917 None => false,
918 };
919
920 failed |= match image_ok {
921 Some(v) => {
922 if copy[8] != v {
923 warn!("\"image_ok\" mismatch at {:#x}", offset);
924 true
925 } else {
926 false
927 }
928 },
929 None => false,
930 };
931
932 failed |= match copy_done {
933 Some(v) => {
934 if copy[0] != v {
935 warn!("\"copy_done\" mismatch at {:#x}", offset);
936 true
937 } else {
938 false
939 }
940 },
941 None => false,
942 };
943
944 !failed
945}
946
947/// The image header
948#[repr(C)]
949pub struct ImageHeader {
950 magic: u32,
951 tlv_size: u16,
952 key_id: u8,
953 _pad1: u8,
954 hdr_size: u16,
955 _pad2: u16,
956 img_size: u32,
957 flags: u32,
958 ver: ImageVersion,
959 _pad3: u32,
960}
961
962impl AsRaw for ImageHeader {}
963
964#[repr(C)]
965pub struct ImageVersion {
966 major: u8,
967 minor: u8,
968 revision: u16,
969 build_num: u32,
970}
971
David Brownd5e632c2017-10-19 10:49:46 -0600972#[derive(Clone)]
David Brown2639e072017-10-11 11:18:44 -0600973struct SlotInfo {
974 base_off: usize,
975 trailer_off: usize,
976}
977
David Brownd5e632c2017-10-19 10:49:46 -0600978struct Images {
David Browndc9cba12017-11-06 13:31:42 -0700979 flash: SimFlash,
David Brown3f687dc2017-11-06 13:41:18 -0700980 areadesc: AreaDesc,
David Brownd5e632c2017-10-19 10:49:46 -0600981 slot0: SlotInfo,
982 slot1: SlotInfo,
David Brown2639e072017-10-11 11:18:44 -0600983 primary: Vec<u8>,
984 upgrade: Vec<u8>,
David Brown541860c2017-11-06 11:25:42 -0700985 align: u8,
David Brown2639e072017-10-11 11:18:44 -0600986}
987
988const MAGIC_VALID: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3,
989 0x60, 0xd2, 0xef, 0x7f,
990 0x35, 0x52, 0x50, 0x0f,
991 0x2c, 0xb6, 0x79, 0x80]);
992const MAGIC_UNSET: Option<&[u8]> = Some(&[0xff; 16]);
993
994const COPY_DONE: Option<u8> = Some(1);
995const IMAGE_OK: Option<u8> = Some(1);
996const UNSET: Option<u8> = Some(0xff);
997
998/// Write out the magic so that the loader tries doing an upgrade.
999fn mark_upgrade(flash: &mut Flash, slot: &SlotInfo) {
1000 let offset = slot.trailer_off + c::boot_max_align() * 2;
1001 flash.write(offset, MAGIC_VALID.unwrap()).unwrap();
1002}
1003
1004/// Writes the image_ok flag which, guess what, tells the bootloader
1005/// the this image is ok (not a test, and no revert is to be performed).
David Brown541860c2017-11-06 11:25:42 -07001006fn mark_permanent_upgrade(flash: &mut Flash, slot: &SlotInfo, align: u8) {
David Brown2639e072017-10-11 11:18:44 -06001007 let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
David Brown2639e072017-10-11 11:18:44 -06001008 let off = slot.trailer_off + c::boot_max_align();
David Brown541860c2017-11-06 11:25:42 -07001009 flash.write(off, &ok[..align as usize]).unwrap();
David Brown2639e072017-10-11 11:18:44 -06001010}
1011
1012// Drop some pseudo-random gibberish onto the data.
1013fn splat(data: &mut [u8], seed: usize) {
1014 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
1015 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
1016 rng.fill_bytes(data);
1017}
1018
1019/// Return a read-only view into the raw bytes of this object
1020trait AsRaw : Sized {
1021 fn as_raw<'a>(&'a self) -> &'a [u8] {
1022 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1023 mem::size_of::<Self>()) }
1024 }
1025}
1026
1027fn show_sizes() {
1028 // This isn't panic safe.
David Brown2639e072017-10-11 11:18:44 -06001029 for min in &[1, 2, 4, 8] {
David Brown541860c2017-11-06 11:25:42 -07001030 let msize = c::boot_trailer_sz(*min);
David Brown2639e072017-10-11 11:18:44 -06001031 println!("{:2}: {} (0x{:x})", min, msize, msize);
1032 }
David Brown2639e072017-10-11 11:18:44 -06001033}