blob: 2b240db00128e28dc6316f2835a35918e06bcb06 [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
Fabio Utziga91c6262017-12-06 09:01:12 -0200670 #[cfg(not(feature = "overwrite-only"))]
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200671 fn trailer_sz(&self) -> usize {
672 c::boot_trailer_sz(self.align) as usize
673 }
674
675 // FIXME: could get status sz from bootloader
Fabio Utziga91c6262017-12-06 09:01:12 -0200676 #[cfg(not(feature = "overwrite-only"))]
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200677 fn status_sz(&self) -> usize {
678 self.trailer_sz() - (16 + 24)
679 }
680
681 /// This test runs a simple upgrade with no fails in the images, but
682 /// allowing for fails in the status area. This should run to the end
683 /// and warn that write fails were detected...
684 #[cfg(not(feature = "validate-slot0"))]
685 pub fn run_with_status_fails_complete(&self) -> bool { false }
686
687 #[cfg(feature = "validate-slot0")]
688 pub fn run_with_status_fails_complete(&self) -> bool {
689 let mut fl = self.flash.clone();
690 let mut fails = 0;
691
692 info!("Try swap with status fails");
693
694 mark_permanent_upgrade(&mut fl, &self.slot1, self.align);
695
696 let status_off = self.slot1.base_off - self.trailer_sz();
697
698 // Always fail writes to status area...
699 let _ = fl.add_bad_region(status_off, self.status_sz(), 1.0);
700
701 let (result, asserts) = c::boot_go(&mut fl, &self.areadesc, None, self.align, true);
702 if result != 0 {
703 warn!("Failed!");
704 fails += 1;
705 }
706
707 // Failed writes to the marked "bad" region don't assert anymore.
708 // Any detected assert() is happening in another part of the code.
709 if asserts != 0 {
710 warn!("At least one assert() was called");
711 fails += 1;
712 }
713
714 if !verify_trailer(&fl, self.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
715 COPY_DONE) {
716 warn!("Mismatched trailer for Slot 0");
717 fails += 1;
718 }
719
720 if !verify_image(&fl, self.slot0.base_off, &self.upgrade) {
721 warn!("Failed image verification");
722 fails += 1;
723 }
724
725 info!("validate slot0 enabled; re-run of boot_go should just work");
726 let (result, _) = c::boot_go(&mut fl, &self.areadesc, None, self.align, false);
727 if result != 0 {
728 warn!("Failed!");
729 fails += 1;
730 }
731
732 if fails > 0 {
733 error!("Error running upgrade with status write fails");
734 }
735
736 fails > 0
737 }
738
739 /// This test runs a simple upgrade with no fails in the images, but
740 /// allowing for fails in the status area. This should run to the end
741 /// and warn that write fails were detected...
742 #[cfg(feature = "validate-slot0")]
743 pub fn run_with_status_fails_with_reset(&self) -> bool {
744 let mut fl = self.flash.clone();
745 let mut fails = 0;
746 let mut count = self.total_count.unwrap() / 2;
747
748 //info!("count={}\n", count);
749
750 info!("Try interrupted swap with status fails");
751
752 mark_permanent_upgrade(&mut fl, &self.slot1, self.align);
753
754 let status_off = self.slot1.base_off - self.trailer_sz();
755
756 // Mark the status area as a bad area
757 let _ = fl.add_bad_region(status_off, self.status_sz(), 0.5);
758
759 // Should not fail, writing to bad regions does not assert
760 let (_, asserts) = c::boot_go(&mut fl, &self.areadesc, Some(&mut count), self.align, true);
761 if asserts != 0 {
762 warn!("At least one assert() was called");
763 fails += 1;
764 }
765
766 fl.reset_bad_regions();
767
768 // Disabling write verification the only assert triggered by
769 // boot_go should be checking for integrity of status bytes.
770 fl.set_verify_writes(false);
771
772 info!("Resuming an interrupted swap operation");
773 let (_, asserts) = c::boot_go(&mut fl, &self.areadesc, None, self.align, true);
774
775 // This might throw no asserts, for large sector devices, where
776 // a single failure writing is indistinguishable from no failure,
777 // or throw a single assert for small sector devices that fail
778 // multiple times...
779 if asserts > 1 {
780 warn!("Expected single assert validating slot0, more detected {}", asserts);
781 fails += 1;
782 }
783
784 if fails > 0 {
785 error!("Error running upgrade with status write fails");
786 }
787
788 fails > 0
789 }
790
791 #[cfg(not(feature = "validate-slot0"))]
792 #[cfg(not(feature = "overwrite-only"))]
793 pub fn run_with_status_fails_with_reset(&self) -> bool {
794 let mut fl = self.flash.clone();
795 let mut fails = 0;
796
797 info!("Try interrupted swap with status fails");
798
799 mark_permanent_upgrade(&mut fl, &self.slot1, self.align);
800
801 let status_off = self.slot1.base_off - self.trailer_sz();
802
803 // Mark the status area as a bad area
804 let _ = fl.add_bad_region(status_off, self.status_sz(), 1.0);
805
806 // This is expected to fail while writing to bad regions...
807 let (_, asserts) = c::boot_go(&mut fl, &self.areadesc, None, self.align, true);
808 if asserts == 0 {
809 warn!("No assert() detected");
810 fails += 1;
811 }
812
813 fails > 0
814 }
815
816 #[cfg(feature = "overwrite-only")]
817 pub fn run_with_status_fails_with_reset(&self) -> bool {
818 false
819 }
David Brown2639e072017-10-11 11:18:44 -0600820}
821
822/// Test a boot, optionally stopping after 'n' flash options. Returns a count
823/// of the number of flash operations done total.
David Brown3f687dc2017-11-06 13:41:18 -0700824fn try_upgrade(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600825 stop: Option<i32>) -> (SimFlash, i32) {
826 // Clone the flash to have a new copy.
827 let mut fl = flash.clone();
828
David Brown541860c2017-11-06 11:25:42 -0700829 mark_permanent_upgrade(&mut fl, &images.slot1, images.align);
David Brown2639e072017-10-11 11:18:44 -0600830
David Brownee61c832017-11-06 11:13:25 -0700831 let mut counter = stop.unwrap_or(0);
832
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200833 let (first_interrupted, count) = match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align, false) {
834 (-0x13579, _) => (true, stop.unwrap()),
835 (0, _) => (false, -counter),
836 (x, _) => panic!("Unknown return: {}", x),
David Brown2639e072017-10-11 11:18:44 -0600837 };
David Brown2639e072017-10-11 11:18:44 -0600838
David Brownee61c832017-11-06 11:13:25 -0700839 counter = 0;
David Brown2639e072017-10-11 11:18:44 -0600840 if first_interrupted {
841 // fl.dump();
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200842 match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align, false) {
843 (-0x13579, _) => panic!("Shouldn't stop again"),
844 (0, _) => (),
845 (x, _) => panic!("Unknown return: {}", x),
David Brown2639e072017-10-11 11:18:44 -0600846 }
847 }
848
David Brownee61c832017-11-06 11:13:25 -0700849 (fl, count - counter)
David Brown2639e072017-10-11 11:18:44 -0600850}
851
852#[cfg(not(feature = "overwrite-only"))]
David Brown541860c2017-11-06 11:25:42 -0700853fn try_revert(flash: &SimFlash, areadesc: &AreaDesc, count: usize, align: u8) -> SimFlash {
David Brown2639e072017-10-11 11:18:44 -0600854 let mut fl = flash.clone();
David Brown2639e072017-10-11 11:18:44 -0600855
856 // fl.write_file("image0.bin").unwrap();
857 for i in 0 .. count {
858 info!("Running boot pass {}", i + 1);
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200859 assert_eq!(c::boot_go(&mut fl, &areadesc, None, align, false), (0, 0));
David Brown2639e072017-10-11 11:18:44 -0600860 }
861 fl
862}
863
864#[cfg(not(feature = "overwrite-only"))]
David Brown3f687dc2017-11-06 13:41:18 -0700865fn try_revert_with_fail_at(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600866 stop: i32) -> bool {
867 let mut fl = flash.clone();
David Brown2639e072017-10-11 11:18:44 -0600868 let mut fails = 0;
869
David Brownee61c832017-11-06 11:13:25 -0700870 let mut counter = stop;
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200871 let (x, _) = c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align, false);
David Brown2639e072017-10-11 11:18:44 -0600872 if x != -0x13579 {
873 warn!("Should have stopped at interruption point");
874 fails += 1;
875 }
876
877 if !verify_trailer(&fl, images.slot0.trailer_off, None, None, UNSET) {
878 warn!("copy_done should be unset");
879 fails += 1;
880 }
881
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200882 let (x, _) = c::boot_go(&mut fl, &images.areadesc, None, images.align, false);
David Brown2639e072017-10-11 11:18:44 -0600883 if x != 0 {
884 warn!("Should have finished upgrade");
885 fails += 1;
886 }
887
888 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
889 warn!("Image in slot 0 before revert is invalid at stop={}", stop);
890 fails += 1;
891 }
892 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
893 warn!("Image in slot 1 before revert is invalid at stop={}", stop);
894 fails += 1;
895 }
896 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
897 COPY_DONE) {
898 warn!("Mismatched trailer for Slot 0 before revert");
899 fails += 1;
900 }
901 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
902 UNSET) {
903 warn!("Mismatched trailer for Slot 1 before revert");
904 fails += 1;
905 }
906
907 // Do Revert
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200908 let (x, _) = c::boot_go(&mut fl, &images.areadesc, None, images.align, false);
David Brown2639e072017-10-11 11:18:44 -0600909 if x != 0 {
910 warn!("Should have finished a revert");
911 fails += 1;
912 }
913
914 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
915 warn!("Image in slot 0 after revert is invalid at stop={}", stop);
916 fails += 1;
917 }
918 if !verify_image(&fl, images.slot1.base_off, &images.upgrade) {
919 warn!("Image in slot 1 after revert is invalid at stop={}", stop);
920 fails += 1;
921 }
922 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
923 COPY_DONE) {
924 warn!("Mismatched trailer for Slot 1 after revert");
925 fails += 1;
926 }
927 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
928 UNSET) {
929 warn!("Mismatched trailer for Slot 1 after revert");
930 fails += 1;
931 }
932
933 fails > 0
934}
935
David Brown3f687dc2017-11-06 13:41:18 -0700936fn try_random_fails(flash: &SimFlash, images: &Images,
David Brown2639e072017-10-11 11:18:44 -0600937 total_ops: i32, count: usize) -> (SimFlash, Vec<i32>) {
938 let mut fl = flash.clone();
939
David Brown541860c2017-11-06 11:25:42 -0700940 mark_permanent_upgrade(&mut fl, &images.slot1, images.align);
David Brown2639e072017-10-11 11:18:44 -0600941
942 let mut rng = rand::thread_rng();
943 let mut resets = vec![0i32; count];
944 let mut remaining_ops = total_ops;
945 for i in 0 .. count {
946 let ops = Range::new(1, remaining_ops / 2);
947 let reset_counter = ops.ind_sample(&mut rng);
David Brownee61c832017-11-06 11:13:25 -0700948 let mut counter = reset_counter;
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200949 match c::boot_go(&mut fl, &images.areadesc, Some(&mut counter), images.align, false) {
950 (0, _) | (-0x13579, _) => (),
951 (x, _) => panic!("Unknown return: {}", x),
David Brown2639e072017-10-11 11:18:44 -0600952 }
953 remaining_ops -= reset_counter;
954 resets[i] = reset_counter;
955 }
956
Fabio Utzig9b0ee902017-11-23 19:49:00 -0200957 match c::boot_go(&mut fl, &images.areadesc, None, images.align, false) {
958 (-0x13579, _) => panic!("Should not be have been interrupted!"),
959 (0, _) => (),
960 (x, _) => panic!("Unknown return: {}", x),
David Brown2639e072017-10-11 11:18:44 -0600961 }
962
963 (fl, resets)
964}
965
966/// Show the flash layout.
967#[allow(dead_code)]
968fn show_flash(flash: &Flash) {
969 println!("---- Flash configuration ----");
970 for sector in flash.sector_iter() {
971 println!(" {:3}: 0x{:08x}, 0x{:08x}",
972 sector.num, sector.base, sector.size);
973 }
974 println!("");
975}
976
977/// Install a "program" into the given image. This fakes the image header, or at least all of the
978/// fields used by the given code. Returns a copy of the image that was written.
979fn install_image(flash: &mut Flash, offset: usize, len: usize,
980 bad_sig: bool) -> Vec<u8> {
981 let offset0 = offset;
982
983 let mut tlv = make_tlv();
984
985 // Generate a boot header. Note that the size doesn't include the header.
986 let header = ImageHeader {
987 magic: 0x96f3b83d,
988 tlv_size: tlv.get_size(),
989 _pad1: 0,
990 hdr_size: 32,
991 key_id: 0,
992 _pad2: 0,
993 img_size: len as u32,
994 flags: tlv.get_flags(),
995 ver: ImageVersion {
996 major: (offset / (128 * 1024)) as u8,
997 minor: 0,
998 revision: 1,
999 build_num: offset as u32,
1000 },
1001 _pad3: 0,
1002 };
1003
1004 let b_header = header.as_raw();
1005 tlv.add_bytes(&b_header);
1006 /*
1007 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
1008 mem::size_of::<ImageHeader>()) };
1009 */
1010 assert_eq!(b_header.len(), 32);
1011 flash.write(offset, &b_header).unwrap();
1012 let offset = offset + b_header.len();
1013
1014 // The core of the image itself is just pseudorandom data.
1015 let mut buf = vec![0; len];
1016 splat(&mut buf, offset);
1017 tlv.add_bytes(&buf);
1018
1019 // Get and append the TLV itself.
1020 if bad_sig {
1021 let good_sig = &mut tlv.make_tlv();
1022 buf.append(&mut vec![0; good_sig.len()]);
1023 } else {
1024 buf.append(&mut tlv.make_tlv());
1025 }
1026
1027 // Pad the block to a flash alignment (8 bytes).
1028 while buf.len() % 8 != 0 {
1029 buf.push(0xFF);
1030 }
1031
1032 flash.write(offset, &buf).unwrap();
1033 let offset = offset + buf.len();
1034
1035 // Copy out the image so that we can verify that the image was installed correctly later.
1036 let mut copy = vec![0u8; offset - offset0];
1037 flash.read(offset0, &mut copy).unwrap();
1038
1039 copy
1040}
1041
1042// The TLV in use depends on what kind of signature we are verifying.
1043#[cfg(feature = "sig-rsa")]
1044fn make_tlv() -> TlvGen {
1045 TlvGen::new_rsa_pss()
1046}
1047
Fabio Utzig80fde2f2017-12-05 09:25:31 -02001048#[cfg(feature = "sig-ecdsa")]
1049fn make_tlv() -> TlvGen {
1050 TlvGen::new_ecdsa()
1051}
1052
David Brown2639e072017-10-11 11:18:44 -06001053#[cfg(not(feature = "sig-rsa"))]
Fabio Utzig80fde2f2017-12-05 09:25:31 -02001054#[cfg(not(feature = "sig-ecdsa"))]
David Brown2639e072017-10-11 11:18:44 -06001055fn make_tlv() -> TlvGen {
1056 TlvGen::new_hash_only()
1057}
1058
1059/// Verify that given image is present in the flash at the given offset.
1060fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
1061 let mut copy = vec![0u8; buf.len()];
1062 flash.read(offset, &mut copy).unwrap();
1063
1064 if buf != &copy[..] {
1065 for i in 0 .. buf.len() {
1066 if buf[i] != copy[i] {
1067 info!("First failure at {:#x}", offset + i);
1068 break;
1069 }
1070 }
1071 false
1072 } else {
1073 true
1074 }
1075}
1076
1077#[cfg(feature = "overwrite-only")]
1078#[allow(unused_variables)]
1079// overwrite-only doesn't employ trailer management
1080fn verify_trailer(flash: &Flash, offset: usize,
1081 magic: Option<&[u8]>, image_ok: Option<u8>,
1082 copy_done: Option<u8>) -> bool {
1083 true
1084}
1085
1086#[cfg(not(feature = "overwrite-only"))]
1087fn verify_trailer(flash: &Flash, offset: usize,
1088 magic: Option<&[u8]>, image_ok: Option<u8>,
1089 copy_done: Option<u8>) -> bool {
1090 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 2];
1091 let mut failed = false;
1092
1093 flash.read(offset, &mut copy).unwrap();
1094
1095 failed |= match magic {
1096 Some(v) => {
1097 if &copy[16..] != v {
1098 warn!("\"magic\" mismatch at {:#x}", offset);
1099 true
1100 } else {
1101 false
1102 }
1103 },
1104 None => false,
1105 };
1106
1107 failed |= match image_ok {
1108 Some(v) => {
1109 if copy[8] != v {
1110 warn!("\"image_ok\" mismatch at {:#x}", offset);
1111 true
1112 } else {
1113 false
1114 }
1115 },
1116 None => false,
1117 };
1118
1119 failed |= match copy_done {
1120 Some(v) => {
1121 if copy[0] != v {
1122 warn!("\"copy_done\" mismatch at {:#x}", offset);
1123 true
1124 } else {
1125 false
1126 }
1127 },
1128 None => false,
1129 };
1130
1131 !failed
1132}
1133
1134/// The image header
1135#[repr(C)]
1136pub struct ImageHeader {
1137 magic: u32,
1138 tlv_size: u16,
1139 key_id: u8,
1140 _pad1: u8,
1141 hdr_size: u16,
1142 _pad2: u16,
1143 img_size: u32,
1144 flags: u32,
1145 ver: ImageVersion,
1146 _pad3: u32,
1147}
1148
1149impl AsRaw for ImageHeader {}
1150
1151#[repr(C)]
1152pub struct ImageVersion {
1153 major: u8,
1154 minor: u8,
1155 revision: u16,
1156 build_num: u32,
1157}
1158
David Brownd5e632c2017-10-19 10:49:46 -06001159#[derive(Clone)]
David Brown2639e072017-10-11 11:18:44 -06001160struct SlotInfo {
1161 base_off: usize,
1162 trailer_off: usize,
1163}
1164
David Brownf48b9502017-11-06 14:00:26 -07001165pub struct Images {
David Browndc9cba12017-11-06 13:31:42 -07001166 flash: SimFlash,
David Brown3f687dc2017-11-06 13:41:18 -07001167 areadesc: AreaDesc,
David Brownd5e632c2017-10-19 10:49:46 -06001168 slot0: SlotInfo,
1169 slot1: SlotInfo,
David Brown2639e072017-10-11 11:18:44 -06001170 primary: Vec<u8>,
1171 upgrade: Vec<u8>,
David Brownc49811e2017-11-06 14:20:45 -07001172 total_count: Option<i32>,
David Brown541860c2017-11-06 11:25:42 -07001173 align: u8,
David Brown2639e072017-10-11 11:18:44 -06001174}
1175
1176const MAGIC_VALID: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3,
1177 0x60, 0xd2, 0xef, 0x7f,
1178 0x35, 0x52, 0x50, 0x0f,
1179 0x2c, 0xb6, 0x79, 0x80]);
1180const MAGIC_UNSET: Option<&[u8]> = Some(&[0xff; 16]);
1181
1182const COPY_DONE: Option<u8> = Some(1);
1183const IMAGE_OK: Option<u8> = Some(1);
1184const UNSET: Option<u8> = Some(0xff);
1185
1186/// Write out the magic so that the loader tries doing an upgrade.
1187fn mark_upgrade(flash: &mut Flash, slot: &SlotInfo) {
1188 let offset = slot.trailer_off + c::boot_max_align() * 2;
1189 flash.write(offset, MAGIC_VALID.unwrap()).unwrap();
1190}
1191
1192/// Writes the image_ok flag which, guess what, tells the bootloader
1193/// the this image is ok (not a test, and no revert is to be performed).
David Brown541860c2017-11-06 11:25:42 -07001194fn mark_permanent_upgrade(flash: &mut Flash, slot: &SlotInfo, align: u8) {
David Brown2639e072017-10-11 11:18:44 -06001195 let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
David Brown2639e072017-10-11 11:18:44 -06001196 let off = slot.trailer_off + c::boot_max_align();
David Brown541860c2017-11-06 11:25:42 -07001197 flash.write(off, &ok[..align as usize]).unwrap();
David Brown2639e072017-10-11 11:18:44 -06001198}
1199
1200// Drop some pseudo-random gibberish onto the data.
1201fn splat(data: &mut [u8], seed: usize) {
1202 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
1203 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
1204 rng.fill_bytes(data);
1205}
1206
1207/// Return a read-only view into the raw bytes of this object
1208trait AsRaw : Sized {
1209 fn as_raw<'a>(&'a self) -> &'a [u8] {
1210 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1211 mem::size_of::<Self>()) }
1212 }
1213}
1214
1215fn show_sizes() {
1216 // This isn't panic safe.
David Brown2639e072017-10-11 11:18:44 -06001217 for min in &[1, 2, 4, 8] {
David Brown541860c2017-11-06 11:25:42 -07001218 let msize = c::boot_trailer_sz(*min);
David Brown2639e072017-10-11 11:18:44 -06001219 println!("{:2}: {} (0x{:x})", min, msize, msize);
1220 }
David Brown2639e072017-10-11 11:18:44 -06001221}