blob: 74f6b0960bc589dcab37412a6dc8ff470f44f9ac [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 Browndb9a3952017-11-06 13:16:15 -0700237 slot0: run.slots[0].clone(),
238 slot1: run.slots[1].clone(),
David Browndc9cba12017-11-06 13:31:42 -0700239 primary: primary,
240 upgrade: upgrade,
David Brown541860c2017-11-06 11:25:42 -0700241 align: align,
David Brown2639e072017-10-11 11:18:44 -0600242 };
243
David Browndc9cba12017-11-06 13:31:42 -0700244 failed |= run_signfail_upgrade(&run.areadesc, &bad_slot1_image);
David Brown2639e072017-10-11 11:18:44 -0600245
David Browndc9cba12017-11-06 13:31:42 -0700246 let mut flash = run.flash.clone();
247 let primary = install_image(&mut flash, run.slots[0].base_off, 32784, false);
248 let upgrade = install_image(&mut flash, run.slots[1].base_off, 41928, false);
249 let mut images = Images {
250 flash: flash,
David Browndb9a3952017-11-06 13:16:15 -0700251 slot0: run.slots[0].clone(),
252 slot1: run.slots[1].clone(),
David Browndc9cba12017-11-06 13:31:42 -0700253 primary: primary,
254 upgrade: upgrade,
David Brown541860c2017-11-06 11:25:42 -0700255 align: align,
David Brown2639e072017-10-11 11:18:44 -0600256 };
257
David Browndc9cba12017-11-06 13:31:42 -0700258 failed |= run_norevert_newimage(&run.areadesc, &images);
David Brown2639e072017-10-11 11:18:44 -0600259
David Browndc9cba12017-11-06 13:31:42 -0700260 mark_upgrade(&mut images.flash, &images.slot1);
David Brown2639e072017-10-11 11:18:44 -0600261
262 // upgrades without fails, counts number of flash operations
David Browndc9cba12017-11-06 13:31:42 -0700263 let total_count = match run_basic_upgrade(&run.areadesc, &images) {
David Brown2639e072017-10-11 11:18:44 -0600264 Ok(v) => v,
265 Err(_) => {
266 self.failures += 1;
267 return;
268 },
269 };
270
David Browndc9cba12017-11-06 13:31:42 -0700271 failed |= run_basic_revert(&run.areadesc, &images);
272 failed |= run_revert_with_fails(&run.areadesc, &images, total_count);
273 failed |= run_perm_with_fails(&run.areadesc, &images, total_count);
274 failed |= run_perm_with_random_fails(&run.areadesc, &images, total_count, 5);
275 failed |= run_norevert(&run.areadesc, &images);
David Brown2639e072017-10-11 11:18:44 -0600276
277 //show_flash(&flash);
278
279 if failed {
280 self.failures += 1;
281 } else {
282 self.passes += 1;
283 }
284 }
David Browndd2b1182017-11-02 15:39:21 -0600285
286 pub fn failures(&self) -> usize {
287 self.failures
288 }
David Brown2639e072017-10-11 11:18:44 -0600289}
290
David Browndecbd042017-10-19 10:43:17 -0600291/// Build the Flash and area descriptor for a given device.
292pub fn make_device(device: DeviceName, align: u8) -> (SimFlash, AreaDesc) {
293 match device {
294 DeviceName::Stm32f4 => {
295 // STM style flash. Large sectors, with a large scratch area.
296 let flash = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
297 64 * 1024,
298 128 * 1024, 128 * 1024, 128 * 1024],
299 align as usize);
300 let mut areadesc = AreaDesc::new(&flash);
301 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
302 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
303 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch);
304 (flash, areadesc)
305 }
306 DeviceName::K64f => {
307 // NXP style flash. Small sectors, one small sector for scratch.
308 let flash = SimFlash::new(vec![4096; 128], align as usize);
309
310 let mut areadesc = AreaDesc::new(&flash);
311 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
312 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
313 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch);
314 (flash, areadesc)
315 }
316 DeviceName::K64fBig => {
317 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
318 // uses small sectors, but we tell the bootloader they are large.
319 let flash = SimFlash::new(vec![4096; 128], align as usize);
320
321 let mut areadesc = AreaDesc::new(&flash);
322 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0);
323 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1);
324 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch);
325 (flash, areadesc)
326 }
327 DeviceName::Nrf52840 => {
328 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
329 // does not divide into the image size.
330 let flash = SimFlash::new(vec![4096; 128], align as usize);
331
332 let mut areadesc = AreaDesc::new(&flash);
333 areadesc.add_image(0x008000, 0x034000, FlashId::Image0);
334 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1);
335 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch);
336 (flash, areadesc)
337 }
338 }
339}
340
David Brown2639e072017-10-11 11:18:44 -0600341/// A simple upgrade without forced failures.
342///
343/// Returns the number of flash operations which can later be used to
344/// inject failures at chosen steps.
David Browndc9cba12017-11-06 13:31:42 -0700345fn run_basic_upgrade(areadesc: &AreaDesc, images: &Images) -> Result<i32, ()> {
346 let (fl, total_count) = try_upgrade(&images.flash, &areadesc, &images, None);
David Brown2639e072017-10-11 11:18:44 -0600347 info!("Total flash operation count={}", total_count);
348
349 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
350 warn!("Image mismatch after first boot");
351 Err(())
352 } else {
353 Ok(total_count)
354 }
355}
356
357#[cfg(feature = "overwrite-only")]
358#[allow(unused_variables)]
David Browndc9cba12017-11-06 13:31:42 -0700359fn run_basic_revert(areadesc: &AreaDesc, images: &Images) -> bool {
David Brown2639e072017-10-11 11:18:44 -0600360 false
361}
362
363#[cfg(not(feature = "overwrite-only"))]
David Browndc9cba12017-11-06 13:31:42 -0700364fn run_basic_revert(areadesc: &AreaDesc, images: &Images) -> bool {
David Brown2639e072017-10-11 11:18:44 -0600365 let mut fails = 0;
366
367 // FIXME: this test would also pass if no swap is ever performed???
368 if Caps::SwapUpgrade.present() {
369 for count in 2 .. 5 {
370 info!("Try revert: {}", count);
David Browndc9cba12017-11-06 13:31:42 -0700371 let fl = try_revert(&images.flash, &areadesc, count, images.align);
David Brown2639e072017-10-11 11:18:44 -0600372 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
373 error!("Revert failure on count {}", count);
374 fails += 1;
375 }
376 }
377 }
378
379 fails > 0
380}
381
David Browndc9cba12017-11-06 13:31:42 -0700382fn run_perm_with_fails(areadesc: &AreaDesc, images: &Images, total_flash_ops: i32) -> bool {
David Brown2639e072017-10-11 11:18:44 -0600383 let mut fails = 0;
384
385 // Let's try an image halfway through.
386 for i in 1 .. total_flash_ops {
387 info!("Try interruption at {}", i);
David Browndc9cba12017-11-06 13:31:42 -0700388 let (fl, count) = try_upgrade(&images.flash, &areadesc, &images, Some(i));
David Brown2639e072017-10-11 11:18:44 -0600389 info!("Second boot, count={}", count);
390 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
391 warn!("FAIL at step {} of {}", i, total_flash_ops);
392 fails += 1;
393 }
394
395 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
396 COPY_DONE) {
397 warn!("Mismatched trailer for Slot 0");
398 fails += 1;
399 }
400
401 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
402 UNSET) {
403 warn!("Mismatched trailer for Slot 1");
404 fails += 1;
405 }
406
407 if Caps::SwapUpgrade.present() {
408 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
409 warn!("Slot 1 FAIL at step {} of {}", i, total_flash_ops);
410 fails += 1;
411 }
412 }
413 }
414
415 if fails > 0 {
416 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
417 fails as f32 * 100.0 / total_flash_ops as f32);
418 }
419
420 fails > 0
421}
422
David Browndc9cba12017-11-06 13:31:42 -0700423fn run_perm_with_random_fails(areadesc: &AreaDesc,
David Brown2639e072017-10-11 11:18:44 -0600424 images: &Images, total_flash_ops: i32,
425 total_fails: usize) -> bool {
426 let mut fails = 0;
David Browndc9cba12017-11-06 13:31:42 -0700427 let (fl, total_counts) = try_random_fails(&images.flash, &areadesc, &images,
David Brown2639e072017-10-11 11:18:44 -0600428 total_flash_ops, total_fails);
429 info!("Random interruptions at reset points={:?}", total_counts);
430
431 let slot0_ok = verify_image(&fl, images.slot0.base_off, &images.upgrade);
432 let slot1_ok = if Caps::SwapUpgrade.present() {
433 verify_image(&fl, images.slot1.base_off, &images.primary)
434 } else {
435 true
436 };
437 if !slot0_ok || !slot1_ok {
438 error!("Image mismatch after random interrupts: slot0={} slot1={}",
439 if slot0_ok { "ok" } else { "fail" },
440 if slot1_ok { "ok" } else { "fail" });
441 fails += 1;
442 }
443 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
444 COPY_DONE) {
445 error!("Mismatched trailer for Slot 0");
446 fails += 1;
447 }
448 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
449 UNSET) {
450 error!("Mismatched trailer for Slot 1");
451 fails += 1;
452 }
453
454 if fails > 0 {
455 error!("Error testing perm upgrade with {} fails", total_fails);
456 }
457
458 fails > 0
459}
460
461#[cfg(feature = "overwrite-only")]
462#[allow(unused_variables)]
David Browndc9cba12017-11-06 13:31:42 -0700463fn run_revert_with_fails(areadesc: &AreaDesc, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600464 total_count: i32) -> bool {
465 false
466}
467
468#[cfg(not(feature = "overwrite-only"))]
David Browndc9cba12017-11-06 13:31:42 -0700469fn run_revert_with_fails(areadesc: &AreaDesc, images: &Images, total_count: i32) -> bool {
David Brown2639e072017-10-11 11:18:44 -0600470 let mut fails = 0;
471
472 if Caps::SwapUpgrade.present() {
473 for i in 1 .. (total_count - 1) {
474 info!("Try interruption at {}", i);
David Browndc9cba12017-11-06 13:31:42 -0700475 if try_revert_with_fail_at(&images.flash, &areadesc, &images, i) {
David Brown2639e072017-10-11 11:18:44 -0600476 error!("Revert failed at interruption {}", i);
477 fails += 1;
478 }
479 }
480 }
481
482 fails > 0
483}
484
485#[cfg(feature = "overwrite-only")]
486#[allow(unused_variables)]
David Browndc9cba12017-11-06 13:31:42 -0700487fn run_norevert(areadesc: &AreaDesc, images: &Images) -> bool {
David Brown2639e072017-10-11 11:18:44 -0600488 false
489}
490
491#[cfg(not(feature = "overwrite-only"))]
David Browndc9cba12017-11-06 13:31:42 -0700492fn run_norevert(areadesc: &AreaDesc, images: &Images) -> bool {
493 let mut fl = images.flash.clone();
David Brown2639e072017-10-11 11:18:44 -0600494 let mut fails = 0;
495
496 info!("Try norevert");
David Brown2639e072017-10-11 11:18:44 -0600497
498 // First do a normal upgrade...
David Brown541860c2017-11-06 11:25:42 -0700499 if c::boot_go(&mut fl, &areadesc, None, images.align) != 0 {
David Brown2639e072017-10-11 11:18:44 -0600500 warn!("Failed first boot");
501 fails += 1;
502 }
503
504 //FIXME: copy_done is written by boot_go, is it ok if no copy
505 // was ever done?
506
507 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
508 warn!("Slot 0 image verification FAIL");
509 fails += 1;
510 }
511 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
512 COPY_DONE) {
513 warn!("Mismatched trailer for Slot 0");
514 fails += 1;
515 }
516 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
517 UNSET) {
518 warn!("Mismatched trailer for Slot 1");
519 fails += 1;
520 }
521
522 // Marks image in slot0 as permanent, no revert should happen...
David Brown541860c2017-11-06 11:25:42 -0700523 mark_permanent_upgrade(&mut fl, &images.slot0, images.align);
David Brown2639e072017-10-11 11:18:44 -0600524
525 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
526 COPY_DONE) {
527 warn!("Mismatched trailer for Slot 0");
528 fails += 1;
529 }
530
David Brown541860c2017-11-06 11:25:42 -0700531 if c::boot_go(&mut fl, &areadesc, None, images.align) != 0 {
David Brown2639e072017-10-11 11:18:44 -0600532 warn!("Failed second boot");
533 fails += 1;
534 }
535
536 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
537 COPY_DONE) {
538 warn!("Mismatched trailer for Slot 0");
539 fails += 1;
540 }
541 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
542 warn!("Failed image verification");
543 fails += 1;
544 }
545
546 if fails > 0 {
547 error!("Error running upgrade without revert");
548 }
549
550 fails > 0
551}
552
553// Tests a new image written to slot0 that already has magic and image_ok set
554// while there is no image on slot1, so no revert should ever happen...
David Browndc9cba12017-11-06 13:31:42 -0700555fn run_norevert_newimage(areadesc: &AreaDesc, images: &Images) -> bool {
556 let mut fl = images.flash.clone();
David Brown2639e072017-10-11 11:18:44 -0600557 let mut fails = 0;
558
559 info!("Try non-revert on imgtool generated image");
David Brown2639e072017-10-11 11:18:44 -0600560
561 mark_upgrade(&mut fl, &images.slot0);
562
563 // This simulates writing an image created by imgtool to Slot 0
564 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET, UNSET) {
565 warn!("Mismatched trailer for Slot 0");
566 fails += 1;
567 }
568
569 // Run the bootloader...
David Brown541860c2017-11-06 11:25:42 -0700570 if c::boot_go(&mut fl, &areadesc, None, images.align) != 0 {
David Brown2639e072017-10-11 11:18:44 -0600571 warn!("Failed first boot");
572 fails += 1;
573 }
574
575 // State should not have changed
576 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
577 warn!("Failed image verification");
578 fails += 1;
579 }
580 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
581 UNSET) {
582 warn!("Mismatched trailer for Slot 0");
583 fails += 1;
584 }
585 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
586 UNSET) {
587 warn!("Mismatched trailer for Slot 1");
588 fails += 1;
589 }
590
591 if fails > 0 {
592 error!("Expected a non revert with new image");
593 }
594
595 fails > 0
596}
597
598// Tests a new image written to slot0 that already has magic and image_ok set
599// while there is no image on slot1, so no revert should ever happen...
David Browndc9cba12017-11-06 13:31:42 -0700600fn run_signfail_upgrade(areadesc: &AreaDesc, images: &Images) -> bool {
601 let mut fl = images.flash.clone();
David Brown2639e072017-10-11 11:18:44 -0600602 let mut fails = 0;
603
604 info!("Try upgrade image with bad signature");
David Brown2639e072017-10-11 11:18:44 -0600605
606 mark_upgrade(&mut fl, &images.slot0);
David Brown541860c2017-11-06 11:25:42 -0700607 mark_permanent_upgrade(&mut fl, &images.slot0, images.align);
David Brown2639e072017-10-11 11:18:44 -0600608 mark_upgrade(&mut fl, &images.slot1);
609
610 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
611 UNSET) {
612 warn!("Mismatched trailer for Slot 0");
613 fails += 1;
614 }
615
616 // Run the bootloader...
David Brown541860c2017-11-06 11:25:42 -0700617 if c::boot_go(&mut fl, &areadesc, None, images.align) != 0 {
David Brown2639e072017-10-11 11:18:44 -0600618 warn!("Failed first boot");
619 fails += 1;
620 }
621
622 // State should not have changed
623 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
624 warn!("Failed image verification");
625 fails += 1;
626 }
627 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
628 UNSET) {
629 warn!("Mismatched trailer for Slot 0");
630 fails += 1;
631 }
632
633 if fails > 0 {
634 error!("Expected an upgrade failure when image has bad signature");
635 }
636
637 fails > 0
638}
639
640/// Test a boot, optionally stopping after 'n' flash options. Returns a count
641/// of the number of flash operations done total.
642fn try_upgrade(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
643 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 Brown541860c2017-11-06 11:25:42 -0700651 let (first_interrupted, count) = match c::boot_go(&mut fl, &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 Brown541860c2017-11-06 11:25:42 -0700660 match c::boot_go(&mut fl, &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"))]
683fn try_revert_with_fail_at(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
684 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 Brown541860c2017-11-06 11:25:42 -0700690 x = c::boot_go(&mut fl, &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 Brown541860c2017-11-06 11:25:42 -0700701 x = c::boot_go(&mut fl, &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 Brown541860c2017-11-06 11:25:42 -0700727 x = c::boot_go(&mut fl, &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
755fn try_random_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
756 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 Brown541860c2017-11-06 11:25:42 -0700768 match c::boot_go(&mut fl, &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 Brown541860c2017-11-06 11:25:42 -0700776 match c::boot_go(&mut fl, &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 Brownd5e632c2017-10-19 10:49:46 -0600980 slot0: SlotInfo,
981 slot1: SlotInfo,
David Brown2639e072017-10-11 11:18:44 -0600982 primary: Vec<u8>,
983 upgrade: Vec<u8>,
David Brown541860c2017-11-06 11:25:42 -0700984 align: u8,
David Brown2639e072017-10-11 11:18:44 -0600985}
986
987const MAGIC_VALID: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3,
988 0x60, 0xd2, 0xef, 0x7f,
989 0x35, 0x52, 0x50, 0x0f,
990 0x2c, 0xb6, 0x79, 0x80]);
991const MAGIC_UNSET: Option<&[u8]> = Some(&[0xff; 16]);
992
993const COPY_DONE: Option<u8> = Some(1);
994const IMAGE_OK: Option<u8> = Some(1);
995const UNSET: Option<u8> = Some(0xff);
996
997/// Write out the magic so that the loader tries doing an upgrade.
998fn mark_upgrade(flash: &mut Flash, slot: &SlotInfo) {
999 let offset = slot.trailer_off + c::boot_max_align() * 2;
1000 flash.write(offset, MAGIC_VALID.unwrap()).unwrap();
1001}
1002
1003/// Writes the image_ok flag which, guess what, tells the bootloader
1004/// the this image is ok (not a test, and no revert is to be performed).
David Brown541860c2017-11-06 11:25:42 -07001005fn mark_permanent_upgrade(flash: &mut Flash, slot: &SlotInfo, align: u8) {
David Brown2639e072017-10-11 11:18:44 -06001006 let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
David Brown2639e072017-10-11 11:18:44 -06001007 let off = slot.trailer_off + c::boot_max_align();
David Brown541860c2017-11-06 11:25:42 -07001008 flash.write(off, &ok[..align as usize]).unwrap();
David Brown2639e072017-10-11 11:18:44 -06001009}
1010
1011// Drop some pseudo-random gibberish onto the data.
1012fn splat(data: &mut [u8], seed: usize) {
1013 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
1014 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
1015 rng.fill_bytes(data);
1016}
1017
1018/// Return a read-only view into the raw bytes of this object
1019trait AsRaw : Sized {
1020 fn as_raw<'a>(&'a self) -> &'a [u8] {
1021 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1022 mem::size_of::<Self>()) }
1023 }
1024}
1025
1026fn show_sizes() {
1027 // This isn't panic safe.
David Brown2639e072017-10-11 11:18:44 -06001028 for min in &[1, 2, 4, 8] {
David Brown541860c2017-11-06 11:25:42 -07001029 let msize = c::boot_trailer_sz(*min);
David Brown2639e072017-10-11 11:18:44 -06001030 println!("{:2}: {} (0x{:x})", min, msize, msize);
1031 }
David Brown2639e072017-10-11 11:18:44 -06001032}