blob: 8b08a81f77fbc5ce39fc7d9a36ad8665858657ce [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 Brown07fb8fa2017-03-20 12:40:57 -060053enum DeviceName { Stm32f4, K64f, K64fBig, Nrf52840 }
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 Brown07fb8fa2017-03-20 12:40:57 -0600119 Some(DeviceName::Nrf52840) => {
120 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
121 // does not divide into the image size.
122 let flash = Flash::new(vec![4096; 128], align as usize);
123
124 let mut areadesc = AreaDesc::new(&flash);
125 areadesc.add_image(0x008000, 0x034000, FlashId::Image0);
126 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1);
127 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch);
128 (flash, areadesc)
129 }
David Brownde7729e2017-01-09 10:41:35 -0700130 };
131
David Brown5c6b6792017-03-20 12:51:28 -0600132 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
133 let (slot1_base, slot1_len) = areadesc.find(FlashId::Image1);
134 let (scratch_base, _) = areadesc.find(FlashId::ImageScratch);
135
136 // Code below assumes that the slots are consecutive.
137 assert_eq!(slot1_base, slot0_base + slot0_len);
138 assert_eq!(scratch_base, slot1_base + slot1_len);
139
David Brownde7729e2017-01-09 10:41:35 -0700140 // println!("Areas: {:#?}", areadesc.get_c());
141
142 // Install the boot trailer signature, so that the code will start an upgrade.
David Brown74cc14c2017-01-23 15:46:40 -0700143 // TODO: This must be a multiple of flash alignment, add support for an image that is smaller,
144 // and just gets padded.
David Brown5c6b6792017-03-20 12:51:28 -0600145 let primary = install_image(&mut flash, slot0_base, 32784);
David Brownde7729e2017-01-09 10:41:35 -0700146
147 // Install an upgrade image.
David Brown5c6b6792017-03-20 12:51:28 -0600148 let upgrade = install_image(&mut flash, slot1_base, 41928);
David Brownde7729e2017-01-09 10:41:35 -0700149
150 // Set an alignment, and position the magic value.
David Brown562a7a02017-01-23 11:19:03 -0700151 c::set_sim_flash_align(align);
David Brownde7729e2017-01-09 10:41:35 -0700152 let trailer_size = c::boot_trailer_sz();
153
154 // Mark the upgrade as ready to install. (This looks like it might be a bug in the code,
155 // however.)
David Brown5c6b6792017-03-20 12:51:28 -0600156 mark_upgrade(&mut flash, scratch_base - trailer_size as usize);
David Brownde7729e2017-01-09 10:41:35 -0700157
158 let (fl2, total_count) = try_upgrade(&flash, &areadesc, None);
David Brown4440af82017-01-09 12:15:05 -0700159 info!("First boot, count={}", total_count);
David Brown5c6b6792017-03-20 12:51:28 -0600160 assert!(verify_image(&fl2, slot0_base, &upgrade));
David Brownde7729e2017-01-09 10:41:35 -0700161
162 let mut bad = 0;
163 // Let's try an image halfway through.
164 for i in 1 .. total_count {
David Brown4440af82017-01-09 12:15:05 -0700165 info!("Try interruption at {}", i);
David Brownde7729e2017-01-09 10:41:35 -0700166 let (fl3, total_count) = try_upgrade(&flash, &areadesc, Some(i));
David Brown4440af82017-01-09 12:15:05 -0700167 info!("Second boot, count={}", total_count);
David Brown5c6b6792017-03-20 12:51:28 -0600168 if !verify_image(&fl3, slot0_base, &upgrade) {
David Brown4440af82017-01-09 12:15:05 -0700169 warn!("FAIL at step {} of {}", i, total_count);
David Brownde7729e2017-01-09 10:41:35 -0700170 bad += 1;
171 }
David Brown5c6b6792017-03-20 12:51:28 -0600172 if !verify_image(&fl3, slot1_base, &primary) {
David Brown4440af82017-01-09 12:15:05 -0700173 warn!("Slot 1 FAIL at step {} of {}", i, total_count);
David Brownde7729e2017-01-09 10:41:35 -0700174 bad += 1;
175 }
176 }
David Brown4440af82017-01-09 12:15:05 -0700177 error!("{} out of {} failed {:.2}%",
178 bad, total_count,
179 bad as f32 * 100.0 / total_count as f32);
David Brownde7729e2017-01-09 10:41:35 -0700180
David Brownc638f792017-01-10 12:34:33 -0700181 for count in 2 .. 5 {
182 info!("Try revert: {}", count);
183 let fl2 = try_revert(&flash, &areadesc, count);
David Brown5c6b6792017-03-20 12:51:28 -0600184 assert!(verify_image(&fl2, slot0_base, &primary));
David Brownc638f792017-01-10 12:34:33 -0700185 }
David Brownde7729e2017-01-09 10:41:35 -0700186
David Brown4440af82017-01-09 12:15:05 -0700187 info!("Try norevert");
David Brownde7729e2017-01-09 10:41:35 -0700188 let fl2 = try_norevert(&flash, &areadesc);
David Brown5c6b6792017-03-20 12:51:28 -0600189 assert!(verify_image(&fl2, slot0_base, &upgrade));
David Brownde7729e2017-01-09 10:41:35 -0700190
191 /*
192 // show_flash(&flash);
193
194 println!("First boot for upgrade");
195 // c::set_flash_counter(570);
196 c::boot_go(&mut flash, &areadesc);
197 // println!("{} flash ops", c::get_flash_counter());
198
David Brown5c6b6792017-03-20 12:51:28 -0600199 verify_image(&flash, slot0_base, &upgrade);
David Brownde7729e2017-01-09 10:41:35 -0700200
201 println!("\n------------------\nSecond boot");
202 c::boot_go(&mut flash, &areadesc);
203 */
204}
205
206/// Test a boot, optionally stopping after 'n' flash options. Returns a count of the number of
207/// flash operations done total.
208fn try_upgrade(flash: &Flash, areadesc: &AreaDesc, stop: Option<i32>) -> (Flash, i32) {
209 // Clone the flash to have a new copy.
210 let mut fl = flash.clone();
211
212 c::set_flash_counter(stop.unwrap_or(0));
213 let (first_interrupted, cnt1) = match c::boot_go(&mut fl, &areadesc) {
214 -0x13579 => (true, stop.unwrap()),
215 0 => (false, -c::get_flash_counter()),
216 x => panic!("Unknown return: {}", x),
217 };
218 c::set_flash_counter(0);
219
220 if first_interrupted {
221 // fl.dump();
222 match c::boot_go(&mut fl, &areadesc) {
223 -0x13579 => panic!("Shouldn't stop again"),
224 0 => (),
225 x => panic!("Unknown return: {}", x),
226 }
227 }
228
229 let cnt2 = cnt1 - c::get_flash_counter();
230
231 (fl, cnt2)
232}
233
David Brownc638f792017-01-10 12:34:33 -0700234fn try_revert(flash: &Flash, areadesc: &AreaDesc, count: usize) -> Flash {
David Brownde7729e2017-01-09 10:41:35 -0700235 let mut fl = flash.clone();
236 c::set_flash_counter(0);
237
David Brown163ab232017-01-23 15:48:35 -0700238 // fl.write_file("image0.bin").unwrap();
239 for i in 0 .. count {
240 info!("Running boot pass {}", i + 1);
David Brownc638f792017-01-10 12:34:33 -0700241 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
242 }
David Brownde7729e2017-01-09 10:41:35 -0700243 fl
244}
245
246fn try_norevert(flash: &Flash, areadesc: &AreaDesc) -> Flash {
247 let mut fl = flash.clone();
248 c::set_flash_counter(0);
249 let align = c::get_sim_flash_align() as usize;
250
251 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
252 // Write boot_ok
David Brown75e16d62017-01-23 15:47:59 -0700253 let ok = [1u8, 0, 0, 0, 0, 0, 0, 0];
David Brown5c6b6792017-03-20 12:51:28 -0600254 let (slot0_base, slot0_len) = areadesc.find(FlashId::Image0);
255 fl.write(slot0_base + slot0_len - align, &ok[..align]).unwrap();
David Brownde7729e2017-01-09 10:41:35 -0700256 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
257 fl
258}
259
260/// Show the flash layout.
261#[allow(dead_code)]
262fn show_flash(flash: &Flash) {
263 println!("---- Flash configuration ----");
264 for sector in flash.sector_iter() {
265 println!(" {:2}: 0x{:08x}, 0x{:08x}",
266 sector.num, sector.base, sector.size);
267 }
268 println!("");
269}
270
271/// Install a "program" into the given image. This fakes the image header, or at least all of the
272/// fields used by the given code. Returns a copy of the image that was written.
273fn install_image(flash: &mut Flash, offset: usize, len: usize) -> Vec<u8> {
274 let offset0 = offset;
275
276 // Generate a boot header. Note that the size doesn't include the header.
277 let header = ImageHeader {
278 magic: 0x96f3b83c,
279 tlv_size: 0,
280 _pad1: 0,
281 hdr_size: 32,
282 key_id: 0,
283 _pad2: 0,
284 img_size: len as u32,
285 flags: 0,
286 ver: ImageVersion {
David Browne380fa62017-01-23 15:49:09 -0700287 major: (offset / (128 * 1024)) as u8,
David Brownde7729e2017-01-09 10:41:35 -0700288 minor: 0,
289 revision: 1,
David Browne380fa62017-01-23 15:49:09 -0700290 build_num: offset as u32,
David Brownde7729e2017-01-09 10:41:35 -0700291 },
292 _pad3: 0,
293 };
294
295 let b_header = header.as_raw();
296 /*
297 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
298 mem::size_of::<ImageHeader>()) };
299 */
300 assert_eq!(b_header.len(), 32);
301 flash.write(offset, &b_header).unwrap();
302 let offset = offset + b_header.len();
303
304 // The core of the image itself is just pseudorandom data.
305 let mut buf = vec![0; len];
306 splat(&mut buf, offset);
307 flash.write(offset, &buf).unwrap();
308 let offset = offset + buf.len();
309
310 // Copy out the image so that we can verify that the image was installed correctly later.
311 let mut copy = vec![0u8; offset - offset0];
312 flash.read(offset0, &mut copy).unwrap();
313
314 copy
315}
316
317/// Verify that given image is present in the flash at the given offset.
318fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
319 let mut copy = vec![0u8; buf.len()];
320 flash.read(offset, &mut copy).unwrap();
321
322 if buf != &copy[..] {
323 for i in 0 .. buf.len() {
324 if buf[i] != copy[i] {
David Brown4440af82017-01-09 12:15:05 -0700325 info!("First failure at {:#x}", offset + i);
David Brownde7729e2017-01-09 10:41:35 -0700326 break;
327 }
328 }
329 false
330 } else {
331 true
332 }
333}
334
335/// The image header
336#[repr(C)]
337pub struct ImageHeader {
338 magic: u32,
339 tlv_size: u16,
340 key_id: u8,
341 _pad1: u8,
342 hdr_size: u16,
343 _pad2: u16,
344 img_size: u32,
345 flags: u32,
346 ver: ImageVersion,
347 _pad3: u32,
348}
349
350impl AsRaw for ImageHeader {}
351
352#[repr(C)]
353pub struct ImageVersion {
354 major: u8,
355 minor: u8,
356 revision: u16,
357 build_num: u32,
358}
359
360/// Write out the magic so that the loader tries doing an upgrade.
361fn mark_upgrade(flash: &mut Flash, offset: usize) {
362 let magic = vec![0x77, 0xc2, 0x95, 0xf3,
363 0x60, 0xd2, 0xef, 0x7f,
364 0x35, 0x52, 0x50, 0x0f,
365 0x2c, 0xb6, 0x79, 0x80];
366 flash.write(offset, &magic).unwrap();
367}
368
369// Drop some pseudo-random gibberish onto the data.
370fn splat(data: &mut [u8], seed: usize) {
371 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
372 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
373 rng.fill_bytes(data);
374}
375
376/// Return a read-only view into the raw bytes of this object
377trait AsRaw : Sized {
378 fn as_raw<'a>(&'a self) -> &'a [u8] {
379 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
380 mem::size_of::<Self>()) }
381 }
382}
383
384fn show_sizes() {
385 // This isn't panic safe.
386 let old_align = c::get_sim_flash_align();
387 for min in &[1, 2, 4, 8] {
388 c::set_sim_flash_align(*min);
389 let msize = c::boot_trailer_sz();
390 println!("{:2}: {} (0x{:x})", min, msize, msize);
391 }
392 c::set_sim_flash_align(old_align);
393}