blob: 92b052e0daa10cc9d6fe0379444ae37eaa362c42 [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
David Brown06ef06e2019-03-05 12:28:10 -070096 // NOTE: not accounting "swap_size" because it is not used by sim...
97 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 2;
David Browne5133242019-02-28 11:05:19 -070098
David Brown06ef06e2019-03-05 12:28:10 -070099 // Construct a primary image.
100 let primary = SlotInfo {
101 base_off: primary_base as usize,
102 trailer_off: primary_base + primary_len - offset_from_end,
103 len: primary_len as usize,
104 dev_id: primary_dev_id,
105 };
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,
113 };
114
115 slots.push([primary, secondary]);
116 }
David Browne5133242019-02-28 11:05:19 -0700117
David Brown5bc62c62019-03-05 12:11:48 -0700118 Some(ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -0700119 flash: flash,
David Browne5133242019-02-28 11:05:19 -0700120 areadesc: areadesc,
David Brown06ef06e2019-03-05 12:28:10 -0700121 slots: slots,
David Brown5bc62c62019-03-05 12:11:48 -0700122 })
David Browne5133242019-02-28 11:05:19 -0700123 }
124
125 pub fn each_device<F>(f: F)
126 where F: Fn(Self)
127 {
128 for &dev in ALL_DEVICES {
129 for &align in &[1, 2, 4, 8] {
130 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700131 match Self::new(dev, align, erased_val) {
132 Some(run) => f(run),
133 None => warn!("Skipping {:?}, insufficient partitions", dev),
134 }
David Browne5133242019-02-28 11:05:19 -0700135 }
136 }
137 }
138 }
139
140 /// Construct an `Images` that doesn't expect an upgrade to happen.
141 pub fn make_no_upgrade_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700142 let mut flash = self.flash;
David Brown84b49f72019-03-01 10:58:22 -0700143 let images = self.slots.into_iter().map(|slots| {
144 let primaries = install_image(&mut flash, &slots, 0, 32784, false);
145 let upgrades = install_image(&mut flash, &slots, 1, 41928, false);
146 OneImage {
147 slots: slots,
148 primaries: primaries,
149 upgrades: upgrades,
150 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700151 Images {
David Brown76101572019-02-28 11:29:03 -0700152 flash: flash,
David Browne5133242019-02-28 11:05:19 -0700153 areadesc: self.areadesc,
David Brown84b49f72019-03-01 10:58:22 -0700154 images: images,
David Browne5133242019-02-28 11:05:19 -0700155 total_count: None,
156 }
157 }
158
159 /// Construct an `Images` for normal testing.
160 pub fn make_image(self) -> Images {
161 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
167 let total_count = match images.run_basic_upgrade() {
168 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| {
181 let primaries = install_image(&mut bad_flash, &slots, 0, 32784, false);
182 let upgrades = install_image(&mut bad_flash, &slots, 1, 41928, true);
183 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.
308 pub fn run_basic_upgrade(&self) -> Result<i32, ()> {
David Browndb505822019-03-01 10:04:20 -0700309 let (flash, total_count) = self.try_upgrade(None);
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);
David Browndb505822019-03-01 10:04:20 -0700349 let (flash, count) = self.try_upgrade(Some(i));
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
385 pub fn run_perm_with_random_fails_5(&self) -> bool {
386 self.run_perm_with_random_fails(5)
387 }
388
389 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
390 let mut fails = 0;
391 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700392 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700393 info!("Random interruptions at reset points={:?}", total_counts);
394
David Brown84b49f72019-03-01 10:58:22 -0700395 let primary_slot_ok = self.verify_images(&flash, 0, 1);
David Vincze2d736ad2019-02-18 11:50:22 +0100396 let secondary_slot_ok = if Caps::SwapUpgrade.present() {
David Brown84b49f72019-03-01 10:58:22 -0700397 // TODO: This result is ignored.
398 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700399 } else {
400 true
401 };
David Vincze2d736ad2019-02-18 11:50:22 +0100402 if !primary_slot_ok || !secondary_slot_ok {
403 error!("Image mismatch after random interrupts: primary slot={} \
404 secondary slot={}",
405 if primary_slot_ok { "ok" } else { "fail" },
406 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700407 fails += 1;
408 }
David Brown84b49f72019-03-01 10:58:22 -0700409 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
410 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100411 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700412 fails += 1;
413 }
David Brown84b49f72019-03-01 10:58:22 -0700414 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
415 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100416 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700417 fails += 1;
418 }
419
420 if fails > 0 {
421 error!("Error testing perm upgrade with {} fails", total_fails);
422 }
423
424 fails > 0
425 }
426
David Brown5c9e0f12019-01-09 16:34:33 -0700427 pub fn run_revert_with_fails(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700428 if Caps::OverwriteUpgrade.present() {
429 return false;
430 }
David Brown5c9e0f12019-01-09 16:34:33 -0700431
David Brown5c9e0f12019-01-09 16:34:33 -0700432 let mut fails = 0;
433
434 if Caps::SwapUpgrade.present() {
435 for i in 1 .. (self.total_count.unwrap() - 1) {
436 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700437 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700438 error!("Revert failed at interruption {}", i);
439 fails += 1;
440 }
441 }
442 }
443
444 fails > 0
445 }
446
David Brown5c9e0f12019-01-09 16:34:33 -0700447 pub fn run_norevert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700448 if Caps::OverwriteUpgrade.present() {
449 return false;
450 }
David Brown5c9e0f12019-01-09 16:34:33 -0700451
David Brown76101572019-02-28 11:29:03 -0700452 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700453 let mut fails = 0;
454
455 info!("Try norevert");
456
457 // First do a normal upgrade...
David Brown76101572019-02-28 11:29:03 -0700458 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700459 if result != 0 {
460 warn!("Failed first boot");
461 fails += 1;
462 }
463
464 //FIXME: copy_done is written by boot_go, is it ok if no copy
465 // was ever done?
466
David Brown84b49f72019-03-01 10:58:22 -0700467 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100468 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700469 fails += 1;
470 }
David Brown84b49f72019-03-01 10:58:22 -0700471 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
472 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100473 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700474 fails += 1;
475 }
David Brown84b49f72019-03-01 10:58:22 -0700476 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
477 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100478 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700479 fails += 1;
480 }
481
David Vincze2d736ad2019-02-18 11:50:22 +0100482 // Marks image in the primary slot as permanent,
483 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700484 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700485
David Brown84b49f72019-03-01 10:58:22 -0700486 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
487 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100488 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700489 fails += 1;
490 }
491
David Brown76101572019-02-28 11:29:03 -0700492 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700493 if result != 0 {
494 warn!("Failed second boot");
495 fails += 1;
496 }
497
David Brown84b49f72019-03-01 10:58:22 -0700498 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
499 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100500 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700501 fails += 1;
502 }
David Brown84b49f72019-03-01 10:58:22 -0700503 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700504 warn!("Failed image verification");
505 fails += 1;
506 }
507
508 if fails > 0 {
509 error!("Error running upgrade without revert");
510 }
511
512 fails > 0
513 }
514
David Vincze2d736ad2019-02-18 11:50:22 +0100515 // Tests a new image written to the primary slot that already has magic and
516 // image_ok set while there is no image on the secondary slot, so no revert
517 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700518 pub fn run_norevert_newimage(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700519 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700520 let mut fails = 0;
521
522 info!("Try non-revert on imgtool generated image");
523
David Brown84b49f72019-03-01 10:58:22 -0700524 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700525
David Vincze2d736ad2019-02-18 11:50:22 +0100526 // This simulates writing an image created by imgtool to
527 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700528 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
529 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100530 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700531 fails += 1;
532 }
533
534 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700535 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700536 if result != 0 {
537 warn!("Failed first boot");
538 fails += 1;
539 }
540
541 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700542 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700543 warn!("Failed image verification");
544 fails += 1;
545 }
David Brown84b49f72019-03-01 10:58:22 -0700546 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
547 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100548 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700549 fails += 1;
550 }
David Brown84b49f72019-03-01 10:58:22 -0700551 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
552 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100553 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700554 fails += 1;
555 }
556
557 if fails > 0 {
558 error!("Expected a non revert with new image");
559 }
560
561 fails > 0
562 }
563
David Vincze2d736ad2019-02-18 11:50:22 +0100564 // Tests a new image written to the primary slot that already has magic and
565 // image_ok set while there is no image on the secondary slot, so no revert
566 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700567 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700568 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700569 let mut fails = 0;
570
571 info!("Try upgrade image with bad signature");
572
David Brown84b49f72019-03-01 10:58:22 -0700573 self.mark_upgrades(&mut flash, 0);
574 self.mark_permanent_upgrades(&mut flash, 0);
575 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700576
David Brown84b49f72019-03-01 10:58:22 -0700577 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
578 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100579 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700580 fails += 1;
581 }
582
583 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700584 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700585 if result != 0 {
586 warn!("Failed first boot");
587 fails += 1;
588 }
589
590 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700591 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700592 warn!("Failed image verification");
593 fails += 1;
594 }
David Brown84b49f72019-03-01 10:58:22 -0700595 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
596 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100597 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700598 fails += 1;
599 }
600
601 if fails > 0 {
602 error!("Expected an upgrade failure when image has bad signature");
603 }
604
605 fails > 0
606 }
607
David Brown5c9e0f12019-01-09 16:34:33 -0700608 fn trailer_sz(&self, align: usize) -> usize {
609 c::boot_trailer_sz(align as u8) as usize
610 }
611
612 // FIXME: could get status sz from bootloader
David Brown5c9e0f12019-01-09 16:34:33 -0700613 fn status_sz(&self, align: usize) -> usize {
David Brown9930a3e2019-01-11 12:28:26 -0700614 let bias = if Caps::EncRsa.present() || Caps::EncKw.present() {
615 32
616 } else {
617 0
618 };
David Brown5c9e0f12019-01-09 16:34:33 -0700619
David Brown9930a3e2019-01-11 12:28:26 -0700620 self.trailer_sz(align) - (16 + 24 + bias)
David Brown5c9e0f12019-01-09 16:34:33 -0700621 }
622
623 /// This test runs a simple upgrade with no fails in the images, but
624 /// allowing for fails in the status area. This should run to the end
625 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700626 pub fn run_with_status_fails_complete(&self) -> bool {
David Vincze2d736ad2019-02-18 11:50:22 +0100627 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700628 return false;
629 }
630
David Brown76101572019-02-28 11:29:03 -0700631 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700632 let mut fails = 0;
633
634 info!("Try swap with status fails");
635
David Brown84b49f72019-03-01 10:58:22 -0700636 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700637 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700638
David Brown76101572019-02-28 11:29:03 -0700639 let (result, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown5c9e0f12019-01-09 16:34:33 -0700640 if result != 0 {
641 warn!("Failed!");
642 fails += 1;
643 }
644
645 // Failed writes to the marked "bad" region don't assert anymore.
646 // Any detected assert() is happening in another part of the code.
647 if asserts != 0 {
648 warn!("At least one assert() was called");
649 fails += 1;
650 }
651
David Brown84b49f72019-03-01 10:58:22 -0700652 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
653 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100654 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700655 fails += 1;
656 }
657
David Brown84b49f72019-03-01 10:58:22 -0700658 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700659 warn!("Failed image verification");
660 fails += 1;
661 }
662
David Vincze2d736ad2019-02-18 11:50:22 +0100663 info!("validate primary slot enabled; \
664 re-run of boot_go should just work");
David Brown76101572019-02-28 11:29:03 -0700665 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700666 if result != 0 {
667 warn!("Failed!");
668 fails += 1;
669 }
670
671 if fails > 0 {
672 error!("Error running upgrade with status write fails");
673 }
674
675 fails > 0
676 }
677
678 /// This test runs a simple upgrade with no fails in the images, but
679 /// allowing for fails in the status area. This should run to the end
680 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700681 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown85904a82019-01-11 13:45:12 -0700682 if Caps::OverwriteUpgrade.present() {
683 false
David Vincze2d736ad2019-02-18 11:50:22 +0100684 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700685
David Brown76101572019-02-28 11:29:03 -0700686 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700687 let mut fails = 0;
688 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700689
David Brown85904a82019-01-11 13:45:12 -0700690 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700691
David Brown85904a82019-01-11 13:45:12 -0700692 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700693
David Brown84b49f72019-03-01 10:58:22 -0700694 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700695 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700696
697 // Should not fail, writing to bad regions does not assert
David Brown76101572019-02-28 11:29:03 -0700698 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true);
David Brown85904a82019-01-11 13:45:12 -0700699 if asserts != 0 {
700 warn!("At least one assert() was called");
701 fails += 1;
702 }
703
David Brown76101572019-02-28 11:29:03 -0700704 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700705
706 info!("Resuming an interrupted swap operation");
David Brown76101572019-02-28 11:29:03 -0700707 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700708
709 // This might throw no asserts, for large sector devices, where
710 // a single failure writing is indistinguishable from no failure,
711 // or throw a single assert for small sector devices that fail
712 // multiple times...
713 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100714 warn!("Expected single assert validating the primary slot, \
715 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700716 fails += 1;
717 }
718
719 if fails > 0 {
720 error!("Error running upgrade with status write fails");
721 }
722
723 fails > 0
724 } else {
David Brown76101572019-02-28 11:29:03 -0700725 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700726 let mut fails = 0;
727
728 info!("Try interrupted swap with status fails");
729
David Brown84b49f72019-03-01 10:58:22 -0700730 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700731 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700732
733 // This is expected to fail while writing to bad regions...
David Brown76101572019-02-28 11:29:03 -0700734 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700735 if asserts == 0 {
736 warn!("No assert() detected");
737 fails += 1;
738 }
739
740 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700741 }
David Brown5c9e0f12019-01-09 16:34:33 -0700742 }
743
744 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -0700745 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -0700746 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -0700747 if Caps::OverwriteUpgrade.present() {
748 return;
749 }
750
David Brown84b49f72019-03-01 10:58:22 -0700751 // Set this for each image.
752 for image in &self.images {
753 let dev_id = &image.slots[slot].dev_id;
754 let dev = flash.get_mut(&dev_id).unwrap();
755 let align = dev.align();
756 let off = &image.slots[0].base_off;
757 let len = &image.slots[0].len;
758 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -0700759
David Brown84b49f72019-03-01 10:58:22 -0700760 // Mark the status area as a bad area
761 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
762 }
David Brown5c9e0f12019-01-09 16:34:33 -0700763 }
764
David Brown76101572019-02-28 11:29:03 -0700765 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +0100766 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700767 return;
768 }
769
David Brown84b49f72019-03-01 10:58:22 -0700770 for image in &self.images {
771 let dev_id = &image.slots[slot].dev_id;
772 let dev = flash.get_mut(&dev_id).unwrap();
773 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -0700774
David Brown84b49f72019-03-01 10:58:22 -0700775 // Disabling write verification the only assert triggered by
776 // boot_go should be checking for integrity of status bytes.
777 dev.set_verify_writes(false);
778 }
David Brown5c9e0f12019-01-09 16:34:33 -0700779 }
780
David Browndb505822019-03-01 10:04:20 -0700781 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
782 /// of the number of flash operations done total.
783 fn try_upgrade(&self, stop: Option<i32>) -> (SimMultiFlash, i32) {
784 // Clone the flash to have a new copy.
785 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700786
David Brown84b49f72019-03-01 10:58:22 -0700787 self.mark_permanent_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700788
David Browndb505822019-03-01 10:04:20 -0700789 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -0700790
David Browndb505822019-03-01 10:04:20 -0700791 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
792 (-0x13579, _) => (true, stop.unwrap()),
793 (0, _) => (false, -counter),
794 (x, _) => panic!("Unknown return: {}", x),
795 };
David Brown5c9e0f12019-01-09 16:34:33 -0700796
David Browndb505822019-03-01 10:04:20 -0700797 counter = 0;
798 if first_interrupted {
799 // fl.dump();
800 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
801 (-0x13579, _) => panic!("Shouldn't stop again"),
802 (0, _) => (),
803 (x, _) => panic!("Unknown return: {}", x),
804 }
805 }
David Brown5c9e0f12019-01-09 16:34:33 -0700806
David Browndb505822019-03-01 10:04:20 -0700807 (flash, count - counter)
808 }
809
810 fn try_revert(&self, count: usize) -> SimMultiFlash {
811 let mut flash = self.flash.clone();
812
813 // fl.write_file("image0.bin").unwrap();
814 for i in 0 .. count {
815 info!("Running boot pass {}", i + 1);
816 assert_eq!(c::boot_go(&mut flash, &self.areadesc, None, false), (0, 0));
817 }
818 flash
819 }
820
821 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
822 let mut flash = self.flash.clone();
823 let mut fails = 0;
824
825 let mut counter = stop;
826 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
827 if x != -0x13579 {
828 warn!("Should have stopped at interruption point");
829 fails += 1;
830 }
831
David Brown84b49f72019-03-01 10:58:22 -0700832 if !self.verify_trailers(&flash, 0, None, None, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -0700833 warn!("copy_done should be unset");
834 fails += 1;
835 }
836
837 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
838 if x != 0 {
839 warn!("Should have finished upgrade");
840 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
865 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
866 if x != 0 {
867 warn!("Should have finished a revert");
868 fails += 1;
869 }
870
David Brown84b49f72019-03-01 10:58:22 -0700871 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -0700872 warn!("Image in the primary slot after revert is invalid at stop={}",
873 stop);
874 fails += 1;
875 }
David Brown84b49f72019-03-01 10:58:22 -0700876 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -0700877 warn!("Image in the secondary slot after revert is invalid at stop={}",
878 stop);
879 fails += 1;
880 }
David Brown84b49f72019-03-01 10:58:22 -0700881 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
882 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -0700883 warn!("Mismatched trailer for the secondary slot after revert");
884 fails += 1;
885 }
David Brown84b49f72019-03-01 10:58:22 -0700886 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
887 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -0700888 warn!("Mismatched trailer for the secondary slot after revert");
889 fails += 1;
890 }
891
892 fails > 0
893 }
894
895 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
896 let mut flash = self.flash.clone();
897
David Brown84b49f72019-03-01 10:58:22 -0700898 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -0700899
900 let mut rng = rand::thread_rng();
901 let mut resets = vec![0i32; count];
902 let mut remaining_ops = total_ops;
903 for i in 0 .. count {
904 let ops = Range::new(1, remaining_ops / 2);
905 let reset_counter = ops.ind_sample(&mut rng);
906 let mut counter = reset_counter;
907 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
908 (0, _) | (-0x13579, _) => (),
909 (x, _) => panic!("Unknown return: {}", x),
910 }
911 remaining_ops -= reset_counter;
912 resets[i] = reset_counter;
913 }
914
915 match c::boot_go(&mut flash, &self.areadesc, None, false) {
916 (-0x13579, _) => panic!("Should not be have been interrupted!"),
David Brown5c9e0f12019-01-09 16:34:33 -0700917 (0, _) => (),
918 (x, _) => panic!("Unknown return: {}", x),
919 }
David Brown5c9e0f12019-01-09 16:34:33 -0700920
David Browndb505822019-03-01 10:04:20 -0700921 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -0700922 }
David Brown84b49f72019-03-01 10:58:22 -0700923
924 /// Verify the image in the given flash device, the specified slot
925 /// against the expected image.
926 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
927 for image in &self.images {
928 if !verify_image(flash, &image.slots, slot,
929 match against {
930 0 => &image.primaries,
931 1 => &image.upgrades,
932 _ => panic!("Invalid 'against'"),
933 }) {
934 return false;
935 }
936 }
937 true
938 }
939
940 /// Verify that the trailers of the images have the specified
941 /// values.
942 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
943 magic: Option<u8>, image_ok: Option<u8>,
944 copy_done: Option<u8>) -> bool {
945 for image in &self.images {
946 if !verify_trailer(flash, &image.slots, slot,
947 magic, image_ok, copy_done) {
948 return false;
949 }
950 }
951 true
952 }
953
954 /// Mark each of the images for permanent upgrade.
955 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
956 for image in &self.images {
957 mark_permanent_upgrade(flash, &image.slots[slot]);
958 }
959 }
960
961 /// Mark each of the images for permanent upgrade.
962 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
963 for image in &self.images {
964 mark_upgrade(flash, &image.slots[slot]);
965 }
966 }
David Brown5c9e0f12019-01-09 16:34:33 -0700967}
968
969/// Show the flash layout.
970#[allow(dead_code)]
971fn show_flash(flash: &dyn Flash) {
972 println!("---- Flash configuration ----");
973 for sector in flash.sector_iter() {
974 println!(" {:3}: 0x{:08x}, 0x{:08x}",
975 sector.num, sector.base, sector.size);
976 }
977 println!("");
978}
979
980/// Install a "program" into the given image. This fakes the image header, or at least all of the
981/// fields used by the given code. Returns a copy of the image that was written.
David Brown76101572019-02-28 11:29:03 -0700982fn install_image(flash: &mut SimMultiFlash, slots: &[SlotInfo], slot: usize, len: usize,
David Brownca234692019-02-28 11:22:19 -0700983 bad_sig: bool) -> ImageData {
David Brown5c9e0f12019-01-09 16:34:33 -0700984 let offset = slots[slot].base_off;
985 let slot_len = slots[slot].len;
986 let dev_id = slots[slot].dev_id;
987
David Brown43643dd2019-01-11 15:43:28 -0700988 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -0700989
990 const HDR_SIZE: usize = 32;
991
992 // Generate a boot header. Note that the size doesn't include the header.
993 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -0700994 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -0700995 load_addr: 0,
996 hdr_size: HDR_SIZE as u16,
997 _pad1: 0,
998 img_size: len as u32,
999 flags: tlv.get_flags(),
1000 ver: ImageVersion {
1001 major: (offset / (128 * 1024)) as u8,
1002 minor: 0,
1003 revision: 1,
1004 build_num: offset as u32,
1005 },
1006 _pad2: 0,
1007 };
1008
1009 let mut b_header = [0; HDR_SIZE];
1010 b_header[..32].clone_from_slice(header.as_raw());
1011 assert_eq!(b_header.len(), HDR_SIZE);
1012
1013 tlv.add_bytes(&b_header);
1014
1015 // The core of the image itself is just pseudorandom data.
1016 let mut b_img = vec![0; len];
1017 splat(&mut b_img, offset);
1018
1019 // TLV signatures work over plain image
1020 tlv.add_bytes(&b_img);
1021
1022 // Generate encrypted images
1023 let flag = TlvFlags::ENCRYPTED as u32;
1024 let is_encrypted = (tlv.get_flags() & flag) == flag;
1025 let mut b_encimg = vec![];
1026 if is_encrypted {
1027 let key = GenericArray::from_slice(AES_SEC_KEY);
1028 let nonce = GenericArray::from_slice(&[0; 16]);
1029 let mut cipher = Aes128Ctr::new(&key, &nonce);
1030 b_encimg = b_img.clone();
1031 cipher.apply_keystream(&mut b_encimg);
1032 }
1033
1034 // Build the TLV itself.
1035 let mut b_tlv = if bad_sig {
1036 let good_sig = &mut tlv.make_tlv();
1037 vec![0; good_sig.len()]
1038 } else {
1039 tlv.make_tlv()
1040 };
1041
1042 // Pad the block to a flash alignment (8 bytes).
1043 while b_tlv.len() % 8 != 0 {
1044 //FIXME: should be erase_val?
1045 b_tlv.push(0xFF);
1046 }
1047
1048 let mut buf = vec![];
1049 buf.append(&mut b_header.to_vec());
1050 buf.append(&mut b_img);
1051 buf.append(&mut b_tlv.clone());
1052
1053 let mut encbuf = vec![];
1054 if is_encrypted {
1055 encbuf.append(&mut b_header.to_vec());
1056 encbuf.append(&mut b_encimg);
1057 encbuf.append(&mut b_tlv);
1058 }
1059
David Vincze2d736ad2019-02-18 11:50:22 +01001060 // Since images are always non-encrypted in the primary slot, we first write
1061 // an encrypted image, re-read to use for verification, erase + flash
1062 // un-encrypted. In the secondary slot the image is written un-encrypted,
1063 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001064
David Brown76101572019-02-28 11:29:03 -07001065 let dev = flash.get_mut(&dev_id).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001066
1067 if slot == 0 {
1068 let enc_copy: Option<Vec<u8>>;
1069
1070 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001071 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001072
1073 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001074 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001075
1076 enc_copy = Some(enc);
1077
David Brown76101572019-02-28 11:29:03 -07001078 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001079 } else {
1080 enc_copy = None;
1081 }
1082
David Brown76101572019-02-28 11:29:03 -07001083 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001084
1085 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001086 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001087
David Brownca234692019-02-28 11:22:19 -07001088 ImageData {
1089 plain: copy,
1090 cipher: enc_copy,
1091 }
David Brown5c9e0f12019-01-09 16:34:33 -07001092 } else {
1093
David Brown76101572019-02-28 11:29:03 -07001094 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001095
1096 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001097 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001098
1099 let enc_copy: Option<Vec<u8>>;
1100
1101 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001102 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001103
David Brown76101572019-02-28 11:29:03 -07001104 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001105
1106 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001107 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001108
1109 enc_copy = Some(enc);
1110 } else {
1111 enc_copy = None;
1112 }
1113
David Brownca234692019-02-28 11:22:19 -07001114 ImageData {
1115 plain: copy,
1116 cipher: enc_copy,
1117 }
David Brown5c9e0f12019-01-09 16:34:33 -07001118 }
David Brown5c9e0f12019-01-09 16:34:33 -07001119}
1120
David Brown5c9e0f12019-01-09 16:34:33 -07001121fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001122 if Caps::EcdsaP224.present() {
1123 panic!("Ecdsa P224 not supported in Simulator");
1124 }
David Brown5c9e0f12019-01-09 16:34:33 -07001125
David Brownb8882112019-01-11 14:04:11 -07001126 if Caps::EncKw.present() {
1127 if Caps::RSA2048.present() {
1128 TlvGen::new_rsa_kw()
1129 } else if Caps::EcdsaP256.present() {
1130 TlvGen::new_ecdsa_kw()
1131 } else {
1132 TlvGen::new_enc_kw()
1133 }
1134 } else if Caps::EncRsa.present() {
1135 if Caps::RSA2048.present() {
1136 TlvGen::new_sig_enc_rsa()
1137 } else {
1138 TlvGen::new_enc_rsa()
1139 }
1140 } else {
1141 // The non-encrypted configuration.
1142 if Caps::RSA2048.present() {
1143 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001144 } else if Caps::RSA3072.present() {
1145 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001146 } else if Caps::EcdsaP256.present() {
1147 TlvGen::new_ecdsa()
1148 } else {
1149 TlvGen::new_hash_only()
1150 }
1151 }
David Brown5c9e0f12019-01-09 16:34:33 -07001152}
1153
David Brownca234692019-02-28 11:22:19 -07001154impl ImageData {
1155 /// Find the image contents for the given slot. This assumes that slot 0
1156 /// is unencrypted, and slot 1 is encrypted.
1157 fn find(&self, slot: usize) -> &Vec<u8> {
1158 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present();
1159 match (encrypted, slot) {
1160 (false, _) => &self.plain,
1161 (true, 0) => &self.plain,
1162 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1163 _ => panic!("Invalid slot requested"),
1164 }
David Brown5c9e0f12019-01-09 16:34:33 -07001165 }
1166}
1167
David Brown5c9e0f12019-01-09 16:34:33 -07001168/// Verify that given image is present in the flash at the given offset.
David Brown76101572019-02-28 11:29:03 -07001169fn verify_image(flash: &SimMultiFlash, slots: &[SlotInfo], slot: usize,
David Brownca234692019-02-28 11:22:19 -07001170 images: &ImageData) -> bool {
1171 let image = images.find(slot);
David Brown5c9e0f12019-01-09 16:34:33 -07001172 let buf = image.as_slice();
1173 let dev_id = slots[slot].dev_id;
1174
1175 let mut copy = vec![0u8; buf.len()];
1176 let offset = slots[slot].base_off;
David Brown76101572019-02-28 11:29:03 -07001177 let dev = flash.get(&dev_id).unwrap();
1178 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001179
1180 if buf != &copy[..] {
1181 for i in 0 .. buf.len() {
1182 if buf[i] != copy[i] {
1183 info!("First failure for slot{} at {:#x} {:#x}!={:#x}",
1184 slot, offset + i, buf[i], copy[i]);
1185 break;
1186 }
1187 }
1188 false
1189 } else {
1190 true
1191 }
1192}
1193
David Brown76101572019-02-28 11:29:03 -07001194fn verify_trailer(flash: &SimMultiFlash, slots: &[SlotInfo], slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001195 magic: Option<u8>, image_ok: Option<u8>,
1196 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001197 if Caps::OverwriteUpgrade.present() {
1198 return true;
1199 }
David Brown5c9e0f12019-01-09 16:34:33 -07001200
David Brown5c9e0f12019-01-09 16:34:33 -07001201 let offset = slots[slot].trailer_off;
1202 let dev_id = slots[slot].dev_id;
1203 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 2];
1204 let mut failed = false;
1205
David Brown76101572019-02-28 11:29:03 -07001206 let dev = flash.get(&dev_id).unwrap();
1207 let erased_val = dev.erased_val();
1208 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001209
1210 failed |= match magic {
1211 Some(v) => {
1212 if v == 1 && &copy[16..] != MAGIC.unwrap() {
1213 warn!("\"magic\" mismatch at {:#x}", offset);
1214 true
1215 } else if v == 3 {
1216 let expected = [erased_val; 16];
1217 if &copy[16..] != expected {
1218 warn!("\"magic\" mismatch at {:#x}", offset);
1219 true
1220 } else {
1221 false
1222 }
1223 } else {
1224 false
1225 }
1226 },
1227 None => false,
1228 };
1229
1230 failed |= match image_ok {
1231 Some(v) => {
1232 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
1233 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1234 true
1235 } else {
1236 false
1237 }
1238 },
1239 None => false,
1240 };
1241
1242 failed |= match copy_done {
1243 Some(v) => {
1244 if (v == 1 && copy[0] != v) || (v == 3 && copy[0] != erased_val) {
1245 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1246 true
1247 } else {
1248 false
1249 }
1250 },
1251 None => false,
1252 };
1253
1254 !failed
1255}
1256
1257/// The image header
1258#[repr(C)]
1259pub struct ImageHeader {
1260 magic: u32,
1261 load_addr: u32,
1262 hdr_size: u16,
1263 _pad1: u16,
1264 img_size: u32,
1265 flags: u32,
1266 ver: ImageVersion,
1267 _pad2: u32,
1268}
1269
1270impl AsRaw for ImageHeader {}
1271
1272#[repr(C)]
1273pub struct ImageVersion {
1274 major: u8,
1275 minor: u8,
1276 revision: u16,
1277 build_num: u32,
1278}
1279
1280#[derive(Clone)]
1281pub struct SlotInfo {
1282 pub base_off: usize,
1283 pub trailer_off: usize,
1284 pub len: usize,
1285 pub dev_id: u8,
1286}
1287
David Brown5c9e0f12019-01-09 16:34:33 -07001288const MAGIC: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3,
1289 0x60, 0xd2, 0xef, 0x7f,
1290 0x35, 0x52, 0x50, 0x0f,
1291 0x2c, 0xb6, 0x79, 0x80]);
1292
1293// Replicates defines found in bootutil.h
1294const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1295const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1296
1297const BOOT_FLAG_SET: Option<u8> = Some(1);
1298const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1299
1300/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001301pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1302 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001303 let offset = slot.trailer_off + c::boot_max_align() * 2;
David Brown76101572019-02-28 11:29:03 -07001304 dev.write(offset, MAGIC.unwrap()).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001305}
1306
1307/// Writes the image_ok flag which, guess what, tells the bootloader
1308/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001309fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1310 let dev = flash.get_mut(&slot.dev_id).unwrap();
1311 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001312 ok[0] = 1u8;
1313 let off = slot.trailer_off + c::boot_max_align();
David Brown76101572019-02-28 11:29:03 -07001314 let align = dev.align();
1315 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001316}
1317
1318// Drop some pseudo-random gibberish onto the data.
1319fn splat(data: &mut [u8], seed: usize) {
1320 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
1321 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
1322 rng.fill_bytes(data);
1323}
1324
1325/// Return a read-only view into the raw bytes of this object
1326trait AsRaw : Sized {
1327 fn as_raw<'a>(&'a self) -> &'a [u8] {
1328 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1329 mem::size_of::<Self>()) }
1330 }
1331}
1332
1333pub fn show_sizes() {
1334 // This isn't panic safe.
1335 for min in &[1, 2, 4, 8] {
1336 let msize = c::boot_trailer_sz(*min);
1337 println!("{:2}: {} (0x{:x})", min, msize, msize);
1338 }
1339}