blob: 82cd7297dfd5f4eac2bb7e7f1741dace5f866372 [file] [log] [blame]
David Brown297029a2019-08-13 14:29:51 -06001use byteorder::{
2 LittleEndian, WriteBytesExt,
3};
4use log::{
5 Level::Info,
6 error,
7 info,
8 log_enabled,
9 warn,
10};
David Brown5c9e0f12019-01-09 16:34:33 -070011use rand::{
12 distributions::{IndependentSample, Range},
13 Rng, SeedableRng, XorShiftRng,
14};
15use std::{
David Brown297029a2019-08-13 14:29:51 -060016 collections::HashSet,
David Browncb47dd72019-08-05 14:21:49 -060017 io::{Cursor, Write},
David Brown5c9e0f12019-01-09 16:34:33 -070018 mem,
19 slice,
20};
21use aes_ctr::{
22 Aes128Ctr,
23 stream_cipher::{
24 generic_array::GenericArray,
25 NewFixStreamCipher,
26 StreamCipherCore,
27 },
28};
29
David Brown76101572019-02-28 11:29:03 -070030use simflash::{Flash, SimFlash, SimMultiFlash};
David Browne5133242019-02-28 11:05:19 -070031use mcuboot_sys::{c, AreaDesc, FlashId};
32use crate::{
33 ALL_DEVICES,
34 DeviceName,
35};
David Brown5c9e0f12019-01-09 16:34:33 -070036use crate::caps::Caps;
David Brownc3898d62019-08-05 14:20:02 -060037use crate::depends::{
38 BoringDep,
39 Depender,
40 DepTest,
41 PairDep,
42 UpgradeInfo,
43};
David Brown43643dd2019-01-11 15:43:28 -070044use crate::tlv::{ManifestGen, TlvGen, TlvFlags, AES_SEC_KEY};
David Brown5c9e0f12019-01-09 16:34:33 -070045
David Browne5133242019-02-28 11:05:19 -070046/// A builder for Images. This describes a single run of the simulator,
47/// capturing the configuration of a particular set of devices, including
48/// the flash simulator(s) and the information about the slots.
49#[derive(Clone)]
50pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070051 flash: SimMultiFlash,
David Browne5133242019-02-28 11:05:19 -070052 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070053 slots: Vec<[SlotInfo; 2]>,
David Browne5133242019-02-28 11:05:19 -070054}
55
David Brown998aa8d2019-02-28 10:54:50 -070056/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070057/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070058/// and upgrades hold the expected contents of these images.
59pub struct Images {
David Brown76101572019-02-28 11:29:03 -070060 flash: SimMultiFlash,
David Brownca234692019-02-28 11:22:19 -070061 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070062 images: Vec<OneImage>,
63 total_count: Option<i32>,
64}
65
66/// When doing multi-image, there is an instance of this information for
67/// each of the images. Single image there will be one of these.
68struct OneImage {
David Brownca234692019-02-28 11:22:19 -070069 slots: [SlotInfo; 2],
70 primaries: ImageData,
71 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070072}
73
74/// The Rust-side representation of an image. For unencrypted images, this
75/// is just the unencrypted payload. For encrypted images, we store both
76/// the encrypted and the plaintext.
77struct ImageData {
78 plain: Vec<u8>,
79 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -070080}
81
David Browne5133242019-02-28 11:05:19 -070082impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -070083 /// Construct a new image builder for the given device. Returns
84 /// Some(builder) if is possible to test this configuration, or None if
85 /// not possible (for example, if there aren't enough image slots).
86 pub fn new(device: DeviceName, align: u8, erased_val: u8) -> Option<Self> {
David Brown76101572019-02-28 11:29:03 -070087 let (flash, areadesc) = Self::make_device(device, align, erased_val);
David Browne5133242019-02-28 11:05:19 -070088
David Brown06ef06e2019-03-05 12:28:10 -070089 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -070090
David Brown06ef06e2019-03-05 12:28:10 -070091 let mut slots = Vec::with_capacity(num_images);
92 for image in 0..num_images {
93 // This mapping must match that defined in
94 // `boot/zephyr/include/sysflash/sysflash.h`.
95 let id0 = match image {
96 0 => FlashId::Image0,
97 1 => FlashId::Image2,
98 _ => panic!("More than 2 images not supported"),
99 };
100 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
101 Some(info) => info,
102 None => return None,
103 };
104 let id1 = match image {
105 0 => FlashId::Image1,
106 1 => FlashId::Image3,
107 _ => panic!("More than 2 images not supported"),
108 };
109 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
110 Some(info) => info,
111 None => return None,
112 };
David Browne5133242019-02-28 11:05:19 -0700113
Christopher Collinsa1c12042019-05-23 14:00:28 -0700114 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700115
David Brown06ef06e2019-03-05 12:28:10 -0700116 // Construct a primary image.
117 let primary = SlotInfo {
118 base_off: primary_base as usize,
119 trailer_off: primary_base + primary_len - offset_from_end,
120 len: primary_len as usize,
121 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600122 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700123 };
124
125 // And an upgrade image.
126 let secondary = SlotInfo {
127 base_off: secondary_base as usize,
128 trailer_off: secondary_base + secondary_len - offset_from_end,
129 len: secondary_len as usize,
130 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600131 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700132 };
133
134 slots.push([primary, secondary]);
135 }
David Browne5133242019-02-28 11:05:19 -0700136
David Brown5bc62c62019-03-05 12:11:48 -0700137 Some(ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -0700138 flash: flash,
David Browne5133242019-02-28 11:05:19 -0700139 areadesc: areadesc,
David Brown06ef06e2019-03-05 12:28:10 -0700140 slots: slots,
David Brown5bc62c62019-03-05 12:11:48 -0700141 })
David Browne5133242019-02-28 11:05:19 -0700142 }
143
144 pub fn each_device<F>(f: F)
145 where F: Fn(Self)
146 {
147 for &dev in ALL_DEVICES {
148 for &align in &[1, 2, 4, 8] {
149 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700150 match Self::new(dev, align, erased_val) {
151 Some(run) => f(run),
152 None => warn!("Skipping {:?}, insufficient partitions", dev),
153 }
David Browne5133242019-02-28 11:05:19 -0700154 }
155 }
156 }
157 }
158
159 /// Construct an `Images` that doesn't expect an upgrade to happen.
David Brownc3898d62019-08-05 14:20:02 -0600160 pub fn make_no_upgrade_image(self, deps: &DepTest) -> Images {
161 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700162 let mut flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600163 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
164 let dep: Box<dyn Depender> = if num_images > 1 {
165 Box::new(PairDep::new(num_images, image_num, deps))
166 } else {
167 Box::new(BoringDep(image_num))
168 };
169 let primaries = install_image(&mut flash, &slots[0], 42784, &*dep, false);
170 let upgrades = install_image(&mut flash, &slots[1], 46928, &*dep, false);
David Brown84b49f72019-03-01 10:58:22 -0700171 OneImage {
172 slots: slots,
173 primaries: primaries,
174 upgrades: upgrades,
175 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600176 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700177 Images {
David Brown76101572019-02-28 11:29:03 -0700178 flash: flash,
David Browne5133242019-02-28 11:05:19 -0700179 areadesc: self.areadesc,
David Brown84b49f72019-03-01 10:58:22 -0700180 images: images,
David Browne5133242019-02-28 11:05:19 -0700181 total_count: None,
182 }
183 }
184
David Brownc3898d62019-08-05 14:20:02 -0600185 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
186 let mut images = self.make_no_upgrade_image(deps);
David Brown84b49f72019-03-01 10:58:22 -0700187 for image in &images.images {
188 mark_upgrade(&mut images.flash, &image.slots[1]);
189 }
David Browne5133242019-02-28 11:05:19 -0700190
191 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300192 let total_count = match images.run_basic_upgrade(permanent) {
David Browne5133242019-02-28 11:05:19 -0700193 Ok(v) => v,
Fabio Utzig7c1d1552019-08-28 10:59:22 -0300194 Err(_) =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600195 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
196 0
197 } else {
198 panic!("Unable to perform basic upgrade");
199 }
David Browne5133242019-02-28 11:05:19 -0700200 };
201
202 images.total_count = Some(total_count);
203 images
204 }
205
206 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700207 let mut bad_flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600208 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
209 let dep = BoringDep(image_num);
210 let primaries = install_image(&mut bad_flash, &slots[0], 32784, &dep, false);
211 let upgrades = install_image(&mut bad_flash, &slots[1], 41928, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700212 OneImage {
213 slots: slots,
214 primaries: primaries,
215 upgrades: upgrades,
216 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700217 Images {
David Brown76101572019-02-28 11:29:03 -0700218 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700219 areadesc: self.areadesc,
David Brown84b49f72019-03-01 10:58:22 -0700220 images: images,
David Browne5133242019-02-28 11:05:19 -0700221 total_count: None,
222 }
223 }
224
225 /// Build the Flash and area descriptor for a given device.
David Brown76101572019-02-28 11:29:03 -0700226 pub fn make_device(device: DeviceName, align: u8, erased_val: u8) -> (SimMultiFlash, AreaDesc) {
David Browne5133242019-02-28 11:05:19 -0700227 match device {
228 DeviceName::Stm32f4 => {
229 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700230 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
231 64 * 1024,
232 128 * 1024, 128 * 1024, 128 * 1024],
233 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700234 let dev_id = 0;
235 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700236 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700237 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
238 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
239 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
240
David Brown76101572019-02-28 11:29:03 -0700241 let mut flash = SimMultiFlash::new();
242 flash.insert(dev_id, dev);
243 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700244 }
245 DeviceName::K64f => {
246 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700247 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700248
249 let dev_id = 0;
250 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700251 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700252 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
253 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
254 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
255
David Brown76101572019-02-28 11:29:03 -0700256 let mut flash = SimMultiFlash::new();
257 flash.insert(dev_id, dev);
258 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700259 }
260 DeviceName::K64fBig => {
261 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
262 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700263 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700264
265 let dev_id = 0;
266 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700267 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700268 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
269 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
270 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
271
David Brown76101572019-02-28 11:29:03 -0700272 let mut flash = SimMultiFlash::new();
273 flash.insert(dev_id, dev);
274 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700275 }
276 DeviceName::Nrf52840 => {
277 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
278 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700279 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700280
281 let dev_id = 0;
282 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700283 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700284 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
285 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
286 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
287
David Brown76101572019-02-28 11:29:03 -0700288 let mut flash = SimMultiFlash::new();
289 flash.insert(dev_id, dev);
290 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700291 }
292 DeviceName::Nrf52840SpiFlash => {
293 // Simulate nrf52840 with external SPI flash. The external SPI flash
294 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700295 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
296 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700297
298 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700299 areadesc.add_flash_sectors(0, &dev0);
300 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700301
302 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
303 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
304 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
305
David Brown76101572019-02-28 11:29:03 -0700306 let mut flash = SimMultiFlash::new();
307 flash.insert(0, dev0);
308 flash.insert(1, dev1);
309 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700310 }
David Brown2bff6472019-03-05 13:58:35 -0700311 DeviceName::K64fMulti => {
312 // NXP style flash, but larger, to support multiple images.
313 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
314
315 let dev_id = 0;
316 let mut areadesc = AreaDesc::new();
317 areadesc.add_flash_sectors(dev_id, &dev);
318 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
319 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
320 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
321 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
322 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
323
324 let mut flash = SimMultiFlash::new();
325 flash.insert(dev_id, dev);
326 (flash, areadesc)
327 }
David Browne5133242019-02-28 11:05:19 -0700328 }
329 }
David Brownc3898d62019-08-05 14:20:02 -0600330
331 pub fn num_images(&self) -> usize {
332 self.slots.len()
333 }
David Browne5133242019-02-28 11:05:19 -0700334}
335
David Brown5c9e0f12019-01-09 16:34:33 -0700336impl Images {
337 /// A simple upgrade without forced failures.
338 ///
339 /// Returns the number of flash operations which can later be used to
340 /// inject failures at chosen steps.
Fabio Utziged4a5362019-07-30 12:43:23 -0300341 pub fn run_basic_upgrade(&self, permanent: bool) -> Result<i32, ()> {
342 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700343 info!("Total flash operation count={}", total_count);
344
David Brown84b49f72019-03-01 10:58:22 -0700345 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700346 warn!("Image mismatch after first boot");
347 Err(())
348 } else {
349 Ok(total_count)
350 }
351 }
352
David Brownc3898d62019-08-05 14:20:02 -0600353 /// Test a simple upgrade, with dependencies given, and verify that the
354 /// image does as is described in the test.
355 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
356 let (flash, _) = self.try_upgrade(None, true);
357
358 self.verify_dep_images(&flash, deps)
359 }
360
David Brown5c9e0f12019-01-09 16:34:33 -0700361 pub fn run_basic_revert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700362 if Caps::OverwriteUpgrade.present() {
363 return false;
364 }
David Brown5c9e0f12019-01-09 16:34:33 -0700365
David Brown5c9e0f12019-01-09 16:34:33 -0700366 let mut fails = 0;
367
368 // FIXME: this test would also pass if no swap is ever performed???
369 if Caps::SwapUpgrade.present() {
370 for count in 2 .. 5 {
371 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700372 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700373 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700374 error!("Revert failure on count {}", count);
375 fails += 1;
376 }
377 }
378 }
379
380 fails > 0
381 }
382
383 pub fn run_perm_with_fails(&self) -> bool {
384 let mut fails = 0;
385 let total_flash_ops = self.total_count.unwrap();
386
387 // Let's try an image halfway through.
388 for i in 1 .. total_flash_ops {
389 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300390 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700391 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700392 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700393 warn!("FAIL at step {} of {}", i, total_flash_ops);
394 fails += 1;
395 }
396
David Brown84b49f72019-03-01 10:58:22 -0700397 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
398 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100399 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700400 fails += 1;
401 }
402
David Brown84b49f72019-03-01 10:58:22 -0700403 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
404 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100405 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700406 fails += 1;
407 }
408
409 if Caps::SwapUpgrade.present() {
David Brown84b49f72019-03-01 10:58:22 -0700410 if !self.verify_images(&flash, 1, 0) {
David Vincze2d736ad2019-02-18 11:50:22 +0100411 warn!("Secondary slot FAIL at step {} of {}",
412 i, total_flash_ops);
David Brown5c9e0f12019-01-09 16:34:33 -0700413 fails += 1;
414 }
415 }
416 }
417
418 if fails > 0 {
419 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
420 fails as f32 * 100.0 / total_flash_ops as f32);
421 }
422
423 fails > 0
424 }
425
David Brown5c9e0f12019-01-09 16:34:33 -0700426 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
427 let mut fails = 0;
428 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700429 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700430 info!("Random interruptions at reset points={:?}", total_counts);
431
David Brown84b49f72019-03-01 10:58:22 -0700432 let primary_slot_ok = self.verify_images(&flash, 0, 1);
David Vincze2d736ad2019-02-18 11:50:22 +0100433 let secondary_slot_ok = if Caps::SwapUpgrade.present() {
David Brown84b49f72019-03-01 10:58:22 -0700434 // TODO: This result is ignored.
435 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700436 } else {
437 true
438 };
David Vincze2d736ad2019-02-18 11:50:22 +0100439 if !primary_slot_ok || !secondary_slot_ok {
440 error!("Image mismatch after random interrupts: primary slot={} \
441 secondary slot={}",
442 if primary_slot_ok { "ok" } else { "fail" },
443 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700444 fails += 1;
445 }
David Brown84b49f72019-03-01 10:58:22 -0700446 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
447 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100448 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700449 fails += 1;
450 }
David Brown84b49f72019-03-01 10:58:22 -0700451 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
452 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100453 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700454 fails += 1;
455 }
456
457 if fails > 0 {
458 error!("Error testing perm upgrade with {} fails", total_fails);
459 }
460
461 fails > 0
462 }
463
David Brown5c9e0f12019-01-09 16:34:33 -0700464 pub fn run_revert_with_fails(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700465 if Caps::OverwriteUpgrade.present() {
466 return false;
467 }
David Brown5c9e0f12019-01-09 16:34:33 -0700468
David Brown5c9e0f12019-01-09 16:34:33 -0700469 let mut fails = 0;
470
471 if Caps::SwapUpgrade.present() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300472 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700473 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700474 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700475 error!("Revert failed at interruption {}", i);
476 fails += 1;
477 }
478 }
479 }
480
481 fails > 0
482 }
483
David Brown5c9e0f12019-01-09 16:34:33 -0700484 pub fn run_norevert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700485 if Caps::OverwriteUpgrade.present() {
486 return false;
487 }
David Brown5c9e0f12019-01-09 16:34:33 -0700488
David Brown76101572019-02-28 11:29:03 -0700489 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700490 let mut fails = 0;
491
492 info!("Try norevert");
493
494 // First do a normal upgrade...
David Brown76101572019-02-28 11:29:03 -0700495 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700496 if result != 0 {
497 warn!("Failed first boot");
498 fails += 1;
499 }
500
501 //FIXME: copy_done is written by boot_go, is it ok if no copy
502 // was ever done?
503
David Brown84b49f72019-03-01 10:58:22 -0700504 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100505 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700506 fails += 1;
507 }
David Brown84b49f72019-03-01 10:58:22 -0700508 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
509 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100510 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700511 fails += 1;
512 }
David Brown84b49f72019-03-01 10:58:22 -0700513 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
514 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100515 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700516 fails += 1;
517 }
518
David Vincze2d736ad2019-02-18 11:50:22 +0100519 // Marks image in the primary slot as permanent,
520 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700521 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700522
David Brown84b49f72019-03-01 10:58:22 -0700523 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
524 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100525 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700526 fails += 1;
527 }
528
David Brown76101572019-02-28 11:29:03 -0700529 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700530 if result != 0 {
531 warn!("Failed second boot");
532 fails += 1;
533 }
534
David Brown84b49f72019-03-01 10:58:22 -0700535 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
536 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100537 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700538 fails += 1;
539 }
David Brown84b49f72019-03-01 10:58:22 -0700540 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700541 warn!("Failed image verification");
542 fails += 1;
543 }
544
545 if fails > 0 {
546 error!("Error running upgrade without revert");
547 }
548
549 fails > 0
550 }
551
David Vincze2d736ad2019-02-18 11:50:22 +0100552 // Tests a new image written to the primary slot that already has magic and
553 // image_ok set while there is no image on the secondary slot, so no revert
554 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700555 pub fn run_norevert_newimage(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700556 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700557 let mut fails = 0;
558
559 info!("Try non-revert on imgtool generated image");
560
David Brown84b49f72019-03-01 10:58:22 -0700561 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700562
David Vincze2d736ad2019-02-18 11:50:22 +0100563 // This simulates writing an image created by imgtool to
564 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700565 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
566 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100567 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700568 fails += 1;
569 }
570
571 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700572 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700573 if result != 0 {
574 warn!("Failed first boot");
575 fails += 1;
576 }
577
578 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700579 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700580 warn!("Failed image verification");
581 fails += 1;
582 }
David Brown84b49f72019-03-01 10:58:22 -0700583 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
584 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100585 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700586 fails += 1;
587 }
David Brown84b49f72019-03-01 10:58:22 -0700588 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
589 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100590 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700591 fails += 1;
592 }
593
594 if fails > 0 {
595 error!("Expected a non revert with new image");
596 }
597
598 fails > 0
599 }
600
David Vincze2d736ad2019-02-18 11:50:22 +0100601 // Tests a new image written to the primary slot that already has magic and
602 // image_ok set while there is no image on the secondary slot, so no revert
603 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700604 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700605 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700606 let mut fails = 0;
607
608 info!("Try upgrade image with bad signature");
609
David Brown84b49f72019-03-01 10:58:22 -0700610 self.mark_upgrades(&mut flash, 0);
611 self.mark_permanent_upgrades(&mut flash, 0);
612 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700613
David Brown84b49f72019-03-01 10:58:22 -0700614 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
615 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100616 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700617 fails += 1;
618 }
619
620 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700621 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700622 if result != 0 {
623 warn!("Failed first boot");
624 fails += 1;
625 }
626
627 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700628 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700629 warn!("Failed image verification");
630 fails += 1;
631 }
David Brown84b49f72019-03-01 10:58:22 -0700632 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
633 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100634 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700635 fails += 1;
636 }
637
638 if fails > 0 {
639 error!("Expected an upgrade failure when image has bad signature");
640 }
641
642 fails > 0
643 }
644
David Brown5c9e0f12019-01-09 16:34:33 -0700645 fn trailer_sz(&self, align: usize) -> usize {
646 c::boot_trailer_sz(align as u8) as usize
647 }
648
649 // FIXME: could get status sz from bootloader
David Brown5c9e0f12019-01-09 16:34:33 -0700650 fn status_sz(&self, align: usize) -> usize {
David Brown9930a3e2019-01-11 12:28:26 -0700651 let bias = if Caps::EncRsa.present() || Caps::EncKw.present() {
652 32
653 } else {
654 0
655 };
David Brown5c9e0f12019-01-09 16:34:33 -0700656
Christopher Collinsa1c12042019-05-23 14:00:28 -0700657 self.trailer_sz(align) - (16 + 32 + bias)
David Brown5c9e0f12019-01-09 16:34:33 -0700658 }
659
660 /// This test runs a simple upgrade with no fails in the images, but
661 /// allowing for fails in the status area. This should run to the end
662 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700663 pub fn run_with_status_fails_complete(&self) -> bool {
David Vincze2d736ad2019-02-18 11:50:22 +0100664 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700665 return false;
666 }
667
David Brown76101572019-02-28 11:29:03 -0700668 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700669 let mut fails = 0;
670
671 info!("Try swap with status fails");
672
David Brown84b49f72019-03-01 10:58:22 -0700673 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700674 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700675
David Brown76101572019-02-28 11:29:03 -0700676 let (result, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown5c9e0f12019-01-09 16:34:33 -0700677 if result != 0 {
678 warn!("Failed!");
679 fails += 1;
680 }
681
682 // Failed writes to the marked "bad" region don't assert anymore.
683 // Any detected assert() is happening in another part of the code.
684 if asserts != 0 {
685 warn!("At least one assert() was called");
686 fails += 1;
687 }
688
David Brown84b49f72019-03-01 10:58:22 -0700689 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
690 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100691 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700692 fails += 1;
693 }
694
David Brown84b49f72019-03-01 10:58:22 -0700695 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700696 warn!("Failed image verification");
697 fails += 1;
698 }
699
David Vincze2d736ad2019-02-18 11:50:22 +0100700 info!("validate primary slot enabled; \
701 re-run of boot_go should just work");
David Brown76101572019-02-28 11:29:03 -0700702 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700703 if result != 0 {
704 warn!("Failed!");
705 fails += 1;
706 }
707
708 if fails > 0 {
709 error!("Error running upgrade with status write fails");
710 }
711
712 fails > 0
713 }
714
715 /// This test runs a simple upgrade with no fails in the images, but
716 /// allowing for fails in the status area. This should run to the end
717 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700718 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown85904a82019-01-11 13:45:12 -0700719 if Caps::OverwriteUpgrade.present() {
720 false
David Vincze2d736ad2019-02-18 11:50:22 +0100721 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700722
David Brown76101572019-02-28 11:29:03 -0700723 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700724 let mut fails = 0;
725 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700726
David Brown85904a82019-01-11 13:45:12 -0700727 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700728
David Brown85904a82019-01-11 13:45:12 -0700729 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700730
David Brown84b49f72019-03-01 10:58:22 -0700731 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700732 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700733
734 // Should not fail, writing to bad regions does not assert
David Brown76101572019-02-28 11:29:03 -0700735 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true);
David Brown85904a82019-01-11 13:45:12 -0700736 if asserts != 0 {
737 warn!("At least one assert() was called");
738 fails += 1;
739 }
740
David Brown76101572019-02-28 11:29:03 -0700741 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700742
743 info!("Resuming an interrupted swap operation");
David Brown76101572019-02-28 11:29:03 -0700744 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700745
746 // This might throw no asserts, for large sector devices, where
747 // a single failure writing is indistinguishable from no failure,
748 // or throw a single assert for small sector devices that fail
749 // multiple times...
750 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100751 warn!("Expected single assert validating the primary slot, \
752 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700753 fails += 1;
754 }
755
756 if fails > 0 {
757 error!("Error running upgrade with status write fails");
758 }
759
760 fails > 0
761 } else {
David Brown76101572019-02-28 11:29:03 -0700762 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700763 let mut fails = 0;
764
765 info!("Try interrupted swap with status fails");
766
David Brown84b49f72019-03-01 10:58:22 -0700767 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700768 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700769
770 // This is expected to fail while writing to bad regions...
David Brown76101572019-02-28 11:29:03 -0700771 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700772 if asserts == 0 {
773 warn!("No assert() detected");
774 fails += 1;
775 }
776
777 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700778 }
David Brown5c9e0f12019-01-09 16:34:33 -0700779 }
780
781 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -0700782 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -0700783 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -0700784 if Caps::OverwriteUpgrade.present() {
785 return;
786 }
787
David Brown84b49f72019-03-01 10:58:22 -0700788 // Set this for each image.
789 for image in &self.images {
790 let dev_id = &image.slots[slot].dev_id;
791 let dev = flash.get_mut(&dev_id).unwrap();
792 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -0700793 let off = &image.slots[slot].base_off;
794 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -0700795 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -0700796
David Brown84b49f72019-03-01 10:58:22 -0700797 // Mark the status area as a bad area
798 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
799 }
David Brown5c9e0f12019-01-09 16:34:33 -0700800 }
801
David Brown76101572019-02-28 11:29:03 -0700802 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +0100803 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700804 return;
805 }
806
David Brown84b49f72019-03-01 10:58:22 -0700807 for image in &self.images {
808 let dev_id = &image.slots[slot].dev_id;
809 let dev = flash.get_mut(&dev_id).unwrap();
810 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -0700811
David Brown84b49f72019-03-01 10:58:22 -0700812 // Disabling write verification the only assert triggered by
813 // boot_go should be checking for integrity of status bytes.
814 dev.set_verify_writes(false);
815 }
David Brown5c9e0f12019-01-09 16:34:33 -0700816 }
817
David Browndb505822019-03-01 10:04:20 -0700818 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
819 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -0300820 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -0700821 // Clone the flash to have a new copy.
822 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700823
Fabio Utziged4a5362019-07-30 12:43:23 -0300824 if permanent {
825 self.mark_permanent_upgrades(&mut flash, 1);
826 }
David Brown5c9e0f12019-01-09 16:34:33 -0700827
David Browndb505822019-03-01 10:04:20 -0700828 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -0700829
David Browndb505822019-03-01 10:04:20 -0700830 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
831 (-0x13579, _) => (true, stop.unwrap()),
832 (0, _) => (false, -counter),
833 (x, _) => panic!("Unknown return: {}", x),
834 };
David Brown5c9e0f12019-01-09 16:34:33 -0700835
David Browndb505822019-03-01 10:04:20 -0700836 counter = 0;
837 if first_interrupted {
838 // fl.dump();
839 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
840 (-0x13579, _) => panic!("Shouldn't stop again"),
841 (0, _) => (),
842 (x, _) => panic!("Unknown return: {}", x),
843 }
844 }
David Brown5c9e0f12019-01-09 16:34:33 -0700845
David Browndb505822019-03-01 10:04:20 -0700846 (flash, count - counter)
847 }
848
849 fn try_revert(&self, count: usize) -> SimMultiFlash {
850 let mut flash = self.flash.clone();
851
852 // fl.write_file("image0.bin").unwrap();
853 for i in 0 .. count {
854 info!("Running boot pass {}", i + 1);
855 assert_eq!(c::boot_go(&mut flash, &self.areadesc, None, false), (0, 0));
856 }
857 flash
858 }
859
860 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
861 let mut flash = self.flash.clone();
862 let mut fails = 0;
863
864 let mut counter = stop;
865 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
866 if x != -0x13579 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700867 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -0700868 fails += 1;
869 }
870
Fabio Utzig8af7f792019-07-30 12:40:01 -0300871 // In a multi-image setup, copy done might be set if any number of
872 // images was already successfully swapped.
873 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
874 warn!("copy_done should be unset");
875 fails += 1;
876 }
877
David Browndb505822019-03-01 10:04:20 -0700878 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
879 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700880 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -0700881 fails += 1;
882 }
883
David Brown84b49f72019-03-01 10:58:22 -0700884 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -0700885 warn!("Image in the primary slot before revert is invalid at stop={}",
886 stop);
887 fails += 1;
888 }
David Brown84b49f72019-03-01 10:58:22 -0700889 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -0700890 warn!("Image in the secondary slot before revert is invalid at stop={}",
891 stop);
892 fails += 1;
893 }
David Brown84b49f72019-03-01 10:58:22 -0700894 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
895 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -0700896 warn!("Mismatched trailer for the primary slot before revert");
897 fails += 1;
898 }
David Brown84b49f72019-03-01 10:58:22 -0700899 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
900 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -0700901 warn!("Mismatched trailer for the secondary slot before revert");
902 fails += 1;
903 }
904
905 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700906 let mut counter = stop;
907 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
908 if x != -0x13579 {
909 warn!("Should have stopped revert at interruption point");
910 fails += 1;
911 }
912
David Browndb505822019-03-01 10:04:20 -0700913 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
914 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700915 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -0700916 fails += 1;
917 }
918
David Brown84b49f72019-03-01 10:58:22 -0700919 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -0700920 warn!("Image in the primary slot after revert is invalid at stop={}",
921 stop);
922 fails += 1;
923 }
David Brown84b49f72019-03-01 10:58:22 -0700924 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -0700925 warn!("Image in the secondary slot after revert is invalid at stop={}",
926 stop);
927 fails += 1;
928 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700929
David Brown84b49f72019-03-01 10:58:22 -0700930 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
931 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700932 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -0700933 fails += 1;
934 }
David Brown84b49f72019-03-01 10:58:22 -0700935 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
936 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -0700937 warn!("Mismatched trailer for the secondary slot after revert");
938 fails += 1;
939 }
940
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700941 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
942 if x != 0 {
943 warn!("Should have finished 3rd boot");
944 fails += 1;
945 }
946
947 if !self.verify_images(&flash, 0, 0) {
948 warn!("Image in the primary slot is invalid on 1st boot after revert");
949 fails += 1;
950 }
951 if !self.verify_images(&flash, 1, 1) {
952 warn!("Image in the secondary slot is invalid on 1st boot after revert");
953 fails += 1;
954 }
955
David Browndb505822019-03-01 10:04:20 -0700956 fails > 0
957 }
958
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700959
David Browndb505822019-03-01 10:04:20 -0700960 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
961 let mut flash = self.flash.clone();
962
David Brown84b49f72019-03-01 10:58:22 -0700963 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -0700964
965 let mut rng = rand::thread_rng();
966 let mut resets = vec![0i32; count];
967 let mut remaining_ops = total_ops;
968 for i in 0 .. count {
969 let ops = Range::new(1, remaining_ops / 2);
970 let reset_counter = ops.ind_sample(&mut rng);
971 let mut counter = reset_counter;
972 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
973 (0, _) | (-0x13579, _) => (),
974 (x, _) => panic!("Unknown return: {}", x),
975 }
976 remaining_ops -= reset_counter;
977 resets[i] = reset_counter;
978 }
979
980 match c::boot_go(&mut flash, &self.areadesc, None, false) {
981 (-0x13579, _) => panic!("Should not be have been interrupted!"),
David Brown5c9e0f12019-01-09 16:34:33 -0700982 (0, _) => (),
983 (x, _) => panic!("Unknown return: {}", x),
984 }
David Brown5c9e0f12019-01-09 16:34:33 -0700985
David Browndb505822019-03-01 10:04:20 -0700986 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -0700987 }
David Brown84b49f72019-03-01 10:58:22 -0700988
989 /// Verify the image in the given flash device, the specified slot
990 /// against the expected image.
991 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -0600992 self.images.iter().all(|image| {
993 verify_image(flash, &image.slots[slot],
994 match against {
995 0 => &image.primaries,
996 1 => &image.upgrades,
997 _ => panic!("Invalid 'against'")
998 })
999 })
David Brown84b49f72019-03-01 10:58:22 -07001000 }
1001
David Brownc3898d62019-08-05 14:20:02 -06001002 /// Verify the images, according to the dependency test.
1003 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1004 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1005 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1006 if !verify_image(flash, &image.slots[0],
1007 match upgrade {
1008 UpgradeInfo::Upgraded => &image.upgrades,
1009 UpgradeInfo::Held => &image.primaries,
1010 }) {
1011 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1012 return true;
1013 }
1014 }
1015
1016 false
1017 }
1018
Fabio Utzig8af7f792019-07-30 12:40:01 -03001019 /// Verify that at least one of the trailers of the images have the
1020 /// specified values.
1021 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1022 magic: Option<u8>, image_ok: Option<u8>,
1023 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001024 self.images.iter().any(|image| {
1025 verify_trailer(flash, &image.slots[slot],
1026 magic, image_ok, copy_done)
1027 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001028 }
1029
David Brown84b49f72019-03-01 10:58:22 -07001030 /// Verify that the trailers of the images have the specified
1031 /// values.
1032 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1033 magic: Option<u8>, image_ok: Option<u8>,
1034 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001035 self.images.iter().all(|image| {
1036 verify_trailer(flash, &image.slots[slot],
1037 magic, image_ok, copy_done)
1038 })
David Brown84b49f72019-03-01 10:58:22 -07001039 }
1040
1041 /// Mark each of the images for permanent upgrade.
1042 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1043 for image in &self.images {
1044 mark_permanent_upgrade(flash, &image.slots[slot]);
1045 }
1046 }
1047
1048 /// Mark each of the images for permanent upgrade.
1049 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1050 for image in &self.images {
1051 mark_upgrade(flash, &image.slots[slot]);
1052 }
1053 }
David Brown297029a2019-08-13 14:29:51 -06001054
1055 /// Dump out the flash image(s) to one or more files for debugging
1056 /// purposes. The names will be written as either "{prefix}.mcubin" or
1057 /// "{prefix}-001.mcubin" depending on how many images there are.
1058 pub fn debug_dump(&self, prefix: &str) {
1059 for (id, fdev) in &self.flash {
1060 let name = if self.flash.len() == 1 {
1061 format!("{}.mcubin", prefix)
1062 } else {
1063 format!("{}-{:>0}.mcubin", prefix, id)
1064 };
1065 fdev.write_file(&name).unwrap();
1066 }
1067 }
David Brown5c9e0f12019-01-09 16:34:33 -07001068}
1069
1070/// Show the flash layout.
1071#[allow(dead_code)]
1072fn show_flash(flash: &dyn Flash) {
1073 println!("---- Flash configuration ----");
1074 for sector in flash.sector_iter() {
1075 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1076 sector.num, sector.base, sector.size);
1077 }
1078 println!("");
1079}
1080
1081/// Install a "program" into the given image. This fakes the image header, or at least all of the
1082/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001083fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownc3898d62019-08-05 14:20:02 -06001084 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001085 let offset = slot.base_off;
1086 let slot_len = slot.len;
1087 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001088
David Brown43643dd2019-01-11 15:43:28 -07001089 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001090
David Brownc3898d62019-08-05 14:20:02 -06001091 // Add the dependencies early to the tlv.
1092 for dep in deps.my_deps(offset, slot.index) {
1093 tlv.add_dependency(deps.other_id(), &dep);
1094 }
1095
David Brown5c9e0f12019-01-09 16:34:33 -07001096 const HDR_SIZE: usize = 32;
1097
1098 // Generate a boot header. Note that the size doesn't include the header.
1099 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001100 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -07001101 load_addr: 0,
1102 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001103 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001104 img_size: len as u32,
1105 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001106 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001107 _pad2: 0,
1108 };
1109
1110 let mut b_header = [0; HDR_SIZE];
1111 b_header[..32].clone_from_slice(header.as_raw());
1112 assert_eq!(b_header.len(), HDR_SIZE);
1113
1114 tlv.add_bytes(&b_header);
1115
1116 // The core of the image itself is just pseudorandom data.
1117 let mut b_img = vec![0; len];
1118 splat(&mut b_img, offset);
1119
David Browncb47dd72019-08-05 14:21:49 -06001120 // Add some information at the start of the payload to make it easier
1121 // to see what it is. This will fail if the image itself is too small.
1122 {
1123 let mut wr = Cursor::new(&mut b_img);
1124 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1125 offset, dev_id, slot).unwrap();
1126 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1127 }
1128
David Brown5c9e0f12019-01-09 16:34:33 -07001129 // TLV signatures work over plain image
1130 tlv.add_bytes(&b_img);
1131
1132 // Generate encrypted images
1133 let flag = TlvFlags::ENCRYPTED as u32;
1134 let is_encrypted = (tlv.get_flags() & flag) == flag;
1135 let mut b_encimg = vec![];
1136 if is_encrypted {
1137 let key = GenericArray::from_slice(AES_SEC_KEY);
1138 let nonce = GenericArray::from_slice(&[0; 16]);
1139 let mut cipher = Aes128Ctr::new(&key, &nonce);
1140 b_encimg = b_img.clone();
1141 cipher.apply_keystream(&mut b_encimg);
1142 }
1143
1144 // Build the TLV itself.
1145 let mut b_tlv = if bad_sig {
1146 let good_sig = &mut tlv.make_tlv();
1147 vec![0; good_sig.len()]
1148 } else {
1149 tlv.make_tlv()
1150 };
1151
1152 // Pad the block to a flash alignment (8 bytes).
1153 while b_tlv.len() % 8 != 0 {
1154 //FIXME: should be erase_val?
1155 b_tlv.push(0xFF);
1156 }
1157
1158 let mut buf = vec![];
1159 buf.append(&mut b_header.to_vec());
1160 buf.append(&mut b_img);
1161 buf.append(&mut b_tlv.clone());
1162
1163 let mut encbuf = vec![];
1164 if is_encrypted {
1165 encbuf.append(&mut b_header.to_vec());
1166 encbuf.append(&mut b_encimg);
1167 encbuf.append(&mut b_tlv);
1168 }
1169
David Vincze2d736ad2019-02-18 11:50:22 +01001170 // Since images are always non-encrypted in the primary slot, we first write
1171 // an encrypted image, re-read to use for verification, erase + flash
1172 // un-encrypted. In the secondary slot the image is written un-encrypted,
1173 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001174
David Brown76101572019-02-28 11:29:03 -07001175 let dev = flash.get_mut(&dev_id).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001176
David Brown3b090212019-07-30 15:59:28 -06001177 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001178 let enc_copy: Option<Vec<u8>>;
1179
1180 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001181 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001182
1183 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001184 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001185
1186 enc_copy = Some(enc);
1187
David Brown76101572019-02-28 11:29:03 -07001188 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001189 } else {
1190 enc_copy = None;
1191 }
1192
David Brown76101572019-02-28 11:29:03 -07001193 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001194
1195 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001196 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001197
David Brownca234692019-02-28 11:22:19 -07001198 ImageData {
1199 plain: copy,
1200 cipher: enc_copy,
1201 }
David Brown5c9e0f12019-01-09 16:34:33 -07001202 } else {
1203
David Brown76101572019-02-28 11:29:03 -07001204 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001205
1206 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001207 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001208
1209 let enc_copy: Option<Vec<u8>>;
1210
1211 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001212 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001213
David Brown76101572019-02-28 11:29:03 -07001214 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001215
1216 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001217 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001218
1219 enc_copy = Some(enc);
1220 } else {
1221 enc_copy = None;
1222 }
1223
David Brownca234692019-02-28 11:22:19 -07001224 ImageData {
1225 plain: copy,
1226 cipher: enc_copy,
1227 }
David Brown5c9e0f12019-01-09 16:34:33 -07001228 }
David Brown5c9e0f12019-01-09 16:34:33 -07001229}
1230
David Brown5c9e0f12019-01-09 16:34:33 -07001231fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001232 if Caps::EcdsaP224.present() {
1233 panic!("Ecdsa P224 not supported in Simulator");
1234 }
David Brown5c9e0f12019-01-09 16:34:33 -07001235
David Brownb8882112019-01-11 14:04:11 -07001236 if Caps::EncKw.present() {
1237 if Caps::RSA2048.present() {
1238 TlvGen::new_rsa_kw()
1239 } else if Caps::EcdsaP256.present() {
1240 TlvGen::new_ecdsa_kw()
1241 } else {
1242 TlvGen::new_enc_kw()
1243 }
1244 } else if Caps::EncRsa.present() {
1245 if Caps::RSA2048.present() {
1246 TlvGen::new_sig_enc_rsa()
1247 } else {
1248 TlvGen::new_enc_rsa()
1249 }
1250 } else {
1251 // The non-encrypted configuration.
1252 if Caps::RSA2048.present() {
1253 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001254 } else if Caps::RSA3072.present() {
1255 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001256 } else if Caps::EcdsaP256.present() {
1257 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001258 } else if Caps::Ed25519.present() {
1259 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001260 } else {
1261 TlvGen::new_hash_only()
1262 }
1263 }
David Brown5c9e0f12019-01-09 16:34:33 -07001264}
1265
David Brownca234692019-02-28 11:22:19 -07001266impl ImageData {
1267 /// Find the image contents for the given slot. This assumes that slot 0
1268 /// is unencrypted, and slot 1 is encrypted.
1269 fn find(&self, slot: usize) -> &Vec<u8> {
1270 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present();
1271 match (encrypted, slot) {
1272 (false, _) => &self.plain,
1273 (true, 0) => &self.plain,
1274 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1275 _ => panic!("Invalid slot requested"),
1276 }
David Brown5c9e0f12019-01-09 16:34:33 -07001277 }
1278}
1279
David Brown5c9e0f12019-01-09 16:34:33 -07001280/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001281fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1282 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001283 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001284 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001285
1286 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001287 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001288 let dev = flash.get(&dev_id).unwrap();
1289 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001290
1291 if buf != &copy[..] {
1292 for i in 0 .. buf.len() {
1293 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001294 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1295 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001296 break;
1297 }
1298 }
1299 false
1300 } else {
1301 true
1302 }
1303}
1304
David Brown3b090212019-07-30 15:59:28 -06001305fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001306 magic: Option<u8>, image_ok: Option<u8>,
1307 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001308 if Caps::OverwriteUpgrade.present() {
1309 return true;
1310 }
David Brown5c9e0f12019-01-09 16:34:33 -07001311
David Brown3b090212019-07-30 15:59:28 -06001312 let offset = slot.trailer_off + c::boot_max_align();
1313 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001314 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001315 let mut failed = false;
1316
David Brown76101572019-02-28 11:29:03 -07001317 let dev = flash.get(&dev_id).unwrap();
1318 let erased_val = dev.erased_val();
1319 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001320
1321 failed |= match magic {
1322 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001323 if v == 1 && &copy[24..] != MAGIC.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -07001324 warn!("\"magic\" mismatch at {:#x}", offset);
1325 true
1326 } else if v == 3 {
1327 let expected = [erased_val; 16];
Christopher Collinsa1c12042019-05-23 14:00:28 -07001328 if &copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001329 warn!("\"magic\" mismatch at {:#x}", offset);
1330 true
1331 } else {
1332 false
1333 }
1334 } else {
1335 false
1336 }
1337 },
1338 None => false,
1339 };
1340
1341 failed |= match image_ok {
1342 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001343 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001344 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1345 true
1346 } else {
1347 false
1348 }
1349 },
1350 None => false,
1351 };
1352
1353 failed |= match copy_done {
1354 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001355 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001356 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1357 true
1358 } else {
1359 false
1360 }
1361 },
1362 None => false,
1363 };
1364
1365 !failed
1366}
1367
David Brown297029a2019-08-13 14:29:51 -06001368/// Install a partition table. This is a simplified partition table that
1369/// we write at the beginning of flash so make it easier for external tools
1370/// to analyze these images.
1371fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1372 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1373 for &id in &ids {
1374 // If there are any partitions in this device that start at 0, and
1375 // aren't marked as the BootLoader partition, avoid adding the
1376 // partition table. This makes it harder to view the image, but
1377 // avoids messing up images already written.
1378 if areadesc.iter_areas().any(|area| {
1379 area.device_id == id &&
1380 area.off == 0 &&
1381 area.flash_id != FlashId::BootLoader
1382 }) {
1383 if log_enabled!(Info) {
1384 let special: Vec<FlashId> = areadesc.iter_areas()
1385 .filter(|area| area.device_id == id && area.off == 0)
1386 .map(|area| area.flash_id)
1387 .collect();
1388 info!("Skipping partition table: {:?}", special);
1389 }
1390 break;
1391 }
1392
1393 let mut buf: Vec<u8> = vec![];
1394 write!(&mut buf, "mcuboot\0").unwrap();
1395
1396 // Iterate through all of the partitions in that device, and encode
1397 // into the table.
1398 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1399 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1400
1401 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1402 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1403 buf.write_u32::<LittleEndian>(area.off).unwrap();
1404 buf.write_u32::<LittleEndian>(area.size).unwrap();
1405 buf.write_u32::<LittleEndian>(0).unwrap();
1406 }
1407
1408 let dev = flash.get_mut(&id).unwrap();
1409
1410 // Pad to alignment.
1411 while buf.len() % dev.align() != 0 {
1412 buf.push(0);
1413 }
1414
1415 dev.write(0, &buf).unwrap();
1416 }
1417}
1418
David Brown5c9e0f12019-01-09 16:34:33 -07001419/// The image header
1420#[repr(C)]
1421pub struct ImageHeader {
1422 magic: u32,
1423 load_addr: u32,
1424 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001425 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001426 img_size: u32,
1427 flags: u32,
1428 ver: ImageVersion,
1429 _pad2: u32,
1430}
1431
1432impl AsRaw for ImageHeader {}
1433
1434#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001435#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001436pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001437 pub major: u8,
1438 pub minor: u8,
1439 pub revision: u16,
1440 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001441}
1442
David Brownc3898d62019-08-05 14:20:02 -06001443#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001444pub struct SlotInfo {
1445 pub base_off: usize,
1446 pub trailer_off: usize,
1447 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001448 // Which slot within this device.
1449 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001450 pub dev_id: u8,
1451}
1452
David Brown5c9e0f12019-01-09 16:34:33 -07001453const MAGIC: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3,
1454 0x60, 0xd2, 0xef, 0x7f,
1455 0x35, 0x52, 0x50, 0x0f,
1456 0x2c, 0xb6, 0x79, 0x80]);
1457
1458// Replicates defines found in bootutil.h
1459const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1460const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1461
1462const BOOT_FLAG_SET: Option<u8> = Some(1);
1463const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1464
1465/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001466pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1467 let dev = flash.get_mut(&slot.dev_id).unwrap();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001468 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown76101572019-02-28 11:29:03 -07001469 dev.write(offset, MAGIC.unwrap()).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001470}
1471
1472/// Writes the image_ok flag which, guess what, tells the bootloader
1473/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001474fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1475 let dev = flash.get_mut(&slot.dev_id).unwrap();
1476 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001477 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001478 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001479 let align = dev.align();
1480 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001481}
1482
1483// Drop some pseudo-random gibberish onto the data.
1484fn splat(data: &mut [u8], seed: usize) {
1485 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
1486 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
1487 rng.fill_bytes(data);
1488}
1489
1490/// Return a read-only view into the raw bytes of this object
1491trait AsRaw : Sized {
1492 fn as_raw<'a>(&'a self) -> &'a [u8] {
1493 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1494 mem::size_of::<Self>()) }
1495 }
1496}
1497
1498pub fn show_sizes() {
1499 // This isn't panic safe.
1500 for min in &[1, 2, 4, 8] {
1501 let msize = c::boot_trailer_sz(*min);
1502 println!("{:2}: {} (0x{:x})", min, msize, msize);
1503 }
1504}