blob: 846adf61fa2788f2104d022d4d8966a8be50a13d [file] [log] [blame]
David Brown2639e072017-10-11 11:18:44 -06001#[macro_use] extern crate log;
2extern crate ring;
3extern crate env_logger;
4extern crate docopt;
5extern crate libc;
6extern crate pem;
7extern crate rand;
8#[macro_use] extern crate serde_derive;
9extern crate serde;
10extern crate simflash;
11extern crate untrusted;
12extern crate mcuboot_sys;
13
14use docopt::Docopt;
15use rand::{Rng, SeedableRng, XorShiftRng};
16use rand::distributions::{IndependentSample, Range};
17use std::fmt;
18use std::mem;
19use std::process;
20use std::slice;
21
22mod caps;
23mod tlv;
David Brownca7b5d32017-11-03 08:37:38 -060024pub mod testlog;
David Brown2639e072017-10-11 11:18:44 -060025
26use simflash::{Flash, SimFlash};
27use mcuboot_sys::{c, AreaDesc, FlashId};
28use caps::Caps;
29use tlv::TlvGen;
30
31const USAGE: &'static str = "
32Mcuboot simulator
33
34Usage:
35 bootsim sizes
36 bootsim run --device TYPE [--align SIZE]
37 bootsim runall
38 bootsim (--help | --version)
39
40Options:
41 -h, --help Show this message
42 --version Version
43 --device TYPE MCU to simulate
44 Valid values: stm32f4, k64f
45 --align SIZE Flash write alignment
46";
47
48#[derive(Debug, Deserialize)]
49struct Args {
50 flag_help: bool,
51 flag_version: bool,
52 flag_device: Option<DeviceName>,
53 flag_align: Option<AlignArg>,
54 cmd_sizes: bool,
55 cmd_run: bool,
56 cmd_runall: bool,
57}
58
59#[derive(Copy, Clone, Debug, Deserialize)]
David Browndecbd042017-10-19 10:43:17 -060060pub enum DeviceName { Stm32f4, K64f, K64fBig, Nrf52840 }
David Brown2639e072017-10-11 11:18:44 -060061
David Browndd2b1182017-11-02 15:39:21 -060062pub static ALL_DEVICES: &'static [DeviceName] = &[
David Brown2639e072017-10-11 11:18:44 -060063 DeviceName::Stm32f4,
64 DeviceName::K64f,
65 DeviceName::K64fBig,
66 DeviceName::Nrf52840,
67];
68
69impl fmt::Display for DeviceName {
70 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
71 let name = match *self {
72 DeviceName::Stm32f4 => "stm32f4",
73 DeviceName::K64f => "k64f",
74 DeviceName::K64fBig => "k64fbig",
75 DeviceName::Nrf52840 => "nrf52840",
76 };
77 f.write_str(name)
78 }
79}
80
81#[derive(Debug)]
82struct AlignArg(u8);
83
84struct AlignArgVisitor;
85
86impl<'de> serde::de::Visitor<'de> for AlignArgVisitor {
87 type Value = AlignArg;
88
89 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
90 formatter.write_str("1, 2, 4 or 8")
91 }
92
93 fn visit_u8<E>(self, n: u8) -> Result<Self::Value, E>
94 where E: serde::de::Error
95 {
96 Ok(match n {
97 1 | 2 | 4 | 8 => AlignArg(n),
98 n => {
99 let err = format!("Could not deserialize '{}' as alignment", n);
100 return Err(E::custom(err));
101 }
102 })
103 }
104}
105
106impl<'de> serde::de::Deserialize<'de> for AlignArg {
107 fn deserialize<D>(d: D) -> Result<AlignArg, D::Error>
108 where D: serde::de::Deserializer<'de>
109 {
110 d.deserialize_u8(AlignArgVisitor)
111 }
112}
113
114pub fn main() {
115 let args: Args = Docopt::new(USAGE)
116 .and_then(|d| d.deserialize())
117 .unwrap_or_else(|e| e.exit());
118 // println!("args: {:#?}", args);
119
120 if args.cmd_sizes {
121 show_sizes();
122 return;
123 }
124
125 let mut status = RunStatus::new();
126 if args.cmd_run {
127
128 let align = args.flag_align.map(|x| x.0).unwrap_or(1);
129
130
131 let device = match args.flag_device {
132 None => panic!("Missing mandatory device argument"),
133 Some(dev) => dev,
134 };
135
136 status.run_single(device, align);
137 }
138
139 if args.cmd_runall {
140 for &dev in ALL_DEVICES {
141 for &align in &[1, 2, 4, 8] {
142 status.run_single(dev, align);
143 }
144 }
145 }
146
147 if status.failures > 0 {
148 error!("{} Tests ran with {} failures", status.failures + status.passes, status.failures);
149 process::exit(1);
150 } else {
151 error!("{} Tests ran successfully", status.passes);
152 process::exit(0);
153 }
154}
155
David Browndd2b1182017-11-02 15:39:21 -0600156pub struct RunStatus {
David Brown2639e072017-10-11 11:18:44 -0600157 failures: usize,
158 passes: usize,
159}
160
161impl RunStatus {
David Browndd2b1182017-11-02 15:39:21 -0600162 pub fn new() -> RunStatus {
David Brown2639e072017-10-11 11:18:44 -0600163 RunStatus {
164 failures: 0,
165 passes: 0,
166 }
167 }
168
David Browndd2b1182017-11-02 15:39:21 -0600169 pub fn run_single(&mut self, device: DeviceName, align: u8) {
David Brown2639e072017-10-11 11:18:44 -0600170 warn!("Running on device {} with alignment {}", device, align);
171
David Browndecbd042017-10-19 10:43:17 -0600172 let (mut flash, areadesc) = make_device(device, align);
David Brown2639e072017-10-11 11:18:44 -0600173
174 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
175 let (slot1_base, slot1_len) = areadesc.find(FlashId::Image1);
176 let (scratch_base, _) = areadesc.find(FlashId::ImageScratch);
177
178 // Code below assumes that the slots are consecutive.
179 assert_eq!(slot1_base, slot0_base + slot0_len);
180 assert_eq!(scratch_base, slot1_base + slot1_len);
181
182 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 2;
183
184 // println!("Areas: {:#?}", areadesc.get_c());
185
186 // Install the boot trailer signature, so that the code will start an upgrade.
187 // TODO: This must be a multiple of flash alignment, add support for an image that is smaller,
188 // and just gets padded.
189
190 // Create original and upgrade images
191 let slot0 = SlotInfo {
192 base_off: slot0_base as usize,
193 trailer_off: slot1_base - offset_from_end,
194 };
195
196 let slot1 = SlotInfo {
197 base_off: slot1_base as usize,
198 trailer_off: scratch_base - offset_from_end,
199 };
200
201 // Set an alignment, and position the magic value.
202 c::set_sim_flash_align(align);
203
204 let mut failed = false;
205
206 // Creates a badly signed image in slot1 to check that it is not
207 // upgraded to
208 let mut bad_flash = flash.clone();
209 let bad_slot1_image = Images {
David Brownd5e632c2017-10-19 10:49:46 -0600210 slot0: slot0.clone(),
211 slot1: slot1.clone(),
David Brown2639e072017-10-11 11:18:44 -0600212 primary: install_image(&mut bad_flash, slot0_base, 32784, false),
213 upgrade: install_image(&mut bad_flash, slot1_base, 41928, true),
214 };
215
216 failed |= run_signfail_upgrade(&bad_flash, &areadesc, &bad_slot1_image);
217
218 let images = Images {
David Brownd5e632c2017-10-19 10:49:46 -0600219 slot0: slot0.clone(),
220 slot1: slot1.clone(),
David Brown2639e072017-10-11 11:18:44 -0600221 primary: install_image(&mut flash, slot0_base, 32784, false),
222 upgrade: install_image(&mut flash, slot1_base, 41928, false),
223 };
224
225 failed |= run_norevert_newimage(&flash, &areadesc, &images);
226
227 mark_upgrade(&mut flash, &images.slot1);
228
229 // upgrades without fails, counts number of flash operations
230 let total_count = match run_basic_upgrade(&flash, &areadesc, &images) {
231 Ok(v) => v,
232 Err(_) => {
233 self.failures += 1;
234 return;
235 },
236 };
237
238 failed |= run_basic_revert(&flash, &areadesc, &images);
239 failed |= run_revert_with_fails(&flash, &areadesc, &images, total_count);
240 failed |= run_perm_with_fails(&flash, &areadesc, &images, total_count);
241 failed |= run_perm_with_random_fails(&flash, &areadesc, &images,
242 total_count, 5);
243 failed |= run_norevert(&flash, &areadesc, &images);
244
245 //show_flash(&flash);
246
247 if failed {
248 self.failures += 1;
249 } else {
250 self.passes += 1;
251 }
252 }
David Browndd2b1182017-11-02 15:39:21 -0600253
254 pub fn failures(&self) -> usize {
255 self.failures
256 }
David Brown2639e072017-10-11 11:18:44 -0600257}
258
David Browndecbd042017-10-19 10:43:17 -0600259/// Build the Flash and area descriptor for a given device.
260pub fn make_device(device: DeviceName, align: u8) -> (SimFlash, AreaDesc) {
261 match device {
262 DeviceName::Stm32f4 => {
263 // STM style flash. Large sectors, with a large scratch area.
264 let flash = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
265 64 * 1024,
266 128 * 1024, 128 * 1024, 128 * 1024],
267 align as usize);
268 let mut areadesc = AreaDesc::new(&flash);
269 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
270 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
271 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch);
272 (flash, areadesc)
273 }
274 DeviceName::K64f => {
275 // NXP style flash. Small sectors, one small sector for scratch.
276 let flash = SimFlash::new(vec![4096; 128], align as usize);
277
278 let mut areadesc = AreaDesc::new(&flash);
279 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
280 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
281 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch);
282 (flash, areadesc)
283 }
284 DeviceName::K64fBig => {
285 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
286 // uses small sectors, but we tell the bootloader they are large.
287 let flash = SimFlash::new(vec![4096; 128], align as usize);
288
289 let mut areadesc = AreaDesc::new(&flash);
290 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0);
291 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1);
292 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch);
293 (flash, areadesc)
294 }
295 DeviceName::Nrf52840 => {
296 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
297 // does not divide into the image size.
298 let flash = SimFlash::new(vec![4096; 128], align as usize);
299
300 let mut areadesc = AreaDesc::new(&flash);
301 areadesc.add_image(0x008000, 0x034000, FlashId::Image0);
302 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1);
303 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch);
304 (flash, areadesc)
305 }
306 }
307}
308
David Brown2639e072017-10-11 11:18:44 -0600309/// A simple upgrade without forced failures.
310///
311/// Returns the number of flash operations which can later be used to
312/// inject failures at chosen steps.
313fn run_basic_upgrade(flash: &SimFlash, areadesc: &AreaDesc, images: &Images)
314 -> Result<i32, ()> {
315 let (fl, total_count) = try_upgrade(&flash, &areadesc, &images, None);
316 info!("Total flash operation count={}", total_count);
317
318 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
319 warn!("Image mismatch after first boot");
320 Err(())
321 } else {
322 Ok(total_count)
323 }
324}
325
326#[cfg(feature = "overwrite-only")]
327#[allow(unused_variables)]
328fn run_basic_revert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool {
329 false
330}
331
332#[cfg(not(feature = "overwrite-only"))]
333fn run_basic_revert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool {
334 let mut fails = 0;
335
336 // FIXME: this test would also pass if no swap is ever performed???
337 if Caps::SwapUpgrade.present() {
338 for count in 2 .. 5 {
339 info!("Try revert: {}", count);
340 let fl = try_revert(&flash, &areadesc, count);
341 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
342 error!("Revert failure on count {}", count);
343 fails += 1;
344 }
345 }
346 }
347
348 fails > 0
349}
350
351fn run_perm_with_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
352 total_flash_ops: i32) -> bool {
353 let mut fails = 0;
354
355 // Let's try an image halfway through.
356 for i in 1 .. total_flash_ops {
357 info!("Try interruption at {}", i);
358 let (fl, count) = try_upgrade(&flash, &areadesc, &images, Some(i));
359 info!("Second boot, count={}", count);
360 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
361 warn!("FAIL at step {} of {}", i, total_flash_ops);
362 fails += 1;
363 }
364
365 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
366 COPY_DONE) {
367 warn!("Mismatched trailer for Slot 0");
368 fails += 1;
369 }
370
371 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
372 UNSET) {
373 warn!("Mismatched trailer for Slot 1");
374 fails += 1;
375 }
376
377 if Caps::SwapUpgrade.present() {
378 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
379 warn!("Slot 1 FAIL at step {} of {}", i, total_flash_ops);
380 fails += 1;
381 }
382 }
383 }
384
385 if fails > 0 {
386 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
387 fails as f32 * 100.0 / total_flash_ops as f32);
388 }
389
390 fails > 0
391}
392
393fn run_perm_with_random_fails(flash: &SimFlash, areadesc: &AreaDesc,
394 images: &Images, total_flash_ops: i32,
395 total_fails: usize) -> bool {
396 let mut fails = 0;
397 let (fl, total_counts) = try_random_fails(&flash, &areadesc, &images,
398 total_flash_ops, total_fails);
399 info!("Random interruptions at reset points={:?}", total_counts);
400
401 let slot0_ok = verify_image(&fl, images.slot0.base_off, &images.upgrade);
402 let slot1_ok = if Caps::SwapUpgrade.present() {
403 verify_image(&fl, images.slot1.base_off, &images.primary)
404 } else {
405 true
406 };
407 if !slot0_ok || !slot1_ok {
408 error!("Image mismatch after random interrupts: slot0={} slot1={}",
409 if slot0_ok { "ok" } else { "fail" },
410 if slot1_ok { "ok" } else { "fail" });
411 fails += 1;
412 }
413 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
414 COPY_DONE) {
415 error!("Mismatched trailer for Slot 0");
416 fails += 1;
417 }
418 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
419 UNSET) {
420 error!("Mismatched trailer for Slot 1");
421 fails += 1;
422 }
423
424 if fails > 0 {
425 error!("Error testing perm upgrade with {} fails", total_fails);
426 }
427
428 fails > 0
429}
430
431#[cfg(feature = "overwrite-only")]
432#[allow(unused_variables)]
433fn run_revert_with_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
434 total_count: i32) -> bool {
435 false
436}
437
438#[cfg(not(feature = "overwrite-only"))]
439fn run_revert_with_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
440 total_count: i32) -> bool {
441 let mut fails = 0;
442
443 if Caps::SwapUpgrade.present() {
444 for i in 1 .. (total_count - 1) {
445 info!("Try interruption at {}", i);
446 if try_revert_with_fail_at(&flash, &areadesc, &images, i) {
447 error!("Revert failed at interruption {}", i);
448 fails += 1;
449 }
450 }
451 }
452
453 fails > 0
454}
455
456#[cfg(feature = "overwrite-only")]
457#[allow(unused_variables)]
458fn run_norevert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool {
459 false
460}
461
462#[cfg(not(feature = "overwrite-only"))]
463fn run_norevert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool {
464 let mut fl = flash.clone();
465 let mut fails = 0;
466
467 info!("Try norevert");
David Brown2639e072017-10-11 11:18:44 -0600468
469 // First do a normal upgrade...
David Brownee61c832017-11-06 11:13:25 -0700470 if c::boot_go(&mut fl, &areadesc, None) != 0 {
David Brown2639e072017-10-11 11:18:44 -0600471 warn!("Failed first boot");
472 fails += 1;
473 }
474
475 //FIXME: copy_done is written by boot_go, is it ok if no copy
476 // was ever done?
477
478 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
479 warn!("Slot 0 image verification FAIL");
480 fails += 1;
481 }
482 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
483 COPY_DONE) {
484 warn!("Mismatched trailer for Slot 0");
485 fails += 1;
486 }
487 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
488 UNSET) {
489 warn!("Mismatched trailer for Slot 1");
490 fails += 1;
491 }
492
493 // Marks image in slot0 as permanent, no revert should happen...
494 mark_permanent_upgrade(&mut fl, &images.slot0);
495
496 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
497 COPY_DONE) {
498 warn!("Mismatched trailer for Slot 0");
499 fails += 1;
500 }
501
David Brownee61c832017-11-06 11:13:25 -0700502 if c::boot_go(&mut fl, &areadesc, None) != 0 {
David Brown2639e072017-10-11 11:18:44 -0600503 warn!("Failed second boot");
504 fails += 1;
505 }
506
507 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
508 COPY_DONE) {
509 warn!("Mismatched trailer for Slot 0");
510 fails += 1;
511 }
512 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
513 warn!("Failed image verification");
514 fails += 1;
515 }
516
517 if fails > 0 {
518 error!("Error running upgrade without revert");
519 }
520
521 fails > 0
522}
523
524// Tests a new image written to slot0 that already has magic and image_ok set
525// while there is no image on slot1, so no revert should ever happen...
526fn run_norevert_newimage(flash: &SimFlash, areadesc: &AreaDesc,
527 images: &Images) -> bool {
528 let mut fl = flash.clone();
529 let mut fails = 0;
530
531 info!("Try non-revert on imgtool generated image");
David Brown2639e072017-10-11 11:18:44 -0600532
533 mark_upgrade(&mut fl, &images.slot0);
534
535 // This simulates writing an image created by imgtool to Slot 0
536 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET, UNSET) {
537 warn!("Mismatched trailer for Slot 0");
538 fails += 1;
539 }
540
541 // Run the bootloader...
David Brownee61c832017-11-06 11:13:25 -0700542 if c::boot_go(&mut fl, &areadesc, None) != 0 {
David Brown2639e072017-10-11 11:18:44 -0600543 warn!("Failed first boot");
544 fails += 1;
545 }
546
547 // State should not have changed
548 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
549 warn!("Failed image verification");
550 fails += 1;
551 }
552 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
553 UNSET) {
554 warn!("Mismatched trailer for Slot 0");
555 fails += 1;
556 }
557 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
558 UNSET) {
559 warn!("Mismatched trailer for Slot 1");
560 fails += 1;
561 }
562
563 if fails > 0 {
564 error!("Expected a non revert with new image");
565 }
566
567 fails > 0
568}
569
570// Tests a new image written to slot0 that already has magic and image_ok set
571// while there is no image on slot1, so no revert should ever happen...
572fn run_signfail_upgrade(flash: &SimFlash, areadesc: &AreaDesc,
573 images: &Images) -> bool {
574 let mut fl = flash.clone();
575 let mut fails = 0;
576
577 info!("Try upgrade image with bad signature");
David Brown2639e072017-10-11 11:18:44 -0600578
579 mark_upgrade(&mut fl, &images.slot0);
580 mark_permanent_upgrade(&mut fl, &images.slot0);
581 mark_upgrade(&mut fl, &images.slot1);
582
583 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
584 UNSET) {
585 warn!("Mismatched trailer for Slot 0");
586 fails += 1;
587 }
588
589 // Run the bootloader...
David Brownee61c832017-11-06 11:13:25 -0700590 if c::boot_go(&mut fl, &areadesc, None) != 0 {
David Brown2639e072017-10-11 11:18:44 -0600591 warn!("Failed first boot");
592 fails += 1;
593 }
594
595 // State should not have changed
596 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
597 warn!("Failed image verification");
598 fails += 1;
599 }
600 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
601 UNSET) {
602 warn!("Mismatched trailer for Slot 0");
603 fails += 1;
604 }
605
606 if fails > 0 {
607 error!("Expected an upgrade failure when image has bad signature");
608 }
609
610 fails > 0
611}
612
613/// Test a boot, optionally stopping after 'n' flash options. Returns a count
614/// of the number of flash operations done total.
615fn try_upgrade(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
616 stop: Option<i32>) -> (SimFlash, i32) {
617 // Clone the flash to have a new copy.
618 let mut fl = flash.clone();
619
620 mark_permanent_upgrade(&mut fl, &images.slot1);
621
David Brownee61c832017-11-06 11:13:25 -0700622 let mut counter = stop.unwrap_or(0);
623
624 let (first_interrupted, count) = match c::boot_go(&mut fl, &areadesc, Some(&mut counter)) {
David Brown2639e072017-10-11 11:18:44 -0600625 -0x13579 => (true, stop.unwrap()),
David Brownee61c832017-11-06 11:13:25 -0700626 0 => (false, -counter),
David Brown2639e072017-10-11 11:18:44 -0600627 x => panic!("Unknown return: {}", x),
628 };
David Brown2639e072017-10-11 11:18:44 -0600629
David Brownee61c832017-11-06 11:13:25 -0700630 counter = 0;
David Brown2639e072017-10-11 11:18:44 -0600631 if first_interrupted {
632 // fl.dump();
David Brownee61c832017-11-06 11:13:25 -0700633 match c::boot_go(&mut fl, &areadesc, Some(&mut counter)) {
David Brown2639e072017-10-11 11:18:44 -0600634 -0x13579 => panic!("Shouldn't stop again"),
635 0 => (),
636 x => panic!("Unknown return: {}", x),
637 }
638 }
639
David Brownee61c832017-11-06 11:13:25 -0700640 (fl, count - counter)
David Brown2639e072017-10-11 11:18:44 -0600641}
642
643#[cfg(not(feature = "overwrite-only"))]
644fn try_revert(flash: &SimFlash, areadesc: &AreaDesc, count: usize) -> SimFlash {
645 let mut fl = flash.clone();
David Brown2639e072017-10-11 11:18:44 -0600646
647 // fl.write_file("image0.bin").unwrap();
648 for i in 0 .. count {
649 info!("Running boot pass {}", i + 1);
David Brownee61c832017-11-06 11:13:25 -0700650 assert_eq!(c::boot_go(&mut fl, &areadesc, None), 0);
David Brown2639e072017-10-11 11:18:44 -0600651 }
652 fl
653}
654
655#[cfg(not(feature = "overwrite-only"))]
656fn try_revert_with_fail_at(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
657 stop: i32) -> bool {
658 let mut fl = flash.clone();
659 let mut x: i32;
660 let mut fails = 0;
661
David Brownee61c832017-11-06 11:13:25 -0700662 let mut counter = stop;
663 x = c::boot_go(&mut fl, &areadesc, Some(&mut counter));
David Brown2639e072017-10-11 11:18:44 -0600664 if x != -0x13579 {
665 warn!("Should have stopped at interruption point");
666 fails += 1;
667 }
668
669 if !verify_trailer(&fl, images.slot0.trailer_off, None, None, UNSET) {
670 warn!("copy_done should be unset");
671 fails += 1;
672 }
673
David Brownee61c832017-11-06 11:13:25 -0700674 x = c::boot_go(&mut fl, &areadesc, None);
David Brown2639e072017-10-11 11:18:44 -0600675 if x != 0 {
676 warn!("Should have finished upgrade");
677 fails += 1;
678 }
679
680 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
681 warn!("Image in slot 0 before revert is invalid at stop={}", stop);
682 fails += 1;
683 }
684 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
685 warn!("Image in slot 1 before revert is invalid at stop={}", stop);
686 fails += 1;
687 }
688 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
689 COPY_DONE) {
690 warn!("Mismatched trailer for Slot 0 before revert");
691 fails += 1;
692 }
693 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
694 UNSET) {
695 warn!("Mismatched trailer for Slot 1 before revert");
696 fails += 1;
697 }
698
699 // Do Revert
David Brownee61c832017-11-06 11:13:25 -0700700 x = c::boot_go(&mut fl, &areadesc, None);
David Brown2639e072017-10-11 11:18:44 -0600701 if x != 0 {
702 warn!("Should have finished a revert");
703 fails += 1;
704 }
705
706 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
707 warn!("Image in slot 0 after revert is invalid at stop={}", stop);
708 fails += 1;
709 }
710 if !verify_image(&fl, images.slot1.base_off, &images.upgrade) {
711 warn!("Image in slot 1 after revert is invalid at stop={}", stop);
712 fails += 1;
713 }
714 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
715 COPY_DONE) {
716 warn!("Mismatched trailer for Slot 1 after revert");
717 fails += 1;
718 }
719 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
720 UNSET) {
721 warn!("Mismatched trailer for Slot 1 after revert");
722 fails += 1;
723 }
724
725 fails > 0
726}
727
728fn try_random_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
729 total_ops: i32, count: usize) -> (SimFlash, Vec<i32>) {
730 let mut fl = flash.clone();
731
732 mark_permanent_upgrade(&mut fl, &images.slot1);
733
734 let mut rng = rand::thread_rng();
735 let mut resets = vec![0i32; count];
736 let mut remaining_ops = total_ops;
737 for i in 0 .. count {
738 let ops = Range::new(1, remaining_ops / 2);
739 let reset_counter = ops.ind_sample(&mut rng);
David Brownee61c832017-11-06 11:13:25 -0700740 let mut counter = reset_counter;
741 match c::boot_go(&mut fl, &areadesc, Some(&mut counter)) {
David Brown2639e072017-10-11 11:18:44 -0600742 0 | -0x13579 => (),
743 x => panic!("Unknown return: {}", x),
744 }
745 remaining_ops -= reset_counter;
746 resets[i] = reset_counter;
747 }
748
David Brownee61c832017-11-06 11:13:25 -0700749 match c::boot_go(&mut fl, &areadesc, None) {
David Brown2639e072017-10-11 11:18:44 -0600750 -0x13579 => panic!("Should not be have been interrupted!"),
751 0 => (),
752 x => panic!("Unknown return: {}", x),
753 }
754
755 (fl, resets)
756}
757
758/// Show the flash layout.
759#[allow(dead_code)]
760fn show_flash(flash: &Flash) {
761 println!("---- Flash configuration ----");
762 for sector in flash.sector_iter() {
763 println!(" {:3}: 0x{:08x}, 0x{:08x}",
764 sector.num, sector.base, sector.size);
765 }
766 println!("");
767}
768
769/// Install a "program" into the given image. This fakes the image header, or at least all of the
770/// fields used by the given code. Returns a copy of the image that was written.
771fn install_image(flash: &mut Flash, offset: usize, len: usize,
772 bad_sig: bool) -> Vec<u8> {
773 let offset0 = offset;
774
775 let mut tlv = make_tlv();
776
777 // Generate a boot header. Note that the size doesn't include the header.
778 let header = ImageHeader {
779 magic: 0x96f3b83d,
780 tlv_size: tlv.get_size(),
781 _pad1: 0,
782 hdr_size: 32,
783 key_id: 0,
784 _pad2: 0,
785 img_size: len as u32,
786 flags: tlv.get_flags(),
787 ver: ImageVersion {
788 major: (offset / (128 * 1024)) as u8,
789 minor: 0,
790 revision: 1,
791 build_num: offset as u32,
792 },
793 _pad3: 0,
794 };
795
796 let b_header = header.as_raw();
797 tlv.add_bytes(&b_header);
798 /*
799 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
800 mem::size_of::<ImageHeader>()) };
801 */
802 assert_eq!(b_header.len(), 32);
803 flash.write(offset, &b_header).unwrap();
804 let offset = offset + b_header.len();
805
806 // The core of the image itself is just pseudorandom data.
807 let mut buf = vec![0; len];
808 splat(&mut buf, offset);
809 tlv.add_bytes(&buf);
810
811 // Get and append the TLV itself.
812 if bad_sig {
813 let good_sig = &mut tlv.make_tlv();
814 buf.append(&mut vec![0; good_sig.len()]);
815 } else {
816 buf.append(&mut tlv.make_tlv());
817 }
818
819 // Pad the block to a flash alignment (8 bytes).
820 while buf.len() % 8 != 0 {
821 buf.push(0xFF);
822 }
823
824 flash.write(offset, &buf).unwrap();
825 let offset = offset + buf.len();
826
827 // Copy out the image so that we can verify that the image was installed correctly later.
828 let mut copy = vec![0u8; offset - offset0];
829 flash.read(offset0, &mut copy).unwrap();
830
831 copy
832}
833
834// The TLV in use depends on what kind of signature we are verifying.
835#[cfg(feature = "sig-rsa")]
836fn make_tlv() -> TlvGen {
837 TlvGen::new_rsa_pss()
838}
839
840#[cfg(not(feature = "sig-rsa"))]
841fn make_tlv() -> TlvGen {
842 TlvGen::new_hash_only()
843}
844
845/// Verify that given image is present in the flash at the given offset.
846fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
847 let mut copy = vec![0u8; buf.len()];
848 flash.read(offset, &mut copy).unwrap();
849
850 if buf != &copy[..] {
851 for i in 0 .. buf.len() {
852 if buf[i] != copy[i] {
853 info!("First failure at {:#x}", offset + i);
854 break;
855 }
856 }
857 false
858 } else {
859 true
860 }
861}
862
863#[cfg(feature = "overwrite-only")]
864#[allow(unused_variables)]
865// overwrite-only doesn't employ trailer management
866fn verify_trailer(flash: &Flash, offset: usize,
867 magic: Option<&[u8]>, image_ok: Option<u8>,
868 copy_done: Option<u8>) -> bool {
869 true
870}
871
872#[cfg(not(feature = "overwrite-only"))]
873fn verify_trailer(flash: &Flash, offset: usize,
874 magic: Option<&[u8]>, image_ok: Option<u8>,
875 copy_done: Option<u8>) -> bool {
876 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 2];
877 let mut failed = false;
878
879 flash.read(offset, &mut copy).unwrap();
880
881 failed |= match magic {
882 Some(v) => {
883 if &copy[16..] != v {
884 warn!("\"magic\" mismatch at {:#x}", offset);
885 true
886 } else {
887 false
888 }
889 },
890 None => false,
891 };
892
893 failed |= match image_ok {
894 Some(v) => {
895 if copy[8] != v {
896 warn!("\"image_ok\" mismatch at {:#x}", offset);
897 true
898 } else {
899 false
900 }
901 },
902 None => false,
903 };
904
905 failed |= match copy_done {
906 Some(v) => {
907 if copy[0] != v {
908 warn!("\"copy_done\" mismatch at {:#x}", offset);
909 true
910 } else {
911 false
912 }
913 },
914 None => false,
915 };
916
917 !failed
918}
919
920/// The image header
921#[repr(C)]
922pub struct ImageHeader {
923 magic: u32,
924 tlv_size: u16,
925 key_id: u8,
926 _pad1: u8,
927 hdr_size: u16,
928 _pad2: u16,
929 img_size: u32,
930 flags: u32,
931 ver: ImageVersion,
932 _pad3: u32,
933}
934
935impl AsRaw for ImageHeader {}
936
937#[repr(C)]
938pub struct ImageVersion {
939 major: u8,
940 minor: u8,
941 revision: u16,
942 build_num: u32,
943}
944
David Brownd5e632c2017-10-19 10:49:46 -0600945#[derive(Clone)]
David Brown2639e072017-10-11 11:18:44 -0600946struct SlotInfo {
947 base_off: usize,
948 trailer_off: usize,
949}
950
David Brownd5e632c2017-10-19 10:49:46 -0600951struct Images {
952 slot0: SlotInfo,
953 slot1: SlotInfo,
David Brown2639e072017-10-11 11:18:44 -0600954 primary: Vec<u8>,
955 upgrade: Vec<u8>,
956}
957
958const MAGIC_VALID: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3,
959 0x60, 0xd2, 0xef, 0x7f,
960 0x35, 0x52, 0x50, 0x0f,
961 0x2c, 0xb6, 0x79, 0x80]);
962const MAGIC_UNSET: Option<&[u8]> = Some(&[0xff; 16]);
963
964const COPY_DONE: Option<u8> = Some(1);
965const IMAGE_OK: Option<u8> = Some(1);
966const UNSET: Option<u8> = Some(0xff);
967
968/// Write out the magic so that the loader tries doing an upgrade.
969fn mark_upgrade(flash: &mut Flash, slot: &SlotInfo) {
970 let offset = slot.trailer_off + c::boot_max_align() * 2;
971 flash.write(offset, MAGIC_VALID.unwrap()).unwrap();
972}
973
974/// Writes the image_ok flag which, guess what, tells the bootloader
975/// the this image is ok (not a test, and no revert is to be performed).
976fn mark_permanent_upgrade(flash: &mut Flash, slot: &SlotInfo) {
977 let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
978 let align = c::get_sim_flash_align() as usize;
979 let off = slot.trailer_off + c::boot_max_align();
980 flash.write(off, &ok[..align]).unwrap();
981}
982
983// Drop some pseudo-random gibberish onto the data.
984fn splat(data: &mut [u8], seed: usize) {
985 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
986 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
987 rng.fill_bytes(data);
988}
989
990/// Return a read-only view into the raw bytes of this object
991trait AsRaw : Sized {
992 fn as_raw<'a>(&'a self) -> &'a [u8] {
993 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
994 mem::size_of::<Self>()) }
995 }
996}
997
998fn show_sizes() {
999 // This isn't panic safe.
1000 let old_align = c::get_sim_flash_align();
1001 for min in &[1, 2, 4, 8] {
1002 c::set_sim_flash_align(*min);
1003 let msize = c::boot_trailer_sz();
1004 println!("{:2}: {} (0x{:x})", min, msize, msize);
1005 }
1006 c::set_sim_flash_align(old_align);
1007}