blob: 533e65186c1791fb213b44cb51a3395cefed8076 [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.
124 let primary = install_image(&mut flash, 0x020000, 32779);
125
126 // Install an upgrade image.
127 let upgrade = install_image(&mut flash, 0x040000, 41922);
128
129 // Set an alignment, and position the magic value.
David Brown562a7a02017-01-23 11:19:03 -0700130 c::set_sim_flash_align(align);
David Brownde7729e2017-01-09 10:41:35 -0700131 let trailer_size = c::boot_trailer_sz();
132
133 // Mark the upgrade as ready to install. (This looks like it might be a bug in the code,
134 // however.)
135 mark_upgrade(&mut flash, 0x060000 - trailer_size as usize);
136
137 let (fl2, total_count) = try_upgrade(&flash, &areadesc, None);
David Brown4440af82017-01-09 12:15:05 -0700138 info!("First boot, count={}", total_count);
David Brownde7729e2017-01-09 10:41:35 -0700139 assert!(verify_image(&fl2, 0x020000, &upgrade));
140
141 let mut bad = 0;
142 // Let's try an image halfway through.
143 for i in 1 .. total_count {
David Brown4440af82017-01-09 12:15:05 -0700144 info!("Try interruption at {}", i);
David Brownde7729e2017-01-09 10:41:35 -0700145 let (fl3, total_count) = try_upgrade(&flash, &areadesc, Some(i));
David Brown4440af82017-01-09 12:15:05 -0700146 info!("Second boot, count={}", total_count);
David Brownde7729e2017-01-09 10:41:35 -0700147 if !verify_image(&fl3, 0x020000, &upgrade) {
David Brown4440af82017-01-09 12:15:05 -0700148 warn!("FAIL at step {} of {}", i, total_count);
David Brownde7729e2017-01-09 10:41:35 -0700149 bad += 1;
150 }
151 if !verify_image(&fl3, 0x040000, &primary) {
David Brown4440af82017-01-09 12:15:05 -0700152 warn!("Slot 1 FAIL at step {} of {}", i, total_count);
David Brownde7729e2017-01-09 10:41:35 -0700153 bad += 1;
154 }
155 }
David Brown4440af82017-01-09 12:15:05 -0700156 error!("{} out of {} failed {:.2}%",
157 bad, total_count,
158 bad as f32 * 100.0 / total_count as f32);
David Brownde7729e2017-01-09 10:41:35 -0700159
David Brownc638f792017-01-10 12:34:33 -0700160 for count in 2 .. 5 {
161 info!("Try revert: {}", count);
162 let fl2 = try_revert(&flash, &areadesc, count);
163 assert!(verify_image(&fl2, 0x020000, &primary));
164 }
David Brownde7729e2017-01-09 10:41:35 -0700165
David Brown4440af82017-01-09 12:15:05 -0700166 info!("Try norevert");
David Brownde7729e2017-01-09 10:41:35 -0700167 let fl2 = try_norevert(&flash, &areadesc);
168 assert!(verify_image(&fl2, 0x020000, &upgrade));
169
170 /*
171 // show_flash(&flash);
172
173 println!("First boot for upgrade");
174 // c::set_flash_counter(570);
175 c::boot_go(&mut flash, &areadesc);
176 // println!("{} flash ops", c::get_flash_counter());
177
178 verify_image(&flash, 0x020000, &upgrade);
179
180 println!("\n------------------\nSecond boot");
181 c::boot_go(&mut flash, &areadesc);
182 */
183}
184
185/// Test a boot, optionally stopping after 'n' flash options. Returns a count of the number of
186/// flash operations done total.
187fn try_upgrade(flash: &Flash, areadesc: &AreaDesc, stop: Option<i32>) -> (Flash, i32) {
188 // Clone the flash to have a new copy.
189 let mut fl = flash.clone();
190
191 c::set_flash_counter(stop.unwrap_or(0));
192 let (first_interrupted, cnt1) = match c::boot_go(&mut fl, &areadesc) {
193 -0x13579 => (true, stop.unwrap()),
194 0 => (false, -c::get_flash_counter()),
195 x => panic!("Unknown return: {}", x),
196 };
197 c::set_flash_counter(0);
198
199 if first_interrupted {
200 // fl.dump();
201 match c::boot_go(&mut fl, &areadesc) {
202 -0x13579 => panic!("Shouldn't stop again"),
203 0 => (),
204 x => panic!("Unknown return: {}", x),
205 }
206 }
207
208 let cnt2 = cnt1 - c::get_flash_counter();
209
210 (fl, cnt2)
211}
212
David Brownc638f792017-01-10 12:34:33 -0700213fn try_revert(flash: &Flash, areadesc: &AreaDesc, count: usize) -> Flash {
David Brownde7729e2017-01-09 10:41:35 -0700214 let mut fl = flash.clone();
215 c::set_flash_counter(0);
216
David Brownc638f792017-01-10 12:34:33 -0700217 for _ in 0 .. count {
218 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
219 }
David Brownde7729e2017-01-09 10:41:35 -0700220 fl
221}
222
223fn try_norevert(flash: &Flash, areadesc: &AreaDesc) -> Flash {
224 let mut fl = flash.clone();
225 c::set_flash_counter(0);
226 let align = c::get_sim_flash_align() as usize;
227
228 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
229 // Write boot_ok
230 fl.write(0x040000 - align, &[1]).unwrap();
231 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
232 fl
233}
234
235/// Show the flash layout.
236#[allow(dead_code)]
237fn show_flash(flash: &Flash) {
238 println!("---- Flash configuration ----");
239 for sector in flash.sector_iter() {
240 println!(" {:2}: 0x{:08x}, 0x{:08x}",
241 sector.num, sector.base, sector.size);
242 }
243 println!("");
244}
245
246/// Install a "program" into the given image. This fakes the image header, or at least all of the
247/// fields used by the given code. Returns a copy of the image that was written.
248fn install_image(flash: &mut Flash, offset: usize, len: usize) -> Vec<u8> {
249 let offset0 = offset;
250
251 // Generate a boot header. Note that the size doesn't include the header.
252 let header = ImageHeader {
253 magic: 0x96f3b83c,
254 tlv_size: 0,
255 _pad1: 0,
256 hdr_size: 32,
257 key_id: 0,
258 _pad2: 0,
259 img_size: len as u32,
260 flags: 0,
261 ver: ImageVersion {
262 major: 1,
263 minor: 0,
264 revision: 1,
265 build_num: 1,
266 },
267 _pad3: 0,
268 };
269
270 let b_header = header.as_raw();
271 /*
272 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
273 mem::size_of::<ImageHeader>()) };
274 */
275 assert_eq!(b_header.len(), 32);
276 flash.write(offset, &b_header).unwrap();
277 let offset = offset + b_header.len();
278
279 // The core of the image itself is just pseudorandom data.
280 let mut buf = vec![0; len];
281 splat(&mut buf, offset);
282 flash.write(offset, &buf).unwrap();
283 let offset = offset + buf.len();
284
285 // Copy out the image so that we can verify that the image was installed correctly later.
286 let mut copy = vec![0u8; offset - offset0];
287 flash.read(offset0, &mut copy).unwrap();
288
289 copy
290}
291
292/// Verify that given image is present in the flash at the given offset.
293fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
294 let mut copy = vec![0u8; buf.len()];
295 flash.read(offset, &mut copy).unwrap();
296
297 if buf != &copy[..] {
298 for i in 0 .. buf.len() {
299 if buf[i] != copy[i] {
David Brown4440af82017-01-09 12:15:05 -0700300 info!("First failure at {:#x}", offset + i);
David Brownde7729e2017-01-09 10:41:35 -0700301 break;
302 }
303 }
304 false
305 } else {
306 true
307 }
308}
309
310/// The image header
311#[repr(C)]
312pub struct ImageHeader {
313 magic: u32,
314 tlv_size: u16,
315 key_id: u8,
316 _pad1: u8,
317 hdr_size: u16,
318 _pad2: u16,
319 img_size: u32,
320 flags: u32,
321 ver: ImageVersion,
322 _pad3: u32,
323}
324
325impl AsRaw for ImageHeader {}
326
327#[repr(C)]
328pub struct ImageVersion {
329 major: u8,
330 minor: u8,
331 revision: u16,
332 build_num: u32,
333}
334
335/// Write out the magic so that the loader tries doing an upgrade.
336fn mark_upgrade(flash: &mut Flash, offset: usize) {
337 let magic = vec![0x77, 0xc2, 0x95, 0xf3,
338 0x60, 0xd2, 0xef, 0x7f,
339 0x35, 0x52, 0x50, 0x0f,
340 0x2c, 0xb6, 0x79, 0x80];
341 flash.write(offset, &magic).unwrap();
342}
343
344// Drop some pseudo-random gibberish onto the data.
345fn splat(data: &mut [u8], seed: usize) {
346 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
347 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
348 rng.fill_bytes(data);
349}
350
351/// Return a read-only view into the raw bytes of this object
352trait AsRaw : Sized {
353 fn as_raw<'a>(&'a self) -> &'a [u8] {
354 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
355 mem::size_of::<Self>()) }
356 }
357}
358
359fn show_sizes() {
360 // This isn't panic safe.
361 let old_align = c::get_sim_flash_align();
362 for min in &[1, 2, 4, 8] {
363 c::set_sim_flash_align(*min);
364 let msize = c::boot_trailer_sz();
365 println!("{:2}: {} (0x{:x})", min, msize, msize);
366 }
367 c::set_sim_flash_align(old_align);
368}