blob: 0889d5b4b84ffbc1b83f113178774382db00978c [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;
12use rand::{Rng, SeedableRng, XorShiftRng};
13use rustc_serialize::{Decodable, Decoder};
David Browna3b93cf2017-03-29 12:41:26 -060014use std::fmt;
David Brownde7729e2017-01-09 10:41:35 -070015use std::mem;
David Brown361be7a2017-03-29 12:28:47 -060016use std::process;
David Brownde7729e2017-01-09 10:41:35 -070017use std::slice;
18
19mod area;
20mod c;
21mod flash;
22pub mod api;
23mod pdump;
24
25use flash::Flash;
26use area::{AreaDesc, FlashId};
27
28const USAGE: &'static str = "
29Mcuboot simulator
30
31Usage:
32 bootsim sizes
33 bootsim run --device TYPE [--align SIZE]
David Browna3b93cf2017-03-29 12:41:26 -060034 bootsim runall
David Brownde7729e2017-01-09 10:41:35 -070035 bootsim (--help | --version)
36
37Options:
38 -h, --help Show this message
39 --version Version
40 --device TYPE MCU to simulate
41 Valid values: stm32f4, k64f
42 --align SIZE Flash write alignment
43";
44
45#[derive(Debug, RustcDecodable)]
46struct Args {
47 flag_help: bool,
48 flag_version: bool,
49 flag_device: Option<DeviceName>,
50 flag_align: Option<AlignArg>,
51 cmd_sizes: bool,
52 cmd_run: bool,
David Browna3b93cf2017-03-29 12:41:26 -060053 cmd_runall: bool,
David Brownde7729e2017-01-09 10:41:35 -070054}
55
David Browna3b93cf2017-03-29 12:41:26 -060056#[derive(Copy, Clone, Debug, RustcDecodable)]
David Brown07fb8fa2017-03-20 12:40:57 -060057enum DeviceName { Stm32f4, K64f, K64fBig, Nrf52840 }
David Brownde7729e2017-01-09 10:41:35 -070058
David Browna3b93cf2017-03-29 12:41:26 -060059static ALL_DEVICES: &'static [DeviceName] = &[
60 DeviceName::Stm32f4,
61 DeviceName::K64f,
62 DeviceName::K64fBig,
63 DeviceName::Nrf52840,
64];
65
66impl fmt::Display for DeviceName {
67 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68 let name = match *self {
69 DeviceName::Stm32f4 => "stm32f4",
70 DeviceName::K64f => "k64f",
71 DeviceName::K64fBig => "k64fbig",
72 DeviceName::Nrf52840 => "nrf52840",
73 };
74 f.write_str(name)
75 }
76}
77
David Brownde7729e2017-01-09 10:41:35 -070078#[derive(Debug)]
79struct AlignArg(u8);
80
81impl Decodable for AlignArg {
82 // Decode the alignment ourselves, to restrict it to the valid possible alignments.
83 fn decode<D: Decoder>(d: &mut D) -> Result<AlignArg, D::Error> {
84 let m = d.read_u8()?;
85 match m {
86 1 | 2 | 4 | 8 => Ok(AlignArg(m)),
87 _ => Err(d.error("Invalid alignment")),
88 }
89 }
90}
91
92fn main() {
David Brown4440af82017-01-09 12:15:05 -070093 env_logger::init().unwrap();
94
David Brownde7729e2017-01-09 10:41:35 -070095 let args: Args = Docopt::new(USAGE)
96 .and_then(|d| d.decode())
97 .unwrap_or_else(|e| e.exit());
98 // println!("args: {:#?}", args);
99
100 if args.cmd_sizes {
101 show_sizes();
102 return;
103 }
104
David Brown361be7a2017-03-29 12:28:47 -0600105 let mut status = RunStatus::new();
David Browna3b93cf2017-03-29 12:41:26 -0600106 if args.cmd_run {
David Brown361be7a2017-03-29 12:28:47 -0600107
David Browna3b93cf2017-03-29 12:41:26 -0600108 let align = args.flag_align.map(|x| x.0).unwrap_or(1);
David Brown562a7a02017-01-23 11:19:03 -0700109
David Browna3b93cf2017-03-29 12:41:26 -0600110 let device = match args.flag_device {
111 None => panic!("Missing mandatory device argument"),
112 Some(dev) => dev,
113 };
David Brownde7729e2017-01-09 10:41:35 -0700114
David Browna3b93cf2017-03-29 12:41:26 -0600115 status.run_single(device, align);
116 }
117
118 if args.cmd_runall {
119 for &dev in ALL_DEVICES {
120 for &align in &[1, 2, 4, 8] {
121 status.run_single(dev, align);
122 }
123 }
124 }
David Brown5c6b6792017-03-20 12:51:28 -0600125
David Brown361be7a2017-03-29 12:28:47 -0600126 if status.failures > 0 {
127 warn!("{} Tests ran with {} failures", status.failures + status.passes, status.failures);
128 process::exit(1);
129 } else {
130 warn!("{} Tests ran successfully", status.passes);
131 process::exit(0);
132 }
133}
David Brown5c6b6792017-03-20 12:51:28 -0600134
David Brown361be7a2017-03-29 12:28:47 -0600135struct RunStatus {
136 failures: usize,
137 passes: usize,
138}
David Brownde7729e2017-01-09 10:41:35 -0700139
David Brown361be7a2017-03-29 12:28:47 -0600140impl RunStatus {
141 fn new() -> RunStatus {
142 RunStatus {
143 failures: 0,
144 passes: 0,
David Brownde7729e2017-01-09 10:41:35 -0700145 }
146 }
David Brownde7729e2017-01-09 10:41:35 -0700147
David Brown361be7a2017-03-29 12:28:47 -0600148 fn run_single(&mut self, device: DeviceName, align: u8) {
149 let mut failed = false;
150
David Browna3b93cf2017-03-29 12:41:26 -0600151 warn!("Running on device {} with alignment {}", device, align);
152
David Brown361be7a2017-03-29 12:28:47 -0600153 let (mut flash, areadesc) = match device {
154 DeviceName::Stm32f4 => {
155 // STM style flash. Large sectors, with a large scratch area.
156 let flash = Flash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
157 64 * 1024,
158 128 * 1024, 128 * 1024, 128 * 1024],
159 align as usize);
160 let mut areadesc = AreaDesc::new(&flash);
161 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
162 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
163 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch);
164 (flash, areadesc)
165 }
166 DeviceName::K64f => {
167 // NXP style flash. Small sectors, one small sector for scratch.
168 let flash = Flash::new(vec![4096; 128], align as usize);
169
170 let mut areadesc = AreaDesc::new(&flash);
171 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
172 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
173 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch);
174 (flash, areadesc)
175 }
176 DeviceName::K64fBig => {
177 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
178 // uses small sectors, but we tell the bootloader they are large.
179 let flash = Flash::new(vec![4096; 128], align as usize);
180
181 let mut areadesc = AreaDesc::new(&flash);
182 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0);
183 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1);
184 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch);
185 (flash, areadesc)
186 }
187 DeviceName::Nrf52840 => {
188 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
189 // does not divide into the image size.
190 let flash = Flash::new(vec![4096; 128], align as usize);
191
192 let mut areadesc = AreaDesc::new(&flash);
193 areadesc.add_image(0x008000, 0x034000, FlashId::Image0);
194 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1);
195 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch);
196 (flash, areadesc)
197 }
198 };
199
200 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
201 let (slot1_base, slot1_len) = areadesc.find(FlashId::Image1);
202 let (scratch_base, _) = areadesc.find(FlashId::ImageScratch);
203
204 // Code below assumes that the slots are consecutive.
205 assert_eq!(slot1_base, slot0_base + slot0_len);
206 assert_eq!(scratch_base, slot1_base + slot1_len);
207
208 // println!("Areas: {:#?}", areadesc.get_c());
209
210 // Install the boot trailer signature, so that the code will start an upgrade.
211 // TODO: This must be a multiple of flash alignment, add support for an image that is smaller,
212 // and just gets padded.
213 let primary = install_image(&mut flash, slot0_base, 32784);
214
215 // Install an upgrade image.
216 let upgrade = install_image(&mut flash, slot1_base, 41928);
217
218 // Set an alignment, and position the magic value.
219 c::set_sim_flash_align(align);
220 let trailer_size = c::boot_trailer_sz();
221
222 // Mark the upgrade as ready to install. (This looks like it might be a bug in the code,
223 // however.)
224 mark_upgrade(&mut flash, scratch_base - trailer_size as usize);
225
226 let (fl2, total_count) = try_upgrade(&flash, &areadesc, None);
227 info!("First boot, count={}", total_count);
228 if !verify_image(&fl2, slot0_base, &upgrade) {
229 error!("Image mismatch after first boot");
230 // This isn't really recoverable, and more tests aren't likely to reveal much.
231 self.failures += 1;
232 return;
233 }
234
235 let mut bad = 0;
236 // Let's try an image halfway through.
237 for i in 1 .. total_count {
238 info!("Try interruption at {}", i);
239 let (fl3, total_count) = try_upgrade(&flash, &areadesc, Some(i));
240 info!("Second boot, count={}", total_count);
241 if !verify_image(&fl3, slot0_base, &upgrade) {
242 warn!("FAIL at step {} of {}", i, total_count);
243 bad += 1;
244 }
245 if !verify_image(&fl3, slot1_base, &primary) {
246 warn!("Slot 1 FAIL at step {} of {}", i, total_count);
247 bad += 1;
248 }
249 }
250 error!("{} out of {} failed {:.2}%",
251 bad, total_count,
252 bad as f32 * 100.0 / total_count as f32);
253 if bad > 0 {
254 failed = true;
255 }
256
257 for count in 2 .. 5 {
258 info!("Try revert: {}", count);
259 let fl2 = try_revert(&flash, &areadesc, count);
260 if !verify_image(&fl2, slot0_base, &primary) {
261 warn!("Revert failure on count {}", count);
262 failed = true;
263 }
264 }
265
266 info!("Try norevert");
267 let fl2 = try_norevert(&flash, &areadesc);
268 if !verify_image(&fl2, slot0_base, &upgrade) {
269 warn!("No revert failed");
270 failed = true;
271 }
272
273 /*
274 // show_flash(&flash);
275
276 println!("First boot for upgrade");
277 // c::set_flash_counter(570);
278 c::boot_go(&mut flash, &areadesc);
279 // println!("{} flash ops", c::get_flash_counter());
280
281 verify_image(&flash, slot0_base, &upgrade);
282
283 println!("\n------------------\nSecond boot");
284 c::boot_go(&mut flash, &areadesc);
285 */
286 if failed {
287 self.failures += 1;
288 } else {
289 self.passes += 1;
290 }
David Brownc638f792017-01-10 12:34:33 -0700291 }
David Brownde7729e2017-01-09 10:41:35 -0700292}
293
294/// Test a boot, optionally stopping after 'n' flash options. Returns a count of the number of
295/// flash operations done total.
296fn try_upgrade(flash: &Flash, areadesc: &AreaDesc, stop: Option<i32>) -> (Flash, i32) {
297 // Clone the flash to have a new copy.
298 let mut fl = flash.clone();
299
300 c::set_flash_counter(stop.unwrap_or(0));
301 let (first_interrupted, cnt1) = match c::boot_go(&mut fl, &areadesc) {
302 -0x13579 => (true, stop.unwrap()),
303 0 => (false, -c::get_flash_counter()),
304 x => panic!("Unknown return: {}", x),
305 };
306 c::set_flash_counter(0);
307
308 if first_interrupted {
309 // fl.dump();
310 match c::boot_go(&mut fl, &areadesc) {
311 -0x13579 => panic!("Shouldn't stop again"),
312 0 => (),
313 x => panic!("Unknown return: {}", x),
314 }
315 }
316
317 let cnt2 = cnt1 - c::get_flash_counter();
318
319 (fl, cnt2)
320}
321
David Brownc638f792017-01-10 12:34:33 -0700322fn try_revert(flash: &Flash, areadesc: &AreaDesc, count: usize) -> Flash {
David Brownde7729e2017-01-09 10:41:35 -0700323 let mut fl = flash.clone();
324 c::set_flash_counter(0);
325
David Brown163ab232017-01-23 15:48:35 -0700326 // fl.write_file("image0.bin").unwrap();
327 for i in 0 .. count {
328 info!("Running boot pass {}", i + 1);
David Brownc638f792017-01-10 12:34:33 -0700329 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
330 }
David Brownde7729e2017-01-09 10:41:35 -0700331 fl
332}
333
334fn try_norevert(flash: &Flash, areadesc: &AreaDesc) -> Flash {
335 let mut fl = flash.clone();
336 c::set_flash_counter(0);
337 let align = c::get_sim_flash_align() as usize;
338
339 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
340 // Write boot_ok
David Brown75e16d62017-01-23 15:47:59 -0700341 let ok = [1u8, 0, 0, 0, 0, 0, 0, 0];
David Brown5c6b6792017-03-20 12:51:28 -0600342 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
343 fl.write(slot0_base + slot0_len - align, &ok[..align]).unwrap();
David Brownde7729e2017-01-09 10:41:35 -0700344 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
345 fl
346}
347
348/// Show the flash layout.
349#[allow(dead_code)]
350fn show_flash(flash: &Flash) {
351 println!("---- Flash configuration ----");
352 for sector in flash.sector_iter() {
353 println!(" {:2}: 0x{:08x}, 0x{:08x}",
354 sector.num, sector.base, sector.size);
355 }
356 println!("");
357}
358
359/// Install a "program" into the given image. This fakes the image header, or at least all of the
360/// fields used by the given code. Returns a copy of the image that was written.
361fn install_image(flash: &mut Flash, offset: usize, len: usize) -> Vec<u8> {
362 let offset0 = offset;
363
364 // Generate a boot header. Note that the size doesn't include the header.
365 let header = ImageHeader {
366 magic: 0x96f3b83c,
367 tlv_size: 0,
368 _pad1: 0,
369 hdr_size: 32,
370 key_id: 0,
371 _pad2: 0,
372 img_size: len as u32,
373 flags: 0,
374 ver: ImageVersion {
David Browne380fa62017-01-23 15:49:09 -0700375 major: (offset / (128 * 1024)) as u8,
David Brownde7729e2017-01-09 10:41:35 -0700376 minor: 0,
377 revision: 1,
David Browne380fa62017-01-23 15:49:09 -0700378 build_num: offset as u32,
David Brownde7729e2017-01-09 10:41:35 -0700379 },
380 _pad3: 0,
381 };
382
383 let b_header = header.as_raw();
384 /*
385 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
386 mem::size_of::<ImageHeader>()) };
387 */
388 assert_eq!(b_header.len(), 32);
389 flash.write(offset, &b_header).unwrap();
390 let offset = offset + b_header.len();
391
392 // The core of the image itself is just pseudorandom data.
393 let mut buf = vec![0; len];
394 splat(&mut buf, offset);
395 flash.write(offset, &buf).unwrap();
396 let offset = offset + buf.len();
397
398 // Copy out the image so that we can verify that the image was installed correctly later.
399 let mut copy = vec![0u8; offset - offset0];
400 flash.read(offset0, &mut copy).unwrap();
401
402 copy
403}
404
405/// Verify that given image is present in the flash at the given offset.
406fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
407 let mut copy = vec![0u8; buf.len()];
408 flash.read(offset, &mut copy).unwrap();
409
410 if buf != &copy[..] {
411 for i in 0 .. buf.len() {
412 if buf[i] != copy[i] {
David Brown4440af82017-01-09 12:15:05 -0700413 info!("First failure at {:#x}", offset + i);
David Brownde7729e2017-01-09 10:41:35 -0700414 break;
415 }
416 }
417 false
418 } else {
419 true
420 }
421}
422
423/// The image header
424#[repr(C)]
425pub struct ImageHeader {
426 magic: u32,
427 tlv_size: u16,
428 key_id: u8,
429 _pad1: u8,
430 hdr_size: u16,
431 _pad2: u16,
432 img_size: u32,
433 flags: u32,
434 ver: ImageVersion,
435 _pad3: u32,
436}
437
438impl AsRaw for ImageHeader {}
439
440#[repr(C)]
441pub struct ImageVersion {
442 major: u8,
443 minor: u8,
444 revision: u16,
445 build_num: u32,
446}
447
448/// Write out the magic so that the loader tries doing an upgrade.
449fn mark_upgrade(flash: &mut Flash, offset: usize) {
450 let magic = vec![0x77, 0xc2, 0x95, 0xf3,
451 0x60, 0xd2, 0xef, 0x7f,
452 0x35, 0x52, 0x50, 0x0f,
453 0x2c, 0xb6, 0x79, 0x80];
454 flash.write(offset, &magic).unwrap();
455}
456
457// Drop some pseudo-random gibberish onto the data.
458fn splat(data: &mut [u8], seed: usize) {
459 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
460 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
461 rng.fill_bytes(data);
462}
463
464/// Return a read-only view into the raw bytes of this object
465trait AsRaw : Sized {
466 fn as_raw<'a>(&'a self) -> &'a [u8] {
467 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
468 mem::size_of::<Self>()) }
469 }
470}
471
472fn show_sizes() {
473 // This isn't panic safe.
474 let old_align = c::get_sim_flash_align();
475 for min in &[1, 2, 4, 8] {
476 c::set_sim_flash_align(*min);
477 let msize = c::boot_trailer_sz();
478 println!("{:2}: {} (0x{:x})", min, msize, msize);
479 }
480 c::set_sim_flash_align(old_align);
481}