blob: de9e5880e261bc859d4b766cf9d37f7ecd79b50a [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;
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;
David Brown4cb26232017-04-11 08:15:18 -0600237 // Let's try an image halfway through.
238 for i in 1 .. total_count {
David Brown361be7a2017-03-29 12:28:47 -0600239 info!("Try interruption at {}", i);
240 let (fl3, total_count) = try_upgrade(&flash, &areadesc, Some(i));
241 info!("Second boot, count={}", total_count);
242 if !verify_image(&fl3, slot0_base, &upgrade) {
243 warn!("FAIL at step {} of {}", i, total_count);
244 bad += 1;
245 }
246 if !verify_image(&fl3, slot1_base, &primary) {
247 warn!("Slot 1 FAIL at step {} of {}", i, total_count);
248 bad += 1;
249 }
250 }
251 error!("{} out of {} failed {:.2}%",
252 bad, total_count,
253 bad as f32 * 100.0 / total_count as f32);
254 if bad > 0 {
255 failed = true;
256 }
257
Fabio Utzig57652312017-04-25 19:54:26 -0300258 let (fl4, total_counts) = try_random_fails(&flash, &areadesc, total_count, 5);
259 info!("Random fails at reset points={:?}", total_counts);
260 let slot0_ok = verify_image(&fl4, slot0_base, &upgrade);
261 let slot1_ok = verify_image(&fl4, slot1_base, &primary);
262 if !slot0_ok || !slot1_ok {
263 error!("Image mismatch after random fails: slot0={} slot1={}",
264 if slot0_ok { "ok" } else { "fail" },
265 if slot1_ok { "ok" } else { "fail" });
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300266 self.failures += 1;
267 return;
268 }
269
David Brown361be7a2017-03-29 12:28:47 -0600270 for count in 2 .. 5 {
271 info!("Try revert: {}", count);
272 let fl2 = try_revert(&flash, &areadesc, count);
273 if !verify_image(&fl2, slot0_base, &primary) {
274 warn!("Revert failure on count {}", count);
275 failed = true;
276 }
277 }
278
279 info!("Try norevert");
280 let fl2 = try_norevert(&flash, &areadesc);
281 if !verify_image(&fl2, slot0_base, &upgrade) {
282 warn!("No revert failed");
283 failed = true;
284 }
285
286 /*
287 // show_flash(&flash);
288
289 println!("First boot for upgrade");
290 // c::set_flash_counter(570);
291 c::boot_go(&mut flash, &areadesc);
292 // println!("{} flash ops", c::get_flash_counter());
293
294 verify_image(&flash, slot0_base, &upgrade);
295
296 println!("\n------------------\nSecond boot");
297 c::boot_go(&mut flash, &areadesc);
298 */
299 if failed {
300 self.failures += 1;
301 } else {
302 self.passes += 1;
303 }
David Brownc638f792017-01-10 12:34:33 -0700304 }
David Brownde7729e2017-01-09 10:41:35 -0700305}
306
307/// Test a boot, optionally stopping after 'n' flash options. Returns a count of the number of
308/// flash operations done total.
309fn try_upgrade(flash: &Flash, areadesc: &AreaDesc, stop: Option<i32>) -> (Flash, i32) {
310 // Clone the flash to have a new copy.
311 let mut fl = flash.clone();
312
Fabio Utzig57652312017-04-25 19:54:26 -0300313 // mark permanent upgrade
314 let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
315 let (base, _) = areadesc.find(FlashId::ImageScratch);
316 let align = c::get_sim_flash_align() as usize;
317 fl.write(base - align, &ok[..align]).unwrap();
318
David Brownde7729e2017-01-09 10:41:35 -0700319 c::set_flash_counter(stop.unwrap_or(0));
320 let (first_interrupted, cnt1) = match c::boot_go(&mut fl, &areadesc) {
321 -0x13579 => (true, stop.unwrap()),
322 0 => (false, -c::get_flash_counter()),
323 x => panic!("Unknown return: {}", x),
324 };
325 c::set_flash_counter(0);
326
327 if first_interrupted {
328 // fl.dump();
329 match c::boot_go(&mut fl, &areadesc) {
330 -0x13579 => panic!("Shouldn't stop again"),
331 0 => (),
332 x => panic!("Unknown return: {}", x),
333 }
334 }
335
336 let cnt2 = cnt1 - c::get_flash_counter();
337
338 (fl, cnt2)
339}
340
David Brownc638f792017-01-10 12:34:33 -0700341fn try_revert(flash: &Flash, areadesc: &AreaDesc, count: usize) -> Flash {
David Brownde7729e2017-01-09 10:41:35 -0700342 let mut fl = flash.clone();
343 c::set_flash_counter(0);
344
David Brown163ab232017-01-23 15:48:35 -0700345 // fl.write_file("image0.bin").unwrap();
346 for i in 0 .. count {
347 info!("Running boot pass {}", i + 1);
David Brownc638f792017-01-10 12:34:33 -0700348 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
349 }
David Brownde7729e2017-01-09 10:41:35 -0700350 fl
351}
352
353fn try_norevert(flash: &Flash, areadesc: &AreaDesc) -> Flash {
354 let mut fl = flash.clone();
355 c::set_flash_counter(0);
356 let align = c::get_sim_flash_align() as usize;
357
358 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
359 // Write boot_ok
David Brown75e16d62017-01-23 15:47:59 -0700360 let ok = [1u8, 0, 0, 0, 0, 0, 0, 0];
David Brown5c6b6792017-03-20 12:51:28 -0600361 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
362 fl.write(slot0_base + slot0_len - align, &ok[..align]).unwrap();
David Brownde7729e2017-01-09 10:41:35 -0700363 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
364 fl
365}
366
Fabio Utzig57652312017-04-25 19:54:26 -0300367fn try_random_fails(flash: &Flash, areadesc: &AreaDesc, total_ops: i32,
368 count: usize) -> (Flash, Vec<i32>) {
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300369 let mut fl = flash.clone();
370
Fabio Utzig57652312017-04-25 19:54:26 -0300371 // mark permanent upgrade
372 let ok = [1u8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
373 let (base, _) = areadesc.find(FlashId::ImageScratch);
374 let align = c::get_sim_flash_align() as usize;
375 fl.write(base - align, &ok[..align]).unwrap();
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300376
377 let mut rng = rand::thread_rng();
Fabio Utzig57652312017-04-25 19:54:26 -0300378 let mut resets = vec![0i32; count];
379 let mut remaining_ops = total_ops;
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300380 for i in 0 .. count {
Fabio Utzig57652312017-04-25 19:54:26 -0300381 let ops = Range::new(1, remaining_ops / 2);
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300382 let reset_counter = ops.ind_sample(&mut rng);
383 c::set_flash_counter(reset_counter);
384 match c::boot_go(&mut fl, &areadesc) {
385 0 | -0x13579 => (),
386 x => panic!("Unknown return: {}", x),
387 }
Fabio Utzig57652312017-04-25 19:54:26 -0300388 remaining_ops -= reset_counter;
389 resets[i] = reset_counter;
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300390 }
391
392 c::set_flash_counter(0);
393 match c::boot_go(&mut fl, &areadesc) {
394 -0x13579 => panic!("Should not be have been interrupted!"),
395 0 => (),
396 x => panic!("Unknown return: {}", x),
397 }
398
Fabio Utzig57652312017-04-25 19:54:26 -0300399 (fl, resets)
Fabio Utzigbb5635e2017-04-10 09:07:02 -0300400}
401
David Brownde7729e2017-01-09 10:41:35 -0700402/// Show the flash layout.
403#[allow(dead_code)]
404fn show_flash(flash: &Flash) {
405 println!("---- Flash configuration ----");
406 for sector in flash.sector_iter() {
407 println!(" {:2}: 0x{:08x}, 0x{:08x}",
408 sector.num, sector.base, sector.size);
409 }
410 println!("");
411}
412
413/// Install a "program" into the given image. This fakes the image header, or at least all of the
414/// fields used by the given code. Returns a copy of the image that was written.
415fn install_image(flash: &mut Flash, offset: usize, len: usize) -> Vec<u8> {
416 let offset0 = offset;
417
418 // Generate a boot header. Note that the size doesn't include the header.
419 let header = ImageHeader {
420 magic: 0x96f3b83c,
421 tlv_size: 0,
422 _pad1: 0,
423 hdr_size: 32,
424 key_id: 0,
425 _pad2: 0,
426 img_size: len as u32,
427 flags: 0,
428 ver: ImageVersion {
David Browne380fa62017-01-23 15:49:09 -0700429 major: (offset / (128 * 1024)) as u8,
David Brownde7729e2017-01-09 10:41:35 -0700430 minor: 0,
431 revision: 1,
David Browne380fa62017-01-23 15:49:09 -0700432 build_num: offset as u32,
David Brownde7729e2017-01-09 10:41:35 -0700433 },
434 _pad3: 0,
435 };
436
437 let b_header = header.as_raw();
438 /*
439 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
440 mem::size_of::<ImageHeader>()) };
441 */
442 assert_eq!(b_header.len(), 32);
443 flash.write(offset, &b_header).unwrap();
444 let offset = offset + b_header.len();
445
446 // The core of the image itself is just pseudorandom data.
447 let mut buf = vec![0; len];
448 splat(&mut buf, offset);
449 flash.write(offset, &buf).unwrap();
450 let offset = offset + buf.len();
451
452 // Copy out the image so that we can verify that the image was installed correctly later.
453 let mut copy = vec![0u8; offset - offset0];
454 flash.read(offset0, &mut copy).unwrap();
455
456 copy
457}
458
459/// Verify that given image is present in the flash at the given offset.
460fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
461 let mut copy = vec![0u8; buf.len()];
462 flash.read(offset, &mut copy).unwrap();
463
464 if buf != &copy[..] {
465 for i in 0 .. buf.len() {
466 if buf[i] != copy[i] {
David Brown4440af82017-01-09 12:15:05 -0700467 info!("First failure at {:#x}", offset + i);
David Brownde7729e2017-01-09 10:41:35 -0700468 break;
469 }
470 }
471 false
472 } else {
473 true
474 }
475}
476
477/// The image header
478#[repr(C)]
479pub struct ImageHeader {
480 magic: u32,
481 tlv_size: u16,
482 key_id: u8,
483 _pad1: u8,
484 hdr_size: u16,
485 _pad2: u16,
486 img_size: u32,
487 flags: u32,
488 ver: ImageVersion,
489 _pad3: u32,
490}
491
492impl AsRaw for ImageHeader {}
493
494#[repr(C)]
495pub struct ImageVersion {
496 major: u8,
497 minor: u8,
498 revision: u16,
499 build_num: u32,
500}
501
502/// Write out the magic so that the loader tries doing an upgrade.
503fn mark_upgrade(flash: &mut Flash, offset: usize) {
504 let magic = vec![0x77, 0xc2, 0x95, 0xf3,
505 0x60, 0xd2, 0xef, 0x7f,
506 0x35, 0x52, 0x50, 0x0f,
507 0x2c, 0xb6, 0x79, 0x80];
508 flash.write(offset, &magic).unwrap();
509}
510
511// Drop some pseudo-random gibberish onto the data.
512fn splat(data: &mut [u8], seed: usize) {
513 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
514 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
515 rng.fill_bytes(data);
516}
517
518/// Return a read-only view into the raw bytes of this object
519trait AsRaw : Sized {
520 fn as_raw<'a>(&'a self) -> &'a [u8] {
521 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
522 mem::size_of::<Self>()) }
523 }
524}
525
526fn show_sizes() {
527 // This isn't panic safe.
528 let old_align = c::get_sim_flash_align();
529 for min in &[1, 2, 4, 8] {
530 c::set_sim_flash_align(*min);
531 let msize = c::boot_trailer_sz();
532 println!("{:2}: {} (0x{:x})", min, msize, msize);
533 }
534 c::set_sim_flash_align(old_align);
535}