blob: 03bb2cb5c2c43cd6d00239f030c2b4d90f4fe810 [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 }
David Brownf48b9502017-11-06 14:00:26 -0700208
209 /// Construct an `Images` that doesn't expect an upgrade to happen.
210 pub fn make_no_upgrade_image(&self) -> Images {
211 let mut flash = self.flash.clone();
212 let primary = install_image(&mut flash, self.slots[0].base_off, 32784, false);
213 let upgrade = install_image(&mut flash, self.slots[1].base_off, 41928, false);
214 Images {
215 flash: flash,
216 areadesc: self.areadesc.clone(),
217 slot0: self.slots[0].clone(),
218 slot1: self.slots[1].clone(),
219 primary: primary,
220 upgrade: upgrade,
David Brownc49811e2017-11-06 14:20:45 -0700221 total_count: None,
David Brownf48b9502017-11-06 14:00:26 -0700222 align: self.align,
223 }
224 }
225
226 /// Construct an `Images` for normal testing.
227 pub fn make_image(&self) -> Images {
228 let mut images = self.make_no_upgrade_image();
229 mark_upgrade(&mut images.flash, &images.slot1);
David Brownc49811e2017-11-06 14:20:45 -0700230
231 // upgrades without fails, counts number of flash operations
232 let total_count = match images.run_basic_upgrade() {
233 Ok(v) => v,
234 Err(_) => {
235 panic!("Unable to perform basic upgrade");
236 },
237 };
238
239 images.total_count = Some(total_count);
David Brownf48b9502017-11-06 14:00:26 -0700240 images
241 }
242
243 pub fn make_bad_slot1_image(&self) -> Images {
244 let mut bad_flash = self.flash.clone();
245 let primary = install_image(&mut bad_flash, self.slots[0].base_off, 32784, false);
246 let upgrade = install_image(&mut bad_flash, self.slots[1].base_off, 41928, true);
247 Images {
248 flash: bad_flash,
249 areadesc: self.areadesc.clone(),
250 slot0: self.slots[0].clone(),
251 slot1: self.slots[1].clone(),
252 primary: primary,
253 upgrade: upgrade,
David Brownc49811e2017-11-06 14:20:45 -0700254 total_count: None,
David Brownf48b9502017-11-06 14:00:26 -0700255 align: self.align,
256 }
257 }
David Brownc49811e2017-11-06 14:20:45 -0700258
David Browndb9a3952017-11-06 13:16:15 -0700259}
260
David Browndd2b1182017-11-02 15:39:21 -0600261pub struct RunStatus {
David Brown2639e072017-10-11 11:18:44 -0600262 failures: usize,
263 passes: usize,
264}
265
266impl RunStatus {
David Browndd2b1182017-11-02 15:39:21 -0600267 pub fn new() -> RunStatus {
David Brown2639e072017-10-11 11:18:44 -0600268 RunStatus {
269 failures: 0,
270 passes: 0,
271 }
272 }
273
David Browndd2b1182017-11-02 15:39:21 -0600274 pub fn run_single(&mut self, device: DeviceName, align: u8) {
David Brown2639e072017-10-11 11:18:44 -0600275 warn!("Running on device {} with alignment {}", device, align);
276
David Browndc9cba12017-11-06 13:31:42 -0700277 let run = Run::new(device, align);
David Brown2639e072017-10-11 11:18:44 -0600278
David Brown2639e072017-10-11 11:18:44 -0600279 let mut failed = false;
280
281 // Creates a badly signed image in slot1 to check that it is not
282 // upgraded to
David Brownf48b9502017-11-06 14:00:26 -0700283 let bad_slot1_image = run.make_bad_slot1_image();
David Brown2639e072017-10-11 11:18:44 -0600284
David Brown5f7ec2b2017-11-06 13:54:02 -0700285 failed |= bad_slot1_image.run_signfail_upgrade();
David Brown2639e072017-10-11 11:18:44 -0600286
David Brownf48b9502017-11-06 14:00:26 -0700287 let images = run.make_no_upgrade_image();
David Brown5f7ec2b2017-11-06 13:54:02 -0700288 failed |= images.run_norevert_newimage();
David Brown2639e072017-10-11 11:18:44 -0600289
David Brownf48b9502017-11-06 14:00:26 -0700290 let images = run.make_image();
David Brown2639e072017-10-11 11:18:44 -0600291
David Brown5f7ec2b2017-11-06 13:54:02 -0700292 failed |= images.run_basic_revert();
David Brownc49811e2017-11-06 14:20:45 -0700293 failed |= images.run_revert_with_fails();
294 failed |= images.run_perm_with_fails();
295 failed |= images.run_perm_with_random_fails(5);
David Brown5f7ec2b2017-11-06 13:54:02 -0700296 failed |= images.run_norevert();
David Brown2639e072017-10-11 11:18:44 -0600297
298 //show_flash(&flash);
299
300 if failed {
301 self.failures += 1;
302 } else {
303 self.passes += 1;
304 }
305 }
David Browndd2b1182017-11-02 15:39:21 -0600306
307 pub fn failures(&self) -> usize {
308 self.failures
309 }
David Brown2639e072017-10-11 11:18:44 -0600310}
311
David Browndecbd042017-10-19 10:43:17 -0600312/// Build the Flash and area descriptor for a given device.
313pub fn make_device(device: DeviceName, align: u8) -> (SimFlash, AreaDesc) {
314 match device {
315 DeviceName::Stm32f4 => {
316 // STM style flash. Large sectors, with a large scratch area.
317 let flash = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
318 64 * 1024,
319 128 * 1024, 128 * 1024, 128 * 1024],
320 align as usize);
321 let mut areadesc = AreaDesc::new(&flash);
322 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
323 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
324 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch);
325 (flash, areadesc)
326 }
327 DeviceName::K64f => {
328 // NXP style flash. Small sectors, one small sector for scratch.
329 let flash = SimFlash::new(vec![4096; 128], align as usize);
330
331 let mut areadesc = AreaDesc::new(&flash);
332 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
333 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
334 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch);
335 (flash, areadesc)
336 }
337 DeviceName::K64fBig => {
338 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
339 // uses small sectors, but we tell the bootloader they are large.
340 let flash = SimFlash::new(vec![4096; 128], align as usize);
341
342 let mut areadesc = AreaDesc::new(&flash);
343 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0);
344 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1);
345 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch);
346 (flash, areadesc)
347 }
348 DeviceName::Nrf52840 => {
349 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
350 // does not divide into the image size.
351 let flash = SimFlash::new(vec![4096; 128], align as usize);
352
353 let mut areadesc = AreaDesc::new(&flash);
354 areadesc.add_image(0x008000, 0x034000, FlashId::Image0);
355 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1);
356 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch);
357 (flash, areadesc)
358 }
359 }
360}
361
David Brown5f7ec2b2017-11-06 13:54:02 -0700362impl Images {
363 /// A simple upgrade without forced failures.
364 ///
365 /// Returns the number of flash operations which can later be used to
366 /// inject failures at chosen steps.
David Brownc49811e2017-11-06 14:20:45 -0700367 pub fn run_basic_upgrade(&self) -> Result<i32, ()> {
David Brown5f7ec2b2017-11-06 13:54:02 -0700368 let (fl, total_count) = try_upgrade(&self.flash, &self, None);
369 info!("Total flash operation count={}", total_count);
David Brown2639e072017-10-11 11:18:44 -0600370
David Brown5f7ec2b2017-11-06 13:54:02 -0700371 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
372 warn!("Image mismatch after first boot");
373 Err(())
374 } else {
375 Ok(total_count)
David Brown2639e072017-10-11 11:18:44 -0600376 }
377 }
378
David Brown5f7ec2b2017-11-06 13:54:02 -0700379 #[cfg(feature = "overwrite-only")]
380 fn run_basic_revert(&self) -> bool {
381 false
382 }
David Brown2639e072017-10-11 11:18:44 -0600383
David Brown5f7ec2b2017-11-06 13:54:02 -0700384 #[cfg(not(feature = "overwrite-only"))]
385 fn run_basic_revert(&self) -> bool {
386 let mut fails = 0;
David Brown2639e072017-10-11 11:18:44 -0600387
David Brown5f7ec2b2017-11-06 13:54:02 -0700388 // FIXME: this test would also pass if no swap is ever performed???
389 if Caps::SwapUpgrade.present() {
390 for count in 2 .. 5 {
391 info!("Try revert: {}", count);
392 let fl = try_revert(&self.flash, &self.areadesc, count, self.align);
393 if !verify_image(&fl, self.slot0.base_off, &self.primary) {
394 error!("Revert failure on count {}", count);
395 fails += 1;
396 }
397 }
398 }
399
400 fails > 0
401 }
402
David Brownc49811e2017-11-06 14:20:45 -0700403 fn run_perm_with_fails(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700404 let mut fails = 0;
David Brownc49811e2017-11-06 14:20:45 -0700405 let total_flash_ops = self.total_count.unwrap();
David Brown5f7ec2b2017-11-06 13:54:02 -0700406
407 // Let's try an image halfway through.
408 for i in 1 .. total_flash_ops {
409 info!("Try interruption at {}", i);
410 let (fl, count) = try_upgrade(&self.flash, &self, Some(i));
411 info!("Second boot, count={}", count);
412 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
413 warn!("FAIL at step {} of {}", i, total_flash_ops);
414 fails += 1;
415 }
416
417 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
418 COPY_DONE) {
419 warn!("Mismatched trailer for Slot 0");
420 fails += 1;
421 }
422
423 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
424 UNSET) {
425 warn!("Mismatched trailer for Slot 1");
426 fails += 1;
427 }
428
429 if Caps::SwapUpgrade.present() {
430 if !verify_image(&fl, self.slot1.base_off, &self.primary) {
431 warn!("Slot 1 FAIL at step {} of {}", i, total_flash_ops);
432 fails += 1;
433 }
434 }
435 }
436
437 if fails > 0 {
438 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
439 fails as f32 * 100.0 / total_flash_ops as f32);
440 }
441
442 fails > 0
443 }
444
David Brownc49811e2017-11-06 14:20:45 -0700445 fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700446 let mut fails = 0;
David Brownc49811e2017-11-06 14:20:45 -0700447 let total_flash_ops = self.total_count.unwrap();
David Brown5f7ec2b2017-11-06 13:54:02 -0700448 let (fl, total_counts) = try_random_fails(&self.flash, &self,
449 total_flash_ops, total_fails);
450 info!("Random interruptions at reset points={:?}", total_counts);
451
452 let slot0_ok = verify_image(&fl, self.slot0.base_off, &self.upgrade);
453 let slot1_ok = if Caps::SwapUpgrade.present() {
454 verify_image(&fl, self.slot1.base_off, &self.primary)
455 } else {
456 true
457 };
458 if !slot0_ok || !slot1_ok {
459 error!("Image mismatch after random interrupts: slot0={} slot1={}",
460 if slot0_ok { "ok" } else { "fail" },
461 if slot1_ok { "ok" } else { "fail" });
462 fails += 1;
463 }
464 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
465 COPY_DONE) {
466 error!("Mismatched trailer for Slot 0");
467 fails += 1;
468 }
469 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
470 UNSET) {
471 error!("Mismatched trailer for Slot 1");
David Brown2639e072017-10-11 11:18:44 -0600472 fails += 1;
473 }
474
David Brown5f7ec2b2017-11-06 13:54:02 -0700475 if fails > 0 {
476 error!("Error testing perm upgrade with {} fails", total_fails);
477 }
478
479 fails > 0
480 }
481
482 #[cfg(feature = "overwrite-only")]
483 #[allow(unused_variables)]
David Brownc49811e2017-11-06 14:20:45 -0700484 fn run_revert_with_fails(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700485 false
486 }
487
488 #[cfg(not(feature = "overwrite-only"))]
David Brownc49811e2017-11-06 14:20:45 -0700489 fn run_revert_with_fails(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700490 let mut fails = 0;
491
492 if Caps::SwapUpgrade.present() {
David Brownc49811e2017-11-06 14:20:45 -0700493 for i in 1 .. (self.total_count.unwrap() - 1) {
David Brown5f7ec2b2017-11-06 13:54:02 -0700494 info!("Try interruption at {}", i);
495 if try_revert_with_fail_at(&self.flash, &self, i) {
496 error!("Revert failed at interruption {}", i);
497 fails += 1;
498 }
499 }
500 }
501
502 fails > 0
503 }
504
505 #[cfg(feature = "overwrite-only")]
506 fn run_norevert(&self) -> bool {
507 false
508 }
509
510 #[cfg(not(feature = "overwrite-only"))]
511 fn run_norevert(&self) -> bool {
512 let mut fl = self.flash.clone();
513 let mut fails = 0;
514
515 info!("Try norevert");
516
517 // First do a normal upgrade...
518 if c::boot_go(&mut fl, &self.areadesc, None, self.align) != 0 {
519 warn!("Failed first boot");
520 fails += 1;
521 }
522
523 //FIXME: copy_done is written by boot_go, is it ok if no copy
524 // was ever done?
525
526 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
527 warn!("Slot 0 image verification FAIL");
528 fails += 1;
529 }
530 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, UNSET,
David Brown2639e072017-10-11 11:18:44 -0600531 COPY_DONE) {
532 warn!("Mismatched trailer for Slot 0");
533 fails += 1;
534 }
David Brown5f7ec2b2017-11-06 13:54:02 -0700535 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
David Brown2639e072017-10-11 11:18:44 -0600536 UNSET) {
537 warn!("Mismatched trailer for Slot 1");
538 fails += 1;
539 }
540
David Brown5f7ec2b2017-11-06 13:54:02 -0700541 // Marks image in slot0 as permanent, no revert should happen...
542 mark_permanent_upgrade(&mut fl, &self.slot0, self.align);
543
544 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
545 COPY_DONE) {
546 warn!("Mismatched trailer for Slot 0");
547 fails += 1;
David Brown2639e072017-10-11 11:18:44 -0600548 }
David Brown2639e072017-10-11 11:18:44 -0600549
David Brown5f7ec2b2017-11-06 13:54:02 -0700550 if c::boot_go(&mut fl, &self.areadesc, None, self.align) != 0 {
551 warn!("Failed second boot");
552 fails += 1;
David Brown2639e072017-10-11 11:18:44 -0600553 }
David Brown5f7ec2b2017-11-06 13:54:02 -0700554
555 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
556 COPY_DONE) {
557 warn!("Mismatched trailer for Slot 0");
558 fails += 1;
559 }
560 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
561 warn!("Failed image verification");
562 fails += 1;
563 }
564
565 if fails > 0 {
566 error!("Error running upgrade without revert");
567 }
568
569 fails > 0
David Brown2639e072017-10-11 11:18:44 -0600570 }
571
David Brown5f7ec2b2017-11-06 13:54:02 -0700572 // Tests a new image written to slot0 that already has magic and image_ok set
573 // while there is no image on slot1, so no revert should ever happen...
David Brownc49811e2017-11-06 14:20:45 -0700574 pub fn run_norevert_newimage(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700575 let mut fl = self.flash.clone();
576 let mut fails = 0;
David Brown2639e072017-10-11 11:18:44 -0600577
David Brown5f7ec2b2017-11-06 13:54:02 -0700578 info!("Try non-revert on imgtool generated image");
David Brown2639e072017-10-11 11:18:44 -0600579
David Brown5f7ec2b2017-11-06 13:54:02 -0700580 mark_upgrade(&mut fl, &self.slot0);
David Brown2639e072017-10-11 11:18:44 -0600581
David Brown5f7ec2b2017-11-06 13:54:02 -0700582 // This simulates writing an image created by imgtool to Slot 0
583 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, UNSET, UNSET) {
584 warn!("Mismatched trailer for Slot 0");
585 fails += 1;
586 }
David Brown2639e072017-10-11 11:18:44 -0600587
David Brown5f7ec2b2017-11-06 13:54:02 -0700588 // Run the bootloader...
589 if c::boot_go(&mut fl, &self.areadesc, None, self.align) != 0 {
590 warn!("Failed first boot");
591 fails += 1;
592 }
593
594 // State should not have changed
595 if !verify_image(&fl, self.slot0.base_off, &self.primary) {
596 warn!("Failed image verification");
597 fails += 1;
598 }
599 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, UNSET,
600 UNSET) {
601 warn!("Mismatched trailer for Slot 0");
602 fails += 1;
603 }
604 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
605 UNSET) {
606 warn!("Mismatched trailer for Slot 1");
607 fails += 1;
608 }
609
610 if fails > 0 {
611 error!("Expected a non revert with new image");
612 }
613
614 fails > 0
David Brown2639e072017-10-11 11:18:44 -0600615 }
616
David Brown5f7ec2b2017-11-06 13:54:02 -0700617 // Tests a new image written to slot0 that already has magic and image_ok set
618 // while there is no image on slot1, so no revert should ever happen...
David Brownc49811e2017-11-06 14:20:45 -0700619 pub fn run_signfail_upgrade(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700620 let mut fl = self.flash.clone();
621 let mut fails = 0;
David Brown2639e072017-10-11 11:18:44 -0600622
David Brown5f7ec2b2017-11-06 13:54:02 -0700623 info!("Try upgrade image with bad signature");
624
625 mark_upgrade(&mut fl, &self.slot0);
626 mark_permanent_upgrade(&mut fl, &self.slot0, self.align);
627 mark_upgrade(&mut fl, &self.slot1);
628
629 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
630 UNSET) {
631 warn!("Mismatched trailer for Slot 0");
632 fails += 1;
633 }
634
635 // Run the bootloader...
636 if c::boot_go(&mut fl, &self.areadesc, None, self.align) != 0 {
637 warn!("Failed first boot");
638 fails += 1;
639 }
640
641 // State should not have changed
642 if !verify_image(&fl, self.slot0.base_off, &self.primary) {
643 warn!("Failed image verification");
644 fails += 1;
645 }
646 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
647 UNSET) {
648 warn!("Mismatched trailer for Slot 0");
649 fails += 1;
650 }
651
652 if fails > 0 {
653 error!("Expected an upgrade failure when image has bad signature");
654 }
655
656 fails > 0
David Brown2639e072017-10-11 11:18:44 -0600657 }
David Brown2639e072017-10-11 11:18:44 -0600658}
659
660/// Test a boot, optionally stopping after 'n' flash options. Returns a count
661/// of the number of flash operations done total.
David Brown3f687dc2017-11-06 13:41:18 -0700662fn try_upgrade(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600663 stop: Option<i32>) -> (SimFlash, i32) {
664 // Clone the flash to have a new copy.
665 let mut fl = flash.clone();
666
David Brown541860c2017-11-06 11:25:42 -0700667 mark_permanent_upgrade(&mut fl, &images.slot1, images.align);
David Brown2639e072017-10-11 11:18:44 -0600668
David Brownee61c832017-11-06 11:13:25 -0700669 let mut counter = stop.unwrap_or(0);
670
David Brown3f687dc2017-11-06 13:41:18 -0700671 let (first_interrupted, count) = match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align) {
David Brown2639e072017-10-11 11:18:44 -0600672 -0x13579 => (true, stop.unwrap()),
David Brownee61c832017-11-06 11:13:25 -0700673 0 => (false, -counter),
David Brown2639e072017-10-11 11:18:44 -0600674 x => panic!("Unknown return: {}", x),
675 };
David Brown2639e072017-10-11 11:18:44 -0600676
David Brownee61c832017-11-06 11:13:25 -0700677 counter = 0;
David Brown2639e072017-10-11 11:18:44 -0600678 if first_interrupted {
679 // fl.dump();
David Brown3f687dc2017-11-06 13:41:18 -0700680 match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align) {
David Brown2639e072017-10-11 11:18:44 -0600681 -0x13579 => panic!("Shouldn't stop again"),
682 0 => (),
683 x => panic!("Unknown return: {}", x),
684 }
685 }
686
David Brownee61c832017-11-06 11:13:25 -0700687 (fl, count - counter)
David Brown2639e072017-10-11 11:18:44 -0600688}
689
690#[cfg(not(feature = "overwrite-only"))]
David Brown541860c2017-11-06 11:25:42 -0700691fn try_revert(flash: &SimFlash, areadesc: &AreaDesc, count: usize, align: u8) -> SimFlash {
David Brown2639e072017-10-11 11:18:44 -0600692 let mut fl = flash.clone();
David Brown2639e072017-10-11 11:18:44 -0600693
694 // fl.write_file("image0.bin").unwrap();
695 for i in 0 .. count {
696 info!("Running boot pass {}", i + 1);
David Brown541860c2017-11-06 11:25:42 -0700697 assert_eq!(c::boot_go(&mut fl, &areadesc, None, align), 0);
David Brown2639e072017-10-11 11:18:44 -0600698 }
699 fl
700}
701
702#[cfg(not(feature = "overwrite-only"))]
David Brown3f687dc2017-11-06 13:41:18 -0700703fn try_revert_with_fail_at(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600704 stop: i32) -> bool {
705 let mut fl = flash.clone();
706 let mut x: i32;
707 let mut fails = 0;
708
David Brownee61c832017-11-06 11:13:25 -0700709 let mut counter = stop;
David Brown3f687dc2017-11-06 13:41:18 -0700710 x = c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align);
David Brown2639e072017-10-11 11:18:44 -0600711 if x != -0x13579 {
712 warn!("Should have stopped at interruption point");
713 fails += 1;
714 }
715
716 if !verify_trailer(&fl, images.slot0.trailer_off, None, None, UNSET) {
717 warn!("copy_done should be unset");
718 fails += 1;
719 }
720
David Brown3f687dc2017-11-06 13:41:18 -0700721 x = c::boot_go(&mut fl, &images.areadesc, None, images.align);
David Brown2639e072017-10-11 11:18:44 -0600722 if x != 0 {
723 warn!("Should have finished upgrade");
724 fails += 1;
725 }
726
727 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
728 warn!("Image in slot 0 before revert is invalid at stop={}", stop);
729 fails += 1;
730 }
731 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
732 warn!("Image in slot 1 before revert is invalid at stop={}", stop);
733 fails += 1;
734 }
735 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
736 COPY_DONE) {
737 warn!("Mismatched trailer for Slot 0 before revert");
738 fails += 1;
739 }
740 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
741 UNSET) {
742 warn!("Mismatched trailer for Slot 1 before revert");
743 fails += 1;
744 }
745
746 // Do Revert
David Brown3f687dc2017-11-06 13:41:18 -0700747 x = c::boot_go(&mut fl, &images.areadesc, None, images.align);
David Brown2639e072017-10-11 11:18:44 -0600748 if x != 0 {
749 warn!("Should have finished a revert");
750 fails += 1;
751 }
752
753 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
754 warn!("Image in slot 0 after revert is invalid at stop={}", stop);
755 fails += 1;
756 }
757 if !verify_image(&fl, images.slot1.base_off, &images.upgrade) {
758 warn!("Image in slot 1 after revert is invalid at stop={}", stop);
759 fails += 1;
760 }
761 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
762 COPY_DONE) {
763 warn!("Mismatched trailer for Slot 1 after revert");
764 fails += 1;
765 }
766 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
767 UNSET) {
768 warn!("Mismatched trailer for Slot 1 after revert");
769 fails += 1;
770 }
771
772 fails > 0
773}
774
David Brown3f687dc2017-11-06 13:41:18 -0700775fn try_random_fails(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600776 total_ops: i32, count: usize) -> (SimFlash, Vec<i32>) {
777 let mut fl = flash.clone();
778
David Brown541860c2017-11-06 11:25:42 -0700779 mark_permanent_upgrade(&mut fl, &images.slot1, images.align);
David Brown2639e072017-10-11 11:18:44 -0600780
781 let mut rng = rand::thread_rng();
782 let mut resets = vec![0i32; count];
783 let mut remaining_ops = total_ops;
784 for i in 0 .. count {
785 let ops = Range::new(1, remaining_ops / 2);
786 let reset_counter = ops.ind_sample(&mut rng);
David Brownee61c832017-11-06 11:13:25 -0700787 let mut counter = reset_counter;
David Brown3f687dc2017-11-06 13:41:18 -0700788 match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align) {
David Brown2639e072017-10-11 11:18:44 -0600789 0 | -0x13579 => (),
790 x => panic!("Unknown return: {}", x),
791 }
792 remaining_ops -= reset_counter;
793 resets[i] = reset_counter;
794 }
795
David Brown3f687dc2017-11-06 13:41:18 -0700796 match c::boot_go(&mut fl, &images.areadesc, None, images.align) {
David Brown2639e072017-10-11 11:18:44 -0600797 -0x13579 => panic!("Should not be have been interrupted!"),
798 0 => (),
799 x => panic!("Unknown return: {}", x),
800 }
801
802 (fl, resets)
803}
804
805/// Show the flash layout.
806#[allow(dead_code)]
807fn show_flash(flash: &Flash) {
808 println!("---- Flash configuration ----");
809 for sector in flash.sector_iter() {
810 println!(" {:3}: 0x{:08x}, 0x{:08x}",
811 sector.num, sector.base, sector.size);
812 }
813 println!("");
814}
815
816/// Install a "program" into the given image. This fakes the image header, or at least all of the
817/// fields used by the given code. Returns a copy of the image that was written.
818fn install_image(flash: &mut Flash, offset: usize, len: usize,
819 bad_sig: bool) -> Vec<u8> {
820 let offset0 = offset;
821
822 let mut tlv = make_tlv();
823
824 // Generate a boot header. Note that the size doesn't include the header.
825 let header = ImageHeader {
826 magic: 0x96f3b83d,
827 tlv_size: tlv.get_size(),
828 _pad1: 0,
829 hdr_size: 32,
830 key_id: 0,
831 _pad2: 0,
832 img_size: len as u32,
833 flags: tlv.get_flags(),
834 ver: ImageVersion {
835 major: (offset / (128 * 1024)) as u8,
836 minor: 0,
837 revision: 1,
838 build_num: offset as u32,
839 },
840 _pad3: 0,
841 };
842
843 let b_header = header.as_raw();
844 tlv.add_bytes(&b_header);
845 /*
846 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
847 mem::size_of::<ImageHeader>()) };
848 */
849 assert_eq!(b_header.len(), 32);
850 flash.write(offset, &b_header).unwrap();
851 let offset = offset + b_header.len();
852
853 // The core of the image itself is just pseudorandom data.
854 let mut buf = vec![0; len];
855 splat(&mut buf, offset);
856 tlv.add_bytes(&buf);
857
858 // Get and append the TLV itself.
859 if bad_sig {
860 let good_sig = &mut tlv.make_tlv();
861 buf.append(&mut vec![0; good_sig.len()]);
862 } else {
863 buf.append(&mut tlv.make_tlv());
864 }
865
866 // Pad the block to a flash alignment (8 bytes).
867 while buf.len() % 8 != 0 {
868 buf.push(0xFF);
869 }
870
871 flash.write(offset, &buf).unwrap();
872 let offset = offset + buf.len();
873
874 // Copy out the image so that we can verify that the image was installed correctly later.
875 let mut copy = vec![0u8; offset - offset0];
876 flash.read(offset0, &mut copy).unwrap();
877
878 copy
879}
880
881// The TLV in use depends on what kind of signature we are verifying.
882#[cfg(feature = "sig-rsa")]
883fn make_tlv() -> TlvGen {
884 TlvGen::new_rsa_pss()
885}
886
887#[cfg(not(feature = "sig-rsa"))]
888fn make_tlv() -> TlvGen {
889 TlvGen::new_hash_only()
890}
891
892/// Verify that given image is present in the flash at the given offset.
893fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
894 let mut copy = vec![0u8; buf.len()];
895 flash.read(offset, &mut copy).unwrap();
896
897 if buf != &copy[..] {
898 for i in 0 .. buf.len() {
899 if buf[i] != copy[i] {
900 info!("First failure at {:#x}", offset + i);
901 break;
902 }
903 }
904 false
905 } else {
906 true
907 }
908}
909
910#[cfg(feature = "overwrite-only")]
911#[allow(unused_variables)]
912// overwrite-only doesn't employ trailer management
913fn verify_trailer(flash: &Flash, offset: usize,
914 magic: Option<&[u8]>, image_ok: Option<u8>,
915 copy_done: Option<u8>) -> bool {
916 true
917}
918
919#[cfg(not(feature = "overwrite-only"))]
920fn verify_trailer(flash: &Flash, offset: usize,
921 magic: Option<&[u8]>, image_ok: Option<u8>,
922 copy_done: Option<u8>) -> bool {
923 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 2];
924 let mut failed = false;
925
926 flash.read(offset, &mut copy).unwrap();
927
928 failed |= match magic {
929 Some(v) => {
930 if &copy[16..] != v {
931 warn!("\"magic\" mismatch at {:#x}", offset);
932 true
933 } else {
934 false
935 }
936 },
937 None => false,
938 };
939
940 failed |= match image_ok {
941 Some(v) => {
942 if copy[8] != v {
943 warn!("\"image_ok\" mismatch at {:#x}", offset);
944 true
945 } else {
946 false
947 }
948 },
949 None => false,
950 };
951
952 failed |= match copy_done {
953 Some(v) => {
954 if copy[0] != v {
955 warn!("\"copy_done\" mismatch at {:#x}", offset);
956 true
957 } else {
958 false
959 }
960 },
961 None => false,
962 };
963
964 !failed
965}
966
967/// The image header
968#[repr(C)]
969pub struct ImageHeader {
970 magic: u32,
971 tlv_size: u16,
972 key_id: u8,
973 _pad1: u8,
974 hdr_size: u16,
975 _pad2: u16,
976 img_size: u32,
977 flags: u32,
978 ver: ImageVersion,
979 _pad3: u32,
980}
981
982impl AsRaw for ImageHeader {}
983
984#[repr(C)]
985pub struct ImageVersion {
986 major: u8,
987 minor: u8,
988 revision: u16,
989 build_num: u32,
990}
991
David Brownd5e632c2017-10-19 10:49:46 -0600992#[derive(Clone)]
David Brown2639e072017-10-11 11:18:44 -0600993struct SlotInfo {
994 base_off: usize,
995 trailer_off: usize,
996}
997
David Brownf48b9502017-11-06 14:00:26 -0700998pub struct Images {
David Browndc9cba12017-11-06 13:31:42 -0700999 flash: SimFlash,
David Brown3f687dc2017-11-06 13:41:18 -07001000 areadesc: AreaDesc,
David Brownd5e632c2017-10-19 10:49:46 -06001001 slot0: SlotInfo,
1002 slot1: SlotInfo,
David Brown2639e072017-10-11 11:18:44 -06001003 primary: Vec<u8>,
1004 upgrade: Vec<u8>,
David Brownc49811e2017-11-06 14:20:45 -07001005 total_count: Option<i32>,
David Brown541860c2017-11-06 11:25:42 -07001006 align: u8,
David Brown2639e072017-10-11 11:18:44 -06001007}
1008
1009const MAGIC_VALID: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3,
1010 0x60, 0xd2, 0xef, 0x7f,
1011 0x35, 0x52, 0x50, 0x0f,
1012 0x2c, 0xb6, 0x79, 0x80]);
1013const MAGIC_UNSET: Option<&[u8]> = Some(&[0xff; 16]);
1014
1015const COPY_DONE: Option<u8> = Some(1);
1016const IMAGE_OK: Option<u8> = Some(1);
1017const UNSET: Option<u8> = Some(0xff);
1018
1019/// Write out the magic so that the loader tries doing an upgrade.
1020fn mark_upgrade(flash: &mut Flash, slot: &SlotInfo) {
1021 let offset = slot.trailer_off + c::boot_max_align() * 2;
1022 flash.write(offset, MAGIC_VALID.unwrap()).unwrap();
1023}
1024
1025/// Writes the image_ok flag which, guess what, tells the bootloader
1026/// the this image is ok (not a test, and no revert is to be performed).
David Brown541860c2017-11-06 11:25:42 -07001027fn mark_permanent_upgrade(flash: &mut Flash, slot: &SlotInfo, align: u8) {
David Brown2639e072017-10-11 11:18:44 -06001028 let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
David Brown2639e072017-10-11 11:18:44 -06001029 let off = slot.trailer_off + c::boot_max_align();
David Brown541860c2017-11-06 11:25:42 -07001030 flash.write(off, &ok[..align as usize]).unwrap();
David Brown2639e072017-10-11 11:18:44 -06001031}
1032
1033// Drop some pseudo-random gibberish onto the data.
1034fn splat(data: &mut [u8], seed: usize) {
1035 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
1036 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
1037 rng.fill_bytes(data);
1038}
1039
1040/// Return a read-only view into the raw bytes of this object
1041trait AsRaw : Sized {
1042 fn as_raw<'a>(&'a self) -> &'a [u8] {
1043 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1044 mem::size_of::<Self>()) }
1045 }
1046}
1047
1048fn show_sizes() {
1049 // This isn't panic safe.
David Brown2639e072017-10-11 11:18:44 -06001050 for min in &[1, 2, 4, 8] {
David Brown541860c2017-11-06 11:25:42 -07001051 let msize = c::boot_trailer_sz(*min);
David Brown2639e072017-10-11 11:18:44 -06001052 println!("{:2}: {} (0x{:x})", min, msize, msize);
1053 }
David Brown2639e072017-10-11 11:18:44 -06001054}