blob: b83e31bd00d4da4872fdb1d67557d31736a9719f [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")]
David Browna4167ef2017-11-06 14:30:05 -0700380 pub fn run_basic_revert(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700381 false
382 }
David Brown2639e072017-10-11 11:18:44 -0600383
David Brown5f7ec2b2017-11-06 13:54:02 -0700384 #[cfg(not(feature = "overwrite-only"))]
David Browna4167ef2017-11-06 14:30:05 -0700385 pub fn run_basic_revert(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700386 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 Browna4167ef2017-11-06 14:30:05 -0700403 pub 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 Browna4167ef2017-11-06 14:30:05 -0700445 pub fn run_perm_with_random_fails_5(&self) -> bool {
446 self.run_perm_with_random_fails(5)
447 }
448
David Brownc49811e2017-11-06 14:20:45 -0700449 fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700450 let mut fails = 0;
David Brownc49811e2017-11-06 14:20:45 -0700451 let total_flash_ops = self.total_count.unwrap();
David Brown5f7ec2b2017-11-06 13:54:02 -0700452 let (fl, total_counts) = try_random_fails(&self.flash, &self,
453 total_flash_ops, total_fails);
454 info!("Random interruptions at reset points={:?}", total_counts);
455
456 let slot0_ok = verify_image(&fl, self.slot0.base_off, &self.upgrade);
457 let slot1_ok = if Caps::SwapUpgrade.present() {
458 verify_image(&fl, self.slot1.base_off, &self.primary)
459 } else {
460 true
461 };
462 if !slot0_ok || !slot1_ok {
463 error!("Image mismatch after random interrupts: slot0={} slot1={}",
464 if slot0_ok { "ok" } else { "fail" },
465 if slot1_ok { "ok" } else { "fail" });
466 fails += 1;
467 }
468 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
469 COPY_DONE) {
470 error!("Mismatched trailer for Slot 0");
471 fails += 1;
472 }
473 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
474 UNSET) {
475 error!("Mismatched trailer for Slot 1");
David Brown2639e072017-10-11 11:18:44 -0600476 fails += 1;
477 }
478
David Brown5f7ec2b2017-11-06 13:54:02 -0700479 if fails > 0 {
480 error!("Error testing perm upgrade with {} fails", total_fails);
481 }
482
483 fails > 0
484 }
485
486 #[cfg(feature = "overwrite-only")]
David Browna4167ef2017-11-06 14:30:05 -0700487 pub fn run_revert_with_fails(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700488 false
489 }
490
491 #[cfg(not(feature = "overwrite-only"))]
David Browna4167ef2017-11-06 14:30:05 -0700492 pub fn run_revert_with_fails(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700493 let mut fails = 0;
494
495 if Caps::SwapUpgrade.present() {
David Brownc49811e2017-11-06 14:20:45 -0700496 for i in 1 .. (self.total_count.unwrap() - 1) {
David Brown5f7ec2b2017-11-06 13:54:02 -0700497 info!("Try interruption at {}", i);
498 if try_revert_with_fail_at(&self.flash, &self, i) {
499 error!("Revert failed at interruption {}", i);
500 fails += 1;
501 }
502 }
503 }
504
505 fails > 0
506 }
507
508 #[cfg(feature = "overwrite-only")]
David Browna4167ef2017-11-06 14:30:05 -0700509 pub fn run_norevert(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700510 false
511 }
512
513 #[cfg(not(feature = "overwrite-only"))]
David Browna4167ef2017-11-06 14:30:05 -0700514 pub fn run_norevert(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700515 let mut fl = self.flash.clone();
516 let mut fails = 0;
517
518 info!("Try norevert");
519
520 // First do a normal upgrade...
521 if c::boot_go(&mut fl, &self.areadesc, None, self.align) != 0 {
522 warn!("Failed first boot");
523 fails += 1;
524 }
525
526 //FIXME: copy_done is written by boot_go, is it ok if no copy
527 // was ever done?
528
529 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
530 warn!("Slot 0 image verification FAIL");
531 fails += 1;
532 }
533 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, UNSET,
David Brown2639e072017-10-11 11:18:44 -0600534 COPY_DONE) {
535 warn!("Mismatched trailer for Slot 0");
536 fails += 1;
537 }
David Brown5f7ec2b2017-11-06 13:54:02 -0700538 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
David Brown2639e072017-10-11 11:18:44 -0600539 UNSET) {
540 warn!("Mismatched trailer for Slot 1");
541 fails += 1;
542 }
543
David Brown5f7ec2b2017-11-06 13:54:02 -0700544 // Marks image in slot0 as permanent, no revert should happen...
545 mark_permanent_upgrade(&mut fl, &self.slot0, self.align);
546
547 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
548 COPY_DONE) {
549 warn!("Mismatched trailer for Slot 0");
550 fails += 1;
David Brown2639e072017-10-11 11:18:44 -0600551 }
David Brown2639e072017-10-11 11:18:44 -0600552
David Brown5f7ec2b2017-11-06 13:54:02 -0700553 if c::boot_go(&mut fl, &self.areadesc, None, self.align) != 0 {
554 warn!("Failed second boot");
555 fails += 1;
David Brown2639e072017-10-11 11:18:44 -0600556 }
David Brown5f7ec2b2017-11-06 13:54:02 -0700557
558 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
559 COPY_DONE) {
560 warn!("Mismatched trailer for Slot 0");
561 fails += 1;
562 }
563 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
564 warn!("Failed image verification");
565 fails += 1;
566 }
567
568 if fails > 0 {
569 error!("Error running upgrade without revert");
570 }
571
572 fails > 0
David Brown2639e072017-10-11 11:18:44 -0600573 }
574
David Brown5f7ec2b2017-11-06 13:54:02 -0700575 // Tests a new image written to slot0 that already has magic and image_ok set
576 // while there is no image on slot1, so no revert should ever happen...
David Brownc49811e2017-11-06 14:20:45 -0700577 pub fn run_norevert_newimage(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700578 let mut fl = self.flash.clone();
579 let mut fails = 0;
David Brown2639e072017-10-11 11:18:44 -0600580
David Brown5f7ec2b2017-11-06 13:54:02 -0700581 info!("Try non-revert on imgtool generated image");
David Brown2639e072017-10-11 11:18:44 -0600582
David Brown5f7ec2b2017-11-06 13:54:02 -0700583 mark_upgrade(&mut fl, &self.slot0);
David Brown2639e072017-10-11 11:18:44 -0600584
David Brown5f7ec2b2017-11-06 13:54:02 -0700585 // This simulates writing an image created by imgtool to Slot 0
586 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, UNSET, UNSET) {
587 warn!("Mismatched trailer for Slot 0");
588 fails += 1;
589 }
David Brown2639e072017-10-11 11:18:44 -0600590
David Brown5f7ec2b2017-11-06 13:54:02 -0700591 // Run the bootloader...
592 if c::boot_go(&mut fl, &self.areadesc, None, self.align) != 0 {
593 warn!("Failed first boot");
594 fails += 1;
595 }
596
597 // State should not have changed
598 if !verify_image(&fl, self.slot0.base_off, &self.primary) {
599 warn!("Failed image verification");
600 fails += 1;
601 }
602 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, UNSET,
603 UNSET) {
604 warn!("Mismatched trailer for Slot 0");
605 fails += 1;
606 }
607 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
608 UNSET) {
609 warn!("Mismatched trailer for Slot 1");
610 fails += 1;
611 }
612
613 if fails > 0 {
614 error!("Expected a non revert with new image");
615 }
616
617 fails > 0
David Brown2639e072017-10-11 11:18:44 -0600618 }
619
David Brown5f7ec2b2017-11-06 13:54:02 -0700620 // Tests a new image written to slot0 that already has magic and image_ok set
621 // while there is no image on slot1, so no revert should ever happen...
David Brownc49811e2017-11-06 14:20:45 -0700622 pub fn run_signfail_upgrade(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700623 let mut fl = self.flash.clone();
624 let mut fails = 0;
David Brown2639e072017-10-11 11:18:44 -0600625
David Brown5f7ec2b2017-11-06 13:54:02 -0700626 info!("Try upgrade image with bad signature");
627
628 mark_upgrade(&mut fl, &self.slot0);
629 mark_permanent_upgrade(&mut fl, &self.slot0, self.align);
630 mark_upgrade(&mut fl, &self.slot1);
631
632 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
633 UNSET) {
634 warn!("Mismatched trailer for Slot 0");
635 fails += 1;
636 }
637
638 // Run the bootloader...
639 if c::boot_go(&mut fl, &self.areadesc, None, self.align) != 0 {
640 warn!("Failed first boot");
641 fails += 1;
642 }
643
644 // State should not have changed
645 if !verify_image(&fl, self.slot0.base_off, &self.primary) {
646 warn!("Failed image verification");
647 fails += 1;
648 }
649 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
650 UNSET) {
651 warn!("Mismatched trailer for Slot 0");
652 fails += 1;
653 }
654
655 if fails > 0 {
656 error!("Expected an upgrade failure when image has bad signature");
657 }
658
659 fails > 0
David Brown2639e072017-10-11 11:18:44 -0600660 }
David Brown2639e072017-10-11 11:18:44 -0600661}
662
663/// Test a boot, optionally stopping after 'n' flash options. Returns a count
664/// of the number of flash operations done total.
David Brown3f687dc2017-11-06 13:41:18 -0700665fn try_upgrade(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600666 stop: Option<i32>) -> (SimFlash, i32) {
667 // Clone the flash to have a new copy.
668 let mut fl = flash.clone();
669
David Brown541860c2017-11-06 11:25:42 -0700670 mark_permanent_upgrade(&mut fl, &images.slot1, images.align);
David Brown2639e072017-10-11 11:18:44 -0600671
David Brownee61c832017-11-06 11:13:25 -0700672 let mut counter = stop.unwrap_or(0);
673
David Brown3f687dc2017-11-06 13:41:18 -0700674 let (first_interrupted, count) = match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align) {
David Brown2639e072017-10-11 11:18:44 -0600675 -0x13579 => (true, stop.unwrap()),
David Brownee61c832017-11-06 11:13:25 -0700676 0 => (false, -counter),
David Brown2639e072017-10-11 11:18:44 -0600677 x => panic!("Unknown return: {}", x),
678 };
David Brown2639e072017-10-11 11:18:44 -0600679
David Brownee61c832017-11-06 11:13:25 -0700680 counter = 0;
David Brown2639e072017-10-11 11:18:44 -0600681 if first_interrupted {
682 // fl.dump();
David Brown3f687dc2017-11-06 13:41:18 -0700683 match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align) {
David Brown2639e072017-10-11 11:18:44 -0600684 -0x13579 => panic!("Shouldn't stop again"),
685 0 => (),
686 x => panic!("Unknown return: {}", x),
687 }
688 }
689
David Brownee61c832017-11-06 11:13:25 -0700690 (fl, count - counter)
David Brown2639e072017-10-11 11:18:44 -0600691}
692
693#[cfg(not(feature = "overwrite-only"))]
David Brown541860c2017-11-06 11:25:42 -0700694fn try_revert(flash: &SimFlash, areadesc: &AreaDesc, count: usize, align: u8) -> SimFlash {
David Brown2639e072017-10-11 11:18:44 -0600695 let mut fl = flash.clone();
David Brown2639e072017-10-11 11:18:44 -0600696
697 // fl.write_file("image0.bin").unwrap();
698 for i in 0 .. count {
699 info!("Running boot pass {}", i + 1);
David Brown541860c2017-11-06 11:25:42 -0700700 assert_eq!(c::boot_go(&mut fl, &areadesc, None, align), 0);
David Brown2639e072017-10-11 11:18:44 -0600701 }
702 fl
703}
704
705#[cfg(not(feature = "overwrite-only"))]
David Brown3f687dc2017-11-06 13:41:18 -0700706fn try_revert_with_fail_at(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600707 stop: i32) -> bool {
708 let mut fl = flash.clone();
709 let mut x: i32;
710 let mut fails = 0;
711
David Brownee61c832017-11-06 11:13:25 -0700712 let mut counter = stop;
David Brown3f687dc2017-11-06 13:41:18 -0700713 x = c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align);
David Brown2639e072017-10-11 11:18:44 -0600714 if x != -0x13579 {
715 warn!("Should have stopped at interruption point");
716 fails += 1;
717 }
718
719 if !verify_trailer(&fl, images.slot0.trailer_off, None, None, UNSET) {
720 warn!("copy_done should be unset");
721 fails += 1;
722 }
723
David Brown3f687dc2017-11-06 13:41:18 -0700724 x = c::boot_go(&mut fl, &images.areadesc, None, images.align);
David Brown2639e072017-10-11 11:18:44 -0600725 if x != 0 {
726 warn!("Should have finished upgrade");
727 fails += 1;
728 }
729
730 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
731 warn!("Image in slot 0 before revert is invalid at stop={}", stop);
732 fails += 1;
733 }
734 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
735 warn!("Image in slot 1 before revert is invalid at stop={}", stop);
736 fails += 1;
737 }
738 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
739 COPY_DONE) {
740 warn!("Mismatched trailer for Slot 0 before revert");
741 fails += 1;
742 }
743 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
744 UNSET) {
745 warn!("Mismatched trailer for Slot 1 before revert");
746 fails += 1;
747 }
748
749 // Do Revert
David Brown3f687dc2017-11-06 13:41:18 -0700750 x = c::boot_go(&mut fl, &images.areadesc, None, images.align);
David Brown2639e072017-10-11 11:18:44 -0600751 if x != 0 {
752 warn!("Should have finished a revert");
753 fails += 1;
754 }
755
756 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
757 warn!("Image in slot 0 after revert is invalid at stop={}", stop);
758 fails += 1;
759 }
760 if !verify_image(&fl, images.slot1.base_off, &images.upgrade) {
761 warn!("Image in slot 1 after revert is invalid at stop={}", stop);
762 fails += 1;
763 }
764 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
765 COPY_DONE) {
766 warn!("Mismatched trailer for Slot 1 after revert");
767 fails += 1;
768 }
769 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
770 UNSET) {
771 warn!("Mismatched trailer for Slot 1 after revert");
772 fails += 1;
773 }
774
775 fails > 0
776}
777
David Brown3f687dc2017-11-06 13:41:18 -0700778fn try_random_fails(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600779 total_ops: i32, count: usize) -> (SimFlash, Vec<i32>) {
780 let mut fl = flash.clone();
781
David Brown541860c2017-11-06 11:25:42 -0700782 mark_permanent_upgrade(&mut fl, &images.slot1, images.align);
David Brown2639e072017-10-11 11:18:44 -0600783
784 let mut rng = rand::thread_rng();
785 let mut resets = vec![0i32; count];
786 let mut remaining_ops = total_ops;
787 for i in 0 .. count {
788 let ops = Range::new(1, remaining_ops / 2);
789 let reset_counter = ops.ind_sample(&mut rng);
David Brownee61c832017-11-06 11:13:25 -0700790 let mut counter = reset_counter;
David Brown3f687dc2017-11-06 13:41:18 -0700791 match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align) {
David Brown2639e072017-10-11 11:18:44 -0600792 0 | -0x13579 => (),
793 x => panic!("Unknown return: {}", x),
794 }
795 remaining_ops -= reset_counter;
796 resets[i] = reset_counter;
797 }
798
David Brown3f687dc2017-11-06 13:41:18 -0700799 match c::boot_go(&mut fl, &images.areadesc, None, images.align) {
David Brown2639e072017-10-11 11:18:44 -0600800 -0x13579 => panic!("Should not be have been interrupted!"),
801 0 => (),
802 x => panic!("Unknown return: {}", x),
803 }
804
805 (fl, resets)
806}
807
808/// Show the flash layout.
809#[allow(dead_code)]
810fn show_flash(flash: &Flash) {
811 println!("---- Flash configuration ----");
812 for sector in flash.sector_iter() {
813 println!(" {:3}: 0x{:08x}, 0x{:08x}",
814 sector.num, sector.base, sector.size);
815 }
816 println!("");
817}
818
819/// Install a "program" into the given image. This fakes the image header, or at least all of the
820/// fields used by the given code. Returns a copy of the image that was written.
821fn install_image(flash: &mut Flash, offset: usize, len: usize,
822 bad_sig: bool) -> Vec<u8> {
823 let offset0 = offset;
824
825 let mut tlv = make_tlv();
826
827 // Generate a boot header. Note that the size doesn't include the header.
828 let header = ImageHeader {
829 magic: 0x96f3b83d,
830 tlv_size: tlv.get_size(),
831 _pad1: 0,
832 hdr_size: 32,
833 key_id: 0,
834 _pad2: 0,
835 img_size: len as u32,
836 flags: tlv.get_flags(),
837 ver: ImageVersion {
838 major: (offset / (128 * 1024)) as u8,
839 minor: 0,
840 revision: 1,
841 build_num: offset as u32,
842 },
843 _pad3: 0,
844 };
845
846 let b_header = header.as_raw();
847 tlv.add_bytes(&b_header);
848 /*
849 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
850 mem::size_of::<ImageHeader>()) };
851 */
852 assert_eq!(b_header.len(), 32);
853 flash.write(offset, &b_header).unwrap();
854 let offset = offset + b_header.len();
855
856 // The core of the image itself is just pseudorandom data.
857 let mut buf = vec![0; len];
858 splat(&mut buf, offset);
859 tlv.add_bytes(&buf);
860
861 // Get and append the TLV itself.
862 if bad_sig {
863 let good_sig = &mut tlv.make_tlv();
864 buf.append(&mut vec![0; good_sig.len()]);
865 } else {
866 buf.append(&mut tlv.make_tlv());
867 }
868
869 // Pad the block to a flash alignment (8 bytes).
870 while buf.len() % 8 != 0 {
871 buf.push(0xFF);
872 }
873
874 flash.write(offset, &buf).unwrap();
875 let offset = offset + buf.len();
876
877 // Copy out the image so that we can verify that the image was installed correctly later.
878 let mut copy = vec![0u8; offset - offset0];
879 flash.read(offset0, &mut copy).unwrap();
880
881 copy
882}
883
884// The TLV in use depends on what kind of signature we are verifying.
885#[cfg(feature = "sig-rsa")]
886fn make_tlv() -> TlvGen {
887 TlvGen::new_rsa_pss()
888}
889
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200890#[cfg(feature = "sig-ecdsa")]
891fn make_tlv() -> TlvGen {
892 TlvGen::new_ecdsa()
893}
894
David Brown2639e072017-10-11 11:18:44 -0600895#[cfg(not(feature = "sig-rsa"))]
Fabio Utzig80fde2f2017-12-05 09:25:31 -0200896#[cfg(not(feature = "sig-ecdsa"))]
David Brown2639e072017-10-11 11:18:44 -0600897fn make_tlv() -> TlvGen {
898 TlvGen::new_hash_only()
899}
900
901/// Verify that given image is present in the flash at the given offset.
902fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
903 let mut copy = vec![0u8; buf.len()];
904 flash.read(offset, &mut copy).unwrap();
905
906 if buf != &copy[..] {
907 for i in 0 .. buf.len() {
908 if buf[i] != copy[i] {
909 info!("First failure at {:#x}", offset + i);
910 break;
911 }
912 }
913 false
914 } else {
915 true
916 }
917}
918
919#[cfg(feature = "overwrite-only")]
920#[allow(unused_variables)]
921// overwrite-only doesn't employ trailer management
922fn verify_trailer(flash: &Flash, offset: usize,
923 magic: Option<&[u8]>, image_ok: Option<u8>,
924 copy_done: Option<u8>) -> bool {
925 true
926}
927
928#[cfg(not(feature = "overwrite-only"))]
929fn verify_trailer(flash: &Flash, offset: usize,
930 magic: Option<&[u8]>, image_ok: Option<u8>,
931 copy_done: Option<u8>) -> bool {
932 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 2];
933 let mut failed = false;
934
935 flash.read(offset, &mut copy).unwrap();
936
937 failed |= match magic {
938 Some(v) => {
939 if &copy[16..] != v {
940 warn!("\"magic\" mismatch at {:#x}", offset);
941 true
942 } else {
943 false
944 }
945 },
946 None => false,
947 };
948
949 failed |= match image_ok {
950 Some(v) => {
951 if copy[8] != v {
952 warn!("\"image_ok\" mismatch at {:#x}", offset);
953 true
954 } else {
955 false
956 }
957 },
958 None => false,
959 };
960
961 failed |= match copy_done {
962 Some(v) => {
963 if copy[0] != v {
964 warn!("\"copy_done\" mismatch at {:#x}", offset);
965 true
966 } else {
967 false
968 }
969 },
970 None => false,
971 };
972
973 !failed
974}
975
976/// The image header
977#[repr(C)]
978pub struct ImageHeader {
979 magic: u32,
980 tlv_size: u16,
981 key_id: u8,
982 _pad1: u8,
983 hdr_size: u16,
984 _pad2: u16,
985 img_size: u32,
986 flags: u32,
987 ver: ImageVersion,
988 _pad3: u32,
989}
990
991impl AsRaw for ImageHeader {}
992
993#[repr(C)]
994pub struct ImageVersion {
995 major: u8,
996 minor: u8,
997 revision: u16,
998 build_num: u32,
999}
1000
David Brownd5e632c2017-10-19 10:49:46 -06001001#[derive(Clone)]
David Brown2639e072017-10-11 11:18:44 -06001002struct SlotInfo {
1003 base_off: usize,
1004 trailer_off: usize,
1005}
1006
David Brownf48b9502017-11-06 14:00:26 -07001007pub struct Images {
David Browndc9cba12017-11-06 13:31:42 -07001008 flash: SimFlash,
David Brown3f687dc2017-11-06 13:41:18 -07001009 areadesc: AreaDesc,
David Brownd5e632c2017-10-19 10:49:46 -06001010 slot0: SlotInfo,
1011 slot1: SlotInfo,
David Brown2639e072017-10-11 11:18:44 -06001012 primary: Vec<u8>,
1013 upgrade: Vec<u8>,
David Brownc49811e2017-11-06 14:20:45 -07001014 total_count: Option<i32>,
David Brown541860c2017-11-06 11:25:42 -07001015 align: u8,
David Brown2639e072017-10-11 11:18:44 -06001016}
1017
1018const MAGIC_VALID: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3,
1019 0x60, 0xd2, 0xef, 0x7f,
1020 0x35, 0x52, 0x50, 0x0f,
1021 0x2c, 0xb6, 0x79, 0x80]);
1022const MAGIC_UNSET: Option<&[u8]> = Some(&[0xff; 16]);
1023
1024const COPY_DONE: Option<u8> = Some(1);
1025const IMAGE_OK: Option<u8> = Some(1);
1026const UNSET: Option<u8> = Some(0xff);
1027
1028/// Write out the magic so that the loader tries doing an upgrade.
1029fn mark_upgrade(flash: &mut Flash, slot: &SlotInfo) {
1030 let offset = slot.trailer_off + c::boot_max_align() * 2;
1031 flash.write(offset, MAGIC_VALID.unwrap()).unwrap();
1032}
1033
1034/// Writes the image_ok flag which, guess what, tells the bootloader
1035/// the this image is ok (not a test, and no revert is to be performed).
David Brown541860c2017-11-06 11:25:42 -07001036fn mark_permanent_upgrade(flash: &mut Flash, slot: &SlotInfo, align: u8) {
David Brown2639e072017-10-11 11:18:44 -06001037 let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
David Brown2639e072017-10-11 11:18:44 -06001038 let off = slot.trailer_off + c::boot_max_align();
David Brown541860c2017-11-06 11:25:42 -07001039 flash.write(off, &ok[..align as usize]).unwrap();
David Brown2639e072017-10-11 11:18:44 -06001040}
1041
1042// Drop some pseudo-random gibberish onto the data.
1043fn splat(data: &mut [u8], seed: usize) {
1044 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
1045 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
1046 rng.fill_bytes(data);
1047}
1048
1049/// Return a read-only view into the raw bytes of this object
1050trait AsRaw : Sized {
1051 fn as_raw<'a>(&'a self) -> &'a [u8] {
1052 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1053 mem::size_of::<Self>()) }
1054 }
1055}
1056
1057fn show_sizes() {
1058 // This isn't panic safe.
David Brown2639e072017-10-11 11:18:44 -06001059 for min in &[1, 2, 4, 8] {
David Brown541860c2017-11-06 11:25:42 -07001060 let msize = c::boot_trailer_sz(*min);
David Brown2639e072017-10-11 11:18:44 -06001061 println!("{:2}: {} (0x{:x})", min, msize, msize);
1062 }
David Brown2639e072017-10-11 11:18:44 -06001063}