blob: 33b2c0c97bb7ca048f7573c4aec144d8f485ed50 [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
82 let (mut flash, areadesc) = match args.flag_device {
83 None => panic!("Missing mandatory argument"),
84 Some(DeviceName::Stm32f4) => {
85 // STM style flash. Large sectors, with a large scratch area.
86 let flash = Flash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
87 64 * 1024,
88 128 * 1024, 128 * 1024, 128 * 1024]);
89 let mut areadesc = AreaDesc::new(&flash);
90 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
91 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
92 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch);
93 (flash, areadesc)
94 }
95 Some(DeviceName::K64f) => {
96 // NXP style flash. Small sectors, one small sector for scratch.
97 let flash = Flash::new(vec![4096; 128]);
98
99 let mut areadesc = AreaDesc::new(&flash);
100 areadesc.add_image(0x020000, 0x020000, FlashId::Image0);
101 areadesc.add_image(0x040000, 0x020000, FlashId::Image1);
102 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch);
103 (flash, areadesc)
104 }
David Brown90c19132017-01-23 10:21:28 -0700105 Some(DeviceName::K64fBig) => {
106 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
107 // uses small sectors, but we tell the bootloader they are large.
108 let flash = Flash::new(vec![4096; 128]);
109
110 let mut areadesc = AreaDesc::new(&flash);
111 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0);
112 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1);
113 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch);
114 (flash, areadesc)
115 }
David Brownde7729e2017-01-09 10:41:35 -0700116 };
117
118 // println!("Areas: {:#?}", areadesc.get_c());
119
120 // Install the boot trailer signature, so that the code will start an upgrade.
121 let primary = install_image(&mut flash, 0x020000, 32779);
122
123 // Install an upgrade image.
124 let upgrade = install_image(&mut flash, 0x040000, 41922);
125
126 // Set an alignment, and position the magic value.
127 c::set_sim_flash_align(args.flag_align.map(|x| x.0).unwrap_or(1));
128 let trailer_size = c::boot_trailer_sz();
129
130 // Mark the upgrade as ready to install. (This looks like it might be a bug in the code,
131 // however.)
132 mark_upgrade(&mut flash, 0x060000 - trailer_size as usize);
133
134 let (fl2, total_count) = try_upgrade(&flash, &areadesc, None);
David Brown4440af82017-01-09 12:15:05 -0700135 info!("First boot, count={}", total_count);
David Brownde7729e2017-01-09 10:41:35 -0700136 assert!(verify_image(&fl2, 0x020000, &upgrade));
137
138 let mut bad = 0;
139 // Let's try an image halfway through.
140 for i in 1 .. total_count {
David Brown4440af82017-01-09 12:15:05 -0700141 info!("Try interruption at {}", i);
David Brownde7729e2017-01-09 10:41:35 -0700142 let (fl3, total_count) = try_upgrade(&flash, &areadesc, Some(i));
David Brown4440af82017-01-09 12:15:05 -0700143 info!("Second boot, count={}", total_count);
David Brownde7729e2017-01-09 10:41:35 -0700144 if !verify_image(&fl3, 0x020000, &upgrade) {
David Brown4440af82017-01-09 12:15:05 -0700145 warn!("FAIL at step {} of {}", i, total_count);
David Brownde7729e2017-01-09 10:41:35 -0700146 bad += 1;
147 }
148 if !verify_image(&fl3, 0x040000, &primary) {
David Brown4440af82017-01-09 12:15:05 -0700149 warn!("Slot 1 FAIL at step {} of {}", i, total_count);
David Brownde7729e2017-01-09 10:41:35 -0700150 bad += 1;
151 }
152 }
David Brown4440af82017-01-09 12:15:05 -0700153 error!("{} out of {} failed {:.2}%",
154 bad, total_count,
155 bad as f32 * 100.0 / total_count as f32);
David Brownde7729e2017-01-09 10:41:35 -0700156
David Brownc638f792017-01-10 12:34:33 -0700157 for count in 2 .. 5 {
158 info!("Try revert: {}", count);
159 let fl2 = try_revert(&flash, &areadesc, count);
160 assert!(verify_image(&fl2, 0x020000, &primary));
161 }
David Brownde7729e2017-01-09 10:41:35 -0700162
David Brown4440af82017-01-09 12:15:05 -0700163 info!("Try norevert");
David Brownde7729e2017-01-09 10:41:35 -0700164 let fl2 = try_norevert(&flash, &areadesc);
165 assert!(verify_image(&fl2, 0x020000, &upgrade));
166
167 /*
168 // show_flash(&flash);
169
170 println!("First boot for upgrade");
171 // c::set_flash_counter(570);
172 c::boot_go(&mut flash, &areadesc);
173 // println!("{} flash ops", c::get_flash_counter());
174
175 verify_image(&flash, 0x020000, &upgrade);
176
177 println!("\n------------------\nSecond boot");
178 c::boot_go(&mut flash, &areadesc);
179 */
180}
181
182/// Test a boot, optionally stopping after 'n' flash options. Returns a count of the number of
183/// flash operations done total.
184fn try_upgrade(flash: &Flash, areadesc: &AreaDesc, stop: Option<i32>) -> (Flash, i32) {
185 // Clone the flash to have a new copy.
186 let mut fl = flash.clone();
187
188 c::set_flash_counter(stop.unwrap_or(0));
189 let (first_interrupted, cnt1) = match c::boot_go(&mut fl, &areadesc) {
190 -0x13579 => (true, stop.unwrap()),
191 0 => (false, -c::get_flash_counter()),
192 x => panic!("Unknown return: {}", x),
193 };
194 c::set_flash_counter(0);
195
196 if first_interrupted {
197 // fl.dump();
198 match c::boot_go(&mut fl, &areadesc) {
199 -0x13579 => panic!("Shouldn't stop again"),
200 0 => (),
201 x => panic!("Unknown return: {}", x),
202 }
203 }
204
205 let cnt2 = cnt1 - c::get_flash_counter();
206
207 (fl, cnt2)
208}
209
David Brownc638f792017-01-10 12:34:33 -0700210fn try_revert(flash: &Flash, areadesc: &AreaDesc, count: usize) -> Flash {
David Brownde7729e2017-01-09 10:41:35 -0700211 let mut fl = flash.clone();
212 c::set_flash_counter(0);
213
David Brownc638f792017-01-10 12:34:33 -0700214 for _ in 0 .. count {
215 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
216 }
David Brownde7729e2017-01-09 10:41:35 -0700217 fl
218}
219
220fn try_norevert(flash: &Flash, areadesc: &AreaDesc) -> Flash {
221 let mut fl = flash.clone();
222 c::set_flash_counter(0);
223 let align = c::get_sim_flash_align() as usize;
224
225 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
226 // Write boot_ok
227 fl.write(0x040000 - align, &[1]).unwrap();
228 assert_eq!(c::boot_go(&mut fl, &areadesc), 0);
229 fl
230}
231
232/// Show the flash layout.
233#[allow(dead_code)]
234fn show_flash(flash: &Flash) {
235 println!("---- Flash configuration ----");
236 for sector in flash.sector_iter() {
237 println!(" {:2}: 0x{:08x}, 0x{:08x}",
238 sector.num, sector.base, sector.size);
239 }
240 println!("");
241}
242
243/// Install a "program" into the given image. This fakes the image header, or at least all of the
244/// fields used by the given code. Returns a copy of the image that was written.
245fn install_image(flash: &mut Flash, offset: usize, len: usize) -> Vec<u8> {
246 let offset0 = offset;
247
248 // Generate a boot header. Note that the size doesn't include the header.
249 let header = ImageHeader {
250 magic: 0x96f3b83c,
251 tlv_size: 0,
252 _pad1: 0,
253 hdr_size: 32,
254 key_id: 0,
255 _pad2: 0,
256 img_size: len as u32,
257 flags: 0,
258 ver: ImageVersion {
259 major: 1,
260 minor: 0,
261 revision: 1,
262 build_num: 1,
263 },
264 _pad3: 0,
265 };
266
267 let b_header = header.as_raw();
268 /*
269 let b_header = unsafe { slice::from_raw_parts(&header as *const _ as *const u8,
270 mem::size_of::<ImageHeader>()) };
271 */
272 assert_eq!(b_header.len(), 32);
273 flash.write(offset, &b_header).unwrap();
274 let offset = offset + b_header.len();
275
276 // The core of the image itself is just pseudorandom data.
277 let mut buf = vec![0; len];
278 splat(&mut buf, offset);
279 flash.write(offset, &buf).unwrap();
280 let offset = offset + buf.len();
281
282 // Copy out the image so that we can verify that the image was installed correctly later.
283 let mut copy = vec![0u8; offset - offset0];
284 flash.read(offset0, &mut copy).unwrap();
285
286 copy
287}
288
289/// Verify that given image is present in the flash at the given offset.
290fn verify_image(flash: &Flash, offset: usize, buf: &[u8]) -> bool {
291 let mut copy = vec![0u8; buf.len()];
292 flash.read(offset, &mut copy).unwrap();
293
294 if buf != &copy[..] {
295 for i in 0 .. buf.len() {
296 if buf[i] != copy[i] {
David Brown4440af82017-01-09 12:15:05 -0700297 info!("First failure at {:#x}", offset + i);
David Brownde7729e2017-01-09 10:41:35 -0700298 break;
299 }
300 }
301 false
302 } else {
303 true
304 }
305}
306
307/// The image header
308#[repr(C)]
309pub struct ImageHeader {
310 magic: u32,
311 tlv_size: u16,
312 key_id: u8,
313 _pad1: u8,
314 hdr_size: u16,
315 _pad2: u16,
316 img_size: u32,
317 flags: u32,
318 ver: ImageVersion,
319 _pad3: u32,
320}
321
322impl AsRaw for ImageHeader {}
323
324#[repr(C)]
325pub struct ImageVersion {
326 major: u8,
327 minor: u8,
328 revision: u16,
329 build_num: u32,
330}
331
332/// Write out the magic so that the loader tries doing an upgrade.
333fn mark_upgrade(flash: &mut Flash, offset: usize) {
334 let magic = vec![0x77, 0xc2, 0x95, 0xf3,
335 0x60, 0xd2, 0xef, 0x7f,
336 0x35, 0x52, 0x50, 0x0f,
337 0x2c, 0xb6, 0x79, 0x80];
338 flash.write(offset, &magic).unwrap();
339}
340
341// Drop some pseudo-random gibberish onto the data.
342fn splat(data: &mut [u8], seed: usize) {
343 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
344 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
345 rng.fill_bytes(data);
346}
347
348/// Return a read-only view into the raw bytes of this object
349trait AsRaw : Sized {
350 fn as_raw<'a>(&'a self) -> &'a [u8] {
351 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
352 mem::size_of::<Self>()) }
353 }
354}
355
356fn show_sizes() {
357 // This isn't panic safe.
358 let old_align = c::get_sim_flash_align();
359 for min in &[1, 2, 4, 8] {
360 c::set_sim_flash_align(*min);
361 let msize = c::boot_trailer_sz();
362 println!("{:2}: {} (0x{:x})", min, msize, msize);
363 }
364 c::set_sim_flash_align(old_align);
365}