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