blob: 60236d6e6f41bbc029fac1cf69c46436c4a892cc [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;
Fabio Utzigbb5635e2017-04-10 09:07:02 -030012use rand::{Rng, SeedableRng, XorShiftRng, thread_rng};
13use 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;
25
26use flash::Flash;
27use area::{AreaDesc, FlashId};
28
29const USAGE: &'static str = "
30Mcuboot simulator
31
32Usage:
33 bootsim sizes
34 bootsim run --device TYPE [--align SIZE]
David Browna3b93cf2017-03-29 12:41:26 -060035 bootsim runall
David Brownde7729e2017-01-09 10:41:35 -070036 bootsim (--help | --version)
37
38Options:
39 -h, --help Show this message
40 --version Version
41 --device TYPE MCU to simulate
42 Valid values: stm32f4, k64f
43 --align SIZE Flash write alignment
44";
45
46#[derive(Debug, RustcDecodable)]
47struct Args {
48 flag_help: bool,
49 flag_version: bool,
50 flag_device: Option<DeviceName>,
51 flag_align: Option<AlignArg>,
52 cmd_sizes: bool,
53 cmd_run: bool,
David Browna3b93cf2017-03-29 12:41:26 -060054 cmd_runall: bool,
David Brownde7729e2017-01-09 10:41:35 -070055}
56
David Browna3b93cf2017-03-29 12:41:26 -060057#[derive(Copy, Clone, Debug, RustcDecodable)]
David Brown07fb8fa2017-03-20 12:40:57 -060058enum DeviceName { Stm32f4, K64f, K64fBig, Nrf52840 }
David Brownde7729e2017-01-09 10:41:35 -070059
David Browna3b93cf2017-03-29 12:41:26 -060060static ALL_DEVICES: &'static [DeviceName] = &[
61 DeviceName::Stm32f4,
62 DeviceName::K64f,
63 DeviceName::K64fBig,
64 DeviceName::Nrf52840,
65];
66
67impl fmt::Display for DeviceName {
68 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69 let name = match *self {
70 DeviceName::Stm32f4 => "stm32f4",
71 DeviceName::K64f => "k64f",
72 DeviceName::K64fBig => "k64fbig",
73 DeviceName::Nrf52840 => "nrf52840",
74 };
75 f.write_str(name)
76 }
77}
78
David Brownde7729e2017-01-09 10:41:35 -070079#[derive(Debug)]
80struct AlignArg(u8);
81
82impl Decodable for AlignArg {
83 // Decode the alignment ourselves, to restrict it to the valid possible alignments.
84 fn decode<D: Decoder>(d: &mut D) -> Result<AlignArg, D::Error> {
85 let m = d.read_u8()?;
86 match m {
87 1 | 2 | 4 | 8 => Ok(AlignArg(m)),
88 _ => Err(d.error("Invalid alignment")),
89 }
90 }
91}
92
93fn main() {
David Brown4440af82017-01-09 12:15:05 -070094 env_logger::init().unwrap();
95
David Brownde7729e2017-01-09 10:41:35 -070096 let args: Args = Docopt::new(USAGE)
97 .and_then(|d| d.decode())
98 .unwrap_or_else(|e| e.exit());
99 // println!("args: {:#?}", args);
100
101 if args.cmd_sizes {
102 show_sizes();
103 return;
104 }
105
David Brown361be7a2017-03-29 12:28:47 -0600106 let mut status = RunStatus::new();
David Browna3b93cf2017-03-29 12:41:26 -0600107 if args.cmd_run {
David Brown361be7a2017-03-29 12:28:47 -0600108
David Browna3b93cf2017-03-29 12:41:26 -0600109 let align = args.flag_align.map(|x| x.0).unwrap_or(1);
David Brown562a7a02017-01-23 11:19:03 -0700110
David Browna3b93cf2017-03-29 12:41:26 -0600111 let device = match args.flag_device {
112 None => panic!("Missing mandatory device argument"),
113 Some(dev) => dev,
114 };
David Brownde7729e2017-01-09 10:41:35 -0700115
David Browna3b93cf2017-03-29 12:41:26 -0600116 status.run_single(device, align);
117 }
118
119 if args.cmd_runall {
120 for &dev in ALL_DEVICES {
121 for &align in &[1, 2, 4, 8] {
122 status.run_single(dev, align);
123 }
124 }
125 }
David Brown5c6b6792017-03-20 12:51:28 -0600126
David Brown361be7a2017-03-29 12:28:47 -0600127 if status.failures > 0 {
128 warn!("{} Tests ran with {} failures", status.failures + status.passes, status.failures);
129 process::exit(1);
130 } else {
131 warn!("{} Tests ran successfully", status.passes);
132 process::exit(0);
133 }
134}
David Brown5c6b6792017-03-20 12:51:28 -0600135
David Brown361be7a2017-03-29 12:28:47 -0600136struct RunStatus {
137 failures: usize,
138 passes: usize,
139}
David Brownde7729e2017-01-09 10:41:35 -0700140
David Brown361be7a2017-03-29 12:28:47 -0600141impl RunStatus {
142 fn new() -> RunStatus {
143 RunStatus {
144 failures: 0,
145 passes: 0,
David Brownde7729e2017-01-09 10:41:35 -0700146 }
147 }
David Brownde7729e2017-01-09 10:41:35 -0700148
David Brown361be7a2017-03-29 12:28:47 -0600149 fn run_single(&mut self, device: DeviceName, align: u8) {
150 let mut failed = false;
151
David Browna3b93cf2017-03-29 12:41:26 -0600152 warn!("Running on device {} with alignment {}", device, align);
153
David Brown361be7a2017-03-29 12:28:47 -0600154 let (mut flash, areadesc) = match device {
155 DeviceName::Stm32f4 => {
156 // STM style flash. Large sectors, with a large scratch area.
157 let flash = Flash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
158 64 * 1024,
159 128 * 1024, 128 * 1024, 128 * 1024],
160 align as usize);
161 let mut areadesc = AreaDesc::new(&flash);
162 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
163 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
164 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch);
165 (flash, areadesc)
166 }
167 DeviceName::K64f => {
168 // NXP style flash. Small sectors, one small sector for scratch.
169 let flash = Flash::new(vec![4096; 128], align as usize);
170
171 let mut areadesc = AreaDesc::new(&flash);
172 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
173 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
174 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch);
175 (flash, areadesc)
176 }
177 DeviceName::K64fBig => {
178 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
179 // uses small sectors, but we tell the bootloader they are large.
180 let flash = Flash::new(vec![4096; 128], align as usize);
181
182 let mut areadesc = AreaDesc::new(&flash);
183 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0);
184 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1);
185 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch);
186 (flash, areadesc)
187 }
188 DeviceName::Nrf52840 => {
189 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
190 // does not divide into the image size.
191 let flash = Flash::new(vec![4096; 128], align as usize);
192
193 let mut areadesc = AreaDesc::new(&flash);
194 areadesc.add_image(0x008000, 0x034000, FlashId::Image0);
195 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1);
196 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch);
197 (flash, areadesc)
198 }
199 };
200
201 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
202 let (slot1_base, slot1_len) = areadesc.find(FlashId::Image1);
203 let (scratch_base, _) = areadesc.find(FlashId::ImageScratch);
204
205 // Code below assumes that the slots are consecutive.
206 assert_eq!(slot1_base, slot0_base + slot0_len);
207 assert_eq!(scratch_base, slot1_base + slot1_len);
208
209 // println!("Areas: {:#?}", areadesc.get_c());
210
211 // Install the boot trailer signature, so that the code will start an upgrade.
212 // TODO: This must be a multiple of flash alignment, add support for an image that is smaller,
213 // and just gets padded.
214 let primary = install_image(&mut flash, slot0_base, 32784);
215
216 // Install an upgrade image.
217 let upgrade = install_image(&mut flash, slot1_base, 41928);
218
219 // Set an alignment, and position the magic value.
220 c::set_sim_flash_align(align);
221 let trailer_size = c::boot_trailer_sz();
222
223 // Mark the upgrade as ready to install. (This looks like it might be a bug in the code,
224 // however.)
225 mark_upgrade(&mut flash, scratch_base - trailer_size as usize);
226
227 let (fl2, total_count) = try_upgrade(&flash, &areadesc, None);
228 info!("First boot, count={}", total_count);
229 if !verify_image(&fl2, slot0_base, &upgrade) {
230 error!("Image mismatch after first boot");
231 // This isn't really recoverable, and more tests aren't likely to reveal much.
232 self.failures += 1;
233 return;
234 }
235
236 let mut bad = 0;
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300237 let mut stops: Vec<i32> = (1..total_count).collect();
238 thread_rng().shuffle(stops.as_mut_slice());
239 for i in stops {
David Brown361be7a2017-03-29 12:28:47 -0600240 info!("Try interruption at {}", i);
241 let (fl3, total_count) = try_upgrade(&flash, &areadesc, Some(i));
242 info!("Second boot, count={}", total_count);
243 if !verify_image(&fl3, slot0_base, &upgrade) {
244 warn!("FAIL at step {} of {}", i, total_count);
245 bad += 1;
246 }
247 if !verify_image(&fl3, slot1_base, &primary) {
248 warn!("Slot 1 FAIL at step {} of {}", i, total_count);
249 bad += 1;
250 }
251 }
252 error!("{} out of {} failed {:.2}%",
253 bad, total_count,
254 bad as f32 * 100.0 / total_count as f32);
255 if bad > 0 {
256 failed = true;
257 }
258
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300259 let (fl4, total_counts) = try_random_fails(&flash, &areadesc, 5);
260 info!("Random fails at counts={:?}", total_counts);
261 if !verify_image(&fl4, slot0_base, &upgrade) {
262 error!("Image mismatch after random fails");
263 self.failures += 1;
264 return;
265 }
266
David Brown361be7a2017-03-29 12:28:47 -0600267 for count in 2 .. 5 {
268 info!("Try revert: {}", count);
269 let fl2 = try_revert(&flash, &areadesc, count);
270 if !verify_image(&fl2, slot0_base, &primary) {
271 warn!("Revert failure on count {}", count);
272 failed = true;
273 }
274 }
275
276 info!("Try norevert");
277 let fl2 = try_norevert(&flash, &areadesc);
278 if !verify_image(&fl2, slot0_base, &upgrade) {
279 warn!("No revert failed");
280 failed = true;
281 }
282
283 /*
284 // show_flash(&flash);
285
286 println!("First boot for upgrade");
287 // c::set_flash_counter(570);
288 c::boot_go(&mut flash, &areadesc);
289 // println!("{} flash ops", c::get_flash_counter());
290
291 verify_image(&flash, slot0_base, &upgrade);
292
293 println!("\n------------------\nSecond boot");
294 c::boot_go(&mut flash, &areadesc);
295 */
296 if failed {
297 self.failures += 1;
298 } else {
299 self.passes += 1;
300 }
David Brownc638f792017-01-10 12:34:33 -0700301 }
David Brownde7729e2017-01-09 10:41:35 -0700302}
303
304/// Test a boot, optionally stopping after 'n' flash options. Returns a count of the number of
305/// flash operations done total.
306fn try_upgrade(flash: &Flash, areadesc: &AreaDesc, stop: Option<i32>) -> (Flash, i32) {
307 // Clone the flash to have a new copy.
308 let mut fl = flash.clone();
309
310 c::set_flash_counter(stop.unwrap_or(0));
311 let (first_interrupted, cnt1) = match c::boot_go(&mut fl, &areadesc) {
312 -0x13579 => (true, stop.unwrap()),
313 0 => (false, -c::get_flash_counter()),
314 x => panic!("Unknown return: {}", x),
315 };
316 c::set_flash_counter(0);
317
318 if first_interrupted {
319 // fl.dump();
320 match c::boot_go(&mut fl, &areadesc) {
321 -0x13579 => panic!("Shouldn't stop again"),
322 0 => (),
323 x => panic!("Unknown return: {}", x),
324 }
325 }
326
327 let cnt2 = cnt1 - c::get_flash_counter();
328
329 (fl, cnt2)
330}
331
David Brownc638f792017-01-10 12:34:33 -0700332fn try_revert(flash: &Flash, areadesc: &AreaDesc, count: usize) -> Flash {
David Brownde7729e2017-01-09 10:41:35 -0700333 let mut fl = flash.clone();
334 c::set_flash_counter(0);
335
David Brown163ab232017-01-23 15:48:35 -0700336 // fl.write_file("image0.bin").unwrap();
337 for i in 0 .. count {
338 info!("Running boot pass {}", i + 1);
David Brownc638f792017-01-10 12:34:33 -0700339 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
340 }
David Brownde7729e2017-01-09 10:41:35 -0700341 fl
342}
343
344fn try_norevert(flash: &Flash, areadesc: &AreaDesc) -> Flash {
345 let mut fl = flash.clone();
346 c::set_flash_counter(0);
347 let align = c::get_sim_flash_align() as usize;
348
349 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
350 // Write boot_ok
David Brown75e16d62017-01-23 15:47:59 -0700351 let ok = [1u8, 0, 0, 0, 0, 0, 0, 0];
David Brown5c6b6792017-03-20 12:51:28 -0600352 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
353 fl.write(slot0_base + slot0_len - align, &ok[..align]).unwrap();
David Brownde7729e2017-01-09 10:41:35 -0700354 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
355 fl
356}
357
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300358fn try_random_fails(flash: &Flash, areadesc: &AreaDesc, count: usize) -> (Flash, Vec<i32>) {
359 // Clone the flash to have a new copy.
360 let mut fl = flash.clone();
361
362 c::set_flash_counter(0);
363 let (_, total_ops) = match c::boot_go(&mut fl, &areadesc) {
364 -0x13579 => panic!("Should not be have been interrupted!"),
365 0 => (false, -c::get_flash_counter()),
366 x => panic!("Unknown return: {}", x),
367 };
368
369 let mut rng = rand::thread_rng();
370 let ops = Range::new(1, total_ops);
371 let mut stops = vec![0i32; count];
372 for i in 0 .. count {
373 let reset_counter = ops.ind_sample(&mut rng);
374 c::set_flash_counter(reset_counter);
375 match c::boot_go(&mut fl, &areadesc) {
376 0 | -0x13579 => (),
377 x => panic!("Unknown return: {}", x),
378 }
379 stops[i] = reset_counter;
380 }
381
382 c::set_flash_counter(0);
383 match c::boot_go(&mut fl, &areadesc) {
384 -0x13579 => panic!("Should not be have been interrupted!"),
385 0 => (),
386 x => panic!("Unknown return: {}", x),
387 }
388
389 (fl, stops)
390}
391
David Brownde7729e2017-01-09 10:41:35 -0700392/// Show the flash layout.
393#[allow(dead_code)]
394fn show_flash(flash: &Flash) {
395 println!("---- Flash configuration ----");
396 for sector in flash.sector_iter() {
397 println!(" {:2}: 0x{:08x}, 0x{:08x}",
398 sector.num, sector.base, sector.size);
399 }
400 println!("");
401}
402
403/// Install a "program" into the given image. This fakes the image header, or at least all of the
404/// fields used by the given code. Returns a copy of the image that was written.
405fn install_image(flash: &mut Flash, offset: usize, len: usize) -> Vec<u8> {
406 let offset0 = offset;
407
408 // Generate a boot header. Note that the size doesn't include the header.
409 let header = ImageHeader {
410 magic: 0x96f3b83c,
411 tlv_size: 0,
412 _pad1: 0,
413 hdr_size: 32,
414 key_id: 0,
415 _pad2: 0,
416 img_size: len as u32,
417 flags: 0,
418 ver: ImageVersion {
David Browne380fa62017-01-23 15:49:09 -0700419 major: (offset / (128 * 1024)) as u8,
David Brownde7729e2017-01-09 10:41:35 -0700420 minor: 0,
421 revision: 1,
David Browne380fa62017-01-23 15:49:09 -0700422 build_num: offset as u32,
David Brownde7729e2017-01-09 10:41:35 -0700423 },
424 _pad3: 0,
425 };
426
427 let b_header = header.as_raw();
428 /*
429 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
430 mem::size_of::<ImageHeader>()) };
431 */
432 assert_eq!(b_header.len(), 32);
433 flash.write(offset, &b_header).unwrap();
434 let offset = offset + b_header.len();
435
436 // The core of the image itself is just pseudorandom data.
437 let mut buf = vec![0; len];
438 splat(&mut buf, offset);
439 flash.write(offset, &buf).unwrap();
440 let offset = offset + buf.len();
441
442 // Copy out the image so that we can verify that the image was installed correctly later.
443 let mut copy = vec![0u8; offset - offset0];
444 flash.read(offset0, &mut copy).unwrap();
445
446 copy
447}
448
449/// Verify that given image is present in the flash at the given offset.
450fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
451 let mut copy = vec![0u8; buf.len()];
452 flash.read(offset, &mut copy).unwrap();
453
454 if buf != &copy[..] {
455 for i in 0 .. buf.len() {
456 if buf[i] != copy[i] {
David Brown4440af82017-01-09 12:15:05 -0700457 info!("First failure at {:#x}", offset + i);
David Brownde7729e2017-01-09 10:41:35 -0700458 break;
459 }
460 }
461 false
462 } else {
463 true
464 }
465}
466
467/// The image header
468#[repr(C)]
469pub struct ImageHeader {
470 magic: u32,
471 tlv_size: u16,
472 key_id: u8,
473 _pad1: u8,
474 hdr_size: u16,
475 _pad2: u16,
476 img_size: u32,
477 flags: u32,
478 ver: ImageVersion,
479 _pad3: u32,
480}
481
482impl AsRaw for ImageHeader {}
483
484#[repr(C)]
485pub struct ImageVersion {
486 major: u8,
487 minor: u8,
488 revision: u16,
489 build_num: u32,
490}
491
492/// Write out the magic so that the loader tries doing an upgrade.
493fn mark_upgrade(flash: &mut Flash, offset: usize) {
494 let magic = vec![0x77, 0xc2, 0x95, 0xf3,
495 0x60, 0xd2, 0xef, 0x7f,
496 0x35, 0x52, 0x50, 0x0f,
497 0x2c, 0xb6, 0x79, 0x80];
498 flash.write(offset, &magic).unwrap();
499}
500
501// Drop some pseudo-random gibberish onto the data.
502fn splat(data: &mut [u8], seed: usize) {
503 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
504 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
505 rng.fill_bytes(data);
506}
507
508/// Return a read-only view into the raw bytes of this object
509trait AsRaw : Sized {
510 fn as_raw<'a>(&'a self) -> &'a [u8] {
511 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
512 mem::size_of::<Self>()) }
513 }
514}
515
516fn show_sizes() {
517 // This isn't panic safe.
518 let old_align = c::get_sim_flash_align();
519 for min in &[1, 2, 4, 8] {
520 c::set_sim_flash_align(*min);
521 let msize = c::boot_trailer_sz();
522 println!("{:2}: {} (0x{:x})", min, msize, msize);
523 }
524 c::set_sim_flash_align(old_align);
525}