David Brown | 2639e07 | 2017-10-11 11:18:44 -0600 | [diff] [blame] | 1 | #[macro_use] extern crate log; |
| 2 | extern crate ring; |
| 3 | extern crate env_logger; |
| 4 | extern crate docopt; |
| 5 | extern crate libc; |
| 6 | extern crate pem; |
| 7 | extern crate rand; |
| 8 | #[macro_use] extern crate serde_derive; |
| 9 | extern crate serde; |
| 10 | extern crate simflash; |
| 11 | extern crate untrusted; |
| 12 | extern crate mcuboot_sys; |
| 13 | |
| 14 | use docopt::Docopt; |
| 15 | use rand::{Rng, SeedableRng, XorShiftRng}; |
| 16 | use rand::distributions::{IndependentSample, Range}; |
| 17 | use std::fmt; |
| 18 | use std::mem; |
| 19 | use std::process; |
| 20 | use std::slice; |
| 21 | |
| 22 | mod caps; |
| 23 | mod tlv; |
| 24 | |
| 25 | use simflash::{Flash, SimFlash}; |
| 26 | use mcuboot_sys::{c, AreaDesc, FlashId}; |
| 27 | use caps::Caps; |
| 28 | use tlv::TlvGen; |
| 29 | |
| 30 | const USAGE: &'static str = " |
| 31 | Mcuboot simulator |
| 32 | |
| 33 | Usage: |
| 34 | bootsim sizes |
| 35 | bootsim run --device TYPE [--align SIZE] |
| 36 | bootsim runall |
| 37 | bootsim (--help | --version) |
| 38 | |
| 39 | Options: |
| 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 | |
| 47 | #[derive(Debug, Deserialize)] |
| 48 | struct 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, |
| 55 | cmd_runall: bool, |
| 56 | } |
| 57 | |
| 58 | #[derive(Copy, Clone, Debug, Deserialize)] |
David Brown | decbd04 | 2017-10-19 10:43:17 -0600 | [diff] [blame^] | 59 | pub enum DeviceName { Stm32f4, K64f, K64fBig, Nrf52840 } |
David Brown | 2639e07 | 2017-10-11 11:18:44 -0600 | [diff] [blame] | 60 | |
| 61 | static ALL_DEVICES: &'static [DeviceName] = &[ |
| 62 | DeviceName::Stm32f4, |
| 63 | DeviceName::K64f, |
| 64 | DeviceName::K64fBig, |
| 65 | DeviceName::Nrf52840, |
| 66 | ]; |
| 67 | |
| 68 | impl 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 | |
| 80 | #[derive(Debug)] |
| 81 | struct AlignArg(u8); |
| 82 | |
| 83 | struct AlignArgVisitor; |
| 84 | |
| 85 | impl<'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 | |
| 105 | impl<'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) |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | pub fn main() { |
| 114 | let args: Args = Docopt::new(USAGE) |
| 115 | .and_then(|d| d.deserialize()) |
| 116 | .unwrap_or_else(|e| e.exit()); |
| 117 | // println!("args: {:#?}", args); |
| 118 | |
| 119 | if args.cmd_sizes { |
| 120 | show_sizes(); |
| 121 | return; |
| 122 | } |
| 123 | |
| 124 | let mut status = RunStatus::new(); |
| 125 | if args.cmd_run { |
| 126 | |
| 127 | let align = args.flag_align.map(|x| x.0).unwrap_or(1); |
| 128 | |
| 129 | |
| 130 | let device = match args.flag_device { |
| 131 | None => panic!("Missing mandatory device argument"), |
| 132 | Some(dev) => dev, |
| 133 | }; |
| 134 | |
| 135 | status.run_single(device, align); |
| 136 | } |
| 137 | |
| 138 | if args.cmd_runall { |
| 139 | for &dev in ALL_DEVICES { |
| 140 | for &align in &[1, 2, 4, 8] { |
| 141 | status.run_single(dev, align); |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | if status.failures > 0 { |
| 147 | error!("{} Tests ran with {} failures", status.failures + status.passes, status.failures); |
| 148 | process::exit(1); |
| 149 | } else { |
| 150 | error!("{} Tests ran successfully", status.passes); |
| 151 | process::exit(0); |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | struct RunStatus { |
| 156 | failures: usize, |
| 157 | passes: usize, |
| 158 | } |
| 159 | |
| 160 | impl RunStatus { |
| 161 | fn new() -> RunStatus { |
| 162 | RunStatus { |
| 163 | failures: 0, |
| 164 | passes: 0, |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | fn run_single(&mut self, device: DeviceName, align: u8) { |
| 169 | warn!("Running on device {} with alignment {}", device, align); |
| 170 | |
David Brown | decbd04 | 2017-10-19 10:43:17 -0600 | [diff] [blame^] | 171 | let (mut flash, areadesc) = make_device(device, align); |
David Brown | 2639e07 | 2017-10-11 11:18:44 -0600 | [diff] [blame] | 172 | |
| 173 | let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0); |
| 174 | let (slot1_base, slot1_len) = areadesc.find(FlashId::Image1); |
| 175 | let (scratch_base, _) = areadesc.find(FlashId::ImageScratch); |
| 176 | |
| 177 | // Code below assumes that the slots are consecutive. |
| 178 | assert_eq!(slot1_base, slot0_base + slot0_len); |
| 179 | assert_eq!(scratch_base, slot1_base + slot1_len); |
| 180 | |
| 181 | let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 2; |
| 182 | |
| 183 | // println!("Areas: {:#?}", areadesc.get_c()); |
| 184 | |
| 185 | // Install the boot trailer signature, so that the code will start an upgrade. |
| 186 | // TODO: This must be a multiple of flash alignment, add support for an image that is smaller, |
| 187 | // and just gets padded. |
| 188 | |
| 189 | // Create original and upgrade images |
| 190 | let slot0 = SlotInfo { |
| 191 | base_off: slot0_base as usize, |
| 192 | trailer_off: slot1_base - offset_from_end, |
| 193 | }; |
| 194 | |
| 195 | let slot1 = SlotInfo { |
| 196 | base_off: slot1_base as usize, |
| 197 | trailer_off: scratch_base - offset_from_end, |
| 198 | }; |
| 199 | |
| 200 | // Set an alignment, and position the magic value. |
| 201 | c::set_sim_flash_align(align); |
| 202 | |
| 203 | let mut failed = false; |
| 204 | |
| 205 | // Creates a badly signed image in slot1 to check that it is not |
| 206 | // upgraded to |
| 207 | let mut bad_flash = flash.clone(); |
| 208 | let bad_slot1_image = Images { |
| 209 | slot0: &slot0, |
| 210 | slot1: &slot1, |
| 211 | primary: install_image(&mut bad_flash, slot0_base, 32784, false), |
| 212 | upgrade: install_image(&mut bad_flash, slot1_base, 41928, true), |
| 213 | }; |
| 214 | |
| 215 | failed |= run_signfail_upgrade(&bad_flash, &areadesc, &bad_slot1_image); |
| 216 | |
| 217 | let images = Images { |
| 218 | slot0: &slot0, |
| 219 | slot1: &slot1, |
| 220 | primary: install_image(&mut flash, slot0_base, 32784, false), |
| 221 | upgrade: install_image(&mut flash, slot1_base, 41928, false), |
| 222 | }; |
| 223 | |
| 224 | failed |= run_norevert_newimage(&flash, &areadesc, &images); |
| 225 | |
| 226 | mark_upgrade(&mut flash, &images.slot1); |
| 227 | |
| 228 | // upgrades without fails, counts number of flash operations |
| 229 | let total_count = match run_basic_upgrade(&flash, &areadesc, &images) { |
| 230 | Ok(v) => v, |
| 231 | Err(_) => { |
| 232 | self.failures += 1; |
| 233 | return; |
| 234 | }, |
| 235 | }; |
| 236 | |
| 237 | failed |= run_basic_revert(&flash, &areadesc, &images); |
| 238 | failed |= run_revert_with_fails(&flash, &areadesc, &images, total_count); |
| 239 | failed |= run_perm_with_fails(&flash, &areadesc, &images, total_count); |
| 240 | failed |= run_perm_with_random_fails(&flash, &areadesc, &images, |
| 241 | total_count, 5); |
| 242 | failed |= run_norevert(&flash, &areadesc, &images); |
| 243 | |
| 244 | //show_flash(&flash); |
| 245 | |
| 246 | if failed { |
| 247 | self.failures += 1; |
| 248 | } else { |
| 249 | self.passes += 1; |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | |
David Brown | decbd04 | 2017-10-19 10:43:17 -0600 | [diff] [blame^] | 254 | /// Build the Flash and area descriptor for a given device. |
| 255 | pub fn make_device(device: DeviceName, align: u8) -> (SimFlash, AreaDesc) { |
| 256 | match device { |
| 257 | DeviceName::Stm32f4 => { |
| 258 | // STM style flash. Large sectors, with a large scratch area. |
| 259 | let flash = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024, |
| 260 | 64 * 1024, |
| 261 | 128 * 1024, 128 * 1024, 128 * 1024], |
| 262 | align as usize); |
| 263 | let mut areadesc = AreaDesc::new(&flash); |
| 264 | areadesc.add_image(0x020000, 0x020000, FlashId::Image0); |
| 265 | areadesc.add_image(0x040000, 0x020000, FlashId::Image1); |
| 266 | areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch); |
| 267 | (flash, areadesc) |
| 268 | } |
| 269 | DeviceName::K64f => { |
| 270 | // NXP style flash. Small sectors, one small sector for scratch. |
| 271 | let flash = SimFlash::new(vec![4096; 128], align as usize); |
| 272 | |
| 273 | let mut areadesc = AreaDesc::new(&flash); |
| 274 | areadesc.add_image(0x020000, 0x020000, FlashId::Image0); |
| 275 | areadesc.add_image(0x040000, 0x020000, FlashId::Image1); |
| 276 | areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch); |
| 277 | (flash, areadesc) |
| 278 | } |
| 279 | DeviceName::K64fBig => { |
| 280 | // Simulating an STM style flash on top of an NXP style flash. Underlying flash device |
| 281 | // uses small sectors, but we tell the bootloader they are large. |
| 282 | let flash = SimFlash::new(vec![4096; 128], align as usize); |
| 283 | |
| 284 | let mut areadesc = AreaDesc::new(&flash); |
| 285 | areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0); |
| 286 | areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1); |
| 287 | areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch); |
| 288 | (flash, areadesc) |
| 289 | } |
| 290 | DeviceName::Nrf52840 => { |
| 291 | // Simulating the flash on the nrf52840 with partitions set up so that the scratch size |
| 292 | // does not divide into the image size. |
| 293 | let flash = SimFlash::new(vec![4096; 128], align as usize); |
| 294 | |
| 295 | let mut areadesc = AreaDesc::new(&flash); |
| 296 | areadesc.add_image(0x008000, 0x034000, FlashId::Image0); |
| 297 | areadesc.add_image(0x03c000, 0x034000, FlashId::Image1); |
| 298 | areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch); |
| 299 | (flash, areadesc) |
| 300 | } |
| 301 | } |
| 302 | } |
| 303 | |
David Brown | 2639e07 | 2017-10-11 11:18:44 -0600 | [diff] [blame] | 304 | /// A simple upgrade without forced failures. |
| 305 | /// |
| 306 | /// Returns the number of flash operations which can later be used to |
| 307 | /// inject failures at chosen steps. |
| 308 | fn run_basic_upgrade(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) |
| 309 | -> Result<i32, ()> { |
| 310 | let (fl, total_count) = try_upgrade(&flash, &areadesc, &images, None); |
| 311 | info!("Total flash operation count={}", total_count); |
| 312 | |
| 313 | if !verify_image(&fl, images.slot0.base_off, &images.upgrade) { |
| 314 | warn!("Image mismatch after first boot"); |
| 315 | Err(()) |
| 316 | } else { |
| 317 | Ok(total_count) |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | #[cfg(feature = "overwrite-only")] |
| 322 | #[allow(unused_variables)] |
| 323 | fn run_basic_revert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool { |
| 324 | false |
| 325 | } |
| 326 | |
| 327 | #[cfg(not(feature = "overwrite-only"))] |
| 328 | fn run_basic_revert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool { |
| 329 | let mut fails = 0; |
| 330 | |
| 331 | // FIXME: this test would also pass if no swap is ever performed??? |
| 332 | if Caps::SwapUpgrade.present() { |
| 333 | for count in 2 .. 5 { |
| 334 | info!("Try revert: {}", count); |
| 335 | let fl = try_revert(&flash, &areadesc, count); |
| 336 | if !verify_image(&fl, images.slot0.base_off, &images.primary) { |
| 337 | error!("Revert failure on count {}", count); |
| 338 | fails += 1; |
| 339 | } |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | fails > 0 |
| 344 | } |
| 345 | |
| 346 | fn run_perm_with_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images, |
| 347 | total_flash_ops: i32) -> bool { |
| 348 | let mut fails = 0; |
| 349 | |
| 350 | // Let's try an image halfway through. |
| 351 | for i in 1 .. total_flash_ops { |
| 352 | info!("Try interruption at {}", i); |
| 353 | let (fl, count) = try_upgrade(&flash, &areadesc, &images, Some(i)); |
| 354 | info!("Second boot, count={}", count); |
| 355 | if !verify_image(&fl, images.slot0.base_off, &images.upgrade) { |
| 356 | warn!("FAIL at step {} of {}", i, total_flash_ops); |
| 357 | fails += 1; |
| 358 | } |
| 359 | |
| 360 | if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK, |
| 361 | COPY_DONE) { |
| 362 | warn!("Mismatched trailer for Slot 0"); |
| 363 | fails += 1; |
| 364 | } |
| 365 | |
| 366 | if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET, |
| 367 | UNSET) { |
| 368 | warn!("Mismatched trailer for Slot 1"); |
| 369 | fails += 1; |
| 370 | } |
| 371 | |
| 372 | if Caps::SwapUpgrade.present() { |
| 373 | if !verify_image(&fl, images.slot1.base_off, &images.primary) { |
| 374 | warn!("Slot 1 FAIL at step {} of {}", i, total_flash_ops); |
| 375 | fails += 1; |
| 376 | } |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | if fails > 0 { |
| 381 | error!("{} out of {} failed {:.2}%", fails, total_flash_ops, |
| 382 | fails as f32 * 100.0 / total_flash_ops as f32); |
| 383 | } |
| 384 | |
| 385 | fails > 0 |
| 386 | } |
| 387 | |
| 388 | fn run_perm_with_random_fails(flash: &SimFlash, areadesc: &AreaDesc, |
| 389 | images: &Images, total_flash_ops: i32, |
| 390 | total_fails: usize) -> bool { |
| 391 | let mut fails = 0; |
| 392 | let (fl, total_counts) = try_random_fails(&flash, &areadesc, &images, |
| 393 | total_flash_ops, total_fails); |
| 394 | info!("Random interruptions at reset points={:?}", total_counts); |
| 395 | |
| 396 | let slot0_ok = verify_image(&fl, images.slot0.base_off, &images.upgrade); |
| 397 | let slot1_ok = if Caps::SwapUpgrade.present() { |
| 398 | verify_image(&fl, images.slot1.base_off, &images.primary) |
| 399 | } else { |
| 400 | true |
| 401 | }; |
| 402 | if !slot0_ok || !slot1_ok { |
| 403 | error!("Image mismatch after random interrupts: slot0={} slot1={}", |
| 404 | if slot0_ok { "ok" } else { "fail" }, |
| 405 | if slot1_ok { "ok" } else { "fail" }); |
| 406 | fails += 1; |
| 407 | } |
| 408 | if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK, |
| 409 | COPY_DONE) { |
| 410 | error!("Mismatched trailer for Slot 0"); |
| 411 | fails += 1; |
| 412 | } |
| 413 | if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET, |
| 414 | UNSET) { |
| 415 | error!("Mismatched trailer for Slot 1"); |
| 416 | fails += 1; |
| 417 | } |
| 418 | |
| 419 | if fails > 0 { |
| 420 | error!("Error testing perm upgrade with {} fails", total_fails); |
| 421 | } |
| 422 | |
| 423 | fails > 0 |
| 424 | } |
| 425 | |
| 426 | #[cfg(feature = "overwrite-only")] |
| 427 | #[allow(unused_variables)] |
| 428 | fn run_revert_with_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images, |
| 429 | total_count: i32) -> bool { |
| 430 | false |
| 431 | } |
| 432 | |
| 433 | #[cfg(not(feature = "overwrite-only"))] |
| 434 | fn run_revert_with_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images, |
| 435 | total_count: i32) -> bool { |
| 436 | let mut fails = 0; |
| 437 | |
| 438 | if Caps::SwapUpgrade.present() { |
| 439 | for i in 1 .. (total_count - 1) { |
| 440 | info!("Try interruption at {}", i); |
| 441 | if try_revert_with_fail_at(&flash, &areadesc, &images, i) { |
| 442 | error!("Revert failed at interruption {}", i); |
| 443 | fails += 1; |
| 444 | } |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | fails > 0 |
| 449 | } |
| 450 | |
| 451 | #[cfg(feature = "overwrite-only")] |
| 452 | #[allow(unused_variables)] |
| 453 | fn run_norevert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool { |
| 454 | false |
| 455 | } |
| 456 | |
| 457 | #[cfg(not(feature = "overwrite-only"))] |
| 458 | fn run_norevert(flash: &SimFlash, areadesc: &AreaDesc, images: &Images) -> bool { |
| 459 | let mut fl = flash.clone(); |
| 460 | let mut fails = 0; |
| 461 | |
| 462 | info!("Try norevert"); |
| 463 | c::set_flash_counter(0); |
| 464 | |
| 465 | // First do a normal upgrade... |
| 466 | if c::boot_go(&mut fl, &areadesc) != 0 { |
| 467 | warn!("Failed first boot"); |
| 468 | fails += 1; |
| 469 | } |
| 470 | |
| 471 | //FIXME: copy_done is written by boot_go, is it ok if no copy |
| 472 | // was ever done? |
| 473 | |
| 474 | if !verify_image(&fl, images.slot0.base_off, &images.upgrade) { |
| 475 | warn!("Slot 0 image verification FAIL"); |
| 476 | fails += 1; |
| 477 | } |
| 478 | if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET, |
| 479 | COPY_DONE) { |
| 480 | warn!("Mismatched trailer for Slot 0"); |
| 481 | fails += 1; |
| 482 | } |
| 483 | if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET, |
| 484 | UNSET) { |
| 485 | warn!("Mismatched trailer for Slot 1"); |
| 486 | fails += 1; |
| 487 | } |
| 488 | |
| 489 | // Marks image in slot0 as permanent, no revert should happen... |
| 490 | mark_permanent_upgrade(&mut fl, &images.slot0); |
| 491 | |
| 492 | if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK, |
| 493 | COPY_DONE) { |
| 494 | warn!("Mismatched trailer for Slot 0"); |
| 495 | fails += 1; |
| 496 | } |
| 497 | |
| 498 | if c::boot_go(&mut fl, &areadesc) != 0 { |
| 499 | warn!("Failed second boot"); |
| 500 | fails += 1; |
| 501 | } |
| 502 | |
| 503 | if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK, |
| 504 | COPY_DONE) { |
| 505 | warn!("Mismatched trailer for Slot 0"); |
| 506 | fails += 1; |
| 507 | } |
| 508 | if !verify_image(&fl, images.slot0.base_off, &images.upgrade) { |
| 509 | warn!("Failed image verification"); |
| 510 | fails += 1; |
| 511 | } |
| 512 | |
| 513 | if fails > 0 { |
| 514 | error!("Error running upgrade without revert"); |
| 515 | } |
| 516 | |
| 517 | fails > 0 |
| 518 | } |
| 519 | |
| 520 | // Tests a new image written to slot0 that already has magic and image_ok set |
| 521 | // while there is no image on slot1, so no revert should ever happen... |
| 522 | fn run_norevert_newimage(flash: &SimFlash, areadesc: &AreaDesc, |
| 523 | images: &Images) -> bool { |
| 524 | let mut fl = flash.clone(); |
| 525 | let mut fails = 0; |
| 526 | |
| 527 | info!("Try non-revert on imgtool generated image"); |
| 528 | c::set_flash_counter(0); |
| 529 | |
| 530 | mark_upgrade(&mut fl, &images.slot0); |
| 531 | |
| 532 | // This simulates writing an image created by imgtool to Slot 0 |
| 533 | if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET, UNSET) { |
| 534 | warn!("Mismatched trailer for Slot 0"); |
| 535 | fails += 1; |
| 536 | } |
| 537 | |
| 538 | // Run the bootloader... |
| 539 | if c::boot_go(&mut fl, &areadesc) != 0 { |
| 540 | warn!("Failed first boot"); |
| 541 | fails += 1; |
| 542 | } |
| 543 | |
| 544 | // State should not have changed |
| 545 | if !verify_image(&fl, images.slot0.base_off, &images.primary) { |
| 546 | warn!("Failed image verification"); |
| 547 | fails += 1; |
| 548 | } |
| 549 | if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET, |
| 550 | UNSET) { |
| 551 | warn!("Mismatched trailer for Slot 0"); |
| 552 | fails += 1; |
| 553 | } |
| 554 | if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET, |
| 555 | UNSET) { |
| 556 | warn!("Mismatched trailer for Slot 1"); |
| 557 | fails += 1; |
| 558 | } |
| 559 | |
| 560 | if fails > 0 { |
| 561 | error!("Expected a non revert with new image"); |
| 562 | } |
| 563 | |
| 564 | fails > 0 |
| 565 | } |
| 566 | |
| 567 | // Tests a new image written to slot0 that already has magic and image_ok set |
| 568 | // while there is no image on slot1, so no revert should ever happen... |
| 569 | fn run_signfail_upgrade(flash: &SimFlash, areadesc: &AreaDesc, |
| 570 | images: &Images) -> bool { |
| 571 | let mut fl = flash.clone(); |
| 572 | let mut fails = 0; |
| 573 | |
| 574 | info!("Try upgrade image with bad signature"); |
| 575 | c::set_flash_counter(0); |
| 576 | |
| 577 | mark_upgrade(&mut fl, &images.slot0); |
| 578 | mark_permanent_upgrade(&mut fl, &images.slot0); |
| 579 | mark_upgrade(&mut fl, &images.slot1); |
| 580 | |
| 581 | if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK, |
| 582 | UNSET) { |
| 583 | warn!("Mismatched trailer for Slot 0"); |
| 584 | fails += 1; |
| 585 | } |
| 586 | |
| 587 | // Run the bootloader... |
| 588 | if c::boot_go(&mut fl, &areadesc) != 0 { |
| 589 | warn!("Failed first boot"); |
| 590 | fails += 1; |
| 591 | } |
| 592 | |
| 593 | // State should not have changed |
| 594 | if !verify_image(&fl, images.slot0.base_off, &images.primary) { |
| 595 | warn!("Failed image verification"); |
| 596 | fails += 1; |
| 597 | } |
| 598 | if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK, |
| 599 | UNSET) { |
| 600 | warn!("Mismatched trailer for Slot 0"); |
| 601 | fails += 1; |
| 602 | } |
| 603 | |
| 604 | if fails > 0 { |
| 605 | error!("Expected an upgrade failure when image has bad signature"); |
| 606 | } |
| 607 | |
| 608 | fails > 0 |
| 609 | } |
| 610 | |
| 611 | /// Test a boot, optionally stopping after 'n' flash options. Returns a count |
| 612 | /// of the number of flash operations done total. |
| 613 | fn try_upgrade(flash: &SimFlash, areadesc: &AreaDesc, images: &Images, |
| 614 | stop: Option<i32>) -> (SimFlash, i32) { |
| 615 | // Clone the flash to have a new copy. |
| 616 | let mut fl = flash.clone(); |
| 617 | |
| 618 | mark_permanent_upgrade(&mut fl, &images.slot1); |
| 619 | |
| 620 | c::set_flash_counter(stop.unwrap_or(0)); |
| 621 | let (first_interrupted, count) = match c::boot_go(&mut fl, &areadesc) { |
| 622 | -0x13579 => (true, stop.unwrap()), |
| 623 | 0 => (false, -c::get_flash_counter()), |
| 624 | x => panic!("Unknown return: {}", x), |
| 625 | }; |
| 626 | c::set_flash_counter(0); |
| 627 | |
| 628 | if first_interrupted { |
| 629 | // fl.dump(); |
| 630 | match c::boot_go(&mut fl, &areadesc) { |
| 631 | -0x13579 => panic!("Shouldn't stop again"), |
| 632 | 0 => (), |
| 633 | x => panic!("Unknown return: {}", x), |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | (fl, count - c::get_flash_counter()) |
| 638 | } |
| 639 | |
| 640 | #[cfg(not(feature = "overwrite-only"))] |
| 641 | fn try_revert(flash: &SimFlash, areadesc: &AreaDesc, count: usize) -> SimFlash { |
| 642 | let mut fl = flash.clone(); |
| 643 | c::set_flash_counter(0); |
| 644 | |
| 645 | // fl.write_file("image0.bin").unwrap(); |
| 646 | for i in 0 .. count { |
| 647 | info!("Running boot pass {}", i + 1); |
| 648 | assert_eq!(c::boot_go(&mut fl, &areadesc), 0); |
| 649 | } |
| 650 | fl |
| 651 | } |
| 652 | |
| 653 | #[cfg(not(feature = "overwrite-only"))] |
| 654 | fn try_revert_with_fail_at(flash: &SimFlash, areadesc: &AreaDesc, images: &Images, |
| 655 | stop: i32) -> bool { |
| 656 | let mut fl = flash.clone(); |
| 657 | let mut x: i32; |
| 658 | let mut fails = 0; |
| 659 | |
| 660 | c::set_flash_counter(stop); |
| 661 | x = c::boot_go(&mut fl, &areadesc); |
| 662 | if x != -0x13579 { |
| 663 | warn!("Should have stopped at interruption point"); |
| 664 | fails += 1; |
| 665 | } |
| 666 | |
| 667 | if !verify_trailer(&fl, images.slot0.trailer_off, None, None, UNSET) { |
| 668 | warn!("copy_done should be unset"); |
| 669 | fails += 1; |
| 670 | } |
| 671 | |
| 672 | c::set_flash_counter(0); |
| 673 | x = c::boot_go(&mut fl, &areadesc); |
| 674 | if x != 0 { |
| 675 | warn!("Should have finished upgrade"); |
| 676 | fails += 1; |
| 677 | } |
| 678 | |
| 679 | if !verify_image(&fl, images.slot0.base_off, &images.upgrade) { |
| 680 | warn!("Image in slot 0 before revert is invalid at stop={}", stop); |
| 681 | fails += 1; |
| 682 | } |
| 683 | if !verify_image(&fl, images.slot1.base_off, &images.primary) { |
| 684 | warn!("Image in slot 1 before revert is invalid at stop={}", stop); |
| 685 | fails += 1; |
| 686 | } |
| 687 | if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, UNSET, |
| 688 | COPY_DONE) { |
| 689 | warn!("Mismatched trailer for Slot 0 before 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 before revert"); |
| 695 | fails += 1; |
| 696 | } |
| 697 | |
| 698 | // Do Revert |
| 699 | c::set_flash_counter(0); |
| 700 | x = c::boot_go(&mut fl, &areadesc); |
| 701 | if x != 0 { |
| 702 | warn!("Should have finished a revert"); |
| 703 | fails += 1; |
| 704 | } |
| 705 | |
| 706 | if !verify_image(&fl, images.slot0.base_off, &images.primary) { |
| 707 | warn!("Image in slot 0 after revert is invalid at stop={}", stop); |
| 708 | fails += 1; |
| 709 | } |
| 710 | if !verify_image(&fl, images.slot1.base_off, &images.upgrade) { |
| 711 | warn!("Image in slot 1 after revert is invalid at stop={}", stop); |
| 712 | fails += 1; |
| 713 | } |
| 714 | if !verify_trailer(&fl, images.slot0.trailer_off, MAGIC_VALID, IMAGE_OK, |
| 715 | COPY_DONE) { |
| 716 | warn!("Mismatched trailer for Slot 1 after revert"); |
| 717 | fails += 1; |
| 718 | } |
| 719 | if !verify_trailer(&fl, images.slot1.trailer_off, MAGIC_UNSET, UNSET, |
| 720 | UNSET) { |
| 721 | warn!("Mismatched trailer for Slot 1 after revert"); |
| 722 | fails += 1; |
| 723 | } |
| 724 | |
| 725 | fails > 0 |
| 726 | } |
| 727 | |
| 728 | fn try_random_fails(flash: &SimFlash, areadesc: &AreaDesc, images: &Images, |
| 729 | total_ops: i32, count: usize) -> (SimFlash, Vec<i32>) { |
| 730 | let mut fl = flash.clone(); |
| 731 | |
| 732 | mark_permanent_upgrade(&mut fl, &images.slot1); |
| 733 | |
| 734 | let mut rng = rand::thread_rng(); |
| 735 | let mut resets = vec![0i32; count]; |
| 736 | let mut remaining_ops = total_ops; |
| 737 | for i in 0 .. count { |
| 738 | let ops = Range::new(1, remaining_ops / 2); |
| 739 | let reset_counter = ops.ind_sample(&mut rng); |
| 740 | c::set_flash_counter(reset_counter); |
| 741 | match c::boot_go(&mut fl, &areadesc) { |
| 742 | 0 | -0x13579 => (), |
| 743 | x => panic!("Unknown return: {}", x), |
| 744 | } |
| 745 | remaining_ops -= reset_counter; |
| 746 | resets[i] = reset_counter; |
| 747 | } |
| 748 | |
| 749 | c::set_flash_counter(0); |
| 750 | match c::boot_go(&mut fl, &areadesc) { |
| 751 | -0x13579 => panic!("Should not be have been interrupted!"), |
| 752 | 0 => (), |
| 753 | x => panic!("Unknown return: {}", x), |
| 754 | } |
| 755 | |
| 756 | (fl, resets) |
| 757 | } |
| 758 | |
| 759 | /// Show the flash layout. |
| 760 | #[allow(dead_code)] |
| 761 | fn show_flash(flash: &Flash) { |
| 762 | println!("---- Flash configuration ----"); |
| 763 | for sector in flash.sector_iter() { |
| 764 | println!(" {:3}: 0x{:08x}, 0x{:08x}", |
| 765 | sector.num, sector.base, sector.size); |
| 766 | } |
| 767 | println!(""); |
| 768 | } |
| 769 | |
| 770 | /// Install a "program" into the given image. This fakes the image header, or at least all of the |
| 771 | /// fields used by the given code. Returns a copy of the image that was written. |
| 772 | fn install_image(flash: &mut Flash, offset: usize, len: usize, |
| 773 | bad_sig: bool) -> Vec<u8> { |
| 774 | let offset0 = offset; |
| 775 | |
| 776 | let mut tlv = make_tlv(); |
| 777 | |
| 778 | // Generate a boot header. Note that the size doesn't include the header. |
| 779 | let header = ImageHeader { |
| 780 | magic: 0x96f3b83d, |
| 781 | tlv_size: tlv.get_size(), |
| 782 | _pad1: 0, |
| 783 | hdr_size: 32, |
| 784 | key_id: 0, |
| 785 | _pad2: 0, |
| 786 | img_size: len as u32, |
| 787 | flags: tlv.get_flags(), |
| 788 | ver: ImageVersion { |
| 789 | major: (offset / (128 * 1024)) as u8, |
| 790 | minor: 0, |
| 791 | revision: 1, |
| 792 | build_num: offset as u32, |
| 793 | }, |
| 794 | _pad3: 0, |
| 795 | }; |
| 796 | |
| 797 | let b_header = header.as_raw(); |
| 798 | tlv.add_bytes(&b_header); |
| 799 | /* |
| 800 | let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8, |
| 801 | mem::size_of::<ImageHeader>()) }; |
| 802 | */ |
| 803 | assert_eq!(b_header.len(), 32); |
| 804 | flash.write(offset, &b_header).unwrap(); |
| 805 | let offset = offset + b_header.len(); |
| 806 | |
| 807 | // The core of the image itself is just pseudorandom data. |
| 808 | let mut buf = vec![0; len]; |
| 809 | splat(&mut buf, offset); |
| 810 | tlv.add_bytes(&buf); |
| 811 | |
| 812 | // Get and append the TLV itself. |
| 813 | if bad_sig { |
| 814 | let good_sig = &mut tlv.make_tlv(); |
| 815 | buf.append(&mut vec![0; good_sig.len()]); |
| 816 | } else { |
| 817 | buf.append(&mut tlv.make_tlv()); |
| 818 | } |
| 819 | |
| 820 | // Pad the block to a flash alignment (8 bytes). |
| 821 | while buf.len() % 8 != 0 { |
| 822 | buf.push(0xFF); |
| 823 | } |
| 824 | |
| 825 | flash.write(offset, &buf).unwrap(); |
| 826 | let offset = offset + buf.len(); |
| 827 | |
| 828 | // Copy out the image so that we can verify that the image was installed correctly later. |
| 829 | let mut copy = vec![0u8; offset - offset0]; |
| 830 | flash.read(offset0, &mut copy).unwrap(); |
| 831 | |
| 832 | copy |
| 833 | } |
| 834 | |
| 835 | // The TLV in use depends on what kind of signature we are verifying. |
| 836 | #[cfg(feature = "sig-rsa")] |
| 837 | fn make_tlv() -> TlvGen { |
| 838 | TlvGen::new_rsa_pss() |
| 839 | } |
| 840 | |
| 841 | #[cfg(not(feature = "sig-rsa"))] |
| 842 | fn make_tlv() -> TlvGen { |
| 843 | TlvGen::new_hash_only() |
| 844 | } |
| 845 | |
| 846 | /// Verify that given image is present in the flash at the given offset. |
| 847 | fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool { |
| 848 | let mut copy = vec![0u8; buf.len()]; |
| 849 | flash.read(offset, &mut copy).unwrap(); |
| 850 | |
| 851 | if buf != ©[..] { |
| 852 | for i in 0 .. buf.len() { |
| 853 | if buf[i] != copy[i] { |
| 854 | info!("First failure at {:#x}", offset + i); |
| 855 | break; |
| 856 | } |
| 857 | } |
| 858 | false |
| 859 | } else { |
| 860 | true |
| 861 | } |
| 862 | } |
| 863 | |
| 864 | #[cfg(feature = "overwrite-only")] |
| 865 | #[allow(unused_variables)] |
| 866 | // overwrite-only doesn't employ trailer management |
| 867 | fn verify_trailer(flash: &Flash, offset: usize, |
| 868 | magic: Option<&[u8]>, image_ok: Option<u8>, |
| 869 | copy_done: Option<u8>) -> bool { |
| 870 | true |
| 871 | } |
| 872 | |
| 873 | #[cfg(not(feature = "overwrite-only"))] |
| 874 | fn verify_trailer(flash: &Flash, offset: usize, |
| 875 | magic: Option<&[u8]>, image_ok: Option<u8>, |
| 876 | copy_done: Option<u8>) -> bool { |
| 877 | let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 2]; |
| 878 | let mut failed = false; |
| 879 | |
| 880 | flash.read(offset, &mut copy).unwrap(); |
| 881 | |
| 882 | failed |= match magic { |
| 883 | Some(v) => { |
| 884 | if ©[16..] != v { |
| 885 | warn!("\"magic\" mismatch at {:#x}", offset); |
| 886 | true |
| 887 | } else { |
| 888 | false |
| 889 | } |
| 890 | }, |
| 891 | None => false, |
| 892 | }; |
| 893 | |
| 894 | failed |= match image_ok { |
| 895 | Some(v) => { |
| 896 | if copy[8] != v { |
| 897 | warn!("\"image_ok\" mismatch at {:#x}", offset); |
| 898 | true |
| 899 | } else { |
| 900 | false |
| 901 | } |
| 902 | }, |
| 903 | None => false, |
| 904 | }; |
| 905 | |
| 906 | failed |= match copy_done { |
| 907 | Some(v) => { |
| 908 | if copy[0] != v { |
| 909 | warn!("\"copy_done\" mismatch at {:#x}", offset); |
| 910 | true |
| 911 | } else { |
| 912 | false |
| 913 | } |
| 914 | }, |
| 915 | None => false, |
| 916 | }; |
| 917 | |
| 918 | !failed |
| 919 | } |
| 920 | |
| 921 | /// The image header |
| 922 | #[repr(C)] |
| 923 | pub struct ImageHeader { |
| 924 | magic: u32, |
| 925 | tlv_size: u16, |
| 926 | key_id: u8, |
| 927 | _pad1: u8, |
| 928 | hdr_size: u16, |
| 929 | _pad2: u16, |
| 930 | img_size: u32, |
| 931 | flags: u32, |
| 932 | ver: ImageVersion, |
| 933 | _pad3: u32, |
| 934 | } |
| 935 | |
| 936 | impl AsRaw for ImageHeader {} |
| 937 | |
| 938 | #[repr(C)] |
| 939 | pub struct ImageVersion { |
| 940 | major: u8, |
| 941 | minor: u8, |
| 942 | revision: u16, |
| 943 | build_num: u32, |
| 944 | } |
| 945 | |
| 946 | struct SlotInfo { |
| 947 | base_off: usize, |
| 948 | trailer_off: usize, |
| 949 | } |
| 950 | |
| 951 | struct Images<'a> { |
| 952 | slot0: &'a SlotInfo, |
| 953 | slot1: &'a SlotInfo, |
| 954 | primary: Vec<u8>, |
| 955 | upgrade: Vec<u8>, |
| 956 | } |
| 957 | |
| 958 | const MAGIC_VALID: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3, |
| 959 | 0x60, 0xd2, 0xef, 0x7f, |
| 960 | 0x35, 0x52, 0x50, 0x0f, |
| 961 | 0x2c, 0xb6, 0x79, 0x80]); |
| 962 | const MAGIC_UNSET: Option<&[u8]> = Some(&[0xff; 16]); |
| 963 | |
| 964 | const COPY_DONE: Option<u8> = Some(1); |
| 965 | const IMAGE_OK: Option<u8> = Some(1); |
| 966 | const UNSET: Option<u8> = Some(0xff); |
| 967 | |
| 968 | /// Write out the magic so that the loader tries doing an upgrade. |
| 969 | fn mark_upgrade(flash: &mut Flash, slot: &SlotInfo) { |
| 970 | let offset = slot.trailer_off + c::boot_max_align() * 2; |
| 971 | flash.write(offset, MAGIC_VALID.unwrap()).unwrap(); |
| 972 | } |
| 973 | |
| 974 | /// Writes the image_ok flag which, guess what, tells the bootloader |
| 975 | /// the this image is ok (not a test, and no revert is to be performed). |
| 976 | fn mark_permanent_upgrade(flash: &mut Flash, slot: &SlotInfo) { |
| 977 | let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]; |
| 978 | let align = c::get_sim_flash_align() as usize; |
| 979 | let off = slot.trailer_off + c::boot_max_align(); |
| 980 | flash.write(off, &ok[..align]).unwrap(); |
| 981 | } |
| 982 | |
| 983 | // Drop some pseudo-random gibberish onto the data. |
| 984 | fn splat(data: &mut [u8], seed: usize) { |
| 985 | let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32]; |
| 986 | let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block); |
| 987 | rng.fill_bytes(data); |
| 988 | } |
| 989 | |
| 990 | /// Return a read-only view into the raw bytes of this object |
| 991 | trait AsRaw : Sized { |
| 992 | fn as_raw<'a>(&'a self) -> &'a [u8] { |
| 993 | unsafe { slice::from_raw_parts(self as *const _ as *const u8, |
| 994 | mem::size_of::<Self>()) } |
| 995 | } |
| 996 | } |
| 997 | |
| 998 | fn show_sizes() { |
| 999 | // This isn't panic safe. |
| 1000 | let old_align = c::get_sim_flash_align(); |
| 1001 | for min in &[1, 2, 4, 8] { |
| 1002 | c::set_sim_flash_align(*min); |
| 1003 | let msize = c::boot_trailer_sz(); |
| 1004 | println!("{:2}: {} (0x{:x})", min, msize, msize); |
| 1005 | } |
| 1006 | c::set_sim_flash_align(old_align); |
| 1007 | } |