blob: 5ec391200e1a075bb96bc78f302046ba7c1247f7 [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;
15use std::slice;
16
17mod area;
18mod c;
19mod flash;
20pub mod api;
21mod pdump;
22
23use flash::Flash;
24use area::{AreaDesc, FlashId};
25
26const USAGE: &'static str = "
27Mcuboot simulator
28
29Usage:
30 bootsim sizes
31 bootsim run --device TYPE [--align SIZE]
32 bootsim (--help | --version)
33
34Options:
35 -h, --help Show this message
36 --version Version
37 --device TYPE MCU to simulate
38 Valid values: stm32f4, k64f
39 --align SIZE Flash write alignment
40";
41
42#[derive(Debug, RustcDecodable)]
43struct Args {
44 flag_help: bool,
45 flag_version: bool,
46 flag_device: Option<DeviceName>,
47 flag_align: Option<AlignArg>,
48 cmd_sizes: bool,
49 cmd_run: bool,
50}
51
52#[derive(Debug, RustcDecodable)]
David Brown90c19132017-01-23 10:21:28 -070053enum DeviceName { Stm32f4, K64f, K64fBig }
David Brownde7729e2017-01-09 10:41:35 -070054
55#[derive(Debug)]
56struct AlignArg(u8);
57
58impl Decodable for AlignArg {
59 // Decode the alignment ourselves, to restrict it to the valid possible alignments.
60 fn decode<D: Decoder>(d: &mut D) -> Result<AlignArg, D::Error> {
61 let m = d.read_u8()?;
62 match m {
63 1 | 2 | 4 | 8 => Ok(AlignArg(m)),
64 _ => Err(d.error("Invalid alignment")),
65 }
66 }
67}
68
69fn main() {
David Brown4440af82017-01-09 12:15:05 -070070 env_logger::init().unwrap();
71
David Brownde7729e2017-01-09 10:41:35 -070072 let args: Args = Docopt::new(USAGE)
73 .and_then(|d| d.decode())
74 .unwrap_or_else(|e| e.exit());
75 // println!("args: {:#?}", args);
76
77 if args.cmd_sizes {
78 show_sizes();
79 return;
80 }
81
David Brown562a7a02017-01-23 11:19:03 -070082 let align = args.flag_align.map(|x| x.0).unwrap_or(1);
83
David Brownde7729e2017-01-09 10:41:35 -070084 let (mut flash, areadesc) = match args.flag_device {
85 None => panic!("Missing mandatory argument"),
86 Some(DeviceName::Stm32f4) => {
87 // STM style flash. Large sectors, with a large scratch area.
88 let flash = Flash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
89 64 * 1024,
David Brown562a7a02017-01-23 11:19:03 -070090 128 * 1024, 128 * 1024, 128 * 1024],
91 align as usize);
David Brownde7729e2017-01-09 10:41:35 -070092 let mut areadesc = AreaDesc::new(&flash);
93 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
94 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
95 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch);
96 (flash, areadesc)
97 }
98 Some(DeviceName::K64f) => {
99 // NXP style flash. Small sectors, one small sector for scratch.
David Brown562a7a02017-01-23 11:19:03 -0700100 let flash = Flash::new(vec![4096; 128], align as usize);
David Brownde7729e2017-01-09 10:41:35 -0700101
102 let mut areadesc = AreaDesc::new(&flash);
103 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
104 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
105 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch);
106 (flash, areadesc)
107 }
David Brown90c19132017-01-23 10:21:28 -0700108 Some(DeviceName::K64fBig) => {
109 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
110 // uses small sectors, but we tell the bootloader they are large.
David Brown562a7a02017-01-23 11:19:03 -0700111 let flash = Flash::new(vec![4096; 128], align as usize);
David Brown90c19132017-01-23 10:21:28 -0700112
113 let mut areadesc = AreaDesc::new(&flash);
114 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0);
115 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1);
116 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch);
117 (flash, areadesc)
118 }
David Brownde7729e2017-01-09 10:41:35 -0700119 };
120
David Brown5c6b6792017-03-20 12:51:28 -0600121 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
122 let (slot1_base, slot1_len) = areadesc.find(FlashId::Image1);
123 let (scratch_base, _) = areadesc.find(FlashId::ImageScratch);
124
125 // Code below assumes that the slots are consecutive.
126 assert_eq!(slot1_base, slot0_base + slot0_len);
127 assert_eq!(scratch_base, slot1_base + slot1_len);
128
David Brownde7729e2017-01-09 10:41:35 -0700129 // println!("Areas: {:#?}", areadesc.get_c());
130
131 // Install the boot trailer signature, so that the code will start an upgrade.
David Brown74cc14c2017-01-23 15:46:40 -0700132 // TODO: This must be a multiple of flash alignment, add support for an image that is smaller,
133 // and just gets padded.
David Brown5c6b6792017-03-20 12:51:28 -0600134 let primary = install_image(&mut flash, slot0_base, 32784);
David Brownde7729e2017-01-09 10:41:35 -0700135
136 // Install an upgrade image.
David Brown5c6b6792017-03-20 12:51:28 -0600137 let upgrade = install_image(&mut flash, slot1_base, 41928);
David Brownde7729e2017-01-09 10:41:35 -0700138
139 // Set an alignment, and position the magic value.
David Brown562a7a02017-01-23 11:19:03 -0700140 c::set_sim_flash_align(align);
David Brownde7729e2017-01-09 10:41:35 -0700141 let trailer_size = c::boot_trailer_sz();
142
143 // Mark the upgrade as ready to install. (This looks like it might be a bug in the code,
144 // however.)
David Brown5c6b6792017-03-20 12:51:28 -0600145 mark_upgrade(&mut flash, scratch_base - trailer_size as usize);
David Brownde7729e2017-01-09 10:41:35 -0700146
147 let (fl2, total_count) = try_upgrade(&flash, &areadesc, None);
David Brown4440af82017-01-09 12:15:05 -0700148 info!("First boot, count={}", total_count);
David Brown5c6b6792017-03-20 12:51:28 -0600149 assert!(verify_image(&fl2, slot0_base, &upgrade));
David Brownde7729e2017-01-09 10:41:35 -0700150
151 let mut bad = 0;
152 // Let's try an image halfway through.
153 for i in 1 .. total_count {
David Brown4440af82017-01-09 12:15:05 -0700154 info!("Try interruption at {}", i);
David Brownde7729e2017-01-09 10:41:35 -0700155 let (fl3, total_count) = try_upgrade(&flash, &areadesc, Some(i));
David Brown4440af82017-01-09 12:15:05 -0700156 info!("Second boot, count={}", total_count);
David Brown5c6b6792017-03-20 12:51:28 -0600157 if !verify_image(&fl3, slot0_base, &upgrade) {
David Brown4440af82017-01-09 12:15:05 -0700158 warn!("FAIL at step {} of {}", i, total_count);
David Brownde7729e2017-01-09 10:41:35 -0700159 bad += 1;
160 }
David Brown5c6b6792017-03-20 12:51:28 -0600161 if !verify_image(&fl3, slot1_base, &primary) {
David Brown4440af82017-01-09 12:15:05 -0700162 warn!("Slot 1 FAIL at step {} of {}", i, total_count);
David Brownde7729e2017-01-09 10:41:35 -0700163 bad += 1;
164 }
165 }
David Brown4440af82017-01-09 12:15:05 -0700166 error!("{} out of {} failed {:.2}%",
167 bad, total_count,
168 bad as f32 * 100.0 / total_count as f32);
David Brownde7729e2017-01-09 10:41:35 -0700169
David Brownc638f792017-01-10 12:34:33 -0700170 for count in 2 .. 5 {
171 info!("Try revert: {}", count);
172 let fl2 = try_revert(&flash, &areadesc, count);
David Brown5c6b6792017-03-20 12:51:28 -0600173 assert!(verify_image(&fl2, slot0_base, &primary));
David Brownc638f792017-01-10 12:34:33 -0700174 }
David Brownde7729e2017-01-09 10:41:35 -0700175
David Brown4440af82017-01-09 12:15:05 -0700176 info!("Try norevert");
David Brownde7729e2017-01-09 10:41:35 -0700177 let fl2 = try_norevert(&flash, &areadesc);
David Brown5c6b6792017-03-20 12:51:28 -0600178 assert!(verify_image(&fl2, slot0_base, &upgrade));
David Brownde7729e2017-01-09 10:41:35 -0700179
180 /*
181 // show_flash(&flash);
182
183 println!("First boot for upgrade");
184 // c::set_flash_counter(570);
185 c::boot_go(&mut flash, &areadesc);
186 // println!("{} flash ops", c::get_flash_counter());
187
David Brown5c6b6792017-03-20 12:51:28 -0600188 verify_image(&flash, slot0_base, &upgrade);
David Brownde7729e2017-01-09 10:41:35 -0700189
190 println!("\n------------------\nSecond boot");
191 c::boot_go(&mut flash, &areadesc);
192 */
193}
194
195/// Test a boot, optionally stopping after 'n' flash options. Returns a count of the number of
196/// flash operations done total.
197fn try_upgrade(flash: &Flash, areadesc: &AreaDesc, stop: Option<i32>) -> (Flash, i32) {
198 // Clone the flash to have a new copy.
199 let mut fl = flash.clone();
200
201 c::set_flash_counter(stop.unwrap_or(0));
202 let (first_interrupted, cnt1) = match c::boot_go(&mut fl, &areadesc) {
203 -0x13579 => (true, stop.unwrap()),
204 0 => (false, -c::get_flash_counter()),
205 x => panic!("Unknown return: {}", x),
206 };
207 c::set_flash_counter(0);
208
209 if first_interrupted {
210 // fl.dump();
211 match c::boot_go(&mut fl, &areadesc) {
212 -0x13579 => panic!("Shouldn't stop again"),
213 0 => (),
214 x => panic!("Unknown return: {}", x),
215 }
216 }
217
218 let cnt2 = cnt1 - c::get_flash_counter();
219
220 (fl, cnt2)
221}
222
David Brownc638f792017-01-10 12:34:33 -0700223fn try_revert(flash: &Flash, areadesc: &AreaDesc, count: usize) -> Flash {
David Brownde7729e2017-01-09 10:41:35 -0700224 let mut fl = flash.clone();
225 c::set_flash_counter(0);
226
David Brown163ab232017-01-23 15:48:35 -0700227 // fl.write_file("image0.bin").unwrap();
228 for i in 0 .. count {
229 info!("Running boot pass {}", i + 1);
David Brownc638f792017-01-10 12:34:33 -0700230 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
231 }
David Brownde7729e2017-01-09 10:41:35 -0700232 fl
233}
234
235fn try_norevert(flash: &Flash, areadesc: &AreaDesc) -> Flash {
236 let mut fl = flash.clone();
237 c::set_flash_counter(0);
238 let align = c::get_sim_flash_align() as usize;
239
240 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
241 // Write boot_ok
David Brown75e16d62017-01-23 15:47:59 -0700242 let ok = [1u8, 0, 0, 0, 0, 0, 0, 0];
David Brown5c6b6792017-03-20 12:51:28 -0600243 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
244 fl.write(slot0_base + slot0_len - align, &ok[..align]).unwrap();
David Brownde7729e2017-01-09 10:41:35 -0700245 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
246 fl
247}
248
249/// Show the flash layout.
250#[allow(dead_code)]
251fn show_flash(flash: &Flash) {
252 println!("---- Flash configuration ----");
253 for sector in flash.sector_iter() {
254 println!(" {:2}: 0x{:08x}, 0x{:08x}",
255 sector.num, sector.base, sector.size);
256 }
257 println!("");
258}
259
260/// Install a "program" into the given image. This fakes the image header, or at least all of the
261/// fields used by the given code. Returns a copy of the image that was written.
262fn install_image(flash: &mut Flash, offset: usize, len: usize) -> Vec<u8> {
263 let offset0 = offset;
264
265 // Generate a boot header. Note that the size doesn't include the header.
266 let header = ImageHeader {
267 magic: 0x96f3b83c,
268 tlv_size: 0,
269 _pad1: 0,
270 hdr_size: 32,
271 key_id: 0,
272 _pad2: 0,
273 img_size: len as u32,
274 flags: 0,
275 ver: ImageVersion {
David Browne380fa62017-01-23 15:49:09 -0700276 major: (offset / (128 * 1024)) as u8,
David Brownde7729e2017-01-09 10:41:35 -0700277 minor: 0,
278 revision: 1,
David Browne380fa62017-01-23 15:49:09 -0700279 build_num: offset as u32,
David Brownde7729e2017-01-09 10:41:35 -0700280 },
281 _pad3: 0,
282 };
283
284 let b_header = header.as_raw();
285 /*
286 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
287 mem::size_of::<ImageHeader>()) };
288 */
289 assert_eq!(b_header.len(), 32);
290 flash.write(offset, &b_header).unwrap();
291 let offset = offset + b_header.len();
292
293 // The core of the image itself is just pseudorandom data.
294 let mut buf = vec![0; len];
295 splat(&mut buf, offset);
296 flash.write(offset, &buf).unwrap();
297 let offset = offset + buf.len();
298
299 // Copy out the image so that we can verify that the image was installed correctly later.
300 let mut copy = vec![0u8; offset - offset0];
301 flash.read(offset0, &mut copy).unwrap();
302
303 copy
304}
305
306/// Verify that given image is present in the flash at the given offset.
307fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
308 let mut copy = vec![0u8; buf.len()];
309 flash.read(offset, &mut copy).unwrap();
310
311 if buf != &copy[..] {
312 for i in 0 .. buf.len() {
313 if buf[i] != copy[i] {
David Brown4440af82017-01-09 12:15:05 -0700314 info!("First failure at {:#x}", offset + i);
David Brownde7729e2017-01-09 10:41:35 -0700315 break;
316 }
317 }
318 false
319 } else {
320 true
321 }
322}
323
324/// The image header
325#[repr(C)]
326pub struct ImageHeader {
327 magic: u32,
328 tlv_size: u16,
329 key_id: u8,
330 _pad1: u8,
331 hdr_size: u16,
332 _pad2: u16,
333 img_size: u32,
334 flags: u32,
335 ver: ImageVersion,
336 _pad3: u32,
337}
338
339impl AsRaw for ImageHeader {}
340
341#[repr(C)]
342pub struct ImageVersion {
343 major: u8,
344 minor: u8,
345 revision: u16,
346 build_num: u32,
347}
348
349/// Write out the magic so that the loader tries doing an upgrade.
350fn mark_upgrade(flash: &mut Flash, offset: usize) {
351 let magic = vec![0x77, 0xc2, 0x95, 0xf3,
352 0x60, 0xd2, 0xef, 0x7f,
353 0x35, 0x52, 0x50, 0x0f,
354 0x2c, 0xb6, 0x79, 0x80];
355 flash.write(offset, &magic).unwrap();
356}
357
358// Drop some pseudo-random gibberish onto the data.
359fn splat(data: &mut [u8], seed: usize) {
360 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
361 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
362 rng.fill_bytes(data);
363}
364
365/// Return a read-only view into the raw bytes of this object
366trait AsRaw : Sized {
367 fn as_raw<'a>(&'a self) -> &'a [u8] {
368 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
369 mem::size_of::<Self>()) }
370 }
371}
372
373fn show_sizes() {
374 // This isn't panic safe.
375 let old_align = c::get_sim_flash_align();
376 for min in &[1, 2, 4, 8] {
377 c::set_sim_flash_align(*min);
378 let msize = c::boot_trailer_sz();
379 println!("{:2}: {} (0x{:x})", min, msize, msize);
380 }
381 c::set_sim_flash_align(old_align);
382}