blob: cddb48c887e466d61fd024aa89264c92f18b7edf [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
Fabio Utzigb841f0a2017-11-24 08:11:05 -0200176 // NOTE: not accounting "swap_size" because it is not used by sim...
David Browndb9a3952017-11-06 13:16:15 -0700177 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 2;
178
179 // Construct a primary image.
180 let slot0 = SlotInfo {
181 base_off: slot0_base as usize,
182 trailer_off: slot1_base - offset_from_end,
183 };
184
185 // And an upgrade image.
186 let slot1 = SlotInfo {
187 base_off: slot1_base as usize,
188 trailer_off: scratch_base - offset_from_end,
189 };
190
191 Run {
192 flash: flash,
193 areadesc: areadesc,
194 slots: [slot0, slot1],
195 align: align,
196 }
197 }
198
199 pub fn each_device<F>(f: F)
200 where F: Fn(&mut Run)
201 {
202 for &dev in ALL_DEVICES {
203 for &align in &[1, 2, 4, 8] {
204 let mut run = Run::new(dev, align);
205 f(&mut run);
206 }
207 }
208 }
David Brownf48b9502017-11-06 14:00:26 -0700209
210 /// Construct an `Images` that doesn't expect an upgrade to happen.
211 pub fn make_no_upgrade_image(&self) -> Images {
212 let mut flash = self.flash.clone();
213 let primary = install_image(&mut flash, self.slots[0].base_off, 32784, false);
214 let upgrade = install_image(&mut flash, self.slots[1].base_off, 41928, false);
215 Images {
216 flash: flash,
217 areadesc: self.areadesc.clone(),
218 slot0: self.slots[0].clone(),
219 slot1: self.slots[1].clone(),
220 primary: primary,
221 upgrade: upgrade,
David Brownc49811e2017-11-06 14:20:45 -0700222 total_count: None,
David Brownf48b9502017-11-06 14:00:26 -0700223 align: self.align,
224 }
225 }
226
227 /// Construct an `Images` for normal testing.
228 pub fn make_image(&self) -> Images {
229 let mut images = self.make_no_upgrade_image();
230 mark_upgrade(&mut images.flash, &images.slot1);
David Brownc49811e2017-11-06 14:20:45 -0700231
232 // upgrades without fails, counts number of flash operations
233 let total_count = match images.run_basic_upgrade() {
234 Ok(v) => v,
235 Err(_) => {
236 panic!("Unable to perform basic upgrade");
237 },
238 };
239
240 images.total_count = Some(total_count);
David Brownf48b9502017-11-06 14:00:26 -0700241 images
242 }
243
244 pub fn make_bad_slot1_image(&self) -> Images {
245 let mut bad_flash = self.flash.clone();
246 let primary = install_image(&mut bad_flash, self.slots[0].base_off, 32784, false);
247 let upgrade = install_image(&mut bad_flash, self.slots[1].base_off, 41928, true);
248 Images {
249 flash: bad_flash,
250 areadesc: self.areadesc.clone(),
251 slot0: self.slots[0].clone(),
252 slot1: self.slots[1].clone(),
253 primary: primary,
254 upgrade: upgrade,
David Brownc49811e2017-11-06 14:20:45 -0700255 total_count: None,
David Brownf48b9502017-11-06 14:00:26 -0700256 align: self.align,
257 }
258 }
David Brownc49811e2017-11-06 14:20:45 -0700259
David Browndb9a3952017-11-06 13:16:15 -0700260}
261
David Browndd2b1182017-11-02 15:39:21 -0600262pub struct RunStatus {
David Brown2639e072017-10-11 11:18:44 -0600263 failures: usize,
264 passes: usize,
265}
266
267impl RunStatus {
David Browndd2b1182017-11-02 15:39:21 -0600268 pub fn new() -> RunStatus {
David Brown2639e072017-10-11 11:18:44 -0600269 RunStatus {
270 failures: 0,
271 passes: 0,
272 }
273 }
274
David Browndd2b1182017-11-02 15:39:21 -0600275 pub fn run_single(&mut self, device: DeviceName, align: u8) {
David Brown2639e072017-10-11 11:18:44 -0600276 warn!("Running on device {} with alignment {}", device, align);
277
David Browndc9cba12017-11-06 13:31:42 -0700278 let run = Run::new(device, align);
David Brown2639e072017-10-11 11:18:44 -0600279
David Brown2639e072017-10-11 11:18:44 -0600280 let mut failed = false;
281
282 // Creates a badly signed image in slot1 to check that it is not
283 // upgraded to
David Brownf48b9502017-11-06 14:00:26 -0700284 let bad_slot1_image = run.make_bad_slot1_image();
David Brown2639e072017-10-11 11:18:44 -0600285
David Brown5f7ec2b2017-11-06 13:54:02 -0700286 failed |= bad_slot1_image.run_signfail_upgrade();
David Brown2639e072017-10-11 11:18:44 -0600287
David Brownf48b9502017-11-06 14:00:26 -0700288 let images = run.make_no_upgrade_image();
David Brown5f7ec2b2017-11-06 13:54:02 -0700289 failed |= images.run_norevert_newimage();
David Brown2639e072017-10-11 11:18:44 -0600290
David Brownf48b9502017-11-06 14:00:26 -0700291 let images = run.make_image();
David Brown2639e072017-10-11 11:18:44 -0600292
David Brown5f7ec2b2017-11-06 13:54:02 -0700293 failed |= images.run_basic_revert();
David Brownc49811e2017-11-06 14:20:45 -0700294 failed |= images.run_revert_with_fails();
295 failed |= images.run_perm_with_fails();
296 failed |= images.run_perm_with_random_fails(5);
David Brown5f7ec2b2017-11-06 13:54:02 -0700297 failed |= images.run_norevert();
David Brown2639e072017-10-11 11:18:44 -0600298
Fabio Utzigb841f0a2017-11-24 08:11:05 -0200299 failed |= images.run_with_status_fails_complete();
300
David Brown2639e072017-10-11 11:18:44 -0600301 //show_flash(&flash);
302
303 if failed {
304 self.failures += 1;
305 } else {
306 self.passes += 1;
307 }
308 }
David Browndd2b1182017-11-02 15:39:21 -0600309
310 pub fn failures(&self) -> usize {
311 self.failures
312 }
David Brown2639e072017-10-11 11:18:44 -0600313}
314
David Browndecbd042017-10-19 10:43:17 -0600315/// Build the Flash and area descriptor for a given device.
316pub fn make_device(device: DeviceName, align: u8) -> (SimFlash, AreaDesc) {
317 match device {
318 DeviceName::Stm32f4 => {
319 // STM style flash. Large sectors, with a large scratch area.
320 let flash = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
321 64 * 1024,
322 128 * 1024, 128 * 1024, 128 * 1024],
323 align as usize);
324 let mut areadesc = AreaDesc::new(&flash);
325 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
326 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
327 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch);
328 (flash, areadesc)
329 }
330 DeviceName::K64f => {
331 // NXP style flash. Small sectors, one small sector for scratch.
332 let flash = SimFlash::new(vec![4096; 128], align as usize);
333
334 let mut areadesc = AreaDesc::new(&flash);
335 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
336 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
337 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch);
338 (flash, areadesc)
339 }
340 DeviceName::K64fBig => {
341 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
342 // uses small sectors, but we tell the bootloader they are large.
343 let flash = SimFlash::new(vec![4096; 128], align as usize);
344
345 let mut areadesc = AreaDesc::new(&flash);
346 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0);
347 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1);
348 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch);
349 (flash, areadesc)
350 }
351 DeviceName::Nrf52840 => {
352 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
353 // does not divide into the image size.
354 let flash = SimFlash::new(vec![4096; 128], align as usize);
355
356 let mut areadesc = AreaDesc::new(&flash);
357 areadesc.add_image(0x008000, 0x034000, FlashId::Image0);
358 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1);
359 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch);
360 (flash, areadesc)
361 }
362 }
363}
364
David Brown5f7ec2b2017-11-06 13:54:02 -0700365impl Images {
366 /// A simple upgrade without forced failures.
367 ///
368 /// Returns the number of flash operations which can later be used to
369 /// inject failures at chosen steps.
David Brownc49811e2017-11-06 14:20:45 -0700370 pub fn run_basic_upgrade(&self) -> Result<i32, ()> {
David Brown5f7ec2b2017-11-06 13:54:02 -0700371 let (fl, total_count) = try_upgrade(&self.flash, &self, None);
372 info!("Total flash operation count={}", total_count);
David Brown2639e072017-10-11 11:18:44 -0600373
David Brown5f7ec2b2017-11-06 13:54:02 -0700374 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
375 warn!("Image mismatch after first boot");
376 Err(())
377 } else {
378 Ok(total_count)
David Brown2639e072017-10-11 11:18:44 -0600379 }
380 }
381
David Brown5f7ec2b2017-11-06 13:54:02 -0700382 #[cfg(feature = "overwrite-only")]
David Browna4167ef2017-11-06 14:30:05 -0700383 pub fn run_basic_revert(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700384 false
385 }
David Brown2639e072017-10-11 11:18:44 -0600386
David Brown5f7ec2b2017-11-06 13:54:02 -0700387 #[cfg(not(feature = "overwrite-only"))]
David Browna4167ef2017-11-06 14:30:05 -0700388 pub fn run_basic_revert(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700389 let mut fails = 0;
David Brown2639e072017-10-11 11:18:44 -0600390
David Brown5f7ec2b2017-11-06 13:54:02 -0700391 // FIXME: this test would also pass if no swap is ever performed???
392 if Caps::SwapUpgrade.present() {
393 for count in 2 .. 5 {
394 info!("Try revert: {}", count);
395 let fl = try_revert(&self.flash, &self.areadesc, count, self.align);
396 if !verify_image(&fl, self.slot0.base_off, &self.primary) {
397 error!("Revert failure on count {}", count);
398 fails += 1;
399 }
400 }
401 }
402
403 fails > 0
404 }
405
David Browna4167ef2017-11-06 14:30:05 -0700406 pub fn run_perm_with_fails(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700407 let mut fails = 0;
David Brownc49811e2017-11-06 14:20:45 -0700408 let total_flash_ops = self.total_count.unwrap();
David Brown5f7ec2b2017-11-06 13:54:02 -0700409
410 // Let's try an image halfway through.
411 for i in 1 .. total_flash_ops {
412 info!("Try interruption at {}", i);
413 let (fl, count) = try_upgrade(&self.flash, &self, Some(i));
414 info!("Second boot, count={}", count);
415 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
416 warn!("FAIL at step {} of {}", i, total_flash_ops);
417 fails += 1;
418 }
419
420 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
421 COPY_DONE) {
422 warn!("Mismatched trailer for Slot 0");
423 fails += 1;
424 }
425
426 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
427 UNSET) {
428 warn!("Mismatched trailer for Slot 1");
429 fails += 1;
430 }
431
432 if Caps::SwapUpgrade.present() {
433 if !verify_image(&fl, self.slot1.base_off, &self.primary) {
434 warn!("Slot 1 FAIL at step {} of {}", i, total_flash_ops);
435 fails += 1;
436 }
437 }
438 }
439
440 if fails > 0 {
441 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
442 fails as f32 * 100.0 / total_flash_ops as f32);
443 }
444
445 fails > 0
446 }
447
David Browna4167ef2017-11-06 14:30:05 -0700448 pub fn run_perm_with_random_fails_5(&self) -> bool {
449 self.run_perm_with_random_fails(5)
450 }
451
David Brownc49811e2017-11-06 14:20:45 -0700452 fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700453 let mut fails = 0;
David Brownc49811e2017-11-06 14:20:45 -0700454 let total_flash_ops = self.total_count.unwrap();
David Brown5f7ec2b2017-11-06 13:54:02 -0700455 let (fl, total_counts) = try_random_fails(&self.flash, &self,
456 total_flash_ops, total_fails);
457 info!("Random interruptions at reset points={:?}", total_counts);
458
459 let slot0_ok = verify_image(&fl, self.slot0.base_off, &self.upgrade);
460 let slot1_ok = if Caps::SwapUpgrade.present() {
461 verify_image(&fl, self.slot1.base_off, &self.primary)
462 } else {
463 true
464 };
465 if !slot0_ok || !slot1_ok {
466 error!("Image mismatch after random interrupts: slot0={} slot1={}",
467 if slot0_ok { "ok" } else { "fail" },
468 if slot1_ok { "ok" } else { "fail" });
469 fails += 1;
470 }
471 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
472 COPY_DONE) {
473 error!("Mismatched trailer for Slot 0");
474 fails += 1;
475 }
476 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
477 UNSET) {
478 error!("Mismatched trailer for Slot 1");
David Brown2639e072017-10-11 11:18:44 -0600479 fails += 1;
480 }
481
David Brown5f7ec2b2017-11-06 13:54:02 -0700482 if fails > 0 {
483 error!("Error testing perm upgrade with {} fails", total_fails);
484 }
485
486 fails > 0
487 }
488
489 #[cfg(feature = "overwrite-only")]
David Browna4167ef2017-11-06 14:30:05 -0700490 pub fn run_revert_with_fails(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700491 false
492 }
493
494 #[cfg(not(feature = "overwrite-only"))]
David Browna4167ef2017-11-06 14:30:05 -0700495 pub fn run_revert_with_fails(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700496 let mut fails = 0;
497
498 if Caps::SwapUpgrade.present() {
David Brownc49811e2017-11-06 14:20:45 -0700499 for i in 1 .. (self.total_count.unwrap() - 1) {
David Brown5f7ec2b2017-11-06 13:54:02 -0700500 info!("Try interruption at {}", i);
501 if try_revert_with_fail_at(&self.flash, &self, i) {
502 error!("Revert failed at interruption {}", i);
503 fails += 1;
504 }
505 }
506 }
507
508 fails > 0
509 }
510
511 #[cfg(feature = "overwrite-only")]
David Browna4167ef2017-11-06 14:30:05 -0700512 pub fn run_norevert(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700513 false
514 }
515
516 #[cfg(not(feature = "overwrite-only"))]
David Browna4167ef2017-11-06 14:30:05 -0700517 pub fn run_norevert(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700518 let mut fl = self.flash.clone();
519 let mut fails = 0;
520
521 info!("Try norevert");
522
523 // First do a normal upgrade...
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200524 let (result, _) = c::boot_go(&mut fl, &self.areadesc, None, self.align, false);
525 if result != 0 {
David Brown5f7ec2b2017-11-06 13:54:02 -0700526 warn!("Failed first boot");
527 fails += 1;
528 }
529
530 //FIXME: copy_done is written by boot_go, is it ok if no copy
531 // was ever done?
532
533 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
534 warn!("Slot 0 image verification FAIL");
535 fails += 1;
536 }
537 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, UNSET,
David Brown2639e072017-10-11 11:18:44 -0600538 COPY_DONE) {
539 warn!("Mismatched trailer for Slot 0");
540 fails += 1;
541 }
David Brown5f7ec2b2017-11-06 13:54:02 -0700542 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
David Brown2639e072017-10-11 11:18:44 -0600543 UNSET) {
544 warn!("Mismatched trailer for Slot 1");
545 fails += 1;
546 }
547
David Brown5f7ec2b2017-11-06 13:54:02 -0700548 // Marks image in slot0 as permanent, no revert should happen...
549 mark_permanent_upgrade(&mut fl, &self.slot0, self.align);
550
551 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
552 COPY_DONE) {
553 warn!("Mismatched trailer for Slot 0");
554 fails += 1;
David Brown2639e072017-10-11 11:18:44 -0600555 }
David Brown2639e072017-10-11 11:18:44 -0600556
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200557 let (result, _) = c::boot_go(&mut fl, &self.areadesc, None, self.align, false);
558 if result != 0 {
David Brown5f7ec2b2017-11-06 13:54:02 -0700559 warn!("Failed second boot");
560 fails += 1;
David Brown2639e072017-10-11 11:18:44 -0600561 }
David Brown5f7ec2b2017-11-06 13:54:02 -0700562
563 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
564 COPY_DONE) {
565 warn!("Mismatched trailer for Slot 0");
566 fails += 1;
567 }
568 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
569 warn!("Failed image verification");
570 fails += 1;
571 }
572
573 if fails > 0 {
574 error!("Error running upgrade without revert");
575 }
576
577 fails > 0
David Brown2639e072017-10-11 11:18:44 -0600578 }
579
David Brown5f7ec2b2017-11-06 13:54:02 -0700580 // Tests a new image written to slot0 that already has magic and image_ok set
581 // while there is no image on slot1, so no revert should ever happen...
David Brownc49811e2017-11-06 14:20:45 -0700582 pub fn run_norevert_newimage(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700583 let mut fl = self.flash.clone();
584 let mut fails = 0;
David Brown2639e072017-10-11 11:18:44 -0600585
David Brown5f7ec2b2017-11-06 13:54:02 -0700586 info!("Try non-revert on imgtool generated image");
David Brown2639e072017-10-11 11:18:44 -0600587
David Brown5f7ec2b2017-11-06 13:54:02 -0700588 mark_upgrade(&mut fl, &self.slot0);
David Brown2639e072017-10-11 11:18:44 -0600589
David Brown5f7ec2b2017-11-06 13:54:02 -0700590 // This simulates writing an image created by imgtool to Slot 0
591 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, UNSET, UNSET) {
592 warn!("Mismatched trailer for Slot 0");
593 fails += 1;
594 }
David Brown2639e072017-10-11 11:18:44 -0600595
David Brown5f7ec2b2017-11-06 13:54:02 -0700596 // Run the bootloader...
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200597 let (result, _) = c::boot_go(&mut fl, &self.areadesc, None, self.align, false);
598 if result != 0 {
David Brown5f7ec2b2017-11-06 13:54:02 -0700599 warn!("Failed first boot");
600 fails += 1;
601 }
602
603 // State should not have changed
604 if !verify_image(&fl, self.slot0.base_off, &self.primary) {
605 warn!("Failed image verification");
606 fails += 1;
607 }
608 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, UNSET,
609 UNSET) {
610 warn!("Mismatched trailer for Slot 0");
611 fails += 1;
612 }
613 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
614 UNSET) {
615 warn!("Mismatched trailer for Slot 1");
616 fails += 1;
617 }
618
619 if fails > 0 {
620 error!("Expected a non revert with new image");
621 }
622
623 fails > 0
David Brown2639e072017-10-11 11:18:44 -0600624 }
625
David Brown5f7ec2b2017-11-06 13:54:02 -0700626 // Tests a new image written to slot0 that already has magic and image_ok set
627 // while there is no image on slot1, so no revert should ever happen...
David Brownc49811e2017-11-06 14:20:45 -0700628 pub fn run_signfail_upgrade(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700629 let mut fl = self.flash.clone();
630 let mut fails = 0;
David Brown2639e072017-10-11 11:18:44 -0600631
David Brown5f7ec2b2017-11-06 13:54:02 -0700632 info!("Try upgrade image with bad signature");
633
634 mark_upgrade(&mut fl, &self.slot0);
635 mark_permanent_upgrade(&mut fl, &self.slot0, self.align);
636 mark_upgrade(&mut fl, &self.slot1);
637
638 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
639 UNSET) {
640 warn!("Mismatched trailer for Slot 0");
641 fails += 1;
642 }
643
644 // Run the bootloader...
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200645 let (result, _) = c::boot_go(&mut fl, &self.areadesc, None, self.align, false);
646 if result != 0 {
David Brown5f7ec2b2017-11-06 13:54:02 -0700647 warn!("Failed first boot");
648 fails += 1;
649 }
650
651 // State should not have changed
652 if !verify_image(&fl, self.slot0.base_off, &self.primary) {
653 warn!("Failed image verification");
654 fails += 1;
655 }
656 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
657 UNSET) {
658 warn!("Mismatched trailer for Slot 0");
659 fails += 1;
660 }
661
662 if fails > 0 {
663 error!("Expected an upgrade failure when image has bad signature");
664 }
665
666 fails > 0
David Brown2639e072017-10-11 11:18:44 -0600667 }
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200668
669 fn trailer_sz(&self) -> usize {
670 c::boot_trailer_sz(self.align) as usize
671 }
672
673 // FIXME: could get status sz from bootloader
674 fn status_sz(&self) -> usize {
675 self.trailer_sz() - (16 + 24)
676 }
677
678 /// This test runs a simple upgrade with no fails in the images, but
679 /// allowing for fails in the status area. This should run to the end
680 /// and warn that write fails were detected...
681 #[cfg(not(feature = "validate-slot0"))]
682 pub fn run_with_status_fails_complete(&self) -> bool { false }
683
684 #[cfg(feature = "validate-slot0")]
685 pub fn run_with_status_fails_complete(&self) -> bool {
686 let mut fl = self.flash.clone();
687 let mut fails = 0;
688
689 info!("Try swap with status fails");
690
691 mark_permanent_upgrade(&mut fl, &self.slot1, self.align);
692
693 let status_off = self.slot1.base_off - self.trailer_sz();
694
695 // Always fail writes to status area...
696 let _ = fl.add_bad_region(status_off, self.status_sz(), 1.0);
697
698 let (result, asserts) = c::boot_go(&mut fl, &self.areadesc, None, self.align, true);
699 if result != 0 {
700 warn!("Failed!");
701 fails += 1;
702 }
703
704 // Failed writes to the marked "bad" region don't assert anymore.
705 // Any detected assert() is happening in another part of the code.
706 if asserts != 0 {
707 warn!("At least one assert() was called");
708 fails += 1;
709 }
710
711 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
712 COPY_DONE) {
713 warn!("Mismatched trailer for Slot 0");
714 fails += 1;
715 }
716
717 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
718 warn!("Failed image verification");
719 fails += 1;
720 }
721
722 info!("validate slot0 enabled; re-run of boot_go should just work");
723 let (result, _) = c::boot_go(&mut fl, &self.areadesc, None, self.align, false);
724 if result != 0 {
725 warn!("Failed!");
726 fails += 1;
727 }
728
729 if fails > 0 {
730 error!("Error running upgrade with status write fails");
731 }
732
733 fails > 0
734 }
735
736 /// This test runs a simple upgrade with no fails in the images, but
737 /// allowing for fails in the status area. This should run to the end
738 /// and warn that write fails were detected...
739 #[cfg(feature = "validate-slot0")]
740 pub fn run_with_status_fails_with_reset(&self) -> bool {
741 let mut fl = self.flash.clone();
742 let mut fails = 0;
743 let mut count = self.total_count.unwrap() / 2;
744
745 //info!("count={}\n", count);
746
747 info!("Try interrupted swap with status fails");
748
749 mark_permanent_upgrade(&mut fl, &self.slot1, self.align);
750
751 let status_off = self.slot1.base_off - self.trailer_sz();
752
753 // Mark the status area as a bad area
754 let _ = fl.add_bad_region(status_off, self.status_sz(), 0.5);
755
756 // Should not fail, writing to bad regions does not assert
757 let (_, asserts) = c::boot_go(&mut fl, &self.areadesc, Some(&mut count), self.align, true);
758 if asserts != 0 {
759 warn!("At least one assert() was called");
760 fails += 1;
761 }
762
763 fl.reset_bad_regions();
764
765 // Disabling write verification the only assert triggered by
766 // boot_go should be checking for integrity of status bytes.
767 fl.set_verify_writes(false);
768
769 info!("Resuming an interrupted swap operation");
770 let (_, asserts) = c::boot_go(&mut fl, &self.areadesc, None, self.align, true);
771
772 // This might throw no asserts, for large sector devices, where
773 // a single failure writing is indistinguishable from no failure,
774 // or throw a single assert for small sector devices that fail
775 // multiple times...
776 if asserts > 1 {
777 warn!("Expected single assert validating slot0, more detected {}", asserts);
778 fails += 1;
779 }
780
781 if fails > 0 {
782 error!("Error running upgrade with status write fails");
783 }
784
785 fails > 0
786 }
787
788 #[cfg(not(feature = "validate-slot0"))]
789 #[cfg(not(feature = "overwrite-only"))]
790 pub fn run_with_status_fails_with_reset(&self) -> bool {
791 let mut fl = self.flash.clone();
792 let mut fails = 0;
793
794 info!("Try interrupted swap with status fails");
795
796 mark_permanent_upgrade(&mut fl, &self.slot1, self.align);
797
798 let status_off = self.slot1.base_off - self.trailer_sz();
799
800 // Mark the status area as a bad area
801 let _ = fl.add_bad_region(status_off, self.status_sz(), 1.0);
802
803 // This is expected to fail while writing to bad regions...
804 let (_, asserts) = c::boot_go(&mut fl, &self.areadesc, None, self.align, true);
805 if asserts == 0 {
806 warn!("No assert() detected");
807 fails += 1;
808 }
809
810 fails > 0
811 }
812
813 #[cfg(feature = "overwrite-only")]
814 pub fn run_with_status_fails_with_reset(&self) -> bool {
815 false
816 }
David Brown2639e072017-10-11 11:18:44 -0600817}
818
819/// Test a boot, optionally stopping after 'n' flash options. Returns a count
820/// of the number of flash operations done total.
David Brown3f687dc2017-11-06 13:41:18 -0700821fn try_upgrade(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600822 stop: Option<i32>) -> (SimFlash, i32) {
823 // Clone the flash to have a new copy.
824 let mut fl = flash.clone();
825
David Brown541860c2017-11-06 11:25:42 -0700826 mark_permanent_upgrade(&mut fl, &images.slot1, images.align);
David Brown2639e072017-10-11 11:18:44 -0600827
David Brownee61c832017-11-06 11:13:25 -0700828 let mut counter = stop.unwrap_or(0);
829
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200830 let (first_interrupted, count) = match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align, false) {
831 (-0x13579, _) => (true, stop.unwrap()),
832 (0, _) => (false, -counter),
833 (x, _) => panic!("Unknown return: {}", x),
David Brown2639e072017-10-11 11:18:44 -0600834 };
David Brown2639e072017-10-11 11:18:44 -0600835
David Brownee61c832017-11-06 11:13:25 -0700836 counter = 0;
David Brown2639e072017-10-11 11:18:44 -0600837 if first_interrupted {
838 // fl.dump();
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200839 match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align, false) {
840 (-0x13579, _) => panic!("Shouldn't stop again"),
841 (0, _) => (),
842 (x, _) => panic!("Unknown return: {}", x),
David Brown2639e072017-10-11 11:18:44 -0600843 }
844 }
845
David Brownee61c832017-11-06 11:13:25 -0700846 (fl, count - counter)
David Brown2639e072017-10-11 11:18:44 -0600847}
848
849#[cfg(not(feature = "overwrite-only"))]
David Brown541860c2017-11-06 11:25:42 -0700850fn try_revert(flash: &SimFlash, areadesc: &AreaDesc, count: usize, align: u8) -> SimFlash {
David Brown2639e072017-10-11 11:18:44 -0600851 let mut fl = flash.clone();
David Brown2639e072017-10-11 11:18:44 -0600852
853 // fl.write_file("image0.bin").unwrap();
854 for i in 0 .. count {
855 info!("Running boot pass {}", i + 1);
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200856 assert_eq!(c::boot_go(&mut fl, &areadesc, None, align, false), (0, 0));
David Brown2639e072017-10-11 11:18:44 -0600857 }
858 fl
859}
860
861#[cfg(not(feature = "overwrite-only"))]
David Brown3f687dc2017-11-06 13:41:18 -0700862fn try_revert_with_fail_at(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600863 stop: i32) -> bool {
864 let mut fl = flash.clone();
David Brown2639e072017-10-11 11:18:44 -0600865 let mut fails = 0;
866
David Brownee61c832017-11-06 11:13:25 -0700867 let mut counter = stop;
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200868 let (x, _) = c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align, false);
David Brown2639e072017-10-11 11:18:44 -0600869 if x != -0x13579 {
870 warn!("Should have stopped at interruption point");
871 fails += 1;
872 }
873
874 if !verify_trailer(&fl, images.slot0.trailer_off, None, None, UNSET) {
875 warn!("copy_done should be unset");
876 fails += 1;
877 }
878
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200879 let (x, _) = c::boot_go(&mut fl, &images.areadesc, None, images.align, false);
David Brown2639e072017-10-11 11:18:44 -0600880 if x != 0 {
881 warn!("Should have finished upgrade");
882 fails += 1;
883 }
884
885 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
886 warn!("Image in slot 0 before revert is invalid at stop={}", stop);
887 fails += 1;
888 }
889 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
890 warn!("Image in slot 1 before revert is invalid at stop={}", stop);
891 fails += 1;
892 }
893 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
894 COPY_DONE) {
895 warn!("Mismatched trailer for Slot 0 before revert");
896 fails += 1;
897 }
898 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
899 UNSET) {
900 warn!("Mismatched trailer for Slot 1 before revert");
901 fails += 1;
902 }
903
904 // Do Revert
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200905 let (x, _) = c::boot_go(&mut fl, &images.areadesc, None, images.align, false);
David Brown2639e072017-10-11 11:18:44 -0600906 if x != 0 {
907 warn!("Should have finished a revert");
908 fails += 1;
909 }
910
911 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
912 warn!("Image in slot 0 after revert is invalid at stop={}", stop);
913 fails += 1;
914 }
915 if !verify_image(&fl, images.slot1.base_off, &images.upgrade) {
916 warn!("Image in slot 1 after revert is invalid at stop={}", stop);
917 fails += 1;
918 }
919 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
920 COPY_DONE) {
921 warn!("Mismatched trailer for Slot 1 after revert");
922 fails += 1;
923 }
924 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
925 UNSET) {
926 warn!("Mismatched trailer for Slot 1 after revert");
927 fails += 1;
928 }
929
930 fails > 0
931}
932
David Brown3f687dc2017-11-06 13:41:18 -0700933fn try_random_fails(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600934 total_ops: i32, count: usize) -> (SimFlash, Vec<i32>) {
935 let mut fl = flash.clone();
936
David Brown541860c2017-11-06 11:25:42 -0700937 mark_permanent_upgrade(&mut fl, &images.slot1, images.align);
David Brown2639e072017-10-11 11:18:44 -0600938
939 let mut rng = rand::thread_rng();
940 let mut resets = vec![0i32; count];
941 let mut remaining_ops = total_ops;
942 for i in 0 .. count {
943 let ops = Range::new(1, remaining_ops / 2);
944 let reset_counter = ops.ind_sample(&mut rng);
David Brownee61c832017-11-06 11:13:25 -0700945 let mut counter = reset_counter;
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200946 match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align, false) {
947 (0, _) | (-0x13579, _) => (),
948 (x, _) => panic!("Unknown return: {}", x),
David Brown2639e072017-10-11 11:18:44 -0600949 }
950 remaining_ops -= reset_counter;
951 resets[i] = reset_counter;
952 }
953
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200954 match c::boot_go(&mut fl, &images.areadesc, None, images.align, false) {
955 (-0x13579, _) => panic!("Should not be have been interrupted!"),
956 (0, _) => (),
957 (x, _) => panic!("Unknown return: {}", x),
David Brown2639e072017-10-11 11:18:44 -0600958 }
959
960 (fl, resets)
961}
962
963/// Show the flash layout.
964#[allow(dead_code)]
965fn show_flash(flash: &Flash) {
966 println!("---- Flash configuration ----");
967 for sector in flash.sector_iter() {
968 println!(" {:3}: 0x{:08x}, 0x{:08x}",
969 sector.num, sector.base, sector.size);
970 }
971 println!("");
972}
973
974/// Install a "program" into the given image. This fakes the image header, or at least all of the
975/// fields used by the given code. Returns a copy of the image that was written.
976fn install_image(flash: &mut Flash, offset: usize, len: usize,
977 bad_sig: bool) -> Vec<u8> {
978 let offset0 = offset;
979
980 let mut tlv = make_tlv();
981
982 // Generate a boot header. Note that the size doesn't include the header.
983 let header = ImageHeader {
984 magic: 0x96f3b83d,
985 tlv_size: tlv.get_size(),
986 _pad1: 0,
987 hdr_size: 32,
988 key_id: 0,
989 _pad2: 0,
990 img_size: len as u32,
991 flags: tlv.get_flags(),
992 ver: ImageVersion {
993 major: (offset / (128 * 1024)) as u8,
994 minor: 0,
995 revision: 1,
996 build_num: offset as u32,
997 },
998 _pad3: 0,
999 };
1000
1001 let b_header = header.as_raw();
1002 tlv.add_bytes(&b_header);
1003 /*
1004 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
1005 mem::size_of::<ImageHeader>()) };
1006 */
1007 assert_eq!(b_header.len(), 32);
1008 flash.write(offset, &b_header).unwrap();
1009 let offset = offset + b_header.len();
1010
1011 // The core of the image itself is just pseudorandom data.
1012 let mut buf = vec![0; len];
1013 splat(&mut buf, offset);
1014 tlv.add_bytes(&buf);
1015
1016 // Get and append the TLV itself.
1017 if bad_sig {
1018 let good_sig = &mut tlv.make_tlv();
1019 buf.append(&mut vec![0; good_sig.len()]);
1020 } else {
1021 buf.append(&mut tlv.make_tlv());
1022 }
1023
1024 // Pad the block to a flash alignment (8 bytes).
1025 while buf.len() % 8 != 0 {
1026 buf.push(0xFF);
1027 }
1028
1029 flash.write(offset, &buf).unwrap();
1030 let offset = offset + buf.len();
1031
1032 // Copy out the image so that we can verify that the image was installed correctly later.
1033 let mut copy = vec![0u8; offset - offset0];
1034 flash.read(offset0, &mut copy).unwrap();
1035
1036 copy
1037}
1038
1039// The TLV in use depends on what kind of signature we are verifying.
1040#[cfg(feature = "sig-rsa")]
1041fn make_tlv() -> TlvGen {
1042 TlvGen::new_rsa_pss()
1043}
1044
Fabio Utzig80fde2f2017-12-05 09:25:31 -02001045#[cfg(feature = "sig-ecdsa")]
1046fn make_tlv() -> TlvGen {
1047 TlvGen::new_ecdsa()
1048}
1049
David Brown2639e072017-10-11 11:18:44 -06001050#[cfg(not(feature = "sig-rsa"))]
Fabio Utzig80fde2f2017-12-05 09:25:31 -02001051#[cfg(not(feature = "sig-ecdsa"))]
David Brown2639e072017-10-11 11:18:44 -06001052fn make_tlv() -> TlvGen {
1053 TlvGen::new_hash_only()
1054}
1055
1056/// Verify that given image is present in the flash at the given offset.
1057fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
1058 let mut copy = vec![0u8; buf.len()];
1059 flash.read(offset, &mut copy).unwrap();
1060
1061 if buf != &copy[..] {
1062 for i in 0 .. buf.len() {
1063 if buf[i] != copy[i] {
1064 info!("First failure at {:#x}", offset + i);
1065 break;
1066 }
1067 }
1068 false
1069 } else {
1070 true
1071 }
1072}
1073
1074#[cfg(feature = "overwrite-only")]
1075#[allow(unused_variables)]
1076// overwrite-only doesn't employ trailer management
1077fn verify_trailer(flash: &Flash, offset: usize,
1078 magic: Option<&[u8]>, image_ok: Option<u8>,
1079 copy_done: Option<u8>) -> bool {
1080 true
1081}
1082
1083#[cfg(not(feature = "overwrite-only"))]
1084fn verify_trailer(flash: &Flash, offset: usize,
1085 magic: Option<&[u8]>, image_ok: Option<u8>,
1086 copy_done: Option<u8>) -> bool {
1087 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 2];
1088 let mut failed = false;
1089
1090 flash.read(offset, &mut copy).unwrap();
1091
1092 failed |= match magic {
1093 Some(v) => {
1094 if &copy[16..] != v {
1095 warn!("\"magic\" mismatch at {:#x}", offset);
1096 true
1097 } else {
1098 false
1099 }
1100 },
1101 None => false,
1102 };
1103
1104 failed |= match image_ok {
1105 Some(v) => {
1106 if copy[8] != v {
1107 warn!("\"image_ok\" mismatch at {:#x}", offset);
1108 true
1109 } else {
1110 false
1111 }
1112 },
1113 None => false,
1114 };
1115
1116 failed |= match copy_done {
1117 Some(v) => {
1118 if copy[0] != v {
1119 warn!("\"copy_done\" mismatch at {:#x}", offset);
1120 true
1121 } else {
1122 false
1123 }
1124 },
1125 None => false,
1126 };
1127
1128 !failed
1129}
1130
1131/// The image header
1132#[repr(C)]
1133pub struct ImageHeader {
1134 magic: u32,
1135 tlv_size: u16,
1136 key_id: u8,
1137 _pad1: u8,
1138 hdr_size: u16,
1139 _pad2: u16,
1140 img_size: u32,
1141 flags: u32,
1142 ver: ImageVersion,
1143 _pad3: u32,
1144}
1145
1146impl AsRaw for ImageHeader {}
1147
1148#[repr(C)]
1149pub struct ImageVersion {
1150 major: u8,
1151 minor: u8,
1152 revision: u16,
1153 build_num: u32,
1154}
1155
David Brownd5e632c2017-10-19 10:49:46 -06001156#[derive(Clone)]
David Brown2639e072017-10-11 11:18:44 -06001157struct SlotInfo {
1158 base_off: usize,
1159 trailer_off: usize,
1160}
1161
David Brownf48b9502017-11-06 14:00:26 -07001162pub struct Images {
David Browndc9cba12017-11-06 13:31:42 -07001163 flash: SimFlash,
David Brown3f687dc2017-11-06 13:41:18 -07001164 areadesc: AreaDesc,
David Brownd5e632c2017-10-19 10:49:46 -06001165 slot0: SlotInfo,
1166 slot1: SlotInfo,
David Brown2639e072017-10-11 11:18:44 -06001167 primary: Vec<u8>,
1168 upgrade: Vec<u8>,
David Brownc49811e2017-11-06 14:20:45 -07001169 total_count: Option<i32>,
David Brown541860c2017-11-06 11:25:42 -07001170 align: u8,
David Brown2639e072017-10-11 11:18:44 -06001171}
1172
1173const MAGIC_VALID: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3,
1174 0x60, 0xd2, 0xef, 0x7f,
1175 0x35, 0x52, 0x50, 0x0f,
1176 0x2c, 0xb6, 0x79, 0x80]);
1177const MAGIC_UNSET: Option<&[u8]> = Some(&[0xff; 16]);
1178
1179const COPY_DONE: Option<u8> = Some(1);
1180const IMAGE_OK: Option<u8> = Some(1);
1181const UNSET: Option<u8> = Some(0xff);
1182
1183/// Write out the magic so that the loader tries doing an upgrade.
1184fn mark_upgrade(flash: &mut Flash, slot: &SlotInfo) {
1185 let offset = slot.trailer_off + c::boot_max_align() * 2;
1186 flash.write(offset, MAGIC_VALID.unwrap()).unwrap();
1187}
1188
1189/// Writes the image_ok flag which, guess what, tells the bootloader
1190/// the this image is ok (not a test, and no revert is to be performed).
David Brown541860c2017-11-06 11:25:42 -07001191fn mark_permanent_upgrade(flash: &mut Flash, slot: &SlotInfo, align: u8) {
David Brown2639e072017-10-11 11:18:44 -06001192 let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
David Brown2639e072017-10-11 11:18:44 -06001193 let off = slot.trailer_off + c::boot_max_align();
David Brown541860c2017-11-06 11:25:42 -07001194 flash.write(off, &ok[..align as usize]).unwrap();
David Brown2639e072017-10-11 11:18:44 -06001195}
1196
1197// Drop some pseudo-random gibberish onto the data.
1198fn splat(data: &mut [u8], seed: usize) {
1199 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
1200 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
1201 rng.fill_bytes(data);
1202}
1203
1204/// Return a read-only view into the raw bytes of this object
1205trait AsRaw : Sized {
1206 fn as_raw<'a>(&'a self) -> &'a [u8] {
1207 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1208 mem::size_of::<Self>()) }
1209 }
1210}
1211
1212fn show_sizes() {
1213 // This isn't panic safe.
David Brown2639e072017-10-11 11:18:44 -06001214 for min in &[1, 2, 4, 8] {
David Brown541860c2017-11-06 11:25:42 -07001215 let msize = c::boot_trailer_sz(*min);
David Brown2639e072017-10-11 11:18:44 -06001216 println!("{:2}: {} (0x{:x})", min, msize, msize);
1217 }
David Brown2639e072017-10-11 11:18:44 -06001218}