blob: 8e394eab3fe8b5e8a9a28bd3b07b1867d63b2c0b [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();
Fabio Utzigeedcc452017-11-24 10:48:52 -0200300 failed |= images.run_with_status_fails_with_reset();
Fabio Utzigb841f0a2017-11-24 08:11:05 -0200301
David Brown2639e072017-10-11 11:18:44 -0600302 //show_flash(&flash);
303
304 if failed {
305 self.failures += 1;
306 } else {
307 self.passes += 1;
308 }
309 }
David Browndd2b1182017-11-02 15:39:21 -0600310
311 pub fn failures(&self) -> usize {
312 self.failures
313 }
David Brown2639e072017-10-11 11:18:44 -0600314}
315
David Browndecbd042017-10-19 10:43:17 -0600316/// Build the Flash and area descriptor for a given device.
317pub fn make_device(device: DeviceName, align: u8) -> (SimFlash, AreaDesc) {
318 match device {
319 DeviceName::Stm32f4 => {
320 // STM style flash. Large sectors, with a large scratch area.
321 let flash = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
322 64 * 1024,
323 128 * 1024, 128 * 1024, 128 * 1024],
324 align as usize);
325 let mut areadesc = AreaDesc::new(&flash);
326 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
327 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
328 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch);
329 (flash, areadesc)
330 }
331 DeviceName::K64f => {
332 // NXP style flash. Small sectors, one small sector for scratch.
333 let flash = SimFlash::new(vec![4096; 128], align as usize);
334
335 let mut areadesc = AreaDesc::new(&flash);
336 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
337 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
338 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch);
339 (flash, areadesc)
340 }
341 DeviceName::K64fBig => {
342 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
343 // uses small sectors, but we tell the bootloader they are large.
344 let flash = SimFlash::new(vec![4096; 128], align as usize);
345
346 let mut areadesc = AreaDesc::new(&flash);
347 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0);
348 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1);
349 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch);
350 (flash, areadesc)
351 }
352 DeviceName::Nrf52840 => {
353 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
354 // does not divide into the image size.
355 let flash = SimFlash::new(vec![4096; 128], align as usize);
356
357 let mut areadesc = AreaDesc::new(&flash);
358 areadesc.add_image(0x008000, 0x034000, FlashId::Image0);
359 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1);
360 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch);
361 (flash, areadesc)
362 }
363 }
364}
365
David Brown5f7ec2b2017-11-06 13:54:02 -0700366impl Images {
367 /// A simple upgrade without forced failures.
368 ///
369 /// Returns the number of flash operations which can later be used to
370 /// inject failures at chosen steps.
David Brownc49811e2017-11-06 14:20:45 -0700371 pub fn run_basic_upgrade(&self) -> Result<i32, ()> {
David Brown5f7ec2b2017-11-06 13:54:02 -0700372 let (fl, total_count) = try_upgrade(&self.flash, &self, None);
373 info!("Total flash operation count={}", total_count);
David Brown2639e072017-10-11 11:18:44 -0600374
David Brown5f7ec2b2017-11-06 13:54:02 -0700375 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
376 warn!("Image mismatch after first boot");
377 Err(())
378 } else {
379 Ok(total_count)
David Brown2639e072017-10-11 11:18:44 -0600380 }
381 }
382
David Brown5f7ec2b2017-11-06 13:54:02 -0700383 #[cfg(feature = "overwrite-only")]
David Browna4167ef2017-11-06 14:30:05 -0700384 pub fn run_basic_revert(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700385 false
386 }
David Brown2639e072017-10-11 11:18:44 -0600387
David Brown5f7ec2b2017-11-06 13:54:02 -0700388 #[cfg(not(feature = "overwrite-only"))]
David Browna4167ef2017-11-06 14:30:05 -0700389 pub fn run_basic_revert(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700390 let mut fails = 0;
David Brown2639e072017-10-11 11:18:44 -0600391
David Brown5f7ec2b2017-11-06 13:54:02 -0700392 // FIXME: this test would also pass if no swap is ever performed???
393 if Caps::SwapUpgrade.present() {
394 for count in 2 .. 5 {
395 info!("Try revert: {}", count);
396 let fl = try_revert(&self.flash, &self.areadesc, count, self.align);
397 if !verify_image(&fl, self.slot0.base_off, &self.primary) {
398 error!("Revert failure on count {}", count);
399 fails += 1;
400 }
401 }
402 }
403
404 fails > 0
405 }
406
David Browna4167ef2017-11-06 14:30:05 -0700407 pub fn run_perm_with_fails(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700408 let mut fails = 0;
David Brownc49811e2017-11-06 14:20:45 -0700409 let total_flash_ops = self.total_count.unwrap();
David Brown5f7ec2b2017-11-06 13:54:02 -0700410
411 // Let's try an image halfway through.
412 for i in 1 .. total_flash_ops {
413 info!("Try interruption at {}", i);
414 let (fl, count) = try_upgrade(&self.flash, &self, Some(i));
415 info!("Second boot, count={}", count);
416 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
417 warn!("FAIL at step {} of {}", i, total_flash_ops);
418 fails += 1;
419 }
420
421 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
422 COPY_DONE) {
423 warn!("Mismatched trailer for Slot 0");
424 fails += 1;
425 }
426
427 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
428 UNSET) {
429 warn!("Mismatched trailer for Slot 1");
430 fails += 1;
431 }
432
433 if Caps::SwapUpgrade.present() {
434 if !verify_image(&fl, self.slot1.base_off, &self.primary) {
435 warn!("Slot 1 FAIL at step {} of {}", i, total_flash_ops);
436 fails += 1;
437 }
438 }
439 }
440
441 if fails > 0 {
442 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
443 fails as f32 * 100.0 / total_flash_ops as f32);
444 }
445
446 fails > 0
447 }
448
David Browna4167ef2017-11-06 14:30:05 -0700449 pub fn run_perm_with_random_fails_5(&self) -> bool {
450 self.run_perm_with_random_fails(5)
451 }
452
David Brownc49811e2017-11-06 14:20:45 -0700453 fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700454 let mut fails = 0;
David Brownc49811e2017-11-06 14:20:45 -0700455 let total_flash_ops = self.total_count.unwrap();
David Brown5f7ec2b2017-11-06 13:54:02 -0700456 let (fl, total_counts) = try_random_fails(&self.flash, &self,
457 total_flash_ops, total_fails);
458 info!("Random interruptions at reset points={:?}", total_counts);
459
460 let slot0_ok = verify_image(&fl, self.slot0.base_off, &self.upgrade);
461 let slot1_ok = if Caps::SwapUpgrade.present() {
462 verify_image(&fl, self.slot1.base_off, &self.primary)
463 } else {
464 true
465 };
466 if !slot0_ok || !slot1_ok {
467 error!("Image mismatch after random interrupts: slot0={} slot1={}",
468 if slot0_ok { "ok" } else { "fail" },
469 if slot1_ok { "ok" } else { "fail" });
470 fails += 1;
471 }
472 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
473 COPY_DONE) {
474 error!("Mismatched trailer for Slot 0");
475 fails += 1;
476 }
477 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
478 UNSET) {
479 error!("Mismatched trailer for Slot 1");
David Brown2639e072017-10-11 11:18:44 -0600480 fails += 1;
481 }
482
David Brown5f7ec2b2017-11-06 13:54:02 -0700483 if fails > 0 {
484 error!("Error testing perm upgrade with {} fails", total_fails);
485 }
486
487 fails > 0
488 }
489
490 #[cfg(feature = "overwrite-only")]
David Browna4167ef2017-11-06 14:30:05 -0700491 pub fn run_revert_with_fails(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700492 false
493 }
494
495 #[cfg(not(feature = "overwrite-only"))]
David Browna4167ef2017-11-06 14:30:05 -0700496 pub fn run_revert_with_fails(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700497 let mut fails = 0;
498
499 if Caps::SwapUpgrade.present() {
David Brownc49811e2017-11-06 14:20:45 -0700500 for i in 1 .. (self.total_count.unwrap() - 1) {
David Brown5f7ec2b2017-11-06 13:54:02 -0700501 info!("Try interruption at {}", i);
502 if try_revert_with_fail_at(&self.flash, &self, i) {
503 error!("Revert failed at interruption {}", i);
504 fails += 1;
505 }
506 }
507 }
508
509 fails > 0
510 }
511
512 #[cfg(feature = "overwrite-only")]
David Browna4167ef2017-11-06 14:30:05 -0700513 pub fn run_norevert(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700514 false
515 }
516
517 #[cfg(not(feature = "overwrite-only"))]
David Browna4167ef2017-11-06 14:30:05 -0700518 pub fn run_norevert(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700519 let mut fl = self.flash.clone();
520 let mut fails = 0;
521
522 info!("Try norevert");
523
524 // First do a normal upgrade...
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200525 let (result, _) = c::boot_go(&mut fl, &self.areadesc, None, self.align, false);
526 if result != 0 {
David Brown5f7ec2b2017-11-06 13:54:02 -0700527 warn!("Failed first boot");
528 fails += 1;
529 }
530
531 //FIXME: copy_done is written by boot_go, is it ok if no copy
532 // was ever done?
533
534 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
535 warn!("Slot 0 image verification FAIL");
536 fails += 1;
537 }
538 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, UNSET,
David Brown2639e072017-10-11 11:18:44 -0600539 COPY_DONE) {
540 warn!("Mismatched trailer for Slot 0");
541 fails += 1;
542 }
David Brown5f7ec2b2017-11-06 13:54:02 -0700543 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
David Brown2639e072017-10-11 11:18:44 -0600544 UNSET) {
545 warn!("Mismatched trailer for Slot 1");
546 fails += 1;
547 }
548
David Brown5f7ec2b2017-11-06 13:54:02 -0700549 // Marks image in slot0 as permanent, no revert should happen...
550 mark_permanent_upgrade(&mut fl, &self.slot0, self.align);
551
552 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
553 COPY_DONE) {
554 warn!("Mismatched trailer for Slot 0");
555 fails += 1;
David Brown2639e072017-10-11 11:18:44 -0600556 }
David Brown2639e072017-10-11 11:18:44 -0600557
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200558 let (result, _) = c::boot_go(&mut fl, &self.areadesc, None, self.align, false);
559 if result != 0 {
David Brown5f7ec2b2017-11-06 13:54:02 -0700560 warn!("Failed second boot");
561 fails += 1;
David Brown2639e072017-10-11 11:18:44 -0600562 }
David Brown5f7ec2b2017-11-06 13:54:02 -0700563
564 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
565 COPY_DONE) {
566 warn!("Mismatched trailer for Slot 0");
567 fails += 1;
568 }
569 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
570 warn!("Failed image verification");
571 fails += 1;
572 }
573
574 if fails > 0 {
575 error!("Error running upgrade without revert");
576 }
577
578 fails > 0
David Brown2639e072017-10-11 11:18:44 -0600579 }
580
David Brown5f7ec2b2017-11-06 13:54:02 -0700581 // Tests a new image written to slot0 that already has magic and image_ok set
582 // while there is no image on slot1, so no revert should ever happen...
David Brownc49811e2017-11-06 14:20:45 -0700583 pub fn run_norevert_newimage(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700584 let mut fl = self.flash.clone();
585 let mut fails = 0;
David Brown2639e072017-10-11 11:18:44 -0600586
David Brown5f7ec2b2017-11-06 13:54:02 -0700587 info!("Try non-revert on imgtool generated image");
David Brown2639e072017-10-11 11:18:44 -0600588
David Brown5f7ec2b2017-11-06 13:54:02 -0700589 mark_upgrade(&mut fl, &self.slot0);
David Brown2639e072017-10-11 11:18:44 -0600590
David Brown5f7ec2b2017-11-06 13:54:02 -0700591 // This simulates writing an image created by imgtool to Slot 0
592 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, UNSET, UNSET) {
593 warn!("Mismatched trailer for Slot 0");
594 fails += 1;
595 }
David Brown2639e072017-10-11 11:18:44 -0600596
David Brown5f7ec2b2017-11-06 13:54:02 -0700597 // Run the bootloader...
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200598 let (result, _) = c::boot_go(&mut fl, &self.areadesc, None, self.align, false);
599 if result != 0 {
David Brown5f7ec2b2017-11-06 13:54:02 -0700600 warn!("Failed first boot");
601 fails += 1;
602 }
603
604 // State should not have changed
605 if !verify_image(&fl, self.slot0.base_off, &self.primary) {
606 warn!("Failed image verification");
607 fails += 1;
608 }
609 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, UNSET,
610 UNSET) {
611 warn!("Mismatched trailer for Slot 0");
612 fails += 1;
613 }
614 if !verify_trailer(&fl, self.slot1.trailer_off, MAGIC_UNSET, UNSET,
615 UNSET) {
616 warn!("Mismatched trailer for Slot 1");
617 fails += 1;
618 }
619
620 if fails > 0 {
621 error!("Expected a non revert with new image");
622 }
623
624 fails > 0
David Brown2639e072017-10-11 11:18:44 -0600625 }
626
David Brown5f7ec2b2017-11-06 13:54:02 -0700627 // Tests a new image written to slot0 that already has magic and image_ok set
628 // while there is no image on slot1, so no revert should ever happen...
David Brownc49811e2017-11-06 14:20:45 -0700629 pub fn run_signfail_upgrade(&self) -> bool {
David Brown5f7ec2b2017-11-06 13:54:02 -0700630 let mut fl = self.flash.clone();
631 let mut fails = 0;
David Brown2639e072017-10-11 11:18:44 -0600632
David Brown5f7ec2b2017-11-06 13:54:02 -0700633 info!("Try upgrade image with bad signature");
634
635 mark_upgrade(&mut fl, &self.slot0);
636 mark_permanent_upgrade(&mut fl, &self.slot0, self.align);
637 mark_upgrade(&mut fl, &self.slot1);
638
639 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
640 UNSET) {
641 warn!("Mismatched trailer for Slot 0");
642 fails += 1;
643 }
644
645 // Run the bootloader...
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200646 let (result, _) = c::boot_go(&mut fl, &self.areadesc, None, self.align, false);
647 if result != 0 {
David Brown5f7ec2b2017-11-06 13:54:02 -0700648 warn!("Failed first boot");
649 fails += 1;
650 }
651
652 // State should not have changed
653 if !verify_image(&fl, self.slot0.base_off, &self.primary) {
654 warn!("Failed image verification");
655 fails += 1;
656 }
657 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
658 UNSET) {
659 warn!("Mismatched trailer for Slot 0");
660 fails += 1;
661 }
662
663 if fails > 0 {
664 error!("Expected an upgrade failure when image has bad signature");
665 }
666
667 fails > 0
David Brown2639e072017-10-11 11:18:44 -0600668 }
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200669
670 fn trailer_sz(&self) -> usize {
671 c::boot_trailer_sz(self.align) as usize
672 }
673
674 // FIXME: could get status sz from bootloader
675 fn status_sz(&self) -> usize {
676 self.trailer_sz() - (16 + 24)
677 }
678
679 /// This test runs a simple upgrade with no fails in the images, but
680 /// allowing for fails in the status area. This should run to the end
681 /// and warn that write fails were detected...
682 #[cfg(not(feature = "validate-slot0"))]
683 pub fn run_with_status_fails_complete(&self) -> bool { false }
684
685 #[cfg(feature = "validate-slot0")]
686 pub fn run_with_status_fails_complete(&self) -> bool {
687 let mut fl = self.flash.clone();
688 let mut fails = 0;
689
690 info!("Try swap with status fails");
691
692 mark_permanent_upgrade(&mut fl, &self.slot1, self.align);
693
694 let status_off = self.slot1.base_off - self.trailer_sz();
695
696 // Always fail writes to status area...
697 let _ = fl.add_bad_region(status_off, self.status_sz(), 1.0);
698
699 let (result, asserts) = c::boot_go(&mut fl, &self.areadesc, None, self.align, true);
700 if result != 0 {
701 warn!("Failed!");
702 fails += 1;
703 }
704
705 // Failed writes to the marked "bad" region don't assert anymore.
706 // Any detected assert() is happening in another part of the code.
707 if asserts != 0 {
708 warn!("At least one assert() was called");
709 fails += 1;
710 }
711
712 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
713 COPY_DONE) {
714 warn!("Mismatched trailer for Slot 0");
715 fails += 1;
716 }
717
718 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
719 warn!("Failed image verification");
720 fails += 1;
721 }
722
723 info!("validate slot0 enabled; re-run of boot_go should just work");
724 let (result, _) = c::boot_go(&mut fl, &self.areadesc, None, self.align, false);
725 if result != 0 {
726 warn!("Failed!");
727 fails += 1;
728 }
729
730 if fails > 0 {
731 error!("Error running upgrade with status write fails");
732 }
733
734 fails > 0
735 }
736
737 /// This test runs a simple upgrade with no fails in the images, but
738 /// allowing for fails in the status area. This should run to the end
739 /// and warn that write fails were detected...
740 #[cfg(feature = "validate-slot0")]
741 pub fn run_with_status_fails_with_reset(&self) -> bool {
742 let mut fl = self.flash.clone();
743 let mut fails = 0;
744 let mut count = self.total_count.unwrap() / 2;
745
746 //info!("count={}\n", count);
747
748 info!("Try interrupted swap with status fails");
749
750 mark_permanent_upgrade(&mut fl, &self.slot1, self.align);
751
752 let status_off = self.slot1.base_off - self.trailer_sz();
753
754 // Mark the status area as a bad area
755 let _ = fl.add_bad_region(status_off, self.status_sz(), 0.5);
756
757 // Should not fail, writing to bad regions does not assert
758 let (_, asserts) = c::boot_go(&mut fl, &self.areadesc, Some(&mut count), self.align, true);
759 if asserts != 0 {
760 warn!("At least one assert() was called");
761 fails += 1;
762 }
763
764 fl.reset_bad_regions();
765
766 // Disabling write verification the only assert triggered by
767 // boot_go should be checking for integrity of status bytes.
768 fl.set_verify_writes(false);
769
770 info!("Resuming an interrupted swap operation");
771 let (_, asserts) = c::boot_go(&mut fl, &self.areadesc, None, self.align, true);
772
773 // This might throw no asserts, for large sector devices, where
774 // a single failure writing is indistinguishable from no failure,
775 // or throw a single assert for small sector devices that fail
776 // multiple times...
777 if asserts > 1 {
778 warn!("Expected single assert validating slot0, more detected {}", asserts);
779 fails += 1;
780 }
781
782 if fails > 0 {
783 error!("Error running upgrade with status write fails");
784 }
785
786 fails > 0
787 }
788
789 #[cfg(not(feature = "validate-slot0"))]
790 #[cfg(not(feature = "overwrite-only"))]
791 pub fn run_with_status_fails_with_reset(&self) -> bool {
792 let mut fl = self.flash.clone();
793 let mut fails = 0;
794
795 info!("Try interrupted swap with status fails");
796
797 mark_permanent_upgrade(&mut fl, &self.slot1, self.align);
798
799 let status_off = self.slot1.base_off - self.trailer_sz();
800
801 // Mark the status area as a bad area
802 let _ = fl.add_bad_region(status_off, self.status_sz(), 1.0);
803
804 // This is expected to fail while writing to bad regions...
805 let (_, asserts) = c::boot_go(&mut fl, &self.areadesc, None, self.align, true);
806 if asserts == 0 {
807 warn!("No assert() detected");
808 fails += 1;
809 }
810
811 fails > 0
812 }
813
814 #[cfg(feature = "overwrite-only")]
815 pub fn run_with_status_fails_with_reset(&self) -> bool {
816 false
817 }
David Brown2639e072017-10-11 11:18:44 -0600818}
819
820/// Test a boot, optionally stopping after 'n' flash options. Returns a count
821/// of the number of flash operations done total.
David Brown3f687dc2017-11-06 13:41:18 -0700822fn try_upgrade(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600823 stop: Option<i32>) -> (SimFlash, i32) {
824 // Clone the flash to have a new copy.
825 let mut fl = flash.clone();
826
David Brown541860c2017-11-06 11:25:42 -0700827 mark_permanent_upgrade(&mut fl, &images.slot1, images.align);
David Brown2639e072017-10-11 11:18:44 -0600828
David Brownee61c832017-11-06 11:13:25 -0700829 let mut counter = stop.unwrap_or(0);
830
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200831 let (first_interrupted, count) = match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align, false) {
832 (-0x13579, _) => (true, stop.unwrap()),
833 (0, _) => (false, -counter),
834 (x, _) => panic!("Unknown return: {}", x),
David Brown2639e072017-10-11 11:18:44 -0600835 };
David Brown2639e072017-10-11 11:18:44 -0600836
David Brownee61c832017-11-06 11:13:25 -0700837 counter = 0;
David Brown2639e072017-10-11 11:18:44 -0600838 if first_interrupted {
839 // fl.dump();
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200840 match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align, false) {
841 (-0x13579, _) => panic!("Shouldn't stop again"),
842 (0, _) => (),
843 (x, _) => panic!("Unknown return: {}", x),
David Brown2639e072017-10-11 11:18:44 -0600844 }
845 }
846
David Brownee61c832017-11-06 11:13:25 -0700847 (fl, count - counter)
David Brown2639e072017-10-11 11:18:44 -0600848}
849
850#[cfg(not(feature = "overwrite-only"))]
David Brown541860c2017-11-06 11:25:42 -0700851fn try_revert(flash: &SimFlash, areadesc: &AreaDesc, count: usize, align: u8) -> SimFlash {
David Brown2639e072017-10-11 11:18:44 -0600852 let mut fl = flash.clone();
David Brown2639e072017-10-11 11:18:44 -0600853
854 // fl.write_file("image0.bin").unwrap();
855 for i in 0 .. count {
856 info!("Running boot pass {}", i + 1);
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200857 assert_eq!(c::boot_go(&mut fl, &areadesc, None, align, false), (0, 0));
David Brown2639e072017-10-11 11:18:44 -0600858 }
859 fl
860}
861
862#[cfg(not(feature = "overwrite-only"))]
David Brown3f687dc2017-11-06 13:41:18 -0700863fn try_revert_with_fail_at(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600864 stop: i32) -> bool {
865 let mut fl = flash.clone();
David Brown2639e072017-10-11 11:18:44 -0600866 let mut fails = 0;
867
David Brownee61c832017-11-06 11:13:25 -0700868 let mut counter = stop;
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200869 let (x, _) = c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align, false);
David Brown2639e072017-10-11 11:18:44 -0600870 if x != -0x13579 {
871 warn!("Should have stopped at interruption point");
872 fails += 1;
873 }
874
875 if !verify_trailer(&fl, images.slot0.trailer_off, None, None, UNSET) {
876 warn!("copy_done should be unset");
877 fails += 1;
878 }
879
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200880 let (x, _) = c::boot_go(&mut fl, &images.areadesc, None, images.align, false);
David Brown2639e072017-10-11 11:18:44 -0600881 if x != 0 {
882 warn!("Should have finished upgrade");
883 fails += 1;
884 }
885
886 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
887 warn!("Image in slot 0 before revert is invalid at stop={}", stop);
888 fails += 1;
889 }
890 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
891 warn!("Image in slot 1 before revert is invalid at stop={}", stop);
892 fails += 1;
893 }
894 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
895 COPY_DONE) {
896 warn!("Mismatched trailer for Slot 0 before revert");
897 fails += 1;
898 }
899 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
900 UNSET) {
901 warn!("Mismatched trailer for Slot 1 before revert");
902 fails += 1;
903 }
904
905 // Do Revert
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200906 let (x, _) = c::boot_go(&mut fl, &images.areadesc, None, images.align, false);
David Brown2639e072017-10-11 11:18:44 -0600907 if x != 0 {
908 warn!("Should have finished a revert");
909 fails += 1;
910 }
911
912 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
913 warn!("Image in slot 0 after revert is invalid at stop={}", stop);
914 fails += 1;
915 }
916 if !verify_image(&fl, images.slot1.base_off, &images.upgrade) {
917 warn!("Image in slot 1 after revert is invalid at stop={}", stop);
918 fails += 1;
919 }
920 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
921 COPY_DONE) {
922 warn!("Mismatched trailer for Slot 1 after revert");
923 fails += 1;
924 }
925 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
926 UNSET) {
927 warn!("Mismatched trailer for Slot 1 after revert");
928 fails += 1;
929 }
930
931 fails > 0
932}
933
David Brown3f687dc2017-11-06 13:41:18 -0700934fn try_random_fails(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600935 total_ops: i32, count: usize) -> (SimFlash, Vec<i32>) {
936 let mut fl = flash.clone();
937
David Brown541860c2017-11-06 11:25:42 -0700938 mark_permanent_upgrade(&mut fl, &images.slot1, images.align);
David Brown2639e072017-10-11 11:18:44 -0600939
940 let mut rng = rand::thread_rng();
941 let mut resets = vec![0i32; count];
942 let mut remaining_ops = total_ops;
943 for i in 0 .. count {
944 let ops = Range::new(1, remaining_ops / 2);
945 let reset_counter = ops.ind_sample(&mut rng);
David Brownee61c832017-11-06 11:13:25 -0700946 let mut counter = reset_counter;
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200947 match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align, false) {
948 (0, _) | (-0x13579, _) => (),
949 (x, _) => panic!("Unknown return: {}", x),
David Brown2639e072017-10-11 11:18:44 -0600950 }
951 remaining_ops -= reset_counter;
952 resets[i] = reset_counter;
953 }
954
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200955 match c::boot_go(&mut fl, &images.areadesc, None, images.align, false) {
956 (-0x13579, _) => panic!("Should not be have been interrupted!"),
957 (0, _) => (),
958 (x, _) => panic!("Unknown return: {}", x),
David Brown2639e072017-10-11 11:18:44 -0600959 }
960
961 (fl, resets)
962}
963
964/// Show the flash layout.
965#[allow(dead_code)]
966fn show_flash(flash: &Flash) {
967 println!("---- Flash configuration ----");
968 for sector in flash.sector_iter() {
969 println!(" {:3}: 0x{:08x}, 0x{:08x}",
970 sector.num, sector.base, sector.size);
971 }
972 println!("");
973}
974
975/// Install a "program" into the given image. This fakes the image header, or at least all of the
976/// fields used by the given code. Returns a copy of the image that was written.
977fn install_image(flash: &mut Flash, offset: usize, len: usize,
978 bad_sig: bool) -> Vec<u8> {
979 let offset0 = offset;
980
981 let mut tlv = make_tlv();
982
983 // Generate a boot header. Note that the size doesn't include the header.
984 let header = ImageHeader {
985 magic: 0x96f3b83d,
986 tlv_size: tlv.get_size(),
987 _pad1: 0,
988 hdr_size: 32,
989 key_id: 0,
990 _pad2: 0,
991 img_size: len as u32,
992 flags: tlv.get_flags(),
993 ver: ImageVersion {
994 major: (offset / (128 * 1024)) as u8,
995 minor: 0,
996 revision: 1,
997 build_num: offset as u32,
998 },
999 _pad3: 0,
1000 };
1001
1002 let b_header = header.as_raw();
1003 tlv.add_bytes(&b_header);
1004 /*
1005 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
1006 mem::size_of::<ImageHeader>()) };
1007 */
1008 assert_eq!(b_header.len(), 32);
1009 flash.write(offset, &b_header).unwrap();
1010 let offset = offset + b_header.len();
1011
1012 // The core of the image itself is just pseudorandom data.
1013 let mut buf = vec![0; len];
1014 splat(&mut buf, offset);
1015 tlv.add_bytes(&buf);
1016
1017 // Get and append the TLV itself.
1018 if bad_sig {
1019 let good_sig = &mut tlv.make_tlv();
1020 buf.append(&mut vec![0; good_sig.len()]);
1021 } else {
1022 buf.append(&mut tlv.make_tlv());
1023 }
1024
1025 // Pad the block to a flash alignment (8 bytes).
1026 while buf.len() % 8 != 0 {
1027 buf.push(0xFF);
1028 }
1029
1030 flash.write(offset, &buf).unwrap();
1031 let offset = offset + buf.len();
1032
1033 // Copy out the image so that we can verify that the image was installed correctly later.
1034 let mut copy = vec![0u8; offset - offset0];
1035 flash.read(offset0, &mut copy).unwrap();
1036
1037 copy
1038}
1039
1040// The TLV in use depends on what kind of signature we are verifying.
1041#[cfg(feature = "sig-rsa")]
1042fn make_tlv() -> TlvGen {
1043 TlvGen::new_rsa_pss()
1044}
1045
Fabio Utzig80fde2f2017-12-05 09:25:31 -02001046#[cfg(feature = "sig-ecdsa")]
1047fn make_tlv() -> TlvGen {
1048 TlvGen::new_ecdsa()
1049}
1050
David Brown2639e072017-10-11 11:18:44 -06001051#[cfg(not(feature = "sig-rsa"))]
Fabio Utzig80fde2f2017-12-05 09:25:31 -02001052#[cfg(not(feature = "sig-ecdsa"))]
David Brown2639e072017-10-11 11:18:44 -06001053fn make_tlv() -> TlvGen {
1054 TlvGen::new_hash_only()
1055}
1056
1057/// Verify that given image is present in the flash at the given offset.
1058fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
1059 let mut copy = vec![0u8; buf.len()];
1060 flash.read(offset, &mut copy).unwrap();
1061
1062 if buf != &copy[..] {
1063 for i in 0 .. buf.len() {
1064 if buf[i] != copy[i] {
1065 info!("First failure at {:#x}", offset + i);
1066 break;
1067 }
1068 }
1069 false
1070 } else {
1071 true
1072 }
1073}
1074
1075#[cfg(feature = "overwrite-only")]
1076#[allow(unused_variables)]
1077// overwrite-only doesn't employ trailer management
1078fn verify_trailer(flash: &Flash, offset: usize,
1079 magic: Option<&[u8]>, image_ok: Option<u8>,
1080 copy_done: Option<u8>) -> bool {
1081 true
1082}
1083
1084#[cfg(not(feature = "overwrite-only"))]
1085fn verify_trailer(flash: &Flash, offset: usize,
1086 magic: Option<&[u8]>, image_ok: Option<u8>,
1087 copy_done: Option<u8>) -> bool {
1088 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 2];
1089 let mut failed = false;
1090
1091 flash.read(offset, &mut copy).unwrap();
1092
1093 failed |= match magic {
1094 Some(v) => {
1095 if &copy[16..] != v {
1096 warn!("\"magic\" mismatch at {:#x}", offset);
1097 true
1098 } else {
1099 false
1100 }
1101 },
1102 None => false,
1103 };
1104
1105 failed |= match image_ok {
1106 Some(v) => {
1107 if copy[8] != v {
1108 warn!("\"image_ok\" mismatch at {:#x}", offset);
1109 true
1110 } else {
1111 false
1112 }
1113 },
1114 None => false,
1115 };
1116
1117 failed |= match copy_done {
1118 Some(v) => {
1119 if copy[0] != v {
1120 warn!("\"copy_done\" mismatch at {:#x}", offset);
1121 true
1122 } else {
1123 false
1124 }
1125 },
1126 None => false,
1127 };
1128
1129 !failed
1130}
1131
1132/// The image header
1133#[repr(C)]
1134pub struct ImageHeader {
1135 magic: u32,
1136 tlv_size: u16,
1137 key_id: u8,
1138 _pad1: u8,
1139 hdr_size: u16,
1140 _pad2: u16,
1141 img_size: u32,
1142 flags: u32,
1143 ver: ImageVersion,
1144 _pad3: u32,
1145}
1146
1147impl AsRaw for ImageHeader {}
1148
1149#[repr(C)]
1150pub struct ImageVersion {
1151 major: u8,
1152 minor: u8,
1153 revision: u16,
1154 build_num: u32,
1155}
1156
David Brownd5e632c2017-10-19 10:49:46 -06001157#[derive(Clone)]
David Brown2639e072017-10-11 11:18:44 -06001158struct SlotInfo {
1159 base_off: usize,
1160 trailer_off: usize,
1161}
1162
David Brownf48b9502017-11-06 14:00:26 -07001163pub struct Images {
David Browndc9cba12017-11-06 13:31:42 -07001164 flash: SimFlash,
David Brown3f687dc2017-11-06 13:41:18 -07001165 areadesc: AreaDesc,
David Brownd5e632c2017-10-19 10:49:46 -06001166 slot0: SlotInfo,
1167 slot1: SlotInfo,
David Brown2639e072017-10-11 11:18:44 -06001168 primary: Vec<u8>,
1169 upgrade: Vec<u8>,
David Brownc49811e2017-11-06 14:20:45 -07001170 total_count: Option<i32>,
David Brown541860c2017-11-06 11:25:42 -07001171 align: u8,
David Brown2639e072017-10-11 11:18:44 -06001172}
1173
1174const MAGIC_VALID: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3,
1175 0x60, 0xd2, 0xef, 0x7f,
1176 0x35, 0x52, 0x50, 0x0f,
1177 0x2c, 0xb6, 0x79, 0x80]);
1178const MAGIC_UNSET: Option<&[u8]> = Some(&[0xff; 16]);
1179
1180const COPY_DONE: Option<u8> = Some(1);
1181const IMAGE_OK: Option<u8> = Some(1);
1182const UNSET: Option<u8> = Some(0xff);
1183
1184/// Write out the magic so that the loader tries doing an upgrade.
1185fn mark_upgrade(flash: &mut Flash, slot: &SlotInfo) {
1186 let offset = slot.trailer_off + c::boot_max_align() * 2;
1187 flash.write(offset, MAGIC_VALID.unwrap()).unwrap();
1188}
1189
1190/// Writes the image_ok flag which, guess what, tells the bootloader
1191/// the this image is ok (not a test, and no revert is to be performed).
David Brown541860c2017-11-06 11:25:42 -07001192fn mark_permanent_upgrade(flash: &mut Flash, slot: &SlotInfo, align: u8) {
David Brown2639e072017-10-11 11:18:44 -06001193 let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
David Brown2639e072017-10-11 11:18:44 -06001194 let off = slot.trailer_off + c::boot_max_align();
David Brown541860c2017-11-06 11:25:42 -07001195 flash.write(off, &ok[..align as usize]).unwrap();
David Brown2639e072017-10-11 11:18:44 -06001196}
1197
1198// Drop some pseudo-random gibberish onto the data.
1199fn splat(data: &mut [u8], seed: usize) {
1200 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
1201 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
1202 rng.fill_bytes(data);
1203}
1204
1205/// Return a read-only view into the raw bytes of this object
1206trait AsRaw : Sized {
1207 fn as_raw<'a>(&'a self) -> &'a [u8] {
1208 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1209 mem::size_of::<Self>()) }
1210 }
1211}
1212
1213fn show_sizes() {
1214 // This isn't panic safe.
David Brown2639e072017-10-11 11:18:44 -06001215 for min in &[1, 2, 4, 8] {
David Brown541860c2017-11-06 11:25:42 -07001216 let msize = c::boot_trailer_sz(*min);
David Brown2639e072017-10-11 11:18:44 -06001217 println!("{:2}: {} (0x{:x})", min, msize, msize);
1218 }
David Brown2639e072017-10-11 11:18:44 -06001219}