blob: f077668d603d32c3164b15d4fa57d8c09a0c5448 [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
121 // println!("Areas: {:#?}", areadesc.get_c());
122
123 // Install the boot trailer signature, so that the code will start an upgrade.
David Brown74cc14c2017-01-23 15:46:40 -0700124 // TODO: This must be a multiple of flash alignment, add support for an image that is smaller,
125 // and just gets padded.
126 let primary = install_image(&mut flash, 0x020000, 32784);
David Brownde7729e2017-01-09 10:41:35 -0700127
128 // Install an upgrade image.
David Brown74cc14c2017-01-23 15:46:40 -0700129 let upgrade = install_image(&mut flash, 0x040000, 41928);
David Brownde7729e2017-01-09 10:41:35 -0700130
131 // Set an alignment, and position the magic value.
David Brown562a7a02017-01-23 11:19:03 -0700132 c::set_sim_flash_align(align);
David Brownde7729e2017-01-09 10:41:35 -0700133 let trailer_size = c::boot_trailer_sz();
134
135 // Mark the upgrade as ready to install. (This looks like it might be a bug in the code,
136 // however.)
137 mark_upgrade(&mut flash, 0x060000 - trailer_size as usize);
138
139 let (fl2, total_count) = try_upgrade(&flash, &areadesc, None);
David Brown4440af82017-01-09 12:15:05 -0700140 info!("First boot, count={}", total_count);
David Brownde7729e2017-01-09 10:41:35 -0700141 assert!(verify_image(&fl2, 0x020000, &upgrade));
142
143 let mut bad = 0;
144 // Let's try an image halfway through.
145 for i in 1 .. total_count {
David Brown4440af82017-01-09 12:15:05 -0700146 info!("Try interruption at {}", i);
David Brownde7729e2017-01-09 10:41:35 -0700147 let (fl3, total_count) = try_upgrade(&flash, &areadesc, Some(i));
David Brown4440af82017-01-09 12:15:05 -0700148 info!("Second boot, count={}", total_count);
David Brownde7729e2017-01-09 10:41:35 -0700149 if !verify_image(&fl3, 0x020000, &upgrade) {
David Brown4440af82017-01-09 12:15:05 -0700150 warn!("FAIL at step {} of {}", i, total_count);
David Brownde7729e2017-01-09 10:41:35 -0700151 bad += 1;
152 }
153 if !verify_image(&fl3, 0x040000, &primary) {
David Brown4440af82017-01-09 12:15:05 -0700154 warn!("Slot 1 FAIL at step {} of {}", i, total_count);
David Brownde7729e2017-01-09 10:41:35 -0700155 bad += 1;
156 }
157 }
David Brown4440af82017-01-09 12:15:05 -0700158 error!("{} out of {} failed {:.2}%",
159 bad, total_count,
160 bad as f32 * 100.0 / total_count as f32);
David Brownde7729e2017-01-09 10:41:35 -0700161
David Brownc638f792017-01-10 12:34:33 -0700162 for count in 2 .. 5 {
163 info!("Try revert: {}", count);
164 let fl2 = try_revert(&flash, &areadesc, count);
165 assert!(verify_image(&fl2, 0x020000, &primary));
166 }
David Brownde7729e2017-01-09 10:41:35 -0700167
David Brown4440af82017-01-09 12:15:05 -0700168 info!("Try norevert");
David Brownde7729e2017-01-09 10:41:35 -0700169 let fl2 = try_norevert(&flash, &areadesc);
170 assert!(verify_image(&fl2, 0x020000, &upgrade));
171
172 /*
173 // show_flash(&flash);
174
175 println!("First boot for upgrade");
176 // c::set_flash_counter(570);
177 c::boot_go(&mut flash, &areadesc);
178 // println!("{} flash ops", c::get_flash_counter());
179
180 verify_image(&flash, 0x020000, &upgrade);
181
182 println!("\n------------------\nSecond boot");
183 c::boot_go(&mut flash, &areadesc);
184 */
185}
186
187/// Test a boot, optionally stopping after 'n' flash options. Returns a count of the number of
188/// flash operations done total.
189fn try_upgrade(flash: &Flash, areadesc: &AreaDesc, stop: Option<i32>) -> (Flash, i32) {
190 // Clone the flash to have a new copy.
191 let mut fl = flash.clone();
192
193 c::set_flash_counter(stop.unwrap_or(0));
194 let (first_interrupted, cnt1) = match c::boot_go(&mut fl, &areadesc) {
195 -0x13579 => (true, stop.unwrap()),
196 0 => (false, -c::get_flash_counter()),
197 x => panic!("Unknown return: {}", x),
198 };
199 c::set_flash_counter(0);
200
201 if first_interrupted {
202 // fl.dump();
203 match c::boot_go(&mut fl, &areadesc) {
204 -0x13579 => panic!("Shouldn't stop again"),
205 0 => (),
206 x => panic!("Unknown return: {}", x),
207 }
208 }
209
210 let cnt2 = cnt1 - c::get_flash_counter();
211
212 (fl, cnt2)
213}
214
David Brownc638f792017-01-10 12:34:33 -0700215fn try_revert(flash: &Flash, areadesc: &AreaDesc, count: usize) -> Flash {
David Brownde7729e2017-01-09 10:41:35 -0700216 let mut fl = flash.clone();
217 c::set_flash_counter(0);
218
David Brown163ab232017-01-23 15:48:35 -0700219 // fl.write_file("image0.bin").unwrap();
220 for i in 0 .. count {
221 info!("Running boot pass {}", i + 1);
David Brownc638f792017-01-10 12:34:33 -0700222 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
223 }
David Brownde7729e2017-01-09 10:41:35 -0700224 fl
225}
226
227fn try_norevert(flash: &Flash, areadesc: &AreaDesc) -> Flash {
228 let mut fl = flash.clone();
229 c::set_flash_counter(0);
230 let align = c::get_sim_flash_align() as usize;
231
232 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
233 // Write boot_ok
David Brown75e16d62017-01-23 15:47:59 -0700234 let ok = [1u8, 0, 0, 0, 0, 0, 0, 0];
235 fl.write(0x040000 - align, &ok[..align]).unwrap();
David Brownde7729e2017-01-09 10:41:35 -0700236 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
237 fl
238}
239
240/// Show the flash layout.
241#[allow(dead_code)]
242fn show_flash(flash: &Flash) {
243 println!("---- Flash configuration ----");
244 for sector in flash.sector_iter() {
245 println!(" {:2}: 0x{:08x}, 0x{:08x}",
246 sector.num, sector.base, sector.size);
247 }
248 println!("");
249}
250
251/// Install a "program" into the given image. This fakes the image header, or at least all of the
252/// fields used by the given code. Returns a copy of the image that was written.
253fn install_image(flash: &mut Flash, offset: usize, len: usize) -> Vec<u8> {
254 let offset0 = offset;
255
256 // Generate a boot header. Note that the size doesn't include the header.
257 let header = ImageHeader {
258 magic: 0x96f3b83c,
259 tlv_size: 0,
260 _pad1: 0,
261 hdr_size: 32,
262 key_id: 0,
263 _pad2: 0,
264 img_size: len as u32,
265 flags: 0,
266 ver: ImageVersion {
David Browne380fa62017-01-23 15:49:09 -0700267 major: (offset / (128 * 1024)) as u8,
David Brownde7729e2017-01-09 10:41:35 -0700268 minor: 0,
269 revision: 1,
David Browne380fa62017-01-23 15:49:09 -0700270 build_num: offset as u32,
David Brownde7729e2017-01-09 10:41:35 -0700271 },
272 _pad3: 0,
273 };
274
275 let b_header = header.as_raw();
276 /*
277 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
278 mem::size_of::<ImageHeader>()) };
279 */
280 assert_eq!(b_header.len(), 32);
281 flash.write(offset, &b_header).unwrap();
282 let offset = offset + b_header.len();
283
284 // The core of the image itself is just pseudorandom data.
285 let mut buf = vec![0; len];
286 splat(&mut buf, offset);
287 flash.write(offset, &buf).unwrap();
288 let offset = offset + buf.len();
289
290 // Copy out the image so that we can verify that the image was installed correctly later.
291 let mut copy = vec![0u8; offset - offset0];
292 flash.read(offset0, &mut copy).unwrap();
293
294 copy
295}
296
297/// Verify that given image is present in the flash at the given offset.
298fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
299 let mut copy = vec![0u8; buf.len()];
300 flash.read(offset, &mut copy).unwrap();
301
302 if buf != &copy[..] {
303 for i in 0 .. buf.len() {
304 if buf[i] != copy[i] {
David Brown4440af82017-01-09 12:15:05 -0700305 info!("First failure at {:#x}", offset + i);
David Brownde7729e2017-01-09 10:41:35 -0700306 break;
307 }
308 }
309 false
310 } else {
311 true
312 }
313}
314
315/// The image header
316#[repr(C)]
317pub struct ImageHeader {
318 magic: u32,
319 tlv_size: u16,
320 key_id: u8,
321 _pad1: u8,
322 hdr_size: u16,
323 _pad2: u16,
324 img_size: u32,
325 flags: u32,
326 ver: ImageVersion,
327 _pad3: u32,
328}
329
330impl AsRaw for ImageHeader {}
331
332#[repr(C)]
333pub struct ImageVersion {
334 major: u8,
335 minor: u8,
336 revision: u16,
337 build_num: u32,
338}
339
340/// Write out the magic so that the loader tries doing an upgrade.
341fn mark_upgrade(flash: &mut Flash, offset: usize) {
342 let magic = vec![0x77, 0xc2, 0x95, 0xf3,
343 0x60, 0xd2, 0xef, 0x7f,
344 0x35, 0x52, 0x50, 0x0f,
345 0x2c, 0xb6, 0x79, 0x80];
346 flash.write(offset, &magic).unwrap();
347}
348
349// Drop some pseudo-random gibberish onto the data.
350fn splat(data: &mut [u8], seed: usize) {
351 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
352 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
353 rng.fill_bytes(data);
354}
355
356/// Return a read-only view into the raw bytes of this object
357trait AsRaw : Sized {
358 fn as_raw<'a>(&'a self) -> &'a [u8] {
359 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
360 mem::size_of::<Self>()) }
361 }
362}
363
364fn show_sizes() {
365 // This isn't panic safe.
366 let old_align = c::get_sim_flash_align();
367 for min in &[1, 2, 4, 8] {
368 c::set_sim_flash_align(*min);
369 let msize = c::boot_trailer_sz();
370 println!("{:2}: {} (0x{:x})", min, msize, msize);
371 }
372 c::set_sim_flash_align(old_align);
373}