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