blob: 39987251667cd1fe6f6245d19b97b49eb21a6bc3 [file] [log] [blame]
David Brown4440af82017-01-09 12:15:05 -07001#[macro_use] extern crate log;
2extern crate env_logger;
David Brownde7729e2017-01-09 10:41:35 -07003extern crate docopt;
4extern crate libc;
5extern crate rand;
6extern crate rustc_serialize;
7
8#[macro_use]
9extern crate error_chain;
10
11use docopt::Docopt;
David Brown4cb26232017-04-11 08:15:18 -060012use rand::{Rng, SeedableRng, XorShiftRng};
Fabio Utzigbb5635e2017-04-10 09:07:02 -030013use rand::distributions::{IndependentSample, Range};
David Brownde7729e2017-01-09 10:41:35 -070014use rustc_serialize::{Decodable, Decoder};
David Browna3b93cf2017-03-29 12:41:26 -060015use std::fmt;
David Brownde7729e2017-01-09 10:41:35 -070016use std::mem;
David Brown361be7a2017-03-29 12:28:47 -060017use std::process;
David Brownde7729e2017-01-09 10:41:35 -070018use std::slice;
19
20mod area;
21mod c;
22mod flash;
23pub mod api;
24mod pdump;
David Brown902d6172017-05-05 09:37:41 -060025mod caps;
David Brownde7729e2017-01-09 10:41:35 -070026
27use flash::Flash;
28use area::{AreaDesc, FlashId};
David Brown902d6172017-05-05 09:37:41 -060029use caps::Caps;
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
48#[derive(Debug, RustcDecodable)]
49struct 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 Browna3b93cf2017-03-29 12:41:26 -060059#[derive(Copy, Clone, Debug, RustcDecodable)]
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
84impl Decodable for AlignArg {
85 // Decode the alignment ourselves, to restrict it to the valid possible alignments.
86 fn decode<D: Decoder>(d: &mut D) -> Result<AlignArg, D::Error> {
87 let m = d.read_u8()?;
88 match m {
89 1 | 2 | 4 | 8 => Ok(AlignArg(m)),
90 _ => Err(d.error("Invalid alignment")),
91 }
92 }
93}
94
95fn main() {
David Brown4440af82017-01-09 12:15:05 -070096 env_logger::init().unwrap();
97
David Brownde7729e2017-01-09 10:41:35 -070098 let args: Args = Docopt::new(USAGE)
99 .and_then(|d| d.decode())
100 .unwrap_or_else(|e| e.exit());
101 // println!("args: {:#?}", args);
102
103 if args.cmd_sizes {
104 show_sizes();
105 return;
106 }
107
David Brown361be7a2017-03-29 12:28:47 -0600108 let mut status = RunStatus::new();
David Browna3b93cf2017-03-29 12:41:26 -0600109 if args.cmd_run {
David Brown361be7a2017-03-29 12:28:47 -0600110
David Browna3b93cf2017-03-29 12:41:26 -0600111 let align = args.flag_align.map(|x| x.0).unwrap_or(1);
David Brown562a7a02017-01-23 11:19:03 -0700112
David Browna3b93cf2017-03-29 12:41:26 -0600113 let device = match args.flag_device {
114 None => panic!("Missing mandatory device argument"),
115 Some(dev) => dev,
116 };
David Brownde7729e2017-01-09 10:41:35 -0700117
David Browna3b93cf2017-03-29 12:41:26 -0600118 status.run_single(device, align);
119 }
120
121 if args.cmd_runall {
122 for &dev in ALL_DEVICES {
123 for &align in &[1, 2, 4, 8] {
124 status.run_single(dev, align);
125 }
126 }
127 }
David Brown5c6b6792017-03-20 12:51:28 -0600128
David Brown361be7a2017-03-29 12:28:47 -0600129 if status.failures > 0 {
130 warn!("{} Tests ran with {} failures", status.failures + status.passes, status.failures);
131 process::exit(1);
132 } else {
133 warn!("{} Tests ran successfully", status.passes);
134 process::exit(0);
135 }
136}
David Brown5c6b6792017-03-20 12:51:28 -0600137
David Brown361be7a2017-03-29 12:28:47 -0600138struct RunStatus {
139 failures: usize,
140 passes: usize,
141}
David Brownde7729e2017-01-09 10:41:35 -0700142
David Brown361be7a2017-03-29 12:28:47 -0600143impl RunStatus {
144 fn new() -> RunStatus {
145 RunStatus {
146 failures: 0,
147 passes: 0,
David Brownde7729e2017-01-09 10:41:35 -0700148 }
149 }
David Brownde7729e2017-01-09 10:41:35 -0700150
David Brown361be7a2017-03-29 12:28:47 -0600151 fn run_single(&mut self, device: DeviceName, align: u8) {
152 let mut failed = false;
153
David Browna3b93cf2017-03-29 12:41:26 -0600154 warn!("Running on device {} with alignment {}", device, align);
155
David Brown361be7a2017-03-29 12:28:47 -0600156 let (mut flash, areadesc) = match device {
157 DeviceName::Stm32f4 => {
158 // STM style flash. Large sectors, with a large scratch area.
159 let flash = Flash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
160 64 * 1024,
161 128 * 1024, 128 * 1024, 128 * 1024],
162 align as usize);
163 let mut areadesc = AreaDesc::new(&flash);
164 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
165 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
166 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch);
167 (flash, areadesc)
168 }
169 DeviceName::K64f => {
170 // NXP style flash. Small sectors, one small sector for scratch.
171 let flash = Flash::new(vec![4096; 128], align as usize);
172
173 let mut areadesc = AreaDesc::new(&flash);
174 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
175 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
176 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch);
177 (flash, areadesc)
178 }
179 DeviceName::K64fBig => {
180 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
181 // uses small sectors, but we tell the bootloader they are large.
182 let flash = Flash::new(vec![4096; 128], align as usize);
183
184 let mut areadesc = AreaDesc::new(&flash);
185 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0);
186 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1);
187 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch);
188 (flash, areadesc)
189 }
190 DeviceName::Nrf52840 => {
191 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
192 // does not divide into the image size.
193 let flash = Flash::new(vec![4096; 128], align as usize);
194
195 let mut areadesc = AreaDesc::new(&flash);
196 areadesc.add_image(0x008000, 0x034000, FlashId::Image0);
197 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1);
198 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch);
199 (flash, areadesc)
200 }
201 };
202
203 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
204 let (slot1_base, slot1_len) = areadesc.find(FlashId::Image1);
205 let (scratch_base, _) = areadesc.find(FlashId::ImageScratch);
206
207 // Code below assumes that the slots are consecutive.
208 assert_eq!(slot1_base, slot0_base + slot0_len);
209 assert_eq!(scratch_base, slot1_base + slot1_len);
210
211 // println!("Areas: {:#?}", areadesc.get_c());
212
213 // Install the boot trailer signature, so that the code will start an upgrade.
214 // TODO: This must be a multiple of flash alignment, add support for an image that is smaller,
215 // and just gets padded.
216 let primary = install_image(&mut flash, slot0_base, 32784);
217
218 // Install an upgrade image.
219 let upgrade = install_image(&mut flash, slot1_base, 41928);
220
221 // Set an alignment, and position the magic value.
222 c::set_sim_flash_align(align);
223 let trailer_size = c::boot_trailer_sz();
224
225 // Mark the upgrade as ready to install. (This looks like it might be a bug in the code,
226 // however.)
227 mark_upgrade(&mut flash, scratch_base - trailer_size as usize);
228
229 let (fl2, total_count) = try_upgrade(&flash, &areadesc, None);
230 info!("First boot, count={}", total_count);
231 if !verify_image(&fl2, slot0_base, &upgrade) {
232 error!("Image mismatch after first boot");
233 // This isn't really recoverable, and more tests aren't likely to reveal much.
234 self.failures += 1;
235 return;
236 }
237
238 let mut bad = 0;
David Brown4cb26232017-04-11 08:15:18 -0600239 // Let's try an image halfway through.
240 for i in 1 .. total_count {
David Brown361be7a2017-03-29 12:28:47 -0600241 info!("Try interruption at {}", i);
242 let (fl3, total_count) = try_upgrade(&flash, &areadesc, Some(i));
243 info!("Second boot, count={}", total_count);
244 if !verify_image(&fl3, slot0_base, &upgrade) {
245 warn!("FAIL at step {} of {}", i, total_count);
246 bad += 1;
247 }
David Brown902d6172017-05-05 09:37:41 -0600248 if Caps::SwapUpgrade.present() {
249 if !verify_image(&fl3, slot1_base, &primary) {
250 warn!("Slot 1 FAIL at step {} of {}", i, total_count);
251 bad += 1;
252 }
David Brown361be7a2017-03-29 12:28:47 -0600253 }
254 }
255 error!("{} out of {} failed {:.2}%",
256 bad, total_count,
257 bad as f32 * 100.0 / total_count as f32);
258 if bad > 0 {
259 failed = true;
260 }
261
Fabio Utzig57652312017-04-25 19:54:26 -0300262 let (fl4, total_counts) = try_random_fails(&flash, &areadesc, total_count, 5);
David Brown902d6172017-05-05 09:37:41 -0600263 info!("Random interruptions at reset points={:?}", total_counts);
Fabio Utzig57652312017-04-25 19:54:26 -0300264 let slot0_ok = verify_image(&fl4, slot0_base, &upgrade);
David Brown902d6172017-05-05 09:37:41 -0600265 let slot1_ok = if Caps::SwapUpgrade.present() {
266 verify_image(&fl4, slot1_base, &primary)
267 } else {
268 true
269 };
270 if !slot0_ok /* || !slot1_ok */ {
271 error!("Image mismatch after random interrupts: slot0={} slot1={}",
Fabio Utzig57652312017-04-25 19:54:26 -0300272 if slot0_ok { "ok" } else { "fail" },
273 if slot1_ok { "ok" } else { "fail" });
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300274 self.failures += 1;
275 return;
276 }
277
David Brown902d6172017-05-05 09:37:41 -0600278 if Caps::SwapUpgrade.present() {
279 for count in 2 .. 5 {
280 info!("Try revert: {}", count);
281 let fl2 = try_revert(&flash, &areadesc, count);
282 if !verify_image(&fl2, slot0_base, &primary) {
283 warn!("Revert failure on count {}", count);
284 failed = true;
285 }
David Brown361be7a2017-03-29 12:28:47 -0600286 }
287 }
288
289 info!("Try norevert");
290 let fl2 = try_norevert(&flash, &areadesc);
291 if !verify_image(&fl2, slot0_base, &upgrade) {
292 warn!("No revert failed");
293 failed = true;
294 }
295
296 /*
297 // show_flash(&flash);
298
299 println!("First boot for upgrade");
300 // c::set_flash_counter(570);
301 c::boot_go(&mut flash, &areadesc);
302 // println!("{} flash ops", c::get_flash_counter());
303
304 verify_image(&flash, slot0_base, &upgrade);
305
306 println!("\n------------------\nSecond boot");
307 c::boot_go(&mut flash, &areadesc);
308 */
309 if failed {
310 self.failures += 1;
311 } else {
312 self.passes += 1;
313 }
David Brownc638f792017-01-10 12:34:33 -0700314 }
David Brownde7729e2017-01-09 10:41:35 -0700315}
316
317/// Test a boot, optionally stopping after 'n' flash options. Returns a count of the number of
318/// flash operations done total.
319fn try_upgrade(flash: &Flash, areadesc: &AreaDesc, stop: Option<i32>) -> (Flash, i32) {
320 // Clone the flash to have a new copy.
321 let mut fl = flash.clone();
322
Fabio Utzig57652312017-04-25 19:54:26 -0300323 // mark permanent upgrade
324 let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
325 let (base, _) = areadesc.find(FlashId::ImageScratch);
326 let align = c::get_sim_flash_align() as usize;
327 fl.write(base - align, &ok[..align]).unwrap();
328
David Brownde7729e2017-01-09 10:41:35 -0700329 c::set_flash_counter(stop.unwrap_or(0));
330 let (first_interrupted, cnt1) = match c::boot_go(&mut fl, &areadesc) {
331 -0x13579 => (true, stop.unwrap()),
332 0 => (false, -c::get_flash_counter()),
333 x => panic!("Unknown return: {}", x),
334 };
335 c::set_flash_counter(0);
336
337 if first_interrupted {
338 // fl.dump();
339 match c::boot_go(&mut fl, &areadesc) {
340 -0x13579 => panic!("Shouldn't stop again"),
341 0 => (),
342 x => panic!("Unknown return: {}", x),
343 }
344 }
345
346 let cnt2 = cnt1 - c::get_flash_counter();
347
348 (fl, cnt2)
349}
350
David Brownc638f792017-01-10 12:34:33 -0700351fn try_revert(flash: &Flash, areadesc: &AreaDesc, count: usize) -> Flash {
David Brownde7729e2017-01-09 10:41:35 -0700352 let mut fl = flash.clone();
353 c::set_flash_counter(0);
354
David Brown163ab232017-01-23 15:48:35 -0700355 // fl.write_file("image0.bin").unwrap();
356 for i in 0 .. count {
357 info!("Running boot pass {}", i + 1);
David Brownc638f792017-01-10 12:34:33 -0700358 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
359 }
David Brownde7729e2017-01-09 10:41:35 -0700360 fl
361}
362
363fn try_norevert(flash: &Flash, areadesc: &AreaDesc) -> Flash {
364 let mut fl = flash.clone();
365 c::set_flash_counter(0);
366 let align = c::get_sim_flash_align() as usize;
367
368 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
369 // Write boot_ok
David Brown75e16d62017-01-23 15:47:59 -0700370 let ok = [1u8, 0, 0, 0, 0, 0, 0, 0];
David Brown5c6b6792017-03-20 12:51:28 -0600371 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
372 fl.write(slot0_base + slot0_len - align, &ok[..align]).unwrap();
David Brownde7729e2017-01-09 10:41:35 -0700373 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
374 fl
375}
376
Fabio Utzig57652312017-04-25 19:54:26 -0300377fn try_random_fails(flash: &Flash, areadesc: &AreaDesc, total_ops: i32,
378 count: usize) -> (Flash, Vec<i32>) {
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300379 let mut fl = flash.clone();
380
Fabio Utzig57652312017-04-25 19:54:26 -0300381 // mark permanent upgrade
382 let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
383 let (base, _) = areadesc.find(FlashId::ImageScratch);
384 let align = c::get_sim_flash_align() as usize;
385 fl.write(base - align, &ok[..align]).unwrap();
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300386
387 let mut rng = rand::thread_rng();
Fabio Utzig57652312017-04-25 19:54:26 -0300388 let mut resets = vec![0i32; count];
389 let mut remaining_ops = total_ops;
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300390 for i in 0 .. count {
Fabio Utzig57652312017-04-25 19:54:26 -0300391 let ops = Range::new(1, remaining_ops / 2);
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300392 let reset_counter = ops.ind_sample(&mut rng);
393 c::set_flash_counter(reset_counter);
394 match c::boot_go(&mut fl, &areadesc) {
395 0 | -0x13579 => (),
396 x => panic!("Unknown return: {}", x),
397 }
Fabio Utzig57652312017-04-25 19:54:26 -0300398 remaining_ops -= reset_counter;
399 resets[i] = reset_counter;
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300400 }
401
402 c::set_flash_counter(0);
403 match c::boot_go(&mut fl, &areadesc) {
404 -0x13579 => panic!("Should not be have been interrupted!"),
405 0 => (),
406 x => panic!("Unknown return: {}", x),
407 }
408
Fabio Utzig57652312017-04-25 19:54:26 -0300409 (fl, resets)
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300410}
411
David Brownde7729e2017-01-09 10:41:35 -0700412/// Show the flash layout.
413#[allow(dead_code)]
414fn show_flash(flash: &Flash) {
415 println!("---- Flash configuration ----");
416 for sector in flash.sector_iter() {
417 println!(" {:2}: 0x{:08x}, 0x{:08x}",
418 sector.num, sector.base, sector.size);
419 }
420 println!("");
421}
422
423/// Install a "program" into the given image. This fakes the image header, or at least all of the
424/// fields used by the given code. Returns a copy of the image that was written.
425fn install_image(flash: &mut Flash, offset: usize, len: usize) -> Vec<u8> {
426 let offset0 = offset;
427
428 // Generate a boot header. Note that the size doesn't include the header.
429 let header = ImageHeader {
430 magic: 0x96f3b83c,
431 tlv_size: 0,
432 _pad1: 0,
433 hdr_size: 32,
434 key_id: 0,
435 _pad2: 0,
436 img_size: len as u32,
437 flags: 0,
438 ver: ImageVersion {
David Browne380fa62017-01-23 15:49:09 -0700439 major: (offset / (128 * 1024)) as u8,
David Brownde7729e2017-01-09 10:41:35 -0700440 minor: 0,
441 revision: 1,
David Browne380fa62017-01-23 15:49:09 -0700442 build_num: offset as u32,
David Brownde7729e2017-01-09 10:41:35 -0700443 },
444 _pad3: 0,
445 };
446
447 let b_header = header.as_raw();
448 /*
449 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
450 mem::size_of::<ImageHeader>()) };
451 */
452 assert_eq!(b_header.len(), 32);
453 flash.write(offset, &b_header).unwrap();
454 let offset = offset + b_header.len();
455
456 // The core of the image itself is just pseudorandom data.
457 let mut buf = vec![0; len];
458 splat(&mut buf, offset);
459 flash.write(offset, &buf).unwrap();
460 let offset = offset + buf.len();
461
462 // Copy out the image so that we can verify that the image was installed correctly later.
463 let mut copy = vec![0u8; offset - offset0];
464 flash.read(offset0, &mut copy).unwrap();
465
466 copy
467}
468
469/// Verify that given image is present in the flash at the given offset.
470fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
471 let mut copy = vec![0u8; buf.len()];
472 flash.read(offset, &mut copy).unwrap();
473
474 if buf != &copy[..] {
475 for i in 0 .. buf.len() {
476 if buf[i] != copy[i] {
David Brown4440af82017-01-09 12:15:05 -0700477 info!("First failure at {:#x}", offset + i);
David Brownde7729e2017-01-09 10:41:35 -0700478 break;
479 }
480 }
481 false
482 } else {
483 true
484 }
485}
486
487/// The image header
488#[repr(C)]
489pub struct ImageHeader {
490 magic: u32,
491 tlv_size: u16,
492 key_id: u8,
493 _pad1: u8,
494 hdr_size: u16,
495 _pad2: u16,
496 img_size: u32,
497 flags: u32,
498 ver: ImageVersion,
499 _pad3: u32,
500}
501
502impl AsRaw for ImageHeader {}
503
504#[repr(C)]
505pub struct ImageVersion {
506 major: u8,
507 minor: u8,
508 revision: u16,
509 build_num: u32,
510}
511
512/// Write out the magic so that the loader tries doing an upgrade.
513fn mark_upgrade(flash: &mut Flash, offset: usize) {
514 let magic = vec![0x77, 0xc2, 0x95, 0xf3,
515 0x60, 0xd2, 0xef, 0x7f,
516 0x35, 0x52, 0x50, 0x0f,
517 0x2c, 0xb6, 0x79, 0x80];
518 flash.write(offset, &magic).unwrap();
519}
520
521// Drop some pseudo-random gibberish onto the data.
522fn splat(data: &mut [u8], seed: usize) {
523 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
524 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
525 rng.fill_bytes(data);
526}
527
528/// Return a read-only view into the raw bytes of this object
529trait AsRaw : Sized {
530 fn as_raw<'a>(&'a self) -> &'a [u8] {
531 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
532 mem::size_of::<Self>()) }
533 }
534}
535
536fn show_sizes() {
537 // This isn't panic safe.
538 let old_align = c::get_sim_flash_align();
539 for min in &[1, 2, 4, 8] {
540 c::set_sim_flash_align(*min);
541 let msize = c::boot_trailer_sz();
542 println!("{:2}: {} (0x{:x})", min, msize, msize);
543 }
544 c::set_sim_flash_align(old_align);
545}