blob: 9e38172899d71a62090bcc42c8b115cd220561c5 [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 Brownde7729e2017-01-09 10:41:35 -07004extern crate docopt;
5extern crate libc;
David Brown7e701d82017-07-11 13:24:25 -06006extern crate pem;
David Brownde7729e2017-01-09 10:41:35 -07007extern crate rand;
David Brown046a0a62017-07-12 16:08:22 -06008#[macro_use] extern crate serde_derive;
9extern crate serde;
David Brown2cbc4702017-07-06 14:18:58 -060010extern crate simflash;
David Brown7e701d82017-07-11 13:24:25 -060011extern crate untrusted;
David Brown63902772017-07-12 09:47:49 -060012extern crate mcuboot_sys;
David Brownde7729e2017-01-09 10:41:35 -070013
14use docopt::Docopt;
David Brown4cb26232017-04-11 08:15:18 -060015use rand::{Rng, SeedableRng, XorShiftRng};
Fabio Utzigbb5635e2017-04-10 09:07:02 -030016use rand::distributions::{IndependentSample, Range};
David Browna3b93cf2017-03-29 12:41:26 -060017use std::fmt;
David Brownde7729e2017-01-09 10:41:35 -070018use std::mem;
David Brown361be7a2017-03-29 12:28:47 -060019use std::process;
David Brownde7729e2017-01-09 10:41:35 -070020use std::slice;
21
David Brown902d6172017-05-05 09:37:41 -060022mod caps;
David Brown187dd882017-07-11 11:15:23 -060023mod tlv;
David Brownde7729e2017-01-09 10:41:35 -070024
David Brown2cbc4702017-07-06 14:18:58 -060025use simflash::{Flash, SimFlash};
David Brownf52272c2017-07-12 09:56:16 -060026use mcuboot_sys::{c, AreaDesc, FlashId};
David Brown902d6172017-05-05 09:37:41 -060027use caps::Caps;
David Brown187dd882017-07-11 11:15:23 -060028use tlv::TlvGen;
David Brownde7729e2017-01-09 10:41:35 -070029
30const USAGE: &'static str = "
31Mcuboot simulator
32
33Usage:
34 bootsim sizes
35 bootsim run --device TYPE [--align SIZE]
David Browna3b93cf2017-03-29 12:41:26 -060036 bootsim runall
David Brownde7729e2017-01-09 10:41:35 -070037 bootsim (--help | --version)
38
39Options:
40 -h, --help Show this message
41 --version Version
42 --device TYPE MCU to simulate
43 Valid values: stm32f4, k64f
44 --align SIZE Flash write alignment
45";
46
David Brown046a0a62017-07-12 16:08:22 -060047#[derive(Debug, Deserialize)]
David Brownde7729e2017-01-09 10:41:35 -070048struct Args {
49 flag_help: bool,
50 flag_version: bool,
51 flag_device: Option<DeviceName>,
52 flag_align: Option<AlignArg>,
53 cmd_sizes: bool,
54 cmd_run: bool,
David Browna3b93cf2017-03-29 12:41:26 -060055 cmd_runall: bool,
David Brownde7729e2017-01-09 10:41:35 -070056}
57
David Brown046a0a62017-07-12 16:08:22 -060058#[derive(Copy, Clone, Debug, Deserialize)]
David Brown07fb8fa2017-03-20 12:40:57 -060059enum DeviceName { Stm32f4, K64f, K64fBig, Nrf52840 }
David Brownde7729e2017-01-09 10:41:35 -070060
David Browna3b93cf2017-03-29 12:41:26 -060061static ALL_DEVICES: &'static [DeviceName] = &[
62 DeviceName::Stm32f4,
63 DeviceName::K64f,
64 DeviceName::K64fBig,
65 DeviceName::Nrf52840,
66];
67
68impl fmt::Display for DeviceName {
69 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70 let name = match *self {
71 DeviceName::Stm32f4 => "stm32f4",
72 DeviceName::K64f => "k64f",
73 DeviceName::K64fBig => "k64fbig",
74 DeviceName::Nrf52840 => "nrf52840",
75 };
76 f.write_str(name)
77 }
78}
79
David Brownde7729e2017-01-09 10:41:35 -070080#[derive(Debug)]
81struct AlignArg(u8);
82
David Brown046a0a62017-07-12 16:08:22 -060083struct AlignArgVisitor;
84
85impl<'de> serde::de::Visitor<'de> for AlignArgVisitor {
86 type Value = AlignArg;
87
88 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
89 formatter.write_str("1, 2, 4 or 8")
90 }
91
92 fn visit_u8<E>(self, n: u8) -> Result<Self::Value, E>
93 where E: serde::de::Error
94 {
95 Ok(match n {
96 1 | 2 | 4 | 8 => AlignArg(n),
97 n => {
98 let err = format!("Could not deserialize '{}' as alignment", n);
99 return Err(E::custom(err));
100 }
101 })
102 }
103}
104
105impl<'de> serde::de::Deserialize<'de> for AlignArg {
106 fn deserialize<D>(d: D) -> Result<AlignArg, D::Error>
107 where D: serde::de::Deserializer<'de>
108 {
109 d.deserialize_u8(AlignArgVisitor)
David Brownde7729e2017-01-09 10:41:35 -0700110 }
111}
112
113fn main() {
David Brown4440af82017-01-09 12:15:05 -0700114 env_logger::init().unwrap();
115
David Brownde7729e2017-01-09 10:41:35 -0700116 let args: Args = Docopt::new(USAGE)
David Brown046a0a62017-07-12 16:08:22 -0600117 .and_then(|d| d.deserialize())
David Brownde7729e2017-01-09 10:41:35 -0700118 .unwrap_or_else(|e| e.exit());
119 // println!("args: {:#?}", args);
120
121 if args.cmd_sizes {
122 show_sizes();
123 return;
124 }
125
David Brown361be7a2017-03-29 12:28:47 -0600126 let mut status = RunStatus::new();
David Browna3b93cf2017-03-29 12:41:26 -0600127 if args.cmd_run {
David Brown361be7a2017-03-29 12:28:47 -0600128
David Browna3b93cf2017-03-29 12:41:26 -0600129 let align = args.flag_align.map(|x| x.0).unwrap_or(1);
David Brown562a7a02017-01-23 11:19:03 -0700130
Fabio Utzigebeecef2017-07-06 10:36:42 -0300131
David Browna3b93cf2017-03-29 12:41:26 -0600132 let device = match args.flag_device {
133 None => panic!("Missing mandatory device argument"),
134 Some(dev) => dev,
135 };
David Brownde7729e2017-01-09 10:41:35 -0700136
David Browna3b93cf2017-03-29 12:41:26 -0600137 status.run_single(device, align);
138 }
139
140 if args.cmd_runall {
141 for &dev in ALL_DEVICES {
142 for &align in &[1, 2, 4, 8] {
143 status.run_single(dev, align);
144 }
145 }
146 }
David Brown5c6b6792017-03-20 12:51:28 -0600147
David Brown361be7a2017-03-29 12:28:47 -0600148 if status.failures > 0 {
David Brown187dd882017-07-11 11:15:23 -0600149 error!("{} Tests ran with {} failures", status.failures + status.passes, status.failures);
David Brown361be7a2017-03-29 12:28:47 -0600150 process::exit(1);
151 } else {
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300152 error!("{} Tests ran successfully", status.passes);
David Brown361be7a2017-03-29 12:28:47 -0600153 process::exit(0);
154 }
155}
David Brown5c6b6792017-03-20 12:51:28 -0600156
David Brown361be7a2017-03-29 12:28:47 -0600157struct RunStatus {
158 failures: usize,
159 passes: usize,
160}
David Brownde7729e2017-01-09 10:41:35 -0700161
David Brown361be7a2017-03-29 12:28:47 -0600162impl RunStatus {
163 fn new() -> RunStatus {
164 RunStatus {
165 failures: 0,
166 passes: 0,
David Brownde7729e2017-01-09 10:41:35 -0700167 }
168 }
David Brownde7729e2017-01-09 10:41:35 -0700169
David Brown361be7a2017-03-29 12:28:47 -0600170 fn run_single(&mut self, device: DeviceName, align: u8) {
David Browna3b93cf2017-03-29 12:41:26 -0600171 warn!("Running on device {} with alignment {}", device, align);
172
David Brown361be7a2017-03-29 12:28:47 -0600173 let (mut flash, areadesc) = match device {
174 DeviceName::Stm32f4 => {
175 // STM style flash. Large sectors, with a large scratch area.
David Brown7ddec0b2017-07-06 10:47:35 -0600176 let flash = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
177 64 * 1024,
178 128 * 1024, 128 * 1024, 128 * 1024],
179 align as usize);
David Brown361be7a2017-03-29 12:28:47 -0600180 let mut areadesc = AreaDesc::new(&flash);
181 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
182 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
183 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch);
184 (flash, areadesc)
185 }
186 DeviceName::K64f => {
187 // NXP style flash. Small sectors, one small sector for scratch.
David Brown7ddec0b2017-07-06 10:47:35 -0600188 let flash = SimFlash::new(vec![4096; 128], align as usize);
David Brown361be7a2017-03-29 12:28:47 -0600189
190 let mut areadesc = AreaDesc::new(&flash);
191 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
192 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
193 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch);
194 (flash, areadesc)
195 }
196 DeviceName::K64fBig => {
197 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
198 // uses small sectors, but we tell the bootloader they are large.
David Brown7ddec0b2017-07-06 10:47:35 -0600199 let flash = SimFlash::new(vec![4096; 128], align as usize);
David Brown361be7a2017-03-29 12:28:47 -0600200
201 let mut areadesc = AreaDesc::new(&flash);
202 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0);
203 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1);
204 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch);
205 (flash, areadesc)
206 }
207 DeviceName::Nrf52840 => {
208 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
209 // does not divide into the image size.
David Brown7ddec0b2017-07-06 10:47:35 -0600210 let flash = SimFlash::new(vec![4096; 128], align as usize);
David Brown361be7a2017-03-29 12:28:47 -0600211
212 let mut areadesc = AreaDesc::new(&flash);
213 areadesc.add_image(0x008000, 0x034000, FlashId::Image0);
214 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1);
215 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch);
216 (flash, areadesc)
217 }
218 };
219
220 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
221 let (slot1_base, slot1_len) = areadesc.find(FlashId::Image1);
222 let (scratch_base, _) = areadesc.find(FlashId::ImageScratch);
223
224 // Code below assumes that the slots are consecutive.
225 assert_eq!(slot1_base, slot0_base + slot0_len);
226 assert_eq!(scratch_base, slot1_base + slot1_len);
227
Fabio Utzigebeecef2017-07-06 10:36:42 -0300228 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 2;
229
David Brown361be7a2017-03-29 12:28:47 -0600230 // println!("Areas: {:#?}", areadesc.get_c());
231
232 // Install the boot trailer signature, so that the code will start an upgrade.
233 // TODO: This must be a multiple of flash alignment, add support for an image that is smaller,
234 // and just gets padded.
David Brown361be7a2017-03-29 12:28:47 -0600235
Fabio Utzigebeecef2017-07-06 10:36:42 -0300236 // Create original and upgrade images
237 let slot0 = SlotInfo {
238 base_off: slot0_base as usize,
239 trailer_off: slot1_base - offset_from_end,
240 };
241
242 let slot1 = SlotInfo {
243 base_off: slot1_base as usize,
244 trailer_off: scratch_base - offset_from_end,
245 };
246
Fabio Utzig645e5142017-07-17 15:36:13 -0300247 // Set an alignment, and position the magic value.
248 c::set_sim_flash_align(align);
Fabio Utzigebeecef2017-07-06 10:36:42 -0300249
250 let mut failed = false;
David Brown361be7a2017-03-29 12:28:47 -0600251
Fabio Utzig645e5142017-07-17 15:36:13 -0300252 // Creates a badly signed image in slot1 to check that it is not
253 // upgraded to
254 let mut bad_flash = flash.clone();
255 let bad_slot1_image = Images {
256 slot0: &slot0,
257 slot1: &slot1,
258 primary: install_image(&mut bad_flash, slot0_base, 32784, false),
259 upgrade: install_image(&mut bad_flash, slot1_base, 41928, true),
260 };
261
262 failed |= run_signfail_upgrade(&bad_flash, &areadesc, &bad_slot1_image);
263
264 let images = Images {
265 slot0: &slot0,
266 slot1: &slot1,
267 primary: install_image(&mut flash, slot0_base, 32784, false),
268 upgrade: install_image(&mut flash, slot1_base, 41928, false),
269 };
David Brown361be7a2017-03-29 12:28:47 -0600270
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300271 failed |= run_norevert_newimage(&flash, &areadesc, &images);
272
Fabio Utzigebeecef2017-07-06 10:36:42 -0300273 mark_upgrade(&mut flash, &images.slot1);
David Brown361be7a2017-03-29 12:28:47 -0600274
Fabio Utzigebeecef2017-07-06 10:36:42 -0300275 // upgrades without fails, counts number of flash operations
276 let total_count = match run_basic_upgrade(&flash, &areadesc, &images) {
277 Ok(v) => v,
278 Err(_) => {
279 self.failures += 1;
280 return;
281 },
David Brown902d6172017-05-05 09:37:41 -0600282 };
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300283
Fabio Utzigebeecef2017-07-06 10:36:42 -0300284 failed |= run_basic_revert(&flash, &areadesc, &images);
285 failed |= run_revert_with_fails(&flash, &areadesc, &images, total_count);
286 failed |= run_perm_with_fails(&flash, &areadesc, &images, total_count);
287 failed |= run_perm_with_random_fails(&flash, &areadesc, &images,
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300288 total_count, 5);
Fabio Utzigebeecef2017-07-06 10:36:42 -0300289 failed |= run_norevert(&flash, &areadesc, &images);
David Brown361be7a2017-03-29 12:28:47 -0600290
Fabio Utzigebeecef2017-07-06 10:36:42 -0300291 //show_flash(&flash);
David Brown361be7a2017-03-29 12:28:47 -0600292
David Brown361be7a2017-03-29 12:28:47 -0600293 if failed {
294 self.failures += 1;
295 } else {
296 self.passes += 1;
297 }
David Brownc638f792017-01-10 12:34:33 -0700298 }
David Brownde7729e2017-01-09 10:41:35 -0700299}
300
Fabio Utzigebeecef2017-07-06 10:36:42 -0300301/// A simple upgrade without forced failures.
302///
303/// Returns the number of flash operations which can later be used to
304/// inject failures at chosen steps.
David Brown7ddec0b2017-07-06 10:47:35 -0600305fn run_basic_upgrade(flash: &SimFlash, areadesc: &AreaDesc, images: &Images)
Fabio Utzigebeecef2017-07-06 10:36:42 -0300306 -> Result<i32, ()> {
307 let (fl, total_count) = try_upgrade(&flash, &areadesc, &images, None);
308 info!("Total flash operation count={}", total_count);
309
310 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
311 warn!("Image mismatch after first boot");
312 Err(())
313 } else {
314 Ok(total_count)
315 }
316}
317
David Brown7ddec0b2017-07-06 10:47:35 -0600318fn run_basic_revert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool {
Fabio Utzigebeecef2017-07-06 10:36:42 -0300319 let mut fails = 0;
320
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300321 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigebeecef2017-07-06 10:36:42 -0300322 if Caps::SwapUpgrade.present() {
323 for count in 2 .. 5 {
324 info!("Try revert: {}", count);
325 let fl = try_revert(&flash, &areadesc, count);
326 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300327 error!("Revert failure on count {}", count);
Fabio Utzigebeecef2017-07-06 10:36:42 -0300328 fails += 1;
329 }
330 }
331 }
332
333 fails > 0
334}
335
David Brown7ddec0b2017-07-06 10:47:35 -0600336fn run_perm_with_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
Fabio Utzigebeecef2017-07-06 10:36:42 -0300337 total_flash_ops: i32) -> bool {
338 let mut fails = 0;
339
340 // Let's try an image halfway through.
341 for i in 1 .. total_flash_ops {
342 info!("Try interruption at {}", i);
343 let (fl, count) = try_upgrade(&flash, &areadesc, &images, Some(i));
344 info!("Second boot, count={}", count);
345 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
346 warn!("FAIL at step {} of {}", i, total_flash_ops);
347 fails += 1;
348 }
349
350 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
351 COPY_DONE) {
352 warn!("Mismatched trailer for Slot 0");
353 fails += 1;
354 }
355
356 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
357 UNSET) {
358 warn!("Mismatched trailer for Slot 1");
359 fails += 1;
360 }
361
362 if Caps::SwapUpgrade.present() {
363 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
364 warn!("Slot 1 FAIL at step {} of {}", i, total_flash_ops);
365 fails += 1;
366 }
367 }
368 }
369
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300370 if fails > 0 {
371 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
372 fails as f32 * 100.0 / total_flash_ops as f32);
373 }
Fabio Utzigebeecef2017-07-06 10:36:42 -0300374
375 fails > 0
376}
377
David Brown7ddec0b2017-07-06 10:47:35 -0600378fn run_perm_with_random_fails(flash: &SimFlash, areadesc: &AreaDesc,
Fabio Utzigebeecef2017-07-06 10:36:42 -0300379 images: &Images, total_flash_ops: i32,
380 total_fails: usize) -> bool {
381 let mut fails = 0;
382 let (fl, total_counts) = try_random_fails(&flash, &areadesc, &images,
383 total_flash_ops, total_fails);
384 info!("Random interruptions at reset points={:?}", total_counts);
385
386 let slot0_ok = verify_image(&fl, images.slot0.base_off, &images.upgrade);
387 let slot1_ok = if Caps::SwapUpgrade.present() {
388 verify_image(&fl, images.slot1.base_off, &images.primary)
389 } else {
390 true
391 };
392 if !slot0_ok || !slot1_ok {
393 error!("Image mismatch after random interrupts: slot0={} slot1={}",
394 if slot0_ok { "ok" } else { "fail" },
395 if slot1_ok { "ok" } else { "fail" });
396 fails += 1;
397 }
398 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
399 COPY_DONE) {
400 error!("Mismatched trailer for Slot 0");
401 fails += 1;
402 }
403 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
404 UNSET) {
405 error!("Mismatched trailer for Slot 1");
406 fails += 1;
407 }
408
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300409 if fails > 0 {
410 error!("Error testing perm upgrade with {} fails", total_fails);
411 }
412
Fabio Utzigebeecef2017-07-06 10:36:42 -0300413 fails > 0
414}
415
David Brown7ddec0b2017-07-06 10:47:35 -0600416fn run_revert_with_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
Fabio Utzigebeecef2017-07-06 10:36:42 -0300417 total_count: i32) -> bool {
418 let mut fails = 0;
419
420 if Caps::SwapUpgrade.present() {
421 for i in 1 .. (total_count - 1) {
422 info!("Try interruption at {}", i);
423 if try_revert_with_fail_at(&flash, &areadesc, &images, i) {
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300424 error!("Revert failed at interruption {}", i);
Fabio Utzigebeecef2017-07-06 10:36:42 -0300425 fails += 1;
426 }
427 }
428 }
429
430 fails > 0
431}
432
David Brown7ddec0b2017-07-06 10:47:35 -0600433fn run_norevert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool {
Fabio Utzigebeecef2017-07-06 10:36:42 -0300434 let mut fl = flash.clone();
435 let mut fails = 0;
436
437 info!("Try norevert");
438 c::set_flash_counter(0);
439
440 // First do a normal upgrade...
441 if c::boot_go(&mut fl, &areadesc) != 0 {
442 warn!("Failed first boot");
443 fails += 1;
444 }
445
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300446 //FIXME: copy_done is written by boot_go, is it ok if no copy
447 // was ever done?
448
Fabio Utzigebeecef2017-07-06 10:36:42 -0300449 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
450 warn!("Slot 0 image verification FAIL");
451 fails += 1;
452 }
453 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
454 COPY_DONE) {
455 warn!("Mismatched trailer for Slot 0");
456 fails += 1;
457 }
458 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
459 UNSET) {
460 warn!("Mismatched trailer for Slot 1");
461 fails += 1;
462 }
463
464 // Marks image in slot0 as permanent, no revert should happen...
465 mark_permanent_upgrade(&mut fl, &images.slot0);
466
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300467 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
Fabio Utzigebeecef2017-07-06 10:36:42 -0300473 if c::boot_go(&mut fl, &areadesc) != 0 {
474 warn!("Failed second boot");
475 fails += 1;
476 }
477
478 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
479 COPY_DONE) {
480 warn!("Mismatched trailer for Slot 0");
481 fails += 1;
482 }
483 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
484 warn!("Failed image verification");
485 fails += 1;
486 }
487
Fabio Utzig7b47ef72017-07-13 09:34:33 -0300488 if fails > 0 {
489 error!("Error running upgrade without revert");
490 }
491
492 fails > 0
493}
494
495// Tests a new image written to slot0 that already has magic and image_ok set
496// while there is no image on slot1, so no revert should ever happen...
497fn run_norevert_newimage(flash: &SimFlash, areadesc: &AreaDesc,
498 images: &Images) -> bool {
499 let mut fl = flash.clone();
500 let mut fails = 0;
501
502 info!("Try non-revert on imgtool generated image");
503 c::set_flash_counter(0);
504
505 mark_upgrade(&mut fl, &images.slot0);
506
507 // This simulates writing an image created by imgtool to Slot 0
508 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET, UNSET) {
509 warn!("Mismatched trailer for Slot 0");
510 fails += 1;
511 }
512
513 // Run the bootloader...
514 if c::boot_go(&mut fl, &areadesc) != 0 {
515 warn!("Failed first boot");
516 fails += 1;
517 }
518
519 // State should not have changed
520 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
521 warn!("Failed image verification");
522 fails += 1;
523 }
524 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
525 UNSET) {
526 warn!("Mismatched trailer for Slot 0");
527 fails += 1;
528 }
529 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
530 UNSET) {
531 warn!("Mismatched trailer for Slot 1");
532 fails += 1;
533 }
534
535 if fails > 0 {
536 error!("Expected a non revert with new image");
537 }
538
Fabio Utzigebeecef2017-07-06 10:36:42 -0300539 fails > 0
540}
541
Fabio Utzig645e5142017-07-17 15:36:13 -0300542// Tests a new image written to slot0 that already has magic and image_ok set
543// while there is no image on slot1, so no revert should ever happen...
544fn run_signfail_upgrade(flash: &SimFlash, areadesc: &AreaDesc,
545 images: &Images) -> bool {
546 let mut fl = flash.clone();
547 let mut fails = 0;
548
549 info!("Try upgrade image with bad signature");
550 c::set_flash_counter(0);
551
552 mark_upgrade(&mut fl, &images.slot0);
553 mark_permanent_upgrade(&mut fl, &images.slot0);
554 mark_upgrade(&mut fl, &images.slot1);
555
556 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
557 UNSET) {
558 warn!("Mismatched trailer for Slot 0");
559 fails += 1;
560 }
561
562 // Run the bootloader...
563 if c::boot_go(&mut fl, &areadesc) != 0 {
564 warn!("Failed first boot");
565 fails += 1;
566 }
567
568 // State should not have changed
569 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
570 warn!("Failed image verification");
571 fails += 1;
572 }
573 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
574 UNSET) {
575 warn!("Mismatched trailer for Slot 0");
576 fails += 1;
577 }
578
579 if fails > 0 {
580 error!("Expected an upgrade failure when image has bad signature");
581 }
582
583 fails > 0
584}
585
Fabio Utzigebeecef2017-07-06 10:36:42 -0300586/// Test a boot, optionally stopping after 'n' flash options. Returns a count
587/// of the number of flash operations done total.
David Brown7ddec0b2017-07-06 10:47:35 -0600588fn try_upgrade(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
589 stop: Option<i32>) -> (SimFlash, i32) {
David Brownde7729e2017-01-09 10:41:35 -0700590 // Clone the flash to have a new copy.
591 let mut fl = flash.clone();
592
Fabio Utzigebeecef2017-07-06 10:36:42 -0300593 mark_permanent_upgrade(&mut fl, &images.slot1);
Fabio Utzig57652312017-04-25 19:54:26 -0300594
David Brownde7729e2017-01-09 10:41:35 -0700595 c::set_flash_counter(stop.unwrap_or(0));
Fabio Utzigebeecef2017-07-06 10:36:42 -0300596 let (first_interrupted, count) = match c::boot_go(&mut fl, &areadesc) {
David Brownde7729e2017-01-09 10:41:35 -0700597 -0x13579 => (true, stop.unwrap()),
598 0 => (false, -c::get_flash_counter()),
599 x => panic!("Unknown return: {}", x),
600 };
601 c::set_flash_counter(0);
602
603 if first_interrupted {
604 // fl.dump();
605 match c::boot_go(&mut fl, &areadesc) {
606 -0x13579 => panic!("Shouldn't stop again"),
607 0 => (),
608 x => panic!("Unknown return: {}", x),
609 }
610 }
611
Fabio Utzigebeecef2017-07-06 10:36:42 -0300612 (fl, count - c::get_flash_counter())
David Brownde7729e2017-01-09 10:41:35 -0700613}
614
David Brown7ddec0b2017-07-06 10:47:35 -0600615fn try_revert(flash: &SimFlash, areadesc: &AreaDesc, count: usize) -> SimFlash {
David Brownde7729e2017-01-09 10:41:35 -0700616 let mut fl = flash.clone();
617 c::set_flash_counter(0);
618
David Brown163ab232017-01-23 15:48:35 -0700619 // fl.write_file("image0.bin").unwrap();
620 for i in 0 .. count {
621 info!("Running boot pass {}", i + 1);
David Brownc638f792017-01-10 12:34:33 -0700622 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
623 }
David Brownde7729e2017-01-09 10:41:35 -0700624 fl
625}
626
David Brown7ddec0b2017-07-06 10:47:35 -0600627fn try_revert_with_fail_at(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
Fabio Utzigebeecef2017-07-06 10:36:42 -0300628 stop: i32) -> bool {
David Brownde7729e2017-01-09 10:41:35 -0700629 let mut fl = flash.clone();
Fabio Utzigebeecef2017-07-06 10:36:42 -0300630 let mut x: i32;
631 let mut fails = 0;
David Brownde7729e2017-01-09 10:41:35 -0700632
Fabio Utzigebeecef2017-07-06 10:36:42 -0300633 c::set_flash_counter(stop);
634 x = c::boot_go(&mut fl, &areadesc);
635 if x != -0x13579 {
636 warn!("Should have stopped at interruption point");
637 fails += 1;
638 }
639
640 if !verify_trailer(&fl, images.slot0.trailer_off, None, None, UNSET) {
641 warn!("copy_done should be unset");
642 fails += 1;
643 }
644
645 c::set_flash_counter(0);
646 x = c::boot_go(&mut fl, &areadesc);
647 if x != 0 {
648 warn!("Should have finished upgrade");
649 fails += 1;
650 }
651
652 if !verify_image(&fl, images.slot0.base_off, &images.upgrade) {
653 warn!("Image in slot 0 before revert is invalid at stop={}", stop);
654 fails += 1;
655 }
656 if !verify_image(&fl, images.slot1.base_off, &images.primary) {
657 warn!("Image in slot 1 before revert is invalid at stop={}", stop);
658 fails += 1;
659 }
660 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET,
661 COPY_DONE) {
662 warn!("Mismatched trailer for Slot 0 before revert");
663 fails += 1;
664 }
665 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
666 UNSET) {
667 warn!("Mismatched trailer for Slot 1 before revert");
668 fails += 1;
669 }
670
671 // Do Revert
672 c::set_flash_counter(0);
673 x = c::boot_go(&mut fl, &areadesc);
674 if x != 0 {
675 warn!("Should have finished a revert");
676 fails += 1;
677 }
678
679 if !verify_image(&fl, images.slot0.base_off, &images.primary) {
680 warn!("Image in slot 0 after revert is invalid at stop={}", stop);
681 fails += 1;
682 }
683 if !verify_image(&fl, images.slot1.base_off, &images.upgrade) {
684 warn!("Image in slot 1 after revert is invalid at stop={}", stop);
685 fails += 1;
686 }
687 if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK,
688 COPY_DONE) {
689 warn!("Mismatched trailer for Slot 1 after revert");
690 fails += 1;
691 }
692 if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET,
693 UNSET) {
694 warn!("Mismatched trailer for Slot 1 after revert");
695 fails += 1;
696 }
697
698 fails > 0
David Brownde7729e2017-01-09 10:41:35 -0700699}
700
David Brown7ddec0b2017-07-06 10:47:35 -0600701fn try_random_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images,
702 total_ops: i32, count: usize) -> (SimFlash, Vec<i32>) {
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300703 let mut fl = flash.clone();
704
Fabio Utzigebeecef2017-07-06 10:36:42 -0300705 mark_permanent_upgrade(&mut fl, &images.slot1);
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300706
707 let mut rng = rand::thread_rng();
Fabio Utzig57652312017-04-25 19:54:26 -0300708 let mut resets = vec![0i32; count];
709 let mut remaining_ops = total_ops;
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300710 for i in 0 .. count {
Fabio Utzig57652312017-04-25 19:54:26 -0300711 let ops = Range::new(1, remaining_ops / 2);
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300712 let reset_counter = ops.ind_sample(&mut rng);
713 c::set_flash_counter(reset_counter);
714 match c::boot_go(&mut fl, &areadesc) {
715 0 | -0x13579 => (),
716 x => panic!("Unknown return: {}", x),
717 }
Fabio Utzig57652312017-04-25 19:54:26 -0300718 remaining_ops -= reset_counter;
719 resets[i] = reset_counter;
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300720 }
721
722 c::set_flash_counter(0);
723 match c::boot_go(&mut fl, &areadesc) {
724 -0x13579 => panic!("Should not be have been interrupted!"),
725 0 => (),
726 x => panic!("Unknown return: {}", x),
727 }
728
Fabio Utzig57652312017-04-25 19:54:26 -0300729 (fl, resets)
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300730}
731
David Brownde7729e2017-01-09 10:41:35 -0700732/// Show the flash layout.
733#[allow(dead_code)]
734fn show_flash(flash: &Flash) {
735 println!("---- Flash configuration ----");
736 for sector in flash.sector_iter() {
Fabio Utzigebeecef2017-07-06 10:36:42 -0300737 println!(" {:3}: 0x{:08x}, 0x{:08x}",
David Brownde7729e2017-01-09 10:41:35 -0700738 sector.num, sector.base, sector.size);
739 }
740 println!("");
741}
742
743/// Install a "program" into the given image. This fakes the image header, or at least all of the
744/// fields used by the given code. Returns a copy of the image that was written.
Fabio Utzig645e5142017-07-17 15:36:13 -0300745fn install_image(flash: &mut Flash, offset: usize, len: usize,
746 bad_sig: bool) -> Vec<u8> {
David Brownde7729e2017-01-09 10:41:35 -0700747 let offset0 = offset;
748
David Brown704ac6f2017-07-12 10:14:47 -0600749 let mut tlv = make_tlv();
David Brown187dd882017-07-11 11:15:23 -0600750
David Brownde7729e2017-01-09 10:41:35 -0700751 // Generate a boot header. Note that the size doesn't include the header.
752 let header = ImageHeader {
753 magic: 0x96f3b83c,
David Brown187dd882017-07-11 11:15:23 -0600754 tlv_size: tlv.get_size(),
David Brownde7729e2017-01-09 10:41:35 -0700755 _pad1: 0,
756 hdr_size: 32,
757 key_id: 0,
758 _pad2: 0,
759 img_size: len as u32,
David Brown187dd882017-07-11 11:15:23 -0600760 flags: tlv.get_flags(),
David Brownde7729e2017-01-09 10:41:35 -0700761 ver: ImageVersion {
David Browne380fa62017-01-23 15:49:09 -0700762 major: (offset / (128 * 1024)) as u8,
David Brownde7729e2017-01-09 10:41:35 -0700763 minor: 0,
764 revision: 1,
David Browne380fa62017-01-23 15:49:09 -0700765 build_num: offset as u32,
David Brownde7729e2017-01-09 10:41:35 -0700766 },
767 _pad3: 0,
768 };
769
770 let b_header = header.as_raw();
David Brown187dd882017-07-11 11:15:23 -0600771 tlv.add_bytes(&b_header);
David Brownde7729e2017-01-09 10:41:35 -0700772 /*
773 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
774 mem::size_of::<ImageHeader>()) };
775 */
776 assert_eq!(b_header.len(), 32);
777 flash.write(offset, &b_header).unwrap();
778 let offset = offset + b_header.len();
779
780 // The core of the image itself is just pseudorandom data.
781 let mut buf = vec![0; len];
782 splat(&mut buf, offset);
David Brown187dd882017-07-11 11:15:23 -0600783 tlv.add_bytes(&buf);
784
785 // Get and append the TLV itself.
Fabio Utzig645e5142017-07-17 15:36:13 -0300786 if bad_sig {
787 let good_sig = &mut tlv.make_tlv();
788 buf.append(&mut vec![0; good_sig.len()]);
789 } else {
790 buf.append(&mut tlv.make_tlv());
791 }
David Brown187dd882017-07-11 11:15:23 -0600792
793 // Pad the block to a flash alignment (8 bytes).
794 while buf.len() % 8 != 0 {
795 buf.push(0xFF);
796 }
797
David Brownde7729e2017-01-09 10:41:35 -0700798 flash.write(offset, &buf).unwrap();
799 let offset = offset + buf.len();
800
801 // Copy out the image so that we can verify that the image was installed correctly later.
802 let mut copy = vec![0u8; offset - offset0];
803 flash.read(offset0, &mut copy).unwrap();
804
805 copy
806}
807
David Brown704ac6f2017-07-12 10:14:47 -0600808// The TLV in use depends on what kind of signature we are verifying.
809#[cfg(feature = "sig-rsa")]
810fn make_tlv() -> TlvGen {
811 TlvGen::new_rsa_pss()
812}
813
814#[cfg(not(feature = "sig-rsa"))]
815fn make_tlv() -> TlvGen {
816 TlvGen::new_hash_only()
817}
818
David Brownde7729e2017-01-09 10:41:35 -0700819/// Verify that given image is present in the flash at the given offset.
820fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
821 let mut copy = vec![0u8; buf.len()];
822 flash.read(offset, &mut copy).unwrap();
823
824 if buf != &copy[..] {
825 for i in 0 .. buf.len() {
826 if buf[i] != copy[i] {
David Brown4440af82017-01-09 12:15:05 -0700827 info!("First failure at {:#x}", offset + i);
David Brownde7729e2017-01-09 10:41:35 -0700828 break;
829 }
830 }
831 false
832 } else {
833 true
834 }
835}
836
Fabio Utzigebeecef2017-07-06 10:36:42 -0300837fn verify_trailer(flash: &Flash, offset: usize,
838 magic: Option<&[u8]>, image_ok: Option<u8>,
839 copy_done: Option<u8>) -> bool {
840 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 2];
841 let mut failed = false;
842
843 flash.read(offset, &mut copy).unwrap();
844
845 failed |= match magic {
846 Some(v) => {
847 if &copy[16..] != v {
848 warn!("\"magic\" mismatch at {:#x}", offset);
849 true
850 } else {
851 false
852 }
853 },
854 None => false,
855 };
856
857 failed |= match image_ok {
858 Some(v) => {
859 if copy[8] != v {
860 warn!("\"image_ok\" mismatch at {:#x}", offset);
861 true
862 } else {
863 false
864 }
865 },
866 None => false,
867 };
868
869 failed |= match copy_done {
870 Some(v) => {
871 if copy[0] != v {
872 warn!("\"copy_done\" mismatch at {:#x}", offset);
873 true
874 } else {
875 false
876 }
877 },
878 None => false,
879 };
880
881 !failed
882}
883
David Brownde7729e2017-01-09 10:41:35 -0700884/// The image header
885#[repr(C)]
886pub struct ImageHeader {
887 magic: u32,
888 tlv_size: u16,
889 key_id: u8,
890 _pad1: u8,
891 hdr_size: u16,
892 _pad2: u16,
893 img_size: u32,
894 flags: u32,
895 ver: ImageVersion,
896 _pad3: u32,
897}
898
899impl AsRaw for ImageHeader {}
900
901#[repr(C)]
902pub struct ImageVersion {
903 major: u8,
904 minor: u8,
905 revision: u16,
906 build_num: u32,
907}
908
Fabio Utzigebeecef2017-07-06 10:36:42 -0300909struct SlotInfo {
910 base_off: usize,
911 trailer_off: usize,
912}
913
Fabio Utzig645e5142017-07-17 15:36:13 -0300914struct Images<'a> {
915 slot0: &'a SlotInfo,
916 slot1: &'a SlotInfo,
Fabio Utzigebeecef2017-07-06 10:36:42 -0300917 primary: Vec<u8>,
918 upgrade: Vec<u8>,
919}
920
921const MAGIC_VALID: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3,
922 0x60, 0xd2, 0xef, 0x7f,
923 0x35, 0x52, 0x50, 0x0f,
924 0x2c, 0xb6, 0x79, 0x80]);
925const MAGIC_UNSET: Option<&[u8]> = Some(&[0xff; 16]);
926
927const COPY_DONE: Option<u8> = Some(1);
928const IMAGE_OK: Option<u8> = Some(1);
929const UNSET: Option<u8> = Some(0xff);
930
David Brownde7729e2017-01-09 10:41:35 -0700931/// Write out the magic so that the loader tries doing an upgrade.
Fabio Utzigebeecef2017-07-06 10:36:42 -0300932fn mark_upgrade(flash: &mut Flash, slot: &SlotInfo) {
933 let offset = slot.trailer_off + c::boot_max_align() * 2;
934 flash.write(offset, MAGIC_VALID.unwrap()).unwrap();
935}
936
937/// Writes the image_ok flag which, guess what, tells the bootloader
938/// the this image is ok (not a test, and no revert is to be performed).
939fn mark_permanent_upgrade(flash: &mut Flash, slot: &SlotInfo) {
940 let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
941 let align = c::get_sim_flash_align() as usize;
942 let off = slot.trailer_off + c::boot_max_align();
943 flash.write(off, &ok[..align]).unwrap();
David Brownde7729e2017-01-09 10:41:35 -0700944}
945
946// Drop some pseudo-random gibberish onto the data.
947fn splat(data: &mut [u8], seed: usize) {
948 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
949 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
950 rng.fill_bytes(data);
951}
952
953/// Return a read-only view into the raw bytes of this object
954trait AsRaw : Sized {
955 fn as_raw<'a>(&'a self) -> &'a [u8] {
956 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
957 mem::size_of::<Self>()) }
958 }
959}
960
961fn show_sizes() {
962 // This isn't panic safe.
963 let old_align = c::get_sim_flash_align();
964 for min in &[1, 2, 4, 8] {
965 c::set_sim_flash_align(*min);
966 let msize = c::boot_trailer_sz();
967 println!("{:2}: {} (0x{:x})", min, msize, msize);
968 }
969 c::set_sim_flash_align(old_align);
970}