blob: eed985520a3b8d4ad01bde8f50124a194aea0aa3 [file] [log] [blame]
David Brown4440af82017-01-09 12:15:05 -07001#[macro_use] extern crate log;
David Brown8054ce22017-07-11 12:12:09 -06002extern crate ring;
David Brown4440af82017-01-09 12:15:05 -07003extern crate env_logger;
David Brown1e158592017-07-11 12:29:25 -06004#[macro_use] extern crate bitflags;
David Brownde7729e2017-01-09 10:41:35 -07005extern crate docopt;
6extern crate libc;
David Brown7e701d82017-07-11 13:24:25 -06007extern crate pem;
David Brownde7729e2017-01-09 10:41:35 -07008extern crate rand;
David Brown046a0a62017-07-12 16:08:22 -06009#[macro_use] extern crate serde_derive;
10extern crate serde;
David Brown2cbc4702017-07-06 14:18:58 -060011extern crate simflash;
David Brown7e701d82017-07-11 13:24:25 -060012extern crate untrusted;
David Brown63902772017-07-12 09:47:49 -060013extern crate mcuboot_sys;
David Brownde7729e2017-01-09 10:41:35 -070014
15use docopt::Docopt;
David Brown4cb26232017-04-11 08:15:18 -060016use rand::{Rng, SeedableRng, XorShiftRng};
Fabio Utzigbb5635e2017-04-10 09:07:02 -030017use rand::distributions::{IndependentSample, Range};
David Browna3b93cf2017-03-29 12:41:26 -060018use std::fmt;
David Brownde7729e2017-01-09 10:41:35 -070019use std::mem;
David Brown361be7a2017-03-29 12:28:47 -060020use std::process;
David Brownde7729e2017-01-09 10:41:35 -070021use std::slice;
22
David Brown902d6172017-05-05 09:37:41 -060023mod caps;
David Brown187dd882017-07-11 11:15:23 -060024mod tlv;
David Brownde7729e2017-01-09 10:41:35 -070025
David Brown2cbc4702017-07-06 14:18:58 -060026use simflash::{Flash, SimFlash};
David Brownf52272c2017-07-12 09:56:16 -060027use mcuboot_sys::{c, AreaDesc, FlashId};
David Brown902d6172017-05-05 09:37:41 -060028use caps::Caps;
David Brown187dd882017-07-11 11:15:23 -060029use tlv::TlvGen;
David Brownde7729e2017-01-09 10:41:35 -070030
31const USAGE: &'static str = "
32Mcuboot simulator
33
34Usage:
35 bootsim sizes
36 bootsim run --device TYPE [--align SIZE]
David Browna3b93cf2017-03-29 12:41:26 -060037 bootsim runall
David Brownde7729e2017-01-09 10:41:35 -070038 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
David Brown046a0a62017-07-12 16:08:22 -060048#[derive(Debug, Deserialize)]
David Brownde7729e2017-01-09 10:41:35 -070049struct 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,
David Browna3b93cf2017-03-29 12:41:26 -060056 cmd_runall: bool,
David Brownde7729e2017-01-09 10:41:35 -070057}
58
David Brown046a0a62017-07-12 16:08:22 -060059#[derive(Copy, Clone, Debug, Deserialize)]
David Brown07fb8fa2017-03-20 12:40:57 -060060enum DeviceName { Stm32f4, K64f, K64fBig, Nrf52840 }
David Brownde7729e2017-01-09 10:41:35 -070061
David Browna3b93cf2017-03-29 12:41:26 -060062static ALL_DEVICES: &'static [DeviceName] = &[
63 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
David Brownde7729e2017-01-09 10:41:35 -070081#[derive(Debug)]
82struct AlignArg(u8);
83
David Brown046a0a62017-07-12 16:08:22 -060084struct 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)
David Brownde7729e2017-01-09 10:41:35 -0700111 }
112}
113
114fn main() {
David Brown4440af82017-01-09 12:15:05 -0700115 env_logger::init().unwrap();
116
David Brownde7729e2017-01-09 10:41:35 -0700117 let args: Args = Docopt::new(USAGE)
David Brown046a0a62017-07-12 16:08:22 -0600118 .and_then(|d| d.deserialize())
David Brownde7729e2017-01-09 10:41:35 -0700119 .unwrap_or_else(|e| e.exit());
120 // println!("args: {:#?}", args);
121
122 if args.cmd_sizes {
123 show_sizes();
124 return;
125 }
126
David Brown361be7a2017-03-29 12:28:47 -0600127 let mut status = RunStatus::new();
David Browna3b93cf2017-03-29 12:41:26 -0600128 if args.cmd_run {
David Brown361be7a2017-03-29 12:28:47 -0600129
David Browna3b93cf2017-03-29 12:41:26 -0600130 let align = args.flag_align.map(|x| x.0).unwrap_or(1);
David Brown562a7a02017-01-23 11:19:03 -0700131
Fabio Utzigebeecef2017-07-06 10:36:42 -0300132
David Browna3b93cf2017-03-29 12:41:26 -0600133 let device = match args.flag_device {
134 None => panic!("Missing mandatory device argument"),
135 Some(dev) => dev,
136 };
David Brownde7729e2017-01-09 10:41:35 -0700137
David Browna3b93cf2017-03-29 12:41:26 -0600138 status.run_single(device, align);
139 }
140
141 if args.cmd_runall {
142 for &dev in ALL_DEVICES {
143 for &align in &[1, 2, 4, 8] {
144 status.run_single(dev, align);
145 }
146 }
147 }
David Brown5c6b6792017-03-20 12:51:28 -0600148
David Brown361be7a2017-03-29 12:28:47 -0600149 if status.failures > 0 {
David Brown187dd882017-07-11 11:15:23 -0600150 error!("{} Tests ran with {} failures", status.failures + status.passes, status.failures);
David Brown361be7a2017-03-29 12:28:47 -0600151 process::exit(1);
152 } else {
153 warn!("{} Tests ran successfully", status.passes);
154 process::exit(0);
155 }
156}
David Brown5c6b6792017-03-20 12:51:28 -0600157
David Brown361be7a2017-03-29 12:28:47 -0600158struct RunStatus {
159 failures: usize,
160 passes: usize,
161}
David Brownde7729e2017-01-09 10:41:35 -0700162
David Brown361be7a2017-03-29 12:28:47 -0600163impl RunStatus {
164 fn new() -> RunStatus {
165 RunStatus {
166 failures: 0,
167 passes: 0,
David Brownde7729e2017-01-09 10:41:35 -0700168 }
169 }
David Brownde7729e2017-01-09 10:41:35 -0700170
David Brown361be7a2017-03-29 12:28:47 -0600171 fn run_single(&mut self, device: DeviceName, align: u8) {
David Browna3b93cf2017-03-29 12:41:26 -0600172 warn!("Running on device {} with alignment {}", device, align);
173
David Brown361be7a2017-03-29 12:28:47 -0600174 let (mut flash, areadesc) = match device {
175 DeviceName::Stm32f4 => {
176 // STM style flash. Large sectors, with a large scratch area.
David Brown7ddec0b2017-07-06 10:47:35 -0600177 let flash = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
178 64 * 1024,
179 128 * 1024, 128 * 1024, 128 * 1024],
180 align as usize);
David Brown361be7a2017-03-29 12:28:47 -0600181 let mut areadesc = AreaDesc::new(&flash);
182 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
183 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
184 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch);
185 (flash, areadesc)
186 }
187 DeviceName::K64f => {
188 // NXP style flash. Small sectors, one small sector for scratch.
David Brown7ddec0b2017-07-06 10:47:35 -0600189 let flash = SimFlash::new(vec![4096; 128], align as usize);
David Brown361be7a2017-03-29 12:28:47 -0600190
191 let mut areadesc = AreaDesc::new(&flash);
192 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
193 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
194 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch);
195 (flash, areadesc)
196 }
197 DeviceName::K64fBig => {
198 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
199 // uses small sectors, but we tell the bootloader they are large.
David Brown7ddec0b2017-07-06 10:47:35 -0600200 let flash = SimFlash::new(vec![4096; 128], align as usize);
David Brown361be7a2017-03-29 12:28:47 -0600201
202 let mut areadesc = AreaDesc::new(&flash);
203 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0);
204 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1);
205 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch);
206 (flash, areadesc)
207 }
208 DeviceName::Nrf52840 => {
209 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
210 // does not divide into the image size.
David Brown7ddec0b2017-07-06 10:47:35 -0600211 let flash = SimFlash::new(vec![4096; 128], align as usize);
David Brown361be7a2017-03-29 12:28:47 -0600212
213 let mut areadesc = AreaDesc::new(&flash);
214 areadesc.add_image(0x008000, 0x034000, FlashId::Image0);
215 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1);
216 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch);
217 (flash, areadesc)
218 }
219 };
220
221 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
222 let (slot1_base, slot1_len) = areadesc.find(FlashId::Image1);
223 let (scratch_base, _) = areadesc.find(FlashId::ImageScratch);
224
225 // Code below assumes that the slots are consecutive.
226 assert_eq!(slot1_base, slot0_base + slot0_len);
227 assert_eq!(scratch_base, slot1_base + slot1_len);
228
Fabio Utzigebeecef2017-07-06 10:36:42 -0300229 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 2;
230
David Brown361be7a2017-03-29 12:28:47 -0600231 // println!("Areas: {:#?}", areadesc.get_c());
232
233 // Install the boot trailer signature, so that the code will start an upgrade.
234 // TODO: This must be a multiple of flash alignment, add support for an image that is smaller,
235 // and just gets padded.
David Brown361be7a2017-03-29 12:28:47 -0600236
Fabio Utzigebeecef2017-07-06 10:36:42 -0300237 // Create original and upgrade images
238 let slot0 = SlotInfo {
239 base_off: slot0_base as usize,
240 trailer_off: slot1_base - offset_from_end,
241 };
242
243 let slot1 = SlotInfo {
244 base_off: slot1_base as usize,
245 trailer_off: scratch_base - offset_from_end,
246 };
247
248 let images = Images {
249 slot0: slot0,
250 slot1: slot1,
251 primary: install_image(&mut flash, slot0_base, 32784),
252 upgrade: install_image(&mut flash, slot1_base, 41928),
253 };
254
255 let mut failed = false;
David Brown361be7a2017-03-29 12:28:47 -0600256
257 // Set an alignment, and position the magic value.
258 c::set_sim_flash_align(align);
David Brown361be7a2017-03-29 12:28:47 -0600259
Fabio Utzigebeecef2017-07-06 10:36:42 -0300260 mark_upgrade(&mut flash, &images.slot1);
David Brown361be7a2017-03-29 12:28:47 -0600261
Fabio Utzigebeecef2017-07-06 10:36:42 -0300262 // upgrades without fails, counts number of flash operations
263 let total_count = match run_basic_upgrade(&flash, &areadesc, &images) {
264 Ok(v) => v,
265 Err(_) => {
266 self.failures += 1;
267 return;
268 },
David Brown902d6172017-05-05 09:37:41 -0600269 };
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300270
Fabio Utzigebeecef2017-07-06 10:36:42 -0300271 failed |= run_basic_revert(&flash, &areadesc, &images);
272 failed |= run_revert_with_fails(&flash, &areadesc, &images, total_count);
273 failed |= run_perm_with_fails(&flash, &areadesc, &images, total_count);
274 failed |= run_perm_with_random_fails(&flash, &areadesc, &images,
275 total_count, 5);
276 failed |= run_norevert(&flash, &areadesc, &images);
David Brown361be7a2017-03-29 12:28:47 -0600277
Fabio Utzigebeecef2017-07-06 10:36:42 -0300278 //show_flash(&flash);
David Brown361be7a2017-03-29 12:28:47 -0600279
David Brown361be7a2017-03-29 12:28:47 -0600280 if failed {
281 self.failures += 1;
282 } else {
283 self.passes += 1;
284 }
David Brownc638f792017-01-10 12:34:33 -0700285 }
David Brownde7729e2017-01-09 10:41:35 -0700286}
287
Fabio Utzigebeecef2017-07-06 10:36:42 -0300288/// A simple upgrade without forced failures.
289///
290/// Returns the number of flash operations which can later be used to
291/// inject failures at chosen steps.
David Brown7ddec0b2017-07-06 10:47:35 -0600292fn run_basic_upgrade(flash: &SimFlash, areadesc: &AreaDesc, images: &Images)
Fabio Utzigebeecef2017-07-06 10:36:42 -0300293 -> Result<i32, ()> {
294 let (fl, total_count) = try_upgrade(&flash, &areadesc, &images, None);
295 info!("Total flash operation count={}", total_count);
296
297 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
298 warn!("Image mismatch after first boot");
299 Err(())
300 } else {
301 Ok(total_count)
302 }
303}
304
David Brown7ddec0b2017-07-06 10:47:35 -0600305fn run_basic_revert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool {
Fabio Utzigebeecef2017-07-06 10:36:42 -0300306 let mut fails = 0;
307
308 if Caps::SwapUpgrade.present() {
309 for count in 2 .. 5 {
310 info!("Try revert: {}", count);
311 let fl = try_revert(&flash, &areadesc, count);
312 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
313 warn!("Revert failure on count {}", count);
314 fails += 1;
315 }
316 }
317 }
318
319 fails > 0
320}
321
David Brown7ddec0b2017-07-06 10:47:35 -0600322fn run_perm_with_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
Fabio Utzigebeecef2017-07-06 10:36:42 -0300323 total_flash_ops: i32) -> bool {
324 let mut fails = 0;
325
326 // Let's try an image halfway through.
327 for i in 1 .. total_flash_ops {
328 info!("Try interruption at {}", i);
329 let (fl, count) = try_upgrade(&flash, &areadesc, &images, Some(i));
330 info!("Second boot, count={}", count);
331 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
332 warn!("FAIL at step {} of {}", i, total_flash_ops);
333 fails += 1;
334 }
335
336 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
337 COPY_DONE) {
338 warn!("Mismatched trailer for Slot 0");
339 fails += 1;
340 }
341
342 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
343 UNSET) {
344 warn!("Mismatched trailer for Slot 1");
345 fails += 1;
346 }
347
348 if Caps::SwapUpgrade.present() {
349 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
350 warn!("Slot 1 FAIL at step {} of {}", i, total_flash_ops);
351 fails += 1;
352 }
353 }
354 }
355
356 info!("{} out of {} failed {:.2}%", fails, total_flash_ops,
357 fails as f32 * 100.0 / total_flash_ops as f32);
358
359 fails > 0
360}
361
David Brown7ddec0b2017-07-06 10:47:35 -0600362fn run_perm_with_random_fails(flash: &SimFlash, areadesc: &AreaDesc,
Fabio Utzigebeecef2017-07-06 10:36:42 -0300363 images: &Images, total_flash_ops: i32,
364 total_fails: usize) -> bool {
365 let mut fails = 0;
366 let (fl, total_counts) = try_random_fails(&flash, &areadesc, &images,
367 total_flash_ops, total_fails);
368 info!("Random interruptions at reset points={:?}", total_counts);
369
370 let slot0_ok = verify_image(&fl, images.slot0.base_off, &images.upgrade);
371 let slot1_ok = if Caps::SwapUpgrade.present() {
372 verify_image(&fl, images.slot1.base_off, &images.primary)
373 } else {
374 true
375 };
376 if !slot0_ok || !slot1_ok {
377 error!("Image mismatch after random interrupts: slot0={} slot1={}",
378 if slot0_ok { "ok" } else { "fail" },
379 if slot1_ok { "ok" } else { "fail" });
380 fails += 1;
381 }
382 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
383 COPY_DONE) {
384 error!("Mismatched trailer for Slot 0");
385 fails += 1;
386 }
387 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
388 UNSET) {
389 error!("Mismatched trailer for Slot 1");
390 fails += 1;
391 }
392
393 fails > 0
394}
395
David Brown7ddec0b2017-07-06 10:47:35 -0600396fn run_revert_with_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
Fabio Utzigebeecef2017-07-06 10:36:42 -0300397 total_count: i32) -> bool {
398 let mut fails = 0;
399
400 if Caps::SwapUpgrade.present() {
401 for i in 1 .. (total_count - 1) {
402 info!("Try interruption at {}", i);
403 if try_revert_with_fail_at(&flash, &areadesc, &images, i) {
404 fails += 1;
405 }
406 }
407 }
408
409 fails > 0
410}
411
David Brown7ddec0b2017-07-06 10:47:35 -0600412fn run_norevert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool {
Fabio Utzigebeecef2017-07-06 10:36:42 -0300413 let mut fl = flash.clone();
414 let mut fails = 0;
415
416 info!("Try norevert");
417 c::set_flash_counter(0);
418
419 // First do a normal upgrade...
420 if c::boot_go(&mut fl, &areadesc) != 0 {
421 warn!("Failed first boot");
422 fails += 1;
423 }
424
425 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
426 warn!("Slot 0 image verification FAIL");
427 fails += 1;
428 }
429 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
430 COPY_DONE) {
431 warn!("Mismatched trailer for Slot 0");
432 fails += 1;
433 }
434 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
435 UNSET) {
436 warn!("Mismatched trailer for Slot 1");
437 fails += 1;
438 }
439
440 // Marks image in slot0 as permanent, no revert should happen...
441 mark_permanent_upgrade(&mut fl, &images.slot0);
442
443 if c::boot_go(&mut fl, &areadesc) != 0 {
444 warn!("Failed second boot");
445 fails += 1;
446 }
447
448 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
449 COPY_DONE) {
450 warn!("Mismatched trailer for Slot 0");
451 fails += 1;
452 }
453 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
454 warn!("Failed image verification");
455 fails += 1;
456 }
457
458 fails > 0
459}
460
461/// Test a boot, optionally stopping after 'n' flash options. Returns a count
462/// of the number of flash operations done total.
David Brown7ddec0b2017-07-06 10:47:35 -0600463fn try_upgrade(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
464 stop: Option<i32>) -> (SimFlash, i32) {
David Brownde7729e2017-01-09 10:41:35 -0700465 // Clone the flash to have a new copy.
466 let mut fl = flash.clone();
467
Fabio Utzigebeecef2017-07-06 10:36:42 -0300468 mark_permanent_upgrade(&mut fl, &images.slot1);
Fabio Utzig57652312017-04-25 19:54:26 -0300469
David Brownde7729e2017-01-09 10:41:35 -0700470 c::set_flash_counter(stop.unwrap_or(0));
Fabio Utzigebeecef2017-07-06 10:36:42 -0300471 let (first_interrupted, count) = match c::boot_go(&mut fl, &areadesc) {
David Brownde7729e2017-01-09 10:41:35 -0700472 -0x13579 => (true, stop.unwrap()),
473 0 => (false, -c::get_flash_counter()),
474 x => panic!("Unknown return: {}", x),
475 };
476 c::set_flash_counter(0);
477
478 if first_interrupted {
479 // fl.dump();
480 match c::boot_go(&mut fl, &areadesc) {
481 -0x13579 => panic!("Shouldn't stop again"),
482 0 => (),
483 x => panic!("Unknown return: {}", x),
484 }
485 }
486
Fabio Utzigebeecef2017-07-06 10:36:42 -0300487 (fl, count - c::get_flash_counter())
David Brownde7729e2017-01-09 10:41:35 -0700488}
489
David Brown7ddec0b2017-07-06 10:47:35 -0600490fn try_revert(flash: &SimFlash, areadesc: &AreaDesc, count: usize) -> SimFlash {
David Brownde7729e2017-01-09 10:41:35 -0700491 let mut fl = flash.clone();
492 c::set_flash_counter(0);
493
David Brown163ab232017-01-23 15:48:35 -0700494 // fl.write_file("image0.bin").unwrap();
495 for i in 0 .. count {
496 info!("Running boot pass {}", i + 1);
David Brownc638f792017-01-10 12:34:33 -0700497 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
498 }
David Brownde7729e2017-01-09 10:41:35 -0700499 fl
500}
501
David Brown7ddec0b2017-07-06 10:47:35 -0600502fn try_revert_with_fail_at(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
Fabio Utzigebeecef2017-07-06 10:36:42 -0300503 stop: i32) -> bool {
David Brownde7729e2017-01-09 10:41:35 -0700504 let mut fl = flash.clone();
Fabio Utzigebeecef2017-07-06 10:36:42 -0300505 let mut x: i32;
506 let mut fails = 0;
David Brownde7729e2017-01-09 10:41:35 -0700507
Fabio Utzigebeecef2017-07-06 10:36:42 -0300508 c::set_flash_counter(stop);
509 x = c::boot_go(&mut fl, &areadesc);
510 if x != -0x13579 {
511 warn!("Should have stopped at interruption point");
512 fails += 1;
513 }
514
515 if !verify_trailer(&fl, images.slot0.trailer_off, None, None, UNSET) {
516 warn!("copy_done should be unset");
517 fails += 1;
518 }
519
520 c::set_flash_counter(0);
521 x = c::boot_go(&mut fl, &areadesc);
522 if x != 0 {
523 warn!("Should have finished upgrade");
524 fails += 1;
525 }
526
527 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
528 warn!("Image in slot 0 before revert is invalid at stop={}", stop);
529 fails += 1;
530 }
531 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
532 warn!("Image in slot 1 before revert is invalid at stop={}", stop);
533 fails += 1;
534 }
535 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
536 COPY_DONE) {
537 warn!("Mismatched trailer for Slot 0 before revert");
538 fails += 1;
539 }
540 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
541 UNSET) {
542 warn!("Mismatched trailer for Slot 1 before revert");
543 fails += 1;
544 }
545
546 // Do Revert
547 c::set_flash_counter(0);
548 x = c::boot_go(&mut fl, &areadesc);
549 if x != 0 {
550 warn!("Should have finished a revert");
551 fails += 1;
552 }
553
554 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
555 warn!("Image in slot 0 after revert is invalid at stop={}", stop);
556 fails += 1;
557 }
558 if !verify_image(&fl, images.slot1.base_off, &images.upgrade) {
559 warn!("Image in slot 1 after revert is invalid at stop={}", stop);
560 fails += 1;
561 }
562 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
563 COPY_DONE) {
564 warn!("Mismatched trailer for Slot 1 after revert");
565 fails += 1;
566 }
567 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
568 UNSET) {
569 warn!("Mismatched trailer for Slot 1 after revert");
570 fails += 1;
571 }
572
573 fails > 0
David Brownde7729e2017-01-09 10:41:35 -0700574}
575
David Brown7ddec0b2017-07-06 10:47:35 -0600576fn try_random_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
577 total_ops: i32, count: usize) -> (SimFlash, Vec<i32>) {
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300578 let mut fl = flash.clone();
579
Fabio Utzigebeecef2017-07-06 10:36:42 -0300580 mark_permanent_upgrade(&mut fl, &images.slot1);
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300581
582 let mut rng = rand::thread_rng();
Fabio Utzig57652312017-04-25 19:54:26 -0300583 let mut resets = vec![0i32; count];
584 let mut remaining_ops = total_ops;
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300585 for i in 0 .. count {
Fabio Utzig57652312017-04-25 19:54:26 -0300586 let ops = Range::new(1, remaining_ops / 2);
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300587 let reset_counter = ops.ind_sample(&mut rng);
588 c::set_flash_counter(reset_counter);
589 match c::boot_go(&mut fl, &areadesc) {
590 0 | -0x13579 => (),
591 x => panic!("Unknown return: {}", x),
592 }
Fabio Utzig57652312017-04-25 19:54:26 -0300593 remaining_ops -= reset_counter;
594 resets[i] = reset_counter;
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300595 }
596
597 c::set_flash_counter(0);
598 match c::boot_go(&mut fl, &areadesc) {
599 -0x13579 => panic!("Should not be have been interrupted!"),
600 0 => (),
601 x => panic!("Unknown return: {}", x),
602 }
603
Fabio Utzig57652312017-04-25 19:54:26 -0300604 (fl, resets)
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300605}
606
David Brownde7729e2017-01-09 10:41:35 -0700607/// Show the flash layout.
608#[allow(dead_code)]
609fn show_flash(flash: &Flash) {
610 println!("---- Flash configuration ----");
611 for sector in flash.sector_iter() {
Fabio Utzigebeecef2017-07-06 10:36:42 -0300612 println!(" {:3}: 0x{:08x}, 0x{:08x}",
David Brownde7729e2017-01-09 10:41:35 -0700613 sector.num, sector.base, sector.size);
614 }
615 println!("");
616}
617
618/// Install a "program" into the given image. This fakes the image header, or at least all of the
619/// fields used by the given code. Returns a copy of the image that was written.
620fn install_image(flash: &mut Flash, offset: usize, len: usize) -> Vec<u8> {
621 let offset0 = offset;
622
David Brown704ac6f2017-07-12 10:14:47 -0600623 let mut tlv = make_tlv();
David Brown187dd882017-07-11 11:15:23 -0600624
David Brownde7729e2017-01-09 10:41:35 -0700625 // Generate a boot header. Note that the size doesn't include the header.
626 let header = ImageHeader {
627 magic: 0x96f3b83c,
David Brown187dd882017-07-11 11:15:23 -0600628 tlv_size: tlv.get_size(),
David Brownde7729e2017-01-09 10:41:35 -0700629 _pad1: 0,
630 hdr_size: 32,
631 key_id: 0,
632 _pad2: 0,
633 img_size: len as u32,
David Brown187dd882017-07-11 11:15:23 -0600634 flags: tlv.get_flags(),
David Brownde7729e2017-01-09 10:41:35 -0700635 ver: ImageVersion {
David Browne380fa62017-01-23 15:49:09 -0700636 major: (offset / (128 * 1024)) as u8,
David Brownde7729e2017-01-09 10:41:35 -0700637 minor: 0,
638 revision: 1,
David Browne380fa62017-01-23 15:49:09 -0700639 build_num: offset as u32,
David Brownde7729e2017-01-09 10:41:35 -0700640 },
641 _pad3: 0,
642 };
643
644 let b_header = header.as_raw();
David Brown187dd882017-07-11 11:15:23 -0600645 tlv.add_bytes(&b_header);
David Brownde7729e2017-01-09 10:41:35 -0700646 /*
647 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
648 mem::size_of::<ImageHeader>()) };
649 */
650 assert_eq!(b_header.len(), 32);
651 flash.write(offset, &b_header).unwrap();
652 let offset = offset + b_header.len();
653
654 // The core of the image itself is just pseudorandom data.
655 let mut buf = vec![0; len];
656 splat(&mut buf, offset);
David Brown187dd882017-07-11 11:15:23 -0600657 tlv.add_bytes(&buf);
658
659 // Get and append the TLV itself.
660 buf.append(&mut tlv.make_tlv());
661
662 // Pad the block to a flash alignment (8 bytes).
663 while buf.len() % 8 != 0 {
664 buf.push(0xFF);
665 }
666
David Brownde7729e2017-01-09 10:41:35 -0700667 flash.write(offset, &buf).unwrap();
668 let offset = offset + buf.len();
669
670 // Copy out the image so that we can verify that the image was installed correctly later.
671 let mut copy = vec![0u8; offset - offset0];
672 flash.read(offset0, &mut copy).unwrap();
673
674 copy
675}
676
David Brown704ac6f2017-07-12 10:14:47 -0600677// The TLV in use depends on what kind of signature we are verifying.
678#[cfg(feature = "sig-rsa")]
679fn make_tlv() -> TlvGen {
680 TlvGen::new_rsa_pss()
681}
682
683#[cfg(not(feature = "sig-rsa"))]
684fn make_tlv() -> TlvGen {
685 TlvGen::new_hash_only()
686}
687
David Brownde7729e2017-01-09 10:41:35 -0700688/// Verify that given image is present in the flash at the given offset.
689fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
690 let mut copy = vec![0u8; buf.len()];
691 flash.read(offset, &mut copy).unwrap();
692
693 if buf != &copy[..] {
694 for i in 0 .. buf.len() {
695 if buf[i] != copy[i] {
David Brown4440af82017-01-09 12:15:05 -0700696 info!("First failure at {:#x}", offset + i);
David Brownde7729e2017-01-09 10:41:35 -0700697 break;
698 }
699 }
700 false
701 } else {
702 true
703 }
704}
705
Fabio Utzigebeecef2017-07-06 10:36:42 -0300706fn verify_trailer(flash: &Flash, offset: usize,
707 magic: Option<&[u8]>, image_ok: Option<u8>,
708 copy_done: Option<u8>) -> bool {
709 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 2];
710 let mut failed = false;
711
712 flash.read(offset, &mut copy).unwrap();
713
714 failed |= match magic {
715 Some(v) => {
716 if &copy[16..] != v {
717 warn!("\"magic\" mismatch at {:#x}", offset);
718 true
719 } else {
720 false
721 }
722 },
723 None => false,
724 };
725
726 failed |= match image_ok {
727 Some(v) => {
728 if copy[8] != v {
729 warn!("\"image_ok\" mismatch at {:#x}", offset);
730 true
731 } else {
732 false
733 }
734 },
735 None => false,
736 };
737
738 failed |= match copy_done {
739 Some(v) => {
740 if copy[0] != v {
741 warn!("\"copy_done\" mismatch at {:#x}", offset);
742 true
743 } else {
744 false
745 }
746 },
747 None => false,
748 };
749
750 !failed
751}
752
David Brownde7729e2017-01-09 10:41:35 -0700753/// The image header
754#[repr(C)]
755pub struct ImageHeader {
756 magic: u32,
757 tlv_size: u16,
758 key_id: u8,
759 _pad1: u8,
760 hdr_size: u16,
761 _pad2: u16,
762 img_size: u32,
763 flags: u32,
764 ver: ImageVersion,
765 _pad3: u32,
766}
767
768impl AsRaw for ImageHeader {}
769
770#[repr(C)]
771pub struct ImageVersion {
772 major: u8,
773 minor: u8,
774 revision: u16,
775 build_num: u32,
776}
777
Fabio Utzigebeecef2017-07-06 10:36:42 -0300778struct SlotInfo {
779 base_off: usize,
780 trailer_off: usize,
781}
782
783struct Images {
784 slot0: SlotInfo,
785 slot1: SlotInfo,
786 primary: Vec<u8>,
787 upgrade: Vec<u8>,
788}
789
790const MAGIC_VALID: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3,
791 0x60, 0xd2, 0xef, 0x7f,
792 0x35, 0x52, 0x50, 0x0f,
793 0x2c, 0xb6, 0x79, 0x80]);
794const MAGIC_UNSET: Option<&[u8]> = Some(&[0xff; 16]);
795
796const COPY_DONE: Option<u8> = Some(1);
797const IMAGE_OK: Option<u8> = Some(1);
798const UNSET: Option<u8> = Some(0xff);
799
David Brownde7729e2017-01-09 10:41:35 -0700800/// Write out the magic so that the loader tries doing an upgrade.
Fabio Utzigebeecef2017-07-06 10:36:42 -0300801fn mark_upgrade(flash: &mut Flash, slot: &SlotInfo) {
802 let offset = slot.trailer_off + c::boot_max_align() * 2;
803 flash.write(offset, MAGIC_VALID.unwrap()).unwrap();
804}
805
806/// Writes the image_ok flag which, guess what, tells the bootloader
807/// the this image is ok (not a test, and no revert is to be performed).
808fn mark_permanent_upgrade(flash: &mut Flash, slot: &SlotInfo) {
809 let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
810 let align = c::get_sim_flash_align() as usize;
811 let off = slot.trailer_off + c::boot_max_align();
812 flash.write(off, &ok[..align]).unwrap();
David Brownde7729e2017-01-09 10:41:35 -0700813}
814
815// Drop some pseudo-random gibberish onto the data.
816fn splat(data: &mut [u8], seed: usize) {
817 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
818 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
819 rng.fill_bytes(data);
820}
821
822/// Return a read-only view into the raw bytes of this object
823trait AsRaw : Sized {
824 fn as_raw<'a>(&'a self) -> &'a [u8] {
825 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
826 mem::size_of::<Self>()) }
827 }
828}
829
830fn show_sizes() {
831 // This isn't panic safe.
832 let old_align = c::get_sim_flash_align();
833 for min in &[1, 2, 4, 8] {
834 c::set_sim_flash_align(*min);
835 let msize = c::boot_trailer_sz();
836 println!("{:2}: {} (0x{:x})", min, msize, msize);
837 }
838 c::set_sim_flash_align(old_align);
839}