David Brown | 4440af8 | 2017-01-09 12:15:05 -0700 | [diff] [blame] | 1 | #[macro_use] extern crate log; |
| 2 | extern crate env_logger; |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 3 | extern crate docopt; |
| 4 | extern crate libc; |
| 5 | extern crate rand; |
| 6 | extern crate rustc_serialize; |
| 7 | |
| 8 | #[macro_use] |
| 9 | extern crate error_chain; |
| 10 | |
| 11 | use docopt::Docopt; |
| 12 | use rand::{Rng, SeedableRng, XorShiftRng}; |
| 13 | use rustc_serialize::{Decodable, Decoder}; |
| 14 | use std::mem; |
| 15 | use std::slice; |
| 16 | |
| 17 | mod area; |
| 18 | mod c; |
| 19 | mod flash; |
| 20 | pub mod api; |
| 21 | mod pdump; |
| 22 | |
| 23 | use flash::Flash; |
| 24 | use area::{AreaDesc, FlashId}; |
| 25 | |
| 26 | const USAGE: &'static str = " |
| 27 | Mcuboot simulator |
| 28 | |
| 29 | Usage: |
| 30 | bootsim sizes |
| 31 | bootsim run --device TYPE [--align SIZE] |
| 32 | bootsim (--help | --version) |
| 33 | |
| 34 | Options: |
| 35 | -h, --help Show this message |
| 36 | --version Version |
| 37 | --device TYPE MCU to simulate |
| 38 | Valid values: stm32f4, k64f |
| 39 | --align SIZE Flash write alignment |
| 40 | "; |
| 41 | |
| 42 | #[derive(Debug, RustcDecodable)] |
| 43 | struct Args { |
| 44 | flag_help: bool, |
| 45 | flag_version: bool, |
| 46 | flag_device: Option<DeviceName>, |
| 47 | flag_align: Option<AlignArg>, |
| 48 | cmd_sizes: bool, |
| 49 | cmd_run: bool, |
| 50 | } |
| 51 | |
| 52 | #[derive(Debug, RustcDecodable)] |
David Brown | 07fb8fa | 2017-03-20 12:40:57 -0600 | [diff] [blame^] | 53 | enum DeviceName { Stm32f4, K64f, K64fBig, Nrf52840 } |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 54 | |
| 55 | #[derive(Debug)] |
| 56 | struct AlignArg(u8); |
| 57 | |
| 58 | impl Decodable for AlignArg { |
| 59 | // Decode the alignment ourselves, to restrict it to the valid possible alignments. |
| 60 | fn decode<D: Decoder>(d: &mut D) -> Result<AlignArg, D::Error> { |
| 61 | let m = d.read_u8()?; |
| 62 | match m { |
| 63 | 1 | 2 | 4 | 8 => Ok(AlignArg(m)), |
| 64 | _ => Err(d.error("Invalid alignment")), |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | fn main() { |
David Brown | 4440af8 | 2017-01-09 12:15:05 -0700 | [diff] [blame] | 70 | env_logger::init().unwrap(); |
| 71 | |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 72 | let args: Args = Docopt::new(USAGE) |
| 73 | .and_then(|d| d.decode()) |
| 74 | .unwrap_or_else(|e| e.exit()); |
| 75 | // println!("args: {:#?}", args); |
| 76 | |
| 77 | if args.cmd_sizes { |
| 78 | show_sizes(); |
| 79 | return; |
| 80 | } |
| 81 | |
David Brown | 562a7a0 | 2017-01-23 11:19:03 -0700 | [diff] [blame] | 82 | let align = args.flag_align.map(|x| x.0).unwrap_or(1); |
| 83 | |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 84 | let (mut flash, areadesc) = match args.flag_device { |
| 85 | None => panic!("Missing mandatory argument"), |
| 86 | Some(DeviceName::Stm32f4) => { |
| 87 | // STM style flash. Large sectors, with a large scratch area. |
| 88 | let flash = Flash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024, |
| 89 | 64 * 1024, |
David Brown | 562a7a0 | 2017-01-23 11:19:03 -0700 | [diff] [blame] | 90 | 128 * 1024, 128 * 1024, 128 * 1024], |
| 91 | align as usize); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 92 | let mut areadesc = AreaDesc::new(&flash); |
| 93 | areadesc.add_image(0x020000, 0x020000, FlashId::Image0); |
| 94 | areadesc.add_image(0x040000, 0x020000, FlashId::Image1); |
| 95 | areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch); |
| 96 | (flash, areadesc) |
| 97 | } |
| 98 | Some(DeviceName::K64f) => { |
| 99 | // NXP style flash. Small sectors, one small sector for scratch. |
David Brown | 562a7a0 | 2017-01-23 11:19:03 -0700 | [diff] [blame] | 100 | let flash = Flash::new(vec![4096; 128], align as usize); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 101 | |
| 102 | let mut areadesc = AreaDesc::new(&flash); |
| 103 | areadesc.add_image(0x020000, 0x020000, FlashId::Image0); |
| 104 | areadesc.add_image(0x040000, 0x020000, FlashId::Image1); |
| 105 | areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch); |
| 106 | (flash, areadesc) |
| 107 | } |
David Brown | 90c1913 | 2017-01-23 10:21:28 -0700 | [diff] [blame] | 108 | Some(DeviceName::K64fBig) => { |
| 109 | // Simulating an STM style flash on top of an NXP style flash. Underlying flash device |
| 110 | // uses small sectors, but we tell the bootloader they are large. |
David Brown | 562a7a0 | 2017-01-23 11:19:03 -0700 | [diff] [blame] | 111 | let flash = Flash::new(vec![4096; 128], align as usize); |
David Brown | 90c1913 | 2017-01-23 10:21:28 -0700 | [diff] [blame] | 112 | |
| 113 | let mut areadesc = AreaDesc::new(&flash); |
| 114 | areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0); |
| 115 | areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1); |
| 116 | areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch); |
| 117 | (flash, areadesc) |
| 118 | } |
David Brown | 07fb8fa | 2017-03-20 12:40:57 -0600 | [diff] [blame^] | 119 | Some(DeviceName::Nrf52840) => { |
| 120 | // Simulating the flash on the nrf52840 with partitions set up so that the scratch size |
| 121 | // does not divide into the image size. |
| 122 | let flash = Flash::new(vec![4096; 128], align as usize); |
| 123 | |
| 124 | let mut areadesc = AreaDesc::new(&flash); |
| 125 | areadesc.add_image(0x008000, 0x034000, FlashId::Image0); |
| 126 | areadesc.add_image(0x03c000, 0x034000, FlashId::Image1); |
| 127 | areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch); |
| 128 | (flash, areadesc) |
| 129 | } |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 130 | }; |
| 131 | |
David Brown | 5c6b679 | 2017-03-20 12:51:28 -0600 | [diff] [blame] | 132 | let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0); |
| 133 | let (slot1_base, slot1_len) = areadesc.find(FlashId::Image1); |
| 134 | let (scratch_base, _) = areadesc.find(FlashId::ImageScratch); |
| 135 | |
| 136 | // Code below assumes that the slots are consecutive. |
| 137 | assert_eq!(slot1_base, slot0_base + slot0_len); |
| 138 | assert_eq!(scratch_base, slot1_base + slot1_len); |
| 139 | |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 140 | // println!("Areas: {:#?}", areadesc.get_c()); |
| 141 | |
| 142 | // Install the boot trailer signature, so that the code will start an upgrade. |
David Brown | 74cc14c | 2017-01-23 15:46:40 -0700 | [diff] [blame] | 143 | // TODO: This must be a multiple of flash alignment, add support for an image that is smaller, |
| 144 | // and just gets padded. |
David Brown | 5c6b679 | 2017-03-20 12:51:28 -0600 | [diff] [blame] | 145 | let primary = install_image(&mut flash, slot0_base, 32784); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 146 | |
| 147 | // Install an upgrade image. |
David Brown | 5c6b679 | 2017-03-20 12:51:28 -0600 | [diff] [blame] | 148 | let upgrade = install_image(&mut flash, slot1_base, 41928); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 149 | |
| 150 | // Set an alignment, and position the magic value. |
David Brown | 562a7a0 | 2017-01-23 11:19:03 -0700 | [diff] [blame] | 151 | c::set_sim_flash_align(align); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 152 | let trailer_size = c::boot_trailer_sz(); |
| 153 | |
| 154 | // Mark the upgrade as ready to install. (This looks like it might be a bug in the code, |
| 155 | // however.) |
David Brown | 5c6b679 | 2017-03-20 12:51:28 -0600 | [diff] [blame] | 156 | mark_upgrade(&mut flash, scratch_base - trailer_size as usize); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 157 | |
| 158 | let (fl2, total_count) = try_upgrade(&flash, &areadesc, None); |
David Brown | 4440af8 | 2017-01-09 12:15:05 -0700 | [diff] [blame] | 159 | info!("First boot, count={}", total_count); |
David Brown | 5c6b679 | 2017-03-20 12:51:28 -0600 | [diff] [blame] | 160 | assert!(verify_image(&fl2, slot0_base, &upgrade)); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 161 | |
| 162 | let mut bad = 0; |
| 163 | // Let's try an image halfway through. |
| 164 | for i in 1 .. total_count { |
David Brown | 4440af8 | 2017-01-09 12:15:05 -0700 | [diff] [blame] | 165 | info!("Try interruption at {}", i); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 166 | let (fl3, total_count) = try_upgrade(&flash, &areadesc, Some(i)); |
David Brown | 4440af8 | 2017-01-09 12:15:05 -0700 | [diff] [blame] | 167 | info!("Second boot, count={}", total_count); |
David Brown | 5c6b679 | 2017-03-20 12:51:28 -0600 | [diff] [blame] | 168 | if !verify_image(&fl3, slot0_base, &upgrade) { |
David Brown | 4440af8 | 2017-01-09 12:15:05 -0700 | [diff] [blame] | 169 | warn!("FAIL at step {} of {}", i, total_count); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 170 | bad += 1; |
| 171 | } |
David Brown | 5c6b679 | 2017-03-20 12:51:28 -0600 | [diff] [blame] | 172 | if !verify_image(&fl3, slot1_base, &primary) { |
David Brown | 4440af8 | 2017-01-09 12:15:05 -0700 | [diff] [blame] | 173 | warn!("Slot 1 FAIL at step {} of {}", i, total_count); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 174 | bad += 1; |
| 175 | } |
| 176 | } |
David Brown | 4440af8 | 2017-01-09 12:15:05 -0700 | [diff] [blame] | 177 | error!("{} out of {} failed {:.2}%", |
| 178 | bad, total_count, |
| 179 | bad as f32 * 100.0 / total_count as f32); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 180 | |
David Brown | c638f79 | 2017-01-10 12:34:33 -0700 | [diff] [blame] | 181 | for count in 2 .. 5 { |
| 182 | info!("Try revert: {}", count); |
| 183 | let fl2 = try_revert(&flash, &areadesc, count); |
David Brown | 5c6b679 | 2017-03-20 12:51:28 -0600 | [diff] [blame] | 184 | assert!(verify_image(&fl2, slot0_base, &primary)); |
David Brown | c638f79 | 2017-01-10 12:34:33 -0700 | [diff] [blame] | 185 | } |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 186 | |
David Brown | 4440af8 | 2017-01-09 12:15:05 -0700 | [diff] [blame] | 187 | info!("Try norevert"); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 188 | let fl2 = try_norevert(&flash, &areadesc); |
David Brown | 5c6b679 | 2017-03-20 12:51:28 -0600 | [diff] [blame] | 189 | assert!(verify_image(&fl2, slot0_base, &upgrade)); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 190 | |
| 191 | /* |
| 192 | // show_flash(&flash); |
| 193 | |
| 194 | println!("First boot for upgrade"); |
| 195 | // c::set_flash_counter(570); |
| 196 | c::boot_go(&mut flash, &areadesc); |
| 197 | // println!("{} flash ops", c::get_flash_counter()); |
| 198 | |
David Brown | 5c6b679 | 2017-03-20 12:51:28 -0600 | [diff] [blame] | 199 | verify_image(&flash, slot0_base, &upgrade); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 200 | |
| 201 | println!("\n------------------\nSecond boot"); |
| 202 | c::boot_go(&mut flash, &areadesc); |
| 203 | */ |
| 204 | } |
| 205 | |
| 206 | /// Test a boot, optionally stopping after 'n' flash options. Returns a count of the number of |
| 207 | /// flash operations done total. |
| 208 | fn try_upgrade(flash: &Flash, areadesc: &AreaDesc, stop: Option<i32>) -> (Flash, i32) { |
| 209 | // Clone the flash to have a new copy. |
| 210 | let mut fl = flash.clone(); |
| 211 | |
| 212 | c::set_flash_counter(stop.unwrap_or(0)); |
| 213 | let (first_interrupted, cnt1) = match c::boot_go(&mut fl, &areadesc) { |
| 214 | -0x13579 => (true, stop.unwrap()), |
| 215 | 0 => (false, -c::get_flash_counter()), |
| 216 | x => panic!("Unknown return: {}", x), |
| 217 | }; |
| 218 | c::set_flash_counter(0); |
| 219 | |
| 220 | if first_interrupted { |
| 221 | // fl.dump(); |
| 222 | match c::boot_go(&mut fl, &areadesc) { |
| 223 | -0x13579 => panic!("Shouldn't stop again"), |
| 224 | 0 => (), |
| 225 | x => panic!("Unknown return: {}", x), |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | let cnt2 = cnt1 - c::get_flash_counter(); |
| 230 | |
| 231 | (fl, cnt2) |
| 232 | } |
| 233 | |
David Brown | c638f79 | 2017-01-10 12:34:33 -0700 | [diff] [blame] | 234 | fn try_revert(flash: &Flash, areadesc: &AreaDesc, count: usize) -> Flash { |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 235 | let mut fl = flash.clone(); |
| 236 | c::set_flash_counter(0); |
| 237 | |
David Brown | 163ab23 | 2017-01-23 15:48:35 -0700 | [diff] [blame] | 238 | // fl.write_file("image0.bin").unwrap(); |
| 239 | for i in 0 .. count { |
| 240 | info!("Running boot pass {}", i + 1); |
David Brown | c638f79 | 2017-01-10 12:34:33 -0700 | [diff] [blame] | 241 | assert_eq!(c::boot_go(&mut fl, &areadesc), 0); |
| 242 | } |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 243 | fl |
| 244 | } |
| 245 | |
| 246 | fn try_norevert(flash: &Flash, areadesc: &AreaDesc) -> Flash { |
| 247 | let mut fl = flash.clone(); |
| 248 | c::set_flash_counter(0); |
| 249 | let align = c::get_sim_flash_align() as usize; |
| 250 | |
| 251 | assert_eq!(c::boot_go(&mut fl, &areadesc), 0); |
| 252 | // Write boot_ok |
David Brown | 75e16d6 | 2017-01-23 15:47:59 -0700 | [diff] [blame] | 253 | let ok = [1u8, 0, 0, 0, 0, 0, 0, 0]; |
David Brown | 5c6b679 | 2017-03-20 12:51:28 -0600 | [diff] [blame] | 254 | let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0); |
| 255 | fl.write(slot0_base + slot0_len - align, &ok[..align]).unwrap(); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 256 | assert_eq!(c::boot_go(&mut fl, &areadesc), 0); |
| 257 | fl |
| 258 | } |
| 259 | |
| 260 | /// Show the flash layout. |
| 261 | #[allow(dead_code)] |
| 262 | fn show_flash(flash: &Flash) { |
| 263 | println!("---- Flash configuration ----"); |
| 264 | for sector in flash.sector_iter() { |
| 265 | println!(" {:2}: 0x{:08x}, 0x{:08x}", |
| 266 | sector.num, sector.base, sector.size); |
| 267 | } |
| 268 | println!(""); |
| 269 | } |
| 270 | |
| 271 | /// Install a "program" into the given image. This fakes the image header, or at least all of the |
| 272 | /// fields used by the given code. Returns a copy of the image that was written. |
| 273 | fn install_image(flash: &mut Flash, offset: usize, len: usize) -> Vec<u8> { |
| 274 | let offset0 = offset; |
| 275 | |
| 276 | // Generate a boot header. Note that the size doesn't include the header. |
| 277 | let header = ImageHeader { |
| 278 | magic: 0x96f3b83c, |
| 279 | tlv_size: 0, |
| 280 | _pad1: 0, |
| 281 | hdr_size: 32, |
| 282 | key_id: 0, |
| 283 | _pad2: 0, |
| 284 | img_size: len as u32, |
| 285 | flags: 0, |
| 286 | ver: ImageVersion { |
David Brown | e380fa6 | 2017-01-23 15:49:09 -0700 | [diff] [blame] | 287 | major: (offset / (128 * 1024)) as u8, |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 288 | minor: 0, |
| 289 | revision: 1, |
David Brown | e380fa6 | 2017-01-23 15:49:09 -0700 | [diff] [blame] | 290 | build_num: offset as u32, |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 291 | }, |
| 292 | _pad3: 0, |
| 293 | }; |
| 294 | |
| 295 | let b_header = header.as_raw(); |
| 296 | /* |
| 297 | let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8, |
| 298 | mem::size_of::<ImageHeader>()) }; |
| 299 | */ |
| 300 | assert_eq!(b_header.len(), 32); |
| 301 | flash.write(offset, &b_header).unwrap(); |
| 302 | let offset = offset + b_header.len(); |
| 303 | |
| 304 | // The core of the image itself is just pseudorandom data. |
| 305 | let mut buf = vec![0; len]; |
| 306 | splat(&mut buf, offset); |
| 307 | flash.write(offset, &buf).unwrap(); |
| 308 | let offset = offset + buf.len(); |
| 309 | |
| 310 | // Copy out the image so that we can verify that the image was installed correctly later. |
| 311 | let mut copy = vec![0u8; offset - offset0]; |
| 312 | flash.read(offset0, &mut copy).unwrap(); |
| 313 | |
| 314 | copy |
| 315 | } |
| 316 | |
| 317 | /// Verify that given image is present in the flash at the given offset. |
| 318 | fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool { |
| 319 | let mut copy = vec![0u8; buf.len()]; |
| 320 | flash.read(offset, &mut copy).unwrap(); |
| 321 | |
| 322 | if buf != ©[..] { |
| 323 | for i in 0 .. buf.len() { |
| 324 | if buf[i] != copy[i] { |
David Brown | 4440af8 | 2017-01-09 12:15:05 -0700 | [diff] [blame] | 325 | info!("First failure at {:#x}", offset + i); |
David Brown | de7729e | 2017-01-09 10:41:35 -0700 | [diff] [blame] | 326 | break; |
| 327 | } |
| 328 | } |
| 329 | false |
| 330 | } else { |
| 331 | true |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | /// The image header |
| 336 | #[repr(C)] |
| 337 | pub struct ImageHeader { |
| 338 | magic: u32, |
| 339 | tlv_size: u16, |
| 340 | key_id: u8, |
| 341 | _pad1: u8, |
| 342 | hdr_size: u16, |
| 343 | _pad2: u16, |
| 344 | img_size: u32, |
| 345 | flags: u32, |
| 346 | ver: ImageVersion, |
| 347 | _pad3: u32, |
| 348 | } |
| 349 | |
| 350 | impl AsRaw for ImageHeader {} |
| 351 | |
| 352 | #[repr(C)] |
| 353 | pub struct ImageVersion { |
| 354 | major: u8, |
| 355 | minor: u8, |
| 356 | revision: u16, |
| 357 | build_num: u32, |
| 358 | } |
| 359 | |
| 360 | /// Write out the magic so that the loader tries doing an upgrade. |
| 361 | fn mark_upgrade(flash: &mut Flash, offset: usize) { |
| 362 | let magic = vec![0x77, 0xc2, 0x95, 0xf3, |
| 363 | 0x60, 0xd2, 0xef, 0x7f, |
| 364 | 0x35, 0x52, 0x50, 0x0f, |
| 365 | 0x2c, 0xb6, 0x79, 0x80]; |
| 366 | flash.write(offset, &magic).unwrap(); |
| 367 | } |
| 368 | |
| 369 | // Drop some pseudo-random gibberish onto the data. |
| 370 | fn splat(data: &mut [u8], seed: usize) { |
| 371 | let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32]; |
| 372 | let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block); |
| 373 | rng.fill_bytes(data); |
| 374 | } |
| 375 | |
| 376 | /// Return a read-only view into the raw bytes of this object |
| 377 | trait AsRaw : Sized { |
| 378 | fn as_raw<'a>(&'a self) -> &'a [u8] { |
| 379 | unsafe { slice::from_raw_parts(self as *const _ as *const u8, |
| 380 | mem::size_of::<Self>()) } |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | fn show_sizes() { |
| 385 | // This isn't panic safe. |
| 386 | let old_align = c::get_sim_flash_align(); |
| 387 | for min in &[1, 2, 4, 8] { |
| 388 | c::set_sim_flash_align(*min); |
| 389 | let msize = c::boot_trailer_sz(); |
| 390 | println!("{:2}: {} (0x{:x})", min, msize, msize); |
| 391 | } |
| 392 | c::set_sim_flash_align(old_align); |
| 393 | } |