blob: ac238e7a5c97d380a16bce75b3970efac61f0a1e [file] [log] [blame]
David Brown5c9e0f12019-01-09 16:34:33 -07001use log::{info, warn, error};
2use rand::{
3 distributions::{IndependentSample, Range},
4 Rng, SeedableRng, XorShiftRng,
5};
6use std::{
7 mem,
8 slice,
9};
10use aes_ctr::{
11 Aes128Ctr,
12 stream_cipher::{
13 generic_array::GenericArray,
14 NewFixStreamCipher,
15 StreamCipherCore,
16 },
17};
18
David Brown76101572019-02-28 11:29:03 -070019use simflash::{Flash, SimFlash, SimMultiFlash};
David Browne5133242019-02-28 11:05:19 -070020use mcuboot_sys::{c, AreaDesc, FlashId};
21use crate::{
22 ALL_DEVICES,
23 DeviceName,
24};
David Brown5c9e0f12019-01-09 16:34:33 -070025use crate::caps::Caps;
David Brown43643dd2019-01-11 15:43:28 -070026use crate::tlv::{ManifestGen, TlvGen, TlvFlags, AES_SEC_KEY};
David Brown5c9e0f12019-01-09 16:34:33 -070027
David Browne5133242019-02-28 11:05:19 -070028/// A builder for Images. This describes a single run of the simulator,
29/// capturing the configuration of a particular set of devices, including
30/// the flash simulator(s) and the information about the slots.
31#[derive(Clone)]
32pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070033 flash: SimMultiFlash,
David Browne5133242019-02-28 11:05:19 -070034 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070035 slots: Vec<[SlotInfo; 2]>,
David Browne5133242019-02-28 11:05:19 -070036}
37
David Brown998aa8d2019-02-28 10:54:50 -070038/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070039/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070040/// and upgrades hold the expected contents of these images.
41pub struct Images {
David Brown76101572019-02-28 11:29:03 -070042 flash: SimMultiFlash,
David Brownca234692019-02-28 11:22:19 -070043 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070044 images: Vec<OneImage>,
45 total_count: Option<i32>,
46}
47
48/// When doing multi-image, there is an instance of this information for
49/// each of the images. Single image there will be one of these.
50struct OneImage {
David Brownca234692019-02-28 11:22:19 -070051 slots: [SlotInfo; 2],
52 primaries: ImageData,
53 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070054}
55
56/// The Rust-side representation of an image. For unencrypted images, this
57/// is just the unencrypted payload. For encrypted images, we store both
58/// the encrypted and the plaintext.
59struct ImageData {
60 plain: Vec<u8>,
61 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -070062}
63
David Browne5133242019-02-28 11:05:19 -070064impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -070065 /// Construct a new image builder for the given device. Returns
66 /// Some(builder) if is possible to test this configuration, or None if
67 /// not possible (for example, if there aren't enough image slots).
68 pub fn new(device: DeviceName, align: u8, erased_val: u8) -> Option<Self> {
David Brown76101572019-02-28 11:29:03 -070069 let (flash, areadesc) = Self::make_device(device, align, erased_val);
David Browne5133242019-02-28 11:05:19 -070070
David Brown06ef06e2019-03-05 12:28:10 -070071 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -070072
David Brown06ef06e2019-03-05 12:28:10 -070073 let mut slots = Vec::with_capacity(num_images);
74 for image in 0..num_images {
75 // This mapping must match that defined in
76 // `boot/zephyr/include/sysflash/sysflash.h`.
77 let id0 = match image {
78 0 => FlashId::Image0,
79 1 => FlashId::Image2,
80 _ => panic!("More than 2 images not supported"),
81 };
82 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
83 Some(info) => info,
84 None => return None,
85 };
86 let id1 = match image {
87 0 => FlashId::Image1,
88 1 => FlashId::Image3,
89 _ => panic!("More than 2 images not supported"),
90 };
91 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
92 Some(info) => info,
93 None => return None,
94 };
David Browne5133242019-02-28 11:05:19 -070095
Christopher Collinsa1c12042019-05-23 14:00:28 -070096 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -070097
David Brown06ef06e2019-03-05 12:28:10 -070098 // Construct a primary image.
99 let primary = SlotInfo {
100 base_off: primary_base as usize,
101 trailer_off: primary_base + primary_len - offset_from_end,
102 len: primary_len as usize,
103 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600104 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700105 };
106
107 // And an upgrade image.
108 let secondary = SlotInfo {
109 base_off: secondary_base as usize,
110 trailer_off: secondary_base + secondary_len - offset_from_end,
111 len: secondary_len as usize,
112 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600113 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700114 };
115
116 slots.push([primary, secondary]);
117 }
David Browne5133242019-02-28 11:05:19 -0700118
David Brown5bc62c62019-03-05 12:11:48 -0700119 Some(ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -0700120 flash: flash,
David Browne5133242019-02-28 11:05:19 -0700121 areadesc: areadesc,
David Brown06ef06e2019-03-05 12:28:10 -0700122 slots: slots,
David Brown5bc62c62019-03-05 12:11:48 -0700123 })
David Browne5133242019-02-28 11:05:19 -0700124 }
125
126 pub fn each_device<F>(f: F)
127 where F: Fn(Self)
128 {
129 for &dev in ALL_DEVICES {
130 for &align in &[1, 2, 4, 8] {
131 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700132 match Self::new(dev, align, erased_val) {
133 Some(run) => f(run),
134 None => warn!("Skipping {:?}, insufficient partitions", dev),
135 }
David Browne5133242019-02-28 11:05:19 -0700136 }
137 }
138 }
139 }
140
141 /// Construct an `Images` that doesn't expect an upgrade to happen.
142 pub fn make_no_upgrade_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700143 let mut flash = self.flash;
David Brown84b49f72019-03-01 10:58:22 -0700144 let images = self.slots.into_iter().map(|slots| {
David Brown3b090212019-07-30 15:59:28 -0600145 let primaries = install_image(&mut flash, &slots[0], 42784, false);
146 let upgrades = install_image(&mut flash, &slots[1], 46928, false);
David Brown84b49f72019-03-01 10:58:22 -0700147 OneImage {
148 slots: slots,
149 primaries: primaries,
150 upgrades: upgrades,
151 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700152 Images {
David Brown76101572019-02-28 11:29:03 -0700153 flash: flash,
David Browne5133242019-02-28 11:05:19 -0700154 areadesc: self.areadesc,
David Brown84b49f72019-03-01 10:58:22 -0700155 images: images,
David Browne5133242019-02-28 11:05:19 -0700156 total_count: None,
157 }
158 }
159
David Browneebf5022019-07-30 15:01:07 -0600160 pub fn make_image(self, permanent: bool) -> Images {
David Browne5133242019-02-28 11:05:19 -0700161 let mut images = self.make_no_upgrade_image();
David Brown84b49f72019-03-01 10:58:22 -0700162 for image in &images.images {
163 mark_upgrade(&mut images.flash, &image.slots[1]);
164 }
David Browne5133242019-02-28 11:05:19 -0700165
166 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300167 let total_count = match images.run_basic_upgrade(permanent) {
David Browne5133242019-02-28 11:05:19 -0700168 Ok(v) => v,
169 Err(_) => {
170 panic!("Unable to perform basic upgrade");
171 },
172 };
173
174 images.total_count = Some(total_count);
175 images
176 }
177
178 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700179 let mut bad_flash = self.flash;
David Brown84b49f72019-03-01 10:58:22 -0700180 let images = self.slots.into_iter().map(|slots| {
David Brown3b090212019-07-30 15:59:28 -0600181 let primaries = install_image(&mut bad_flash, &slots[0], 32784, false);
182 let upgrades = install_image(&mut bad_flash, &slots[1], 41928, true);
David Brown84b49f72019-03-01 10:58:22 -0700183 OneImage {
184 slots: slots,
185 primaries: primaries,
186 upgrades: upgrades,
187 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700188 Images {
David Brown76101572019-02-28 11:29:03 -0700189 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700190 areadesc: self.areadesc,
David Brown84b49f72019-03-01 10:58:22 -0700191 images: images,
David Browne5133242019-02-28 11:05:19 -0700192 total_count: None,
193 }
194 }
195
196 /// Build the Flash and area descriptor for a given device.
David Brown76101572019-02-28 11:29:03 -0700197 pub fn make_device(device: DeviceName, align: u8, erased_val: u8) -> (SimMultiFlash, AreaDesc) {
David Browne5133242019-02-28 11:05:19 -0700198 match device {
199 DeviceName::Stm32f4 => {
200 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700201 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
202 64 * 1024,
203 128 * 1024, 128 * 1024, 128 * 1024],
204 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700205 let dev_id = 0;
206 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700207 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700208 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
209 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
210 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
211
David Brown76101572019-02-28 11:29:03 -0700212 let mut flash = SimMultiFlash::new();
213 flash.insert(dev_id, dev);
214 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700215 }
216 DeviceName::K64f => {
217 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700218 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700219
220 let dev_id = 0;
221 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700222 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700223 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
224 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
225 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
226
David Brown76101572019-02-28 11:29:03 -0700227 let mut flash = SimMultiFlash::new();
228 flash.insert(dev_id, dev);
229 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700230 }
231 DeviceName::K64fBig => {
232 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
233 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700234 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700235
236 let dev_id = 0;
237 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700238 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700239 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
240 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
241 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
242
David Brown76101572019-02-28 11:29:03 -0700243 let mut flash = SimMultiFlash::new();
244 flash.insert(dev_id, dev);
245 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700246 }
247 DeviceName::Nrf52840 => {
248 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
249 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700250 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700251
252 let dev_id = 0;
253 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700254 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700255 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
256 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
257 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
258
David Brown76101572019-02-28 11:29:03 -0700259 let mut flash = SimMultiFlash::new();
260 flash.insert(dev_id, dev);
261 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700262 }
263 DeviceName::Nrf52840SpiFlash => {
264 // Simulate nrf52840 with external SPI flash. The external SPI flash
265 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700266 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
267 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700268
269 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700270 areadesc.add_flash_sectors(0, &dev0);
271 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700272
273 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
274 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
275 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
276
David Brown76101572019-02-28 11:29:03 -0700277 let mut flash = SimMultiFlash::new();
278 flash.insert(0, dev0);
279 flash.insert(1, dev1);
280 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700281 }
David Brown2bff6472019-03-05 13:58:35 -0700282 DeviceName::K64fMulti => {
283 // NXP style flash, but larger, to support multiple images.
284 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
285
286 let dev_id = 0;
287 let mut areadesc = AreaDesc::new();
288 areadesc.add_flash_sectors(dev_id, &dev);
289 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
290 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
291 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
292 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
293 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
294
295 let mut flash = SimMultiFlash::new();
296 flash.insert(dev_id, dev);
297 (flash, areadesc)
298 }
David Browne5133242019-02-28 11:05:19 -0700299 }
300 }
301}
302
David Brown5c9e0f12019-01-09 16:34:33 -0700303impl Images {
304 /// A simple upgrade without forced failures.
305 ///
306 /// Returns the number of flash operations which can later be used to
307 /// inject failures at chosen steps.
Fabio Utziged4a5362019-07-30 12:43:23 -0300308 pub fn run_basic_upgrade(&self, permanent: bool) -> Result<i32, ()> {
309 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700310 info!("Total flash operation count={}", total_count);
311
David Brown84b49f72019-03-01 10:58:22 -0700312 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700313 warn!("Image mismatch after first boot");
314 Err(())
315 } else {
316 Ok(total_count)
317 }
318 }
319
David Brown5c9e0f12019-01-09 16:34:33 -0700320 pub fn run_basic_revert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700321 if Caps::OverwriteUpgrade.present() {
322 return false;
323 }
David Brown5c9e0f12019-01-09 16:34:33 -0700324
David Brown5c9e0f12019-01-09 16:34:33 -0700325 let mut fails = 0;
326
327 // FIXME: this test would also pass if no swap is ever performed???
328 if Caps::SwapUpgrade.present() {
329 for count in 2 .. 5 {
330 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700331 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700332 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700333 error!("Revert failure on count {}", count);
334 fails += 1;
335 }
336 }
337 }
338
339 fails > 0
340 }
341
342 pub fn run_perm_with_fails(&self) -> bool {
343 let mut fails = 0;
344 let total_flash_ops = self.total_count.unwrap();
345
346 // Let's try an image halfway through.
347 for i in 1 .. total_flash_ops {
348 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300349 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700350 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700351 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700352 warn!("FAIL at step {} of {}", i, total_flash_ops);
353 fails += 1;
354 }
355
David Brown84b49f72019-03-01 10:58:22 -0700356 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
357 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100358 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700359 fails += 1;
360 }
361
David Brown84b49f72019-03-01 10:58:22 -0700362 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
363 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100364 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700365 fails += 1;
366 }
367
368 if Caps::SwapUpgrade.present() {
David Brown84b49f72019-03-01 10:58:22 -0700369 if !self.verify_images(&flash, 1, 0) {
David Vincze2d736ad2019-02-18 11:50:22 +0100370 warn!("Secondary slot FAIL at step {} of {}",
371 i, total_flash_ops);
David Brown5c9e0f12019-01-09 16:34:33 -0700372 fails += 1;
373 }
374 }
375 }
376
377 if fails > 0 {
378 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
379 fails as f32 * 100.0 / total_flash_ops as f32);
380 }
381
382 fails > 0
383 }
384
David Brown5c9e0f12019-01-09 16:34:33 -0700385 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
386 let mut fails = 0;
387 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700388 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700389 info!("Random interruptions at reset points={:?}", total_counts);
390
David Brown84b49f72019-03-01 10:58:22 -0700391 let primary_slot_ok = self.verify_images(&flash, 0, 1);
David Vincze2d736ad2019-02-18 11:50:22 +0100392 let secondary_slot_ok = if Caps::SwapUpgrade.present() {
David Brown84b49f72019-03-01 10:58:22 -0700393 // TODO: This result is ignored.
394 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700395 } else {
396 true
397 };
David Vincze2d736ad2019-02-18 11:50:22 +0100398 if !primary_slot_ok || !secondary_slot_ok {
399 error!("Image mismatch after random interrupts: primary slot={} \
400 secondary slot={}",
401 if primary_slot_ok { "ok" } else { "fail" },
402 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700403 fails += 1;
404 }
David Brown84b49f72019-03-01 10:58:22 -0700405 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
406 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100407 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700408 fails += 1;
409 }
David Brown84b49f72019-03-01 10:58:22 -0700410 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
411 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100412 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700413 fails += 1;
414 }
415
416 if fails > 0 {
417 error!("Error testing perm upgrade with {} fails", total_fails);
418 }
419
420 fails > 0
421 }
422
David Brown5c9e0f12019-01-09 16:34:33 -0700423 pub fn run_revert_with_fails(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700424 if Caps::OverwriteUpgrade.present() {
425 return false;
426 }
David Brown5c9e0f12019-01-09 16:34:33 -0700427
David Brown5c9e0f12019-01-09 16:34:33 -0700428 let mut fails = 0;
429
430 if Caps::SwapUpgrade.present() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300431 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700432 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700433 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700434 error!("Revert failed at interruption {}", i);
435 fails += 1;
436 }
437 }
438 }
439
440 fails > 0
441 }
442
David Brown5c9e0f12019-01-09 16:34:33 -0700443 pub fn run_norevert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700444 if Caps::OverwriteUpgrade.present() {
445 return false;
446 }
David Brown5c9e0f12019-01-09 16:34:33 -0700447
David Brown76101572019-02-28 11:29:03 -0700448 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700449 let mut fails = 0;
450
451 info!("Try norevert");
452
453 // First do a normal upgrade...
David Brown76101572019-02-28 11:29:03 -0700454 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700455 if result != 0 {
456 warn!("Failed first boot");
457 fails += 1;
458 }
459
460 //FIXME: copy_done is written by boot_go, is it ok if no copy
461 // was ever done?
462
David Brown84b49f72019-03-01 10:58:22 -0700463 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100464 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700465 fails += 1;
466 }
David Brown84b49f72019-03-01 10:58:22 -0700467 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
468 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100469 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700470 fails += 1;
471 }
David Brown84b49f72019-03-01 10:58:22 -0700472 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
473 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100474 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700475 fails += 1;
476 }
477
David Vincze2d736ad2019-02-18 11:50:22 +0100478 // Marks image in the primary slot as permanent,
479 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700480 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700481
David Brown84b49f72019-03-01 10:58:22 -0700482 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
483 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100484 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700485 fails += 1;
486 }
487
David Brown76101572019-02-28 11:29:03 -0700488 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700489 if result != 0 {
490 warn!("Failed second boot");
491 fails += 1;
492 }
493
David Brown84b49f72019-03-01 10:58:22 -0700494 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
495 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100496 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700497 fails += 1;
498 }
David Brown84b49f72019-03-01 10:58:22 -0700499 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700500 warn!("Failed image verification");
501 fails += 1;
502 }
503
504 if fails > 0 {
505 error!("Error running upgrade without revert");
506 }
507
508 fails > 0
509 }
510
David Vincze2d736ad2019-02-18 11:50:22 +0100511 // Tests a new image written to the primary slot that already has magic and
512 // image_ok set while there is no image on the secondary slot, so no revert
513 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700514 pub fn run_norevert_newimage(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700515 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700516 let mut fails = 0;
517
518 info!("Try non-revert on imgtool generated image");
519
David Brown84b49f72019-03-01 10:58:22 -0700520 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700521
David Vincze2d736ad2019-02-18 11:50:22 +0100522 // This simulates writing an image created by imgtool to
523 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700524 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
525 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100526 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700527 fails += 1;
528 }
529
530 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700531 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700532 if result != 0 {
533 warn!("Failed first boot");
534 fails += 1;
535 }
536
537 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700538 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700539 warn!("Failed image verification");
540 fails += 1;
541 }
David Brown84b49f72019-03-01 10:58:22 -0700542 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
543 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100544 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700545 fails += 1;
546 }
David Brown84b49f72019-03-01 10:58:22 -0700547 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
548 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100549 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700550 fails += 1;
551 }
552
553 if fails > 0 {
554 error!("Expected a non revert with new image");
555 }
556
557 fails > 0
558 }
559
David Vincze2d736ad2019-02-18 11:50:22 +0100560 // Tests a new image written to the primary slot that already has magic and
561 // image_ok set while there is no image on the secondary slot, so no revert
562 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700563 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700564 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700565 let mut fails = 0;
566
567 info!("Try upgrade image with bad signature");
568
David Brown84b49f72019-03-01 10:58:22 -0700569 self.mark_upgrades(&mut flash, 0);
570 self.mark_permanent_upgrades(&mut flash, 0);
571 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700572
David Brown84b49f72019-03-01 10:58:22 -0700573 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
574 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100575 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700576 fails += 1;
577 }
578
579 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700580 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700581 if result != 0 {
582 warn!("Failed first boot");
583 fails += 1;
584 }
585
586 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700587 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700588 warn!("Failed image verification");
589 fails += 1;
590 }
David Brown84b49f72019-03-01 10:58:22 -0700591 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
592 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100593 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700594 fails += 1;
595 }
596
597 if fails > 0 {
598 error!("Expected an upgrade failure when image has bad signature");
599 }
600
601 fails > 0
602 }
603
David Brown5c9e0f12019-01-09 16:34:33 -0700604 fn trailer_sz(&self, align: usize) -> usize {
605 c::boot_trailer_sz(align as u8) as usize
606 }
607
608 // FIXME: could get status sz from bootloader
David Brown5c9e0f12019-01-09 16:34:33 -0700609 fn status_sz(&self, align: usize) -> usize {
David Brown9930a3e2019-01-11 12:28:26 -0700610 let bias = if Caps::EncRsa.present() || Caps::EncKw.present() {
611 32
612 } else {
613 0
614 };
David Brown5c9e0f12019-01-09 16:34:33 -0700615
Christopher Collinsa1c12042019-05-23 14:00:28 -0700616 self.trailer_sz(align) - (16 + 32 + bias)
David Brown5c9e0f12019-01-09 16:34:33 -0700617 }
618
619 /// This test runs a simple upgrade with no fails in the images, but
620 /// allowing for fails in the status area. This should run to the end
621 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700622 pub fn run_with_status_fails_complete(&self) -> bool {
David Vincze2d736ad2019-02-18 11:50:22 +0100623 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700624 return false;
625 }
626
David Brown76101572019-02-28 11:29:03 -0700627 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700628 let mut fails = 0;
629
630 info!("Try swap with status fails");
631
David Brown84b49f72019-03-01 10:58:22 -0700632 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700633 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700634
David Brown76101572019-02-28 11:29:03 -0700635 let (result, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown5c9e0f12019-01-09 16:34:33 -0700636 if result != 0 {
637 warn!("Failed!");
638 fails += 1;
639 }
640
641 // Failed writes to the marked "bad" region don't assert anymore.
642 // Any detected assert() is happening in another part of the code.
643 if asserts != 0 {
644 warn!("At least one assert() was called");
645 fails += 1;
646 }
647
David Brown84b49f72019-03-01 10:58:22 -0700648 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
649 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100650 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700651 fails += 1;
652 }
653
David Brown84b49f72019-03-01 10:58:22 -0700654 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700655 warn!("Failed image verification");
656 fails += 1;
657 }
658
David Vincze2d736ad2019-02-18 11:50:22 +0100659 info!("validate primary slot enabled; \
660 re-run of boot_go should just work");
David Brown76101572019-02-28 11:29:03 -0700661 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700662 if result != 0 {
663 warn!("Failed!");
664 fails += 1;
665 }
666
667 if fails > 0 {
668 error!("Error running upgrade with status write fails");
669 }
670
671 fails > 0
672 }
673
674 /// This test runs a simple upgrade with no fails in the images, but
675 /// allowing for fails in the status area. This should run to the end
676 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700677 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown85904a82019-01-11 13:45:12 -0700678 if Caps::OverwriteUpgrade.present() {
679 false
David Vincze2d736ad2019-02-18 11:50:22 +0100680 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700681
David Brown76101572019-02-28 11:29:03 -0700682 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700683 let mut fails = 0;
684 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700685
David Brown85904a82019-01-11 13:45:12 -0700686 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700687
David Brown85904a82019-01-11 13:45:12 -0700688 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700689
David Brown84b49f72019-03-01 10:58:22 -0700690 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700691 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700692
693 // Should not fail, writing to bad regions does not assert
David Brown76101572019-02-28 11:29:03 -0700694 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true);
David Brown85904a82019-01-11 13:45:12 -0700695 if asserts != 0 {
696 warn!("At least one assert() was called");
697 fails += 1;
698 }
699
David Brown76101572019-02-28 11:29:03 -0700700 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700701
702 info!("Resuming an interrupted swap operation");
David Brown76101572019-02-28 11:29:03 -0700703 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700704
705 // This might throw no asserts, for large sector devices, where
706 // a single failure writing is indistinguishable from no failure,
707 // or throw a single assert for small sector devices that fail
708 // multiple times...
709 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100710 warn!("Expected single assert validating the primary slot, \
711 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700712 fails += 1;
713 }
714
715 if fails > 0 {
716 error!("Error running upgrade with status write fails");
717 }
718
719 fails > 0
720 } else {
David Brown76101572019-02-28 11:29:03 -0700721 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700722 let mut fails = 0;
723
724 info!("Try interrupted swap with status fails");
725
David Brown84b49f72019-03-01 10:58:22 -0700726 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700727 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700728
729 // This is expected to fail while writing to bad regions...
David Brown76101572019-02-28 11:29:03 -0700730 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700731 if asserts == 0 {
732 warn!("No assert() detected");
733 fails += 1;
734 }
735
736 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700737 }
David Brown5c9e0f12019-01-09 16:34:33 -0700738 }
739
740 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -0700741 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -0700742 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -0700743 if Caps::OverwriteUpgrade.present() {
744 return;
745 }
746
David Brown84b49f72019-03-01 10:58:22 -0700747 // Set this for each image.
748 for image in &self.images {
749 let dev_id = &image.slots[slot].dev_id;
750 let dev = flash.get_mut(&dev_id).unwrap();
751 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -0700752 let off = &image.slots[slot].base_off;
753 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -0700754 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -0700755
David Brown84b49f72019-03-01 10:58:22 -0700756 // Mark the status area as a bad area
757 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
758 }
David Brown5c9e0f12019-01-09 16:34:33 -0700759 }
760
David Brown76101572019-02-28 11:29:03 -0700761 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +0100762 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700763 return;
764 }
765
David Brown84b49f72019-03-01 10:58:22 -0700766 for image in &self.images {
767 let dev_id = &image.slots[slot].dev_id;
768 let dev = flash.get_mut(&dev_id).unwrap();
769 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -0700770
David Brown84b49f72019-03-01 10:58:22 -0700771 // Disabling write verification the only assert triggered by
772 // boot_go should be checking for integrity of status bytes.
773 dev.set_verify_writes(false);
774 }
David Brown5c9e0f12019-01-09 16:34:33 -0700775 }
776
David Browndb505822019-03-01 10:04:20 -0700777 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
778 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -0300779 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -0700780 // Clone the flash to have a new copy.
781 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700782
Fabio Utziged4a5362019-07-30 12:43:23 -0300783 if permanent {
784 self.mark_permanent_upgrades(&mut flash, 1);
785 }
David Brown5c9e0f12019-01-09 16:34:33 -0700786
David Browndb505822019-03-01 10:04:20 -0700787 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -0700788
David Browndb505822019-03-01 10:04:20 -0700789 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
790 (-0x13579, _) => (true, stop.unwrap()),
791 (0, _) => (false, -counter),
792 (x, _) => panic!("Unknown return: {}", x),
793 };
David Brown5c9e0f12019-01-09 16:34:33 -0700794
David Browndb505822019-03-01 10:04:20 -0700795 counter = 0;
796 if first_interrupted {
797 // fl.dump();
798 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
799 (-0x13579, _) => panic!("Shouldn't stop again"),
800 (0, _) => (),
801 (x, _) => panic!("Unknown return: {}", x),
802 }
803 }
David Brown5c9e0f12019-01-09 16:34:33 -0700804
David Browndb505822019-03-01 10:04:20 -0700805 (flash, count - counter)
806 }
807
808 fn try_revert(&self, count: usize) -> SimMultiFlash {
809 let mut flash = self.flash.clone();
810
811 // fl.write_file("image0.bin").unwrap();
812 for i in 0 .. count {
813 info!("Running boot pass {}", i + 1);
814 assert_eq!(c::boot_go(&mut flash, &self.areadesc, None, false), (0, 0));
815 }
816 flash
817 }
818
819 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
820 let mut flash = self.flash.clone();
821 let mut fails = 0;
822
823 let mut counter = stop;
824 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
825 if x != -0x13579 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700826 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -0700827 fails += 1;
828 }
829
Fabio Utzig8af7f792019-07-30 12:40:01 -0300830 // In a multi-image setup, copy done might be set if any number of
831 // images was already successfully swapped.
832 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
833 warn!("copy_done should be unset");
834 fails += 1;
835 }
836
David Browndb505822019-03-01 10:04:20 -0700837 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
838 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700839 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -0700840 fails += 1;
841 }
842
David Brown84b49f72019-03-01 10:58:22 -0700843 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -0700844 warn!("Image in the primary slot before revert is invalid at stop={}",
845 stop);
846 fails += 1;
847 }
David Brown84b49f72019-03-01 10:58:22 -0700848 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -0700849 warn!("Image in the secondary slot before revert is invalid at stop={}",
850 stop);
851 fails += 1;
852 }
David Brown84b49f72019-03-01 10:58:22 -0700853 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
854 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -0700855 warn!("Mismatched trailer for the primary slot before revert");
856 fails += 1;
857 }
David Brown84b49f72019-03-01 10:58:22 -0700858 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
859 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -0700860 warn!("Mismatched trailer for the secondary slot before revert");
861 fails += 1;
862 }
863
864 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700865 let mut counter = stop;
866 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
867 if x != -0x13579 {
868 warn!("Should have stopped revert at interruption point");
869 fails += 1;
870 }
871
David Browndb505822019-03-01 10:04:20 -0700872 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
873 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700874 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -0700875 fails += 1;
876 }
877
David Brown84b49f72019-03-01 10:58:22 -0700878 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -0700879 warn!("Image in the primary slot after revert is invalid at stop={}",
880 stop);
881 fails += 1;
882 }
David Brown84b49f72019-03-01 10:58:22 -0700883 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -0700884 warn!("Image in the secondary slot after revert is invalid at stop={}",
885 stop);
886 fails += 1;
887 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700888
David Brown84b49f72019-03-01 10:58:22 -0700889 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
890 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700891 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -0700892 fails += 1;
893 }
David Brown84b49f72019-03-01 10:58:22 -0700894 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
895 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -0700896 warn!("Mismatched trailer for the secondary slot after revert");
897 fails += 1;
898 }
899
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700900 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
901 if x != 0 {
902 warn!("Should have finished 3rd boot");
903 fails += 1;
904 }
905
906 if !self.verify_images(&flash, 0, 0) {
907 warn!("Image in the primary slot is invalid on 1st boot after revert");
908 fails += 1;
909 }
910 if !self.verify_images(&flash, 1, 1) {
911 warn!("Image in the secondary slot is invalid on 1st boot after revert");
912 fails += 1;
913 }
914
David Browndb505822019-03-01 10:04:20 -0700915 fails > 0
916 }
917
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700918
David Browndb505822019-03-01 10:04:20 -0700919 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
920 let mut flash = self.flash.clone();
921
David Brown84b49f72019-03-01 10:58:22 -0700922 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -0700923
924 let mut rng = rand::thread_rng();
925 let mut resets = vec![0i32; count];
926 let mut remaining_ops = total_ops;
927 for i in 0 .. count {
928 let ops = Range::new(1, remaining_ops / 2);
929 let reset_counter = ops.ind_sample(&mut rng);
930 let mut counter = reset_counter;
931 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
932 (0, _) | (-0x13579, _) => (),
933 (x, _) => panic!("Unknown return: {}", x),
934 }
935 remaining_ops -= reset_counter;
936 resets[i] = reset_counter;
937 }
938
939 match c::boot_go(&mut flash, &self.areadesc, None, false) {
940 (-0x13579, _) => panic!("Should not be have been interrupted!"),
David Brown5c9e0f12019-01-09 16:34:33 -0700941 (0, _) => (),
942 (x, _) => panic!("Unknown return: {}", x),
943 }
David Brown5c9e0f12019-01-09 16:34:33 -0700944
David Browndb505822019-03-01 10:04:20 -0700945 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -0700946 }
David Brown84b49f72019-03-01 10:58:22 -0700947
948 /// Verify the image in the given flash device, the specified slot
949 /// against the expected image.
950 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
951 for image in &self.images {
David Brown3b090212019-07-30 15:59:28 -0600952 if !verify_image(flash, &image.slots[slot],
David Brown84b49f72019-03-01 10:58:22 -0700953 match against {
954 0 => &image.primaries,
955 1 => &image.upgrades,
956 _ => panic!("Invalid 'against'"),
957 }) {
958 return false;
959 }
960 }
961 true
962 }
963
Fabio Utzig8af7f792019-07-30 12:40:01 -0300964 /// Verify that at least one of the trailers of the images have the
965 /// specified values.
966 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
967 magic: Option<u8>, image_ok: Option<u8>,
968 copy_done: Option<u8>) -> bool {
969 for image in &self.images {
David Brown3b090212019-07-30 15:59:28 -0600970 if verify_trailer(flash, &image.slots[slot],
Fabio Utzig8af7f792019-07-30 12:40:01 -0300971 magic, image_ok, copy_done) {
972 return true;
973 }
974 }
975 false
976 }
977
David Brown84b49f72019-03-01 10:58:22 -0700978 /// Verify that the trailers of the images have the specified
979 /// values.
980 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
981 magic: Option<u8>, image_ok: Option<u8>,
982 copy_done: Option<u8>) -> bool {
983 for image in &self.images {
David Brown3b090212019-07-30 15:59:28 -0600984 if !verify_trailer(flash, &image.slots[slot],
David Brown84b49f72019-03-01 10:58:22 -0700985 magic, image_ok, copy_done) {
986 return false;
987 }
988 }
989 true
990 }
991
992 /// Mark each of the images for permanent upgrade.
993 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
994 for image in &self.images {
995 mark_permanent_upgrade(flash, &image.slots[slot]);
996 }
997 }
998
999 /// Mark each of the images for permanent upgrade.
1000 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1001 for image in &self.images {
1002 mark_upgrade(flash, &image.slots[slot]);
1003 }
1004 }
David Brown5c9e0f12019-01-09 16:34:33 -07001005}
1006
1007/// Show the flash layout.
1008#[allow(dead_code)]
1009fn show_flash(flash: &dyn Flash) {
1010 println!("---- Flash configuration ----");
1011 for sector in flash.sector_iter() {
1012 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1013 sector.num, sector.base, sector.size);
1014 }
1015 println!("");
1016}
1017
1018/// Install a "program" into the given image. This fakes the image header, or at least all of the
1019/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001020fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownca234692019-02-28 11:22:19 -07001021 bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001022 let offset = slot.base_off;
1023 let slot_len = slot.len;
1024 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001025
David Brown43643dd2019-01-11 15:43:28 -07001026 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001027
1028 const HDR_SIZE: usize = 32;
1029
1030 // Generate a boot header. Note that the size doesn't include the header.
1031 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001032 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -07001033 load_addr: 0,
1034 hdr_size: HDR_SIZE as u16,
1035 _pad1: 0,
1036 img_size: len as u32,
1037 flags: tlv.get_flags(),
1038 ver: ImageVersion {
1039 major: (offset / (128 * 1024)) as u8,
1040 minor: 0,
1041 revision: 1,
1042 build_num: offset as u32,
1043 },
1044 _pad2: 0,
1045 };
1046
1047 let mut b_header = [0; HDR_SIZE];
1048 b_header[..32].clone_from_slice(header.as_raw());
1049 assert_eq!(b_header.len(), HDR_SIZE);
1050
1051 tlv.add_bytes(&b_header);
1052
1053 // The core of the image itself is just pseudorandom data.
1054 let mut b_img = vec![0; len];
1055 splat(&mut b_img, offset);
1056
1057 // TLV signatures work over plain image
1058 tlv.add_bytes(&b_img);
1059
1060 // Generate encrypted images
1061 let flag = TlvFlags::ENCRYPTED as u32;
1062 let is_encrypted = (tlv.get_flags() & flag) == flag;
1063 let mut b_encimg = vec![];
1064 if is_encrypted {
1065 let key = GenericArray::from_slice(AES_SEC_KEY);
1066 let nonce = GenericArray::from_slice(&[0; 16]);
1067 let mut cipher = Aes128Ctr::new(&key, &nonce);
1068 b_encimg = b_img.clone();
1069 cipher.apply_keystream(&mut b_encimg);
1070 }
1071
1072 // Build the TLV itself.
1073 let mut b_tlv = if bad_sig {
1074 let good_sig = &mut tlv.make_tlv();
1075 vec![0; good_sig.len()]
1076 } else {
1077 tlv.make_tlv()
1078 };
1079
1080 // Pad the block to a flash alignment (8 bytes).
1081 while b_tlv.len() % 8 != 0 {
1082 //FIXME: should be erase_val?
1083 b_tlv.push(0xFF);
1084 }
1085
1086 let mut buf = vec![];
1087 buf.append(&mut b_header.to_vec());
1088 buf.append(&mut b_img);
1089 buf.append(&mut b_tlv.clone());
1090
1091 let mut encbuf = vec![];
1092 if is_encrypted {
1093 encbuf.append(&mut b_header.to_vec());
1094 encbuf.append(&mut b_encimg);
1095 encbuf.append(&mut b_tlv);
1096 }
1097
David Vincze2d736ad2019-02-18 11:50:22 +01001098 // Since images are always non-encrypted in the primary slot, we first write
1099 // an encrypted image, re-read to use for verification, erase + flash
1100 // un-encrypted. In the secondary slot the image is written un-encrypted,
1101 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001102
David Brown76101572019-02-28 11:29:03 -07001103 let dev = flash.get_mut(&dev_id).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001104
David Brown3b090212019-07-30 15:59:28 -06001105 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001106 let enc_copy: Option<Vec<u8>>;
1107
1108 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001109 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001110
1111 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001112 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001113
1114 enc_copy = Some(enc);
1115
David Brown76101572019-02-28 11:29:03 -07001116 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001117 } else {
1118 enc_copy = None;
1119 }
1120
David Brown76101572019-02-28 11:29:03 -07001121 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001122
1123 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001124 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001125
David Brownca234692019-02-28 11:22:19 -07001126 ImageData {
1127 plain: copy,
1128 cipher: enc_copy,
1129 }
David Brown5c9e0f12019-01-09 16:34:33 -07001130 } else {
1131
David Brown76101572019-02-28 11:29:03 -07001132 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001133
1134 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001135 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001136
1137 let enc_copy: Option<Vec<u8>>;
1138
1139 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001140 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001141
David Brown76101572019-02-28 11:29:03 -07001142 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001143
1144 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001145 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001146
1147 enc_copy = Some(enc);
1148 } else {
1149 enc_copy = None;
1150 }
1151
David Brownca234692019-02-28 11:22:19 -07001152 ImageData {
1153 plain: copy,
1154 cipher: enc_copy,
1155 }
David Brown5c9e0f12019-01-09 16:34:33 -07001156 }
David Brown5c9e0f12019-01-09 16:34:33 -07001157}
1158
David Brown5c9e0f12019-01-09 16:34:33 -07001159fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001160 if Caps::EcdsaP224.present() {
1161 panic!("Ecdsa P224 not supported in Simulator");
1162 }
David Brown5c9e0f12019-01-09 16:34:33 -07001163
David Brownb8882112019-01-11 14:04:11 -07001164 if Caps::EncKw.present() {
1165 if Caps::RSA2048.present() {
1166 TlvGen::new_rsa_kw()
1167 } else if Caps::EcdsaP256.present() {
1168 TlvGen::new_ecdsa_kw()
1169 } else {
1170 TlvGen::new_enc_kw()
1171 }
1172 } else if Caps::EncRsa.present() {
1173 if Caps::RSA2048.present() {
1174 TlvGen::new_sig_enc_rsa()
1175 } else {
1176 TlvGen::new_enc_rsa()
1177 }
1178 } else {
1179 // The non-encrypted configuration.
1180 if Caps::RSA2048.present() {
1181 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001182 } else if Caps::RSA3072.present() {
1183 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001184 } else if Caps::EcdsaP256.present() {
1185 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001186 } else if Caps::Ed25519.present() {
1187 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001188 } else {
1189 TlvGen::new_hash_only()
1190 }
1191 }
David Brown5c9e0f12019-01-09 16:34:33 -07001192}
1193
David Brownca234692019-02-28 11:22:19 -07001194impl ImageData {
1195 /// Find the image contents for the given slot. This assumes that slot 0
1196 /// is unencrypted, and slot 1 is encrypted.
1197 fn find(&self, slot: usize) -> &Vec<u8> {
1198 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present();
1199 match (encrypted, slot) {
1200 (false, _) => &self.plain,
1201 (true, 0) => &self.plain,
1202 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1203 _ => panic!("Invalid slot requested"),
1204 }
David Brown5c9e0f12019-01-09 16:34:33 -07001205 }
1206}
1207
David Brown5c9e0f12019-01-09 16:34:33 -07001208/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001209fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1210 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001211 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001212 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001213
1214 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001215 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001216 let dev = flash.get(&dev_id).unwrap();
1217 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001218
1219 if buf != &copy[..] {
1220 for i in 0 .. buf.len() {
1221 if buf[i] != copy[i] {
1222 info!("First failure for slot{} at {:#x} {:#x}!={:#x}",
David Brown3b090212019-07-30 15:59:28 -06001223 slot.index, offset + i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001224 break;
1225 }
1226 }
1227 false
1228 } else {
1229 true
1230 }
1231}
1232
David Brown3b090212019-07-30 15:59:28 -06001233fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001234 magic: Option<u8>, image_ok: Option<u8>,
1235 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001236 if Caps::OverwriteUpgrade.present() {
1237 return true;
1238 }
David Brown5c9e0f12019-01-09 16:34:33 -07001239
David Brown3b090212019-07-30 15:59:28 -06001240 let offset = slot.trailer_off + c::boot_max_align();
1241 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001242 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001243 let mut failed = false;
1244
David Brown76101572019-02-28 11:29:03 -07001245 let dev = flash.get(&dev_id).unwrap();
1246 let erased_val = dev.erased_val();
1247 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001248
1249 failed |= match magic {
1250 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001251 if v == 1 && &copy[24..] != MAGIC.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -07001252 warn!("\"magic\" mismatch at {:#x}", offset);
1253 true
1254 } else if v == 3 {
1255 let expected = [erased_val; 16];
Christopher Collinsa1c12042019-05-23 14:00:28 -07001256 if &copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001257 warn!("\"magic\" mismatch at {:#x}", offset);
1258 true
1259 } else {
1260 false
1261 }
1262 } else {
1263 false
1264 }
1265 },
1266 None => false,
1267 };
1268
1269 failed |= match image_ok {
1270 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001271 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001272 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1273 true
1274 } else {
1275 false
1276 }
1277 },
1278 None => false,
1279 };
1280
1281 failed |= match copy_done {
1282 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001283 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001284 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1285 true
1286 } else {
1287 false
1288 }
1289 },
1290 None => false,
1291 };
1292
1293 !failed
1294}
1295
1296/// The image header
1297#[repr(C)]
1298pub struct ImageHeader {
1299 magic: u32,
1300 load_addr: u32,
1301 hdr_size: u16,
1302 _pad1: u16,
1303 img_size: u32,
1304 flags: u32,
1305 ver: ImageVersion,
1306 _pad2: u32,
1307}
1308
1309impl AsRaw for ImageHeader {}
1310
1311#[repr(C)]
1312pub struct ImageVersion {
1313 major: u8,
1314 minor: u8,
1315 revision: u16,
1316 build_num: u32,
1317}
1318
1319#[derive(Clone)]
1320pub struct SlotInfo {
1321 pub base_off: usize,
1322 pub trailer_off: usize,
1323 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001324 // Which slot within this device.
1325 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001326 pub dev_id: u8,
1327}
1328
David Brown5c9e0f12019-01-09 16:34:33 -07001329const MAGIC: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3,
1330 0x60, 0xd2, 0xef, 0x7f,
1331 0x35, 0x52, 0x50, 0x0f,
1332 0x2c, 0xb6, 0x79, 0x80]);
1333
1334// Replicates defines found in bootutil.h
1335const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1336const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1337
1338const BOOT_FLAG_SET: Option<u8> = Some(1);
1339const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1340
1341/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001342pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1343 let dev = flash.get_mut(&slot.dev_id).unwrap();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001344 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown76101572019-02-28 11:29:03 -07001345 dev.write(offset, MAGIC.unwrap()).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001346}
1347
1348/// Writes the image_ok flag which, guess what, tells the bootloader
1349/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001350fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1351 let dev = flash.get_mut(&slot.dev_id).unwrap();
1352 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001353 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001354 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001355 let align = dev.align();
1356 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001357}
1358
1359// Drop some pseudo-random gibberish onto the data.
1360fn splat(data: &mut [u8], seed: usize) {
1361 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
1362 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
1363 rng.fill_bytes(data);
1364}
1365
1366/// Return a read-only view into the raw bytes of this object
1367trait AsRaw : Sized {
1368 fn as_raw<'a>(&'a self) -> &'a [u8] {
1369 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1370 mem::size_of::<Self>()) }
1371 }
1372}
1373
1374pub fn show_sizes() {
1375 // This isn't panic safe.
1376 for min in &[1, 2, 4, 8] {
1377 let msize = c::boot_trailer_sz(*min);
1378 println!("{:2}: {} (0x{:x})", min, msize, msize);
1379 }
1380}