blob: 106b42370bd7e9800de754454b69889928d92095 [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 {
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300153 error!("{} Tests ran successfully", status.passes);
David Brown361be7a2017-03-29 12:28:47 -0600154 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 Utzig7b47ef72017-07-13 09:34:33 -0300260 failed |= run_norevert_newimage(&flash, &areadesc, &images);
261
Fabio Utzigebeecef2017-07-06 10:36:42 -0300262 mark_upgrade(&mut flash, &images.slot1);
David Brown361be7a2017-03-29 12:28:47 -0600263
Fabio Utzigebeecef2017-07-06 10:36:42 -0300264 // upgrades without fails, counts number of flash operations
265 let total_count = match run_basic_upgrade(&flash, &areadesc, &images) {
266 Ok(v) => v,
267 Err(_) => {
268 self.failures += 1;
269 return;
270 },
David Brown902d6172017-05-05 09:37:41 -0600271 };
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300272
Fabio Utzigebeecef2017-07-06 10:36:42 -0300273 failed |= run_basic_revert(&flash, &areadesc, &images);
274 failed |= run_revert_with_fails(&flash, &areadesc, &images, total_count);
275 failed |= run_perm_with_fails(&flash, &areadesc, &images, total_count);
276 failed |= run_perm_with_random_fails(&flash, &areadesc, &images,
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300277 total_count, 5);
Fabio Utzigebeecef2017-07-06 10:36:42 -0300278 failed |= run_norevert(&flash, &areadesc, &images);
David Brown361be7a2017-03-29 12:28:47 -0600279
Fabio Utzigebeecef2017-07-06 10:36:42 -0300280 //show_flash(&flash);
David Brown361be7a2017-03-29 12:28:47 -0600281
David Brown361be7a2017-03-29 12:28:47 -0600282 if failed {
283 self.failures += 1;
284 } else {
285 self.passes += 1;
286 }
David Brownc638f792017-01-10 12:34:33 -0700287 }
David Brownde7729e2017-01-09 10:41:35 -0700288}
289
Fabio Utzigebeecef2017-07-06 10:36:42 -0300290/// A simple upgrade without forced failures.
291///
292/// Returns the number of flash operations which can later be used to
293/// inject failures at chosen steps.
David Brown7ddec0b2017-07-06 10:47:35 -0600294fn run_basic_upgrade(flash: &SimFlash, areadesc: &AreaDesc, images: &Images)
Fabio Utzigebeecef2017-07-06 10:36:42 -0300295 -> Result<i32, ()> {
296 let (fl, total_count) = try_upgrade(&flash, &areadesc, &images, None);
297 info!("Total flash operation count={}", total_count);
298
299 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
300 warn!("Image mismatch after first boot");
301 Err(())
302 } else {
303 Ok(total_count)
304 }
305}
306
David Brown7ddec0b2017-07-06 10:47:35 -0600307fn run_basic_revert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool {
Fabio Utzigebeecef2017-07-06 10:36:42 -0300308 let mut fails = 0;
309
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300310 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigebeecef2017-07-06 10:36:42 -0300311 if Caps::SwapUpgrade.present() {
312 for count in 2 .. 5 {
313 info!("Try revert: {}", count);
314 let fl = try_revert(&flash, &areadesc, count);
315 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300316 error!("Revert failure on count {}", count);
Fabio Utzigebeecef2017-07-06 10:36:42 -0300317 fails += 1;
318 }
319 }
320 }
321
322 fails > 0
323}
324
David Brown7ddec0b2017-07-06 10:47:35 -0600325fn run_perm_with_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
Fabio Utzigebeecef2017-07-06 10:36:42 -0300326 total_flash_ops: i32) -> bool {
327 let mut fails = 0;
328
329 // Let's try an image halfway through.
330 for i in 1 .. total_flash_ops {
331 info!("Try interruption at {}", i);
332 let (fl, count) = try_upgrade(&flash, &areadesc, &images, Some(i));
333 info!("Second boot, count={}", count);
334 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
335 warn!("FAIL at step {} of {}", i, total_flash_ops);
336 fails += 1;
337 }
338
339 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
340 COPY_DONE) {
341 warn!("Mismatched trailer for Slot 0");
342 fails += 1;
343 }
344
345 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
346 UNSET) {
347 warn!("Mismatched trailer for Slot 1");
348 fails += 1;
349 }
350
351 if Caps::SwapUpgrade.present() {
352 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
353 warn!("Slot 1 FAIL at step {} of {}", i, total_flash_ops);
354 fails += 1;
355 }
356 }
357 }
358
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300359 if fails > 0 {
360 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
361 fails as f32 * 100.0 / total_flash_ops as f32);
362 }
Fabio Utzigebeecef2017-07-06 10:36:42 -0300363
364 fails > 0
365}
366
David Brown7ddec0b2017-07-06 10:47:35 -0600367fn run_perm_with_random_fails(flash: &SimFlash, areadesc: &AreaDesc,
Fabio Utzigebeecef2017-07-06 10:36:42 -0300368 images: &Images, total_flash_ops: i32,
369 total_fails: usize) -> bool {
370 let mut fails = 0;
371 let (fl, total_counts) = try_random_fails(&flash, &areadesc, &images,
372 total_flash_ops, total_fails);
373 info!("Random interruptions at reset points={:?}", total_counts);
374
375 let slot0_ok = verify_image(&fl, images.slot0.base_off, &images.upgrade);
376 let slot1_ok = if Caps::SwapUpgrade.present() {
377 verify_image(&fl, images.slot1.base_off, &images.primary)
378 } else {
379 true
380 };
381 if !slot0_ok || !slot1_ok {
382 error!("Image mismatch after random interrupts: slot0={} slot1={}",
383 if slot0_ok { "ok" } else { "fail" },
384 if slot1_ok { "ok" } else { "fail" });
385 fails += 1;
386 }
387 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
388 COPY_DONE) {
389 error!("Mismatched trailer for Slot 0");
390 fails += 1;
391 }
392 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
393 UNSET) {
394 error!("Mismatched trailer for Slot 1");
395 fails += 1;
396 }
397
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300398 if fails > 0 {
399 error!("Error testing perm upgrade with {} fails", total_fails);
400 }
401
Fabio Utzigebeecef2017-07-06 10:36:42 -0300402 fails > 0
403}
404
David Brown7ddec0b2017-07-06 10:47:35 -0600405fn run_revert_with_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
Fabio Utzigebeecef2017-07-06 10:36:42 -0300406 total_count: i32) -> bool {
407 let mut fails = 0;
408
409 if Caps::SwapUpgrade.present() {
410 for i in 1 .. (total_count - 1) {
411 info!("Try interruption at {}", i);
412 if try_revert_with_fail_at(&flash, &areadesc, &images, i) {
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300413 error!("Revert failed at interruption {}", i);
Fabio Utzigebeecef2017-07-06 10:36:42 -0300414 fails += 1;
415 }
416 }
417 }
418
419 fails > 0
420}
421
David Brown7ddec0b2017-07-06 10:47:35 -0600422fn run_norevert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool {
Fabio Utzigebeecef2017-07-06 10:36:42 -0300423 let mut fl = flash.clone();
424 let mut fails = 0;
425
426 info!("Try norevert");
427 c::set_flash_counter(0);
428
429 // First do a normal upgrade...
430 if c::boot_go(&mut fl, &areadesc) != 0 {
431 warn!("Failed first boot");
432 fails += 1;
433 }
434
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300435 //FIXME: copy_done is written by boot_go, is it ok if no copy
436 // was ever done?
437
Fabio Utzigebeecef2017-07-06 10:36:42 -0300438 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
439 warn!("Slot 0 image verification FAIL");
440 fails += 1;
441 }
442 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
443 COPY_DONE) {
444 warn!("Mismatched trailer for Slot 0");
445 fails += 1;
446 }
447 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
448 UNSET) {
449 warn!("Mismatched trailer for Slot 1");
450 fails += 1;
451 }
452
453 // Marks image in slot0 as permanent, no revert should happen...
454 mark_permanent_upgrade(&mut fl, &images.slot0);
455
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300456 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
457 COPY_DONE) {
458 warn!("Mismatched trailer for Slot 0");
459 fails += 1;
460 }
461
Fabio Utzigebeecef2017-07-06 10:36:42 -0300462 if c::boot_go(&mut fl, &areadesc) != 0 {
463 warn!("Failed second boot");
464 fails += 1;
465 }
466
467 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
468 COPY_DONE) {
469 warn!("Mismatched trailer for Slot 0");
470 fails += 1;
471 }
472 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
473 warn!("Failed image verification");
474 fails += 1;
475 }
476
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300477 if fails > 0 {
478 error!("Error running upgrade without revert");
479 }
480
481 fails > 0
482}
483
484// Tests a new image written to slot0 that already has magic and image_ok set
485// while there is no image on slot1, so no revert should ever happen...
486fn run_norevert_newimage(flash: &SimFlash, areadesc: &AreaDesc,
487 images: &Images) -> bool {
488 let mut fl = flash.clone();
489 let mut fails = 0;
490
491 info!("Try non-revert on imgtool generated image");
492 c::set_flash_counter(0);
493
494 mark_upgrade(&mut fl, &images.slot0);
495
496 // This simulates writing an image created by imgtool to Slot 0
497 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET, UNSET) {
498 warn!("Mismatched trailer for Slot 0");
499 fails += 1;
500 }
501
502 // Run the bootloader...
503 if c::boot_go(&mut fl, &areadesc) != 0 {
504 warn!("Failed first boot");
505 fails += 1;
506 }
507
508 // State should not have changed
509 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
510 warn!("Failed image verification");
511 fails += 1;
512 }
513 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
514 UNSET) {
515 warn!("Mismatched trailer for Slot 0");
516 fails += 1;
517 }
518 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
519 UNSET) {
520 warn!("Mismatched trailer for Slot 1");
521 fails += 1;
522 }
523
524 if fails > 0 {
525 error!("Expected a non revert with new image");
526 }
527
Fabio Utzigebeecef2017-07-06 10:36:42 -0300528 fails > 0
529}
530
531/// Test a boot, optionally stopping after 'n' flash options. Returns a count
532/// of the number of flash operations done total.
David Brown7ddec0b2017-07-06 10:47:35 -0600533fn try_upgrade(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
534 stop: Option<i32>) -> (SimFlash, i32) {
David Brownde7729e2017-01-09 10:41:35 -0700535 // Clone the flash to have a new copy.
536 let mut fl = flash.clone();
537
Fabio Utzigebeecef2017-07-06 10:36:42 -0300538 mark_permanent_upgrade(&mut fl, &images.slot1);
Fabio Utzig57652312017-04-25 19:54:26 -0300539
David Brownde7729e2017-01-09 10:41:35 -0700540 c::set_flash_counter(stop.unwrap_or(0));
Fabio Utzigebeecef2017-07-06 10:36:42 -0300541 let (first_interrupted, count) = match c::boot_go(&mut fl, &areadesc) {
David Brownde7729e2017-01-09 10:41:35 -0700542 -0x13579 => (true, stop.unwrap()),
543 0 => (false, -c::get_flash_counter()),
544 x => panic!("Unknown return: {}", x),
545 };
546 c::set_flash_counter(0);
547
548 if first_interrupted {
549 // fl.dump();
550 match c::boot_go(&mut fl, &areadesc) {
551 -0x13579 => panic!("Shouldn't stop again"),
552 0 => (),
553 x => panic!("Unknown return: {}", x),
554 }
555 }
556
Fabio Utzigebeecef2017-07-06 10:36:42 -0300557 (fl, count - c::get_flash_counter())
David Brownde7729e2017-01-09 10:41:35 -0700558}
559
David Brown7ddec0b2017-07-06 10:47:35 -0600560fn try_revert(flash: &SimFlash, areadesc: &AreaDesc, count: usize) -> SimFlash {
David Brownde7729e2017-01-09 10:41:35 -0700561 let mut fl = flash.clone();
562 c::set_flash_counter(0);
563
David Brown163ab232017-01-23 15:48:35 -0700564 // fl.write_file("image0.bin").unwrap();
565 for i in 0 .. count {
566 info!("Running boot pass {}", i + 1);
David Brownc638f792017-01-10 12:34:33 -0700567 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
568 }
David Brownde7729e2017-01-09 10:41:35 -0700569 fl
570}
571
David Brown7ddec0b2017-07-06 10:47:35 -0600572fn try_revert_with_fail_at(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
Fabio Utzigebeecef2017-07-06 10:36:42 -0300573 stop: i32) -> bool {
David Brownde7729e2017-01-09 10:41:35 -0700574 let mut fl = flash.clone();
Fabio Utzigebeecef2017-07-06 10:36:42 -0300575 let mut x: i32;
576 let mut fails = 0;
David Brownde7729e2017-01-09 10:41:35 -0700577
Fabio Utzigebeecef2017-07-06 10:36:42 -0300578 c::set_flash_counter(stop);
579 x = c::boot_go(&mut fl, &areadesc);
580 if x != -0x13579 {
581 warn!("Should have stopped at interruption point");
582 fails += 1;
583 }
584
585 if !verify_trailer(&fl, images.slot0.trailer_off, None, None, UNSET) {
586 warn!("copy_done should be unset");
587 fails += 1;
588 }
589
590 c::set_flash_counter(0);
591 x = c::boot_go(&mut fl, &areadesc);
592 if x != 0 {
593 warn!("Should have finished upgrade");
594 fails += 1;
595 }
596
597 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
598 warn!("Image in slot 0 before revert is invalid at stop={}", stop);
599 fails += 1;
600 }
601 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
602 warn!("Image in slot 1 before revert is invalid at stop={}", stop);
603 fails += 1;
604 }
605 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
606 COPY_DONE) {
607 warn!("Mismatched trailer for Slot 0 before revert");
608 fails += 1;
609 }
610 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
611 UNSET) {
612 warn!("Mismatched trailer for Slot 1 before revert");
613 fails += 1;
614 }
615
616 // Do Revert
617 c::set_flash_counter(0);
618 x = c::boot_go(&mut fl, &areadesc);
619 if x != 0 {
620 warn!("Should have finished a revert");
621 fails += 1;
622 }
623
624 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
625 warn!("Image in slot 0 after revert is invalid at stop={}", stop);
626 fails += 1;
627 }
628 if !verify_image(&fl, images.slot1.base_off, &images.upgrade) {
629 warn!("Image in slot 1 after revert is invalid at stop={}", stop);
630 fails += 1;
631 }
632 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
633 COPY_DONE) {
634 warn!("Mismatched trailer for Slot 1 after revert");
635 fails += 1;
636 }
637 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
638 UNSET) {
639 warn!("Mismatched trailer for Slot 1 after revert");
640 fails += 1;
641 }
642
643 fails > 0
David Brownde7729e2017-01-09 10:41:35 -0700644}
645
David Brown7ddec0b2017-07-06 10:47:35 -0600646fn try_random_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
647 total_ops: i32, count: usize) -> (SimFlash, Vec<i32>) {
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300648 let mut fl = flash.clone();
649
Fabio Utzigebeecef2017-07-06 10:36:42 -0300650 mark_permanent_upgrade(&mut fl, &images.slot1);
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300651
652 let mut rng = rand::thread_rng();
Fabio Utzig57652312017-04-25 19:54:26 -0300653 let mut resets = vec![0i32; count];
654 let mut remaining_ops = total_ops;
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300655 for i in 0 .. count {
Fabio Utzig57652312017-04-25 19:54:26 -0300656 let ops = Range::new(1, remaining_ops / 2);
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300657 let reset_counter = ops.ind_sample(&mut rng);
658 c::set_flash_counter(reset_counter);
659 match c::boot_go(&mut fl, &areadesc) {
660 0 | -0x13579 => (),
661 x => panic!("Unknown return: {}", x),
662 }
Fabio Utzig57652312017-04-25 19:54:26 -0300663 remaining_ops -= reset_counter;
664 resets[i] = reset_counter;
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300665 }
666
667 c::set_flash_counter(0);
668 match c::boot_go(&mut fl, &areadesc) {
669 -0x13579 => panic!("Should not be have been interrupted!"),
670 0 => (),
671 x => panic!("Unknown return: {}", x),
672 }
673
Fabio Utzig57652312017-04-25 19:54:26 -0300674 (fl, resets)
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300675}
676
David Brownde7729e2017-01-09 10:41:35 -0700677/// Show the flash layout.
678#[allow(dead_code)]
679fn show_flash(flash: &Flash) {
680 println!("---- Flash configuration ----");
681 for sector in flash.sector_iter() {
Fabio Utzigebeecef2017-07-06 10:36:42 -0300682 println!(" {:3}: 0x{:08x}, 0x{:08x}",
David Brownde7729e2017-01-09 10:41:35 -0700683 sector.num, sector.base, sector.size);
684 }
685 println!("");
686}
687
688/// Install a "program" into the given image. This fakes the image header, or at least all of the
689/// fields used by the given code. Returns a copy of the image that was written.
690fn install_image(flash: &mut Flash, offset: usize, len: usize) -> Vec<u8> {
691 let offset0 = offset;
692
David Brown704ac6f2017-07-12 10:14:47 -0600693 let mut tlv = make_tlv();
David Brown187dd882017-07-11 11:15:23 -0600694
David Brownde7729e2017-01-09 10:41:35 -0700695 // Generate a boot header. Note that the size doesn't include the header.
696 let header = ImageHeader {
697 magic: 0x96f3b83c,
David Brown187dd882017-07-11 11:15:23 -0600698 tlv_size: tlv.get_size(),
David Brownde7729e2017-01-09 10:41:35 -0700699 _pad1: 0,
700 hdr_size: 32,
701 key_id: 0,
702 _pad2: 0,
703 img_size: len as u32,
David Brown187dd882017-07-11 11:15:23 -0600704 flags: tlv.get_flags(),
David Brownde7729e2017-01-09 10:41:35 -0700705 ver: ImageVersion {
David Browne380fa62017-01-23 15:49:09 -0700706 major: (offset / (128 * 1024)) as u8,
David Brownde7729e2017-01-09 10:41:35 -0700707 minor: 0,
708 revision: 1,
David Browne380fa62017-01-23 15:49:09 -0700709 build_num: offset as u32,
David Brownde7729e2017-01-09 10:41:35 -0700710 },
711 _pad3: 0,
712 };
713
714 let b_header = header.as_raw();
David Brown187dd882017-07-11 11:15:23 -0600715 tlv.add_bytes(&b_header);
David Brownde7729e2017-01-09 10:41:35 -0700716 /*
717 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
718 mem::size_of::<ImageHeader>()) };
719 */
720 assert_eq!(b_header.len(), 32);
721 flash.write(offset, &b_header).unwrap();
722 let offset = offset + b_header.len();
723
724 // The core of the image itself is just pseudorandom data.
725 let mut buf = vec![0; len];
726 splat(&mut buf, offset);
David Brown187dd882017-07-11 11:15:23 -0600727 tlv.add_bytes(&buf);
728
729 // Get and append the TLV itself.
730 buf.append(&mut tlv.make_tlv());
731
732 // Pad the block to a flash alignment (8 bytes).
733 while buf.len() % 8 != 0 {
734 buf.push(0xFF);
735 }
736
David Brownde7729e2017-01-09 10:41:35 -0700737 flash.write(offset, &buf).unwrap();
738 let offset = offset + buf.len();
739
740 // Copy out the image so that we can verify that the image was installed correctly later.
741 let mut copy = vec![0u8; offset - offset0];
742 flash.read(offset0, &mut copy).unwrap();
743
744 copy
745}
746
David Brown704ac6f2017-07-12 10:14:47 -0600747// The TLV in use depends on what kind of signature we are verifying.
748#[cfg(feature = "sig-rsa")]
749fn make_tlv() -> TlvGen {
750 TlvGen::new_rsa_pss()
751}
752
753#[cfg(not(feature = "sig-rsa"))]
754fn make_tlv() -> TlvGen {
755 TlvGen::new_hash_only()
756}
757
David Brownde7729e2017-01-09 10:41:35 -0700758/// Verify that given image is present in the flash at the given offset.
759fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
760 let mut copy = vec![0u8; buf.len()];
761 flash.read(offset, &mut copy).unwrap();
762
763 if buf != &copy[..] {
764 for i in 0 .. buf.len() {
765 if buf[i] != copy[i] {
David Brown4440af82017-01-09 12:15:05 -0700766 info!("First failure at {:#x}", offset + i);
David Brownde7729e2017-01-09 10:41:35 -0700767 break;
768 }
769 }
770 false
771 } else {
772 true
773 }
774}
775
Fabio Utzigebeecef2017-07-06 10:36:42 -0300776fn verify_trailer(flash: &Flash, offset: usize,
777 magic: Option<&[u8]>, image_ok: Option<u8>,
778 copy_done: Option<u8>) -> bool {
779 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 2];
780 let mut failed = false;
781
782 flash.read(offset, &mut copy).unwrap();
783
784 failed |= match magic {
785 Some(v) => {
786 if &copy[16..] != v {
787 warn!("\"magic\" mismatch at {:#x}", offset);
788 true
789 } else {
790 false
791 }
792 },
793 None => false,
794 };
795
796 failed |= match image_ok {
797 Some(v) => {
798 if copy[8] != v {
799 warn!("\"image_ok\" mismatch at {:#x}", offset);
800 true
801 } else {
802 false
803 }
804 },
805 None => false,
806 };
807
808 failed |= match copy_done {
809 Some(v) => {
810 if copy[0] != v {
811 warn!("\"copy_done\" mismatch at {:#x}", offset);
812 true
813 } else {
814 false
815 }
816 },
817 None => false,
818 };
819
820 !failed
821}
822
David Brownde7729e2017-01-09 10:41:35 -0700823/// The image header
824#[repr(C)]
825pub struct ImageHeader {
826 magic: u32,
827 tlv_size: u16,
828 key_id: u8,
829 _pad1: u8,
830 hdr_size: u16,
831 _pad2: u16,
832 img_size: u32,
833 flags: u32,
834 ver: ImageVersion,
835 _pad3: u32,
836}
837
838impl AsRaw for ImageHeader {}
839
840#[repr(C)]
841pub struct ImageVersion {
842 major: u8,
843 minor: u8,
844 revision: u16,
845 build_num: u32,
846}
847
Fabio Utzigebeecef2017-07-06 10:36:42 -0300848struct SlotInfo {
849 base_off: usize,
850 trailer_off: usize,
851}
852
853struct Images {
854 slot0: SlotInfo,
855 slot1: SlotInfo,
856 primary: Vec<u8>,
857 upgrade: Vec<u8>,
858}
859
860const MAGIC_VALID: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3,
861 0x60, 0xd2, 0xef, 0x7f,
862 0x35, 0x52, 0x50, 0x0f,
863 0x2c, 0xb6, 0x79, 0x80]);
864const MAGIC_UNSET: Option<&[u8]> = Some(&[0xff; 16]);
865
866const COPY_DONE: Option<u8> = Some(1);
867const IMAGE_OK: Option<u8> = Some(1);
868const UNSET: Option<u8> = Some(0xff);
869
David Brownde7729e2017-01-09 10:41:35 -0700870/// Write out the magic so that the loader tries doing an upgrade.
Fabio Utzigebeecef2017-07-06 10:36:42 -0300871fn mark_upgrade(flash: &mut Flash, slot: &SlotInfo) {
872 let offset = slot.trailer_off + c::boot_max_align() * 2;
873 flash.write(offset, MAGIC_VALID.unwrap()).unwrap();
874}
875
876/// Writes the image_ok flag which, guess what, tells the bootloader
877/// the this image is ok (not a test, and no revert is to be performed).
878fn mark_permanent_upgrade(flash: &mut Flash, slot: &SlotInfo) {
879 let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
880 let align = c::get_sim_flash_align() as usize;
881 let off = slot.trailer_off + c::boot_max_align();
882 flash.write(off, &ok[..align]).unwrap();
David Brownde7729e2017-01-09 10:41:35 -0700883}
884
885// Drop some pseudo-random gibberish onto the data.
886fn splat(data: &mut [u8], seed: usize) {
887 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
888 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
889 rng.fill_bytes(data);
890}
891
892/// Return a read-only view into the raw bytes of this object
893trait AsRaw : Sized {
894 fn as_raw<'a>(&'a self) -> &'a [u8] {
895 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
896 mem::size_of::<Self>()) }
897 }
898}
899
900fn show_sizes() {
901 // This isn't panic safe.
902 let old_align = c::get_sim_flash_align();
903 for min in &[1, 2, 4, 8] {
904 c::set_sim_flash_align(*min);
905 let msize = c::boot_trailer_sz();
906 println!("{:2}: {} (0x{:x})", min, msize, msize);
907 }
908 c::set_sim_flash_align(old_align);
909}