blob: cfb51982c1b30a797f91a5baefdb52ff0c00cb2a [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,
David Brown873be312019-09-03 12:22:32 -060041 DepType,
David Brownc3898d62019-08-05 14:20:02 -060042 PairDep,
43 UpgradeInfo,
44};
Fabio Utzig90f449e2019-10-24 07:43:53 -030045use crate::tlv::{ManifestGen, TlvGen, TlvFlags};
David Brown5c9e0f12019-01-09 16:34:33 -070046
David Browne5133242019-02-28 11:05:19 -070047/// A builder for Images. This describes a single run of the simulator,
48/// capturing the configuration of a particular set of devices, including
49/// the flash simulator(s) and the information about the slots.
50#[derive(Clone)]
51pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070052 flash: SimMultiFlash,
David Browne5133242019-02-28 11:05:19 -070053 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070054 slots: Vec<[SlotInfo; 2]>,
David Browne5133242019-02-28 11:05:19 -070055}
56
David Brown998aa8d2019-02-28 10:54:50 -070057/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070058/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070059/// and upgrades hold the expected contents of these images.
60pub struct Images {
David Brown76101572019-02-28 11:29:03 -070061 flash: SimMultiFlash,
David Brownca234692019-02-28 11:22:19 -070062 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070063 images: Vec<OneImage>,
64 total_count: Option<i32>,
65}
66
67/// When doing multi-image, there is an instance of this information for
68/// each of the images. Single image there will be one of these.
69struct OneImage {
David Brownca234692019-02-28 11:22:19 -070070 slots: [SlotInfo; 2],
71 primaries: ImageData,
72 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070073}
74
75/// The Rust-side representation of an image. For unencrypted images, this
76/// is just the unencrypted payload. For encrypted images, we store both
77/// the encrypted and the plaintext.
78struct ImageData {
79 plain: Vec<u8>,
80 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -070081}
82
David Browne5133242019-02-28 11:05:19 -070083impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -070084 /// Construct a new image builder for the given device. Returns
85 /// Some(builder) if is possible to test this configuration, or None if
86 /// not possible (for example, if there aren't enough image slots).
David Brown5a317752019-11-15 09:53:39 -070087 pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Option<Self> {
David Brown76101572019-02-28 11:29:03 -070088 let (flash, areadesc) = Self::make_device(device, align, erased_val);
David Browne5133242019-02-28 11:05:19 -070089
David Brown06ef06e2019-03-05 12:28:10 -070090 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -070091
David Brown06ef06e2019-03-05 12:28:10 -070092 let mut slots = Vec::with_capacity(num_images);
93 for image in 0..num_images {
94 // This mapping must match that defined in
95 // `boot/zephyr/include/sysflash/sysflash.h`.
96 let id0 = match image {
97 0 => FlashId::Image0,
98 1 => FlashId::Image2,
99 _ => panic!("More than 2 images not supported"),
100 };
101 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
102 Some(info) => info,
103 None => return None,
104 };
105 let id1 = match image {
106 0 => FlashId::Image1,
107 1 => FlashId::Image3,
108 _ => panic!("More than 2 images not supported"),
109 };
110 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
111 Some(info) => info,
112 None => return None,
113 };
David Browne5133242019-02-28 11:05:19 -0700114
Christopher Collinsa1c12042019-05-23 14:00:28 -0700115 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700116
David Brown06ef06e2019-03-05 12:28:10 -0700117 // Construct a primary image.
118 let primary = SlotInfo {
119 base_off: primary_base as usize,
120 trailer_off: primary_base + primary_len - offset_from_end,
121 len: primary_len as usize,
122 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600123 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700124 };
125
126 // And an upgrade image.
127 let secondary = SlotInfo {
128 base_off: secondary_base as usize,
129 trailer_off: secondary_base + secondary_len - offset_from_end,
130 len: secondary_len as usize,
131 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600132 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700133 };
134
135 slots.push([primary, secondary]);
136 }
David Browne5133242019-02-28 11:05:19 -0700137
David Brown5bc62c62019-03-05 12:11:48 -0700138 Some(ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -0700139 flash: flash,
David Browne5133242019-02-28 11:05:19 -0700140 areadesc: areadesc,
David Brown06ef06e2019-03-05 12:28:10 -0700141 slots: slots,
David Brown5bc62c62019-03-05 12:11:48 -0700142 })
David Browne5133242019-02-28 11:05:19 -0700143 }
144
145 pub fn each_device<F>(f: F)
146 where F: Fn(Self)
147 {
148 for &dev in ALL_DEVICES {
David Brown95de4502019-11-15 12:01:34 -0700149 for &align in test_alignments() {
David Browne5133242019-02-28 11:05:19 -0700150 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700151 match Self::new(dev, align, erased_val) {
152 Some(run) => f(run),
153 None => warn!("Skipping {:?}, insufficient partitions", dev),
154 }
David Browne5133242019-02-28 11:05:19 -0700155 }
156 }
157 }
158 }
159
160 /// Construct an `Images` that doesn't expect an upgrade to happen.
David Brownc3898d62019-08-05 14:20:02 -0600161 pub fn make_no_upgrade_image(self, deps: &DepTest) -> Images {
162 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700163 let mut flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600164 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
165 let dep: Box<dyn Depender> = if num_images > 1 {
166 Box::new(PairDep::new(num_images, image_num, deps))
167 } else {
168 Box::new(BoringDep(image_num))
169 };
170 let primaries = install_image(&mut flash, &slots[0], 42784, &*dep, false);
David Brown873be312019-09-03 12:22:32 -0600171 let upgrades = match deps.depends[image_num] {
172 DepType::NoUpgrade => install_no_image(),
173 _ => install_image(&mut flash, &slots[1], 46928, &*dep, false)
174 };
David Brown84b49f72019-03-01 10:58:22 -0700175 OneImage {
176 slots: slots,
177 primaries: primaries,
178 upgrades: upgrades,
179 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600180 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700181 Images {
David Brown76101572019-02-28 11:29:03 -0700182 flash: flash,
David Browne5133242019-02-28 11:05:19 -0700183 areadesc: self.areadesc,
David Brown84b49f72019-03-01 10:58:22 -0700184 images: images,
David Browne5133242019-02-28 11:05:19 -0700185 total_count: None,
186 }
187 }
188
David Brownc3898d62019-08-05 14:20:02 -0600189 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
190 let mut images = self.make_no_upgrade_image(deps);
David Brown84b49f72019-03-01 10:58:22 -0700191 for image in &images.images {
192 mark_upgrade(&mut images.flash, &image.slots[1]);
193 }
David Browne5133242019-02-28 11:05:19 -0700194
195 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300196 let total_count = match images.run_basic_upgrade(permanent) {
David Browne5133242019-02-28 11:05:19 -0700197 Ok(v) => v,
Fabio Utzig7c1d1552019-08-28 10:59:22 -0300198 Err(_) =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600199 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
200 0
201 } else {
202 panic!("Unable to perform basic upgrade");
203 }
David Browne5133242019-02-28 11:05:19 -0700204 };
205
206 images.total_count = Some(total_count);
207 images
208 }
209
210 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700211 let mut bad_flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600212 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
213 let dep = BoringDep(image_num);
214 let primaries = install_image(&mut bad_flash, &slots[0], 32784, &dep, false);
215 let upgrades = install_image(&mut bad_flash, &slots[1], 41928, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700216 OneImage {
217 slots: slots,
218 primaries: primaries,
219 upgrades: upgrades,
220 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700221 Images {
David Brown76101572019-02-28 11:29:03 -0700222 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700223 areadesc: self.areadesc,
David Brown84b49f72019-03-01 10:58:22 -0700224 images: images,
David Browne5133242019-02-28 11:05:19 -0700225 total_count: None,
226 }
227 }
228
229 /// Build the Flash and area descriptor for a given device.
David Brown5a317752019-11-15 09:53:39 -0700230 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc) {
David Browne5133242019-02-28 11:05:19 -0700231 match device {
232 DeviceName::Stm32f4 => {
233 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700234 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
235 64 * 1024,
236 128 * 1024, 128 * 1024, 128 * 1024],
237 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700238 let dev_id = 0;
239 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700240 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700241 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
242 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
243 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
244
David Brown76101572019-02-28 11:29:03 -0700245 let mut flash = SimMultiFlash::new();
246 flash.insert(dev_id, dev);
247 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700248 }
249 DeviceName::K64f => {
250 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700251 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700252
253 let dev_id = 0;
254 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700255 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700256 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
257 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
258 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
259
David Brown76101572019-02-28 11:29:03 -0700260 let mut flash = SimMultiFlash::new();
261 flash.insert(dev_id, dev);
262 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700263 }
264 DeviceName::K64fBig => {
265 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
266 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700267 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700268
269 let dev_id = 0;
270 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700271 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700272 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
273 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
274 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
275
David Brown76101572019-02-28 11:29:03 -0700276 let mut flash = SimMultiFlash::new();
277 flash.insert(dev_id, dev);
278 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700279 }
280 DeviceName::Nrf52840 => {
281 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
282 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700283 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700284
285 let dev_id = 0;
286 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700287 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700288 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
289 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
290 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
291
David Brown76101572019-02-28 11:29:03 -0700292 let mut flash = SimMultiFlash::new();
293 flash.insert(dev_id, dev);
294 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700295 }
296 DeviceName::Nrf52840SpiFlash => {
297 // Simulate nrf52840 with external SPI flash. The external SPI flash
298 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700299 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
300 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700301
302 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700303 areadesc.add_flash_sectors(0, &dev0);
304 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700305
306 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
307 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
308 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
309
David Brown76101572019-02-28 11:29:03 -0700310 let mut flash = SimMultiFlash::new();
311 flash.insert(0, dev0);
312 flash.insert(1, dev1);
313 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700314 }
David Brown2bff6472019-03-05 13:58:35 -0700315 DeviceName::K64fMulti => {
316 // NXP style flash, but larger, to support multiple images.
317 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
318
319 let dev_id = 0;
320 let mut areadesc = AreaDesc::new();
321 areadesc.add_flash_sectors(dev_id, &dev);
322 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
323 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
324 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
325 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
326 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
327
328 let mut flash = SimMultiFlash::new();
329 flash.insert(dev_id, dev);
330 (flash, areadesc)
331 }
David Browne5133242019-02-28 11:05:19 -0700332 }
333 }
David Brownc3898d62019-08-05 14:20:02 -0600334
335 pub fn num_images(&self) -> usize {
336 self.slots.len()
337 }
David Browne5133242019-02-28 11:05:19 -0700338}
339
David Brown5c9e0f12019-01-09 16:34:33 -0700340impl Images {
341 /// A simple upgrade without forced failures.
342 ///
343 /// Returns the number of flash operations which can later be used to
344 /// inject failures at chosen steps.
Fabio Utziged4a5362019-07-30 12:43:23 -0300345 pub fn run_basic_upgrade(&self, permanent: bool) -> Result<i32, ()> {
346 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700347 info!("Total flash operation count={}", total_count);
348
David Brown84b49f72019-03-01 10:58:22 -0700349 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700350 warn!("Image mismatch after first boot");
351 Err(())
352 } else {
353 Ok(total_count)
354 }
355 }
356
David Brownc3898d62019-08-05 14:20:02 -0600357 /// Test a simple upgrade, with dependencies given, and verify that the
358 /// image does as is described in the test.
359 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
360 let (flash, _) = self.try_upgrade(None, true);
361
362 self.verify_dep_images(&flash, deps)
363 }
364
David Brown5c9e0f12019-01-09 16:34:33 -0700365 pub fn run_basic_revert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700366 if Caps::OverwriteUpgrade.present() {
367 return false;
368 }
David Brown5c9e0f12019-01-09 16:34:33 -0700369
David Brown5c9e0f12019-01-09 16:34:33 -0700370 let mut fails = 0;
371
372 // FIXME: this test would also pass if no swap is ever performed???
373 if Caps::SwapUpgrade.present() {
374 for count in 2 .. 5 {
375 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700376 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700377 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700378 error!("Revert failure on count {}", count);
379 fails += 1;
380 }
381 }
382 }
383
384 fails > 0
385 }
386
387 pub fn run_perm_with_fails(&self) -> bool {
388 let mut fails = 0;
389 let total_flash_ops = self.total_count.unwrap();
390
391 // Let's try an image halfway through.
392 for i in 1 .. total_flash_ops {
393 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300394 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700395 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700396 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700397 warn!("FAIL at step {} of {}", i, total_flash_ops);
398 fails += 1;
399 }
400
David Brown84b49f72019-03-01 10:58:22 -0700401 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
402 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100403 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700404 fails += 1;
405 }
406
David Brown84b49f72019-03-01 10:58:22 -0700407 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
408 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100409 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700410 fails += 1;
411 }
412
413 if Caps::SwapUpgrade.present() {
David Brown84b49f72019-03-01 10:58:22 -0700414 if !self.verify_images(&flash, 1, 0) {
David Vincze2d736ad2019-02-18 11:50:22 +0100415 warn!("Secondary slot FAIL at step {} of {}",
416 i, total_flash_ops);
David Brown5c9e0f12019-01-09 16:34:33 -0700417 fails += 1;
418 }
419 }
420 }
421
422 if fails > 0 {
423 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
424 fails as f32 * 100.0 / total_flash_ops as f32);
425 }
426
427 fails > 0
428 }
429
David Brown5c9e0f12019-01-09 16:34:33 -0700430 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
431 let mut fails = 0;
432 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700433 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700434 info!("Random interruptions at reset points={:?}", total_counts);
435
David Brown84b49f72019-03-01 10:58:22 -0700436 let primary_slot_ok = self.verify_images(&flash, 0, 1);
David Vincze2d736ad2019-02-18 11:50:22 +0100437 let secondary_slot_ok = if Caps::SwapUpgrade.present() {
David Brown84b49f72019-03-01 10:58:22 -0700438 // TODO: This result is ignored.
439 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700440 } else {
441 true
442 };
David Vincze2d736ad2019-02-18 11:50:22 +0100443 if !primary_slot_ok || !secondary_slot_ok {
444 error!("Image mismatch after random interrupts: primary slot={} \
445 secondary slot={}",
446 if primary_slot_ok { "ok" } else { "fail" },
447 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700448 fails += 1;
449 }
David Brown84b49f72019-03-01 10:58:22 -0700450 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
451 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100452 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700453 fails += 1;
454 }
David Brown84b49f72019-03-01 10:58:22 -0700455 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
456 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100457 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700458 fails += 1;
459 }
460
461 if fails > 0 {
462 error!("Error testing perm upgrade with {} fails", total_fails);
463 }
464
465 fails > 0
466 }
467
David Brown5c9e0f12019-01-09 16:34:33 -0700468 pub fn run_revert_with_fails(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700469 if Caps::OverwriteUpgrade.present() {
470 return false;
471 }
David Brown5c9e0f12019-01-09 16:34:33 -0700472
David Brown5c9e0f12019-01-09 16:34:33 -0700473 let mut fails = 0;
474
475 if Caps::SwapUpgrade.present() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300476 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700477 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700478 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700479 error!("Revert failed at interruption {}", i);
480 fails += 1;
481 }
482 }
483 }
484
485 fails > 0
486 }
487
David Brown5c9e0f12019-01-09 16:34:33 -0700488 pub fn run_norevert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700489 if Caps::OverwriteUpgrade.present() {
490 return false;
491 }
David Brown5c9e0f12019-01-09 16:34:33 -0700492
David Brown76101572019-02-28 11:29:03 -0700493 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700494 let mut fails = 0;
495
496 info!("Try norevert");
497
498 // First do a normal upgrade...
David Brown76101572019-02-28 11:29:03 -0700499 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700500 if result != 0 {
501 warn!("Failed first boot");
502 fails += 1;
503 }
504
505 //FIXME: copy_done is written by boot_go, is it ok if no copy
506 // was ever done?
507
David Brown84b49f72019-03-01 10:58:22 -0700508 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100509 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700510 fails += 1;
511 }
David Brown84b49f72019-03-01 10:58:22 -0700512 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
513 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100514 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700515 fails += 1;
516 }
David Brown84b49f72019-03-01 10:58:22 -0700517 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
518 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100519 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700520 fails += 1;
521 }
522
David Vincze2d736ad2019-02-18 11:50:22 +0100523 // Marks image in the primary slot as permanent,
524 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700525 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700526
David Brown84b49f72019-03-01 10:58:22 -0700527 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
528 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100529 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700530 fails += 1;
531 }
532
David Brown76101572019-02-28 11:29:03 -0700533 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700534 if result != 0 {
535 warn!("Failed second boot");
536 fails += 1;
537 }
538
David Brown84b49f72019-03-01 10:58:22 -0700539 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
540 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100541 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700542 fails += 1;
543 }
David Brown84b49f72019-03-01 10:58:22 -0700544 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700545 warn!("Failed image verification");
546 fails += 1;
547 }
548
549 if fails > 0 {
550 error!("Error running upgrade without revert");
551 }
552
553 fails > 0
554 }
555
David Vincze2d736ad2019-02-18 11:50:22 +0100556 // Tests a new image written to the primary slot that already has magic and
557 // image_ok set while there is no image on the secondary slot, so no revert
558 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700559 pub fn run_norevert_newimage(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700560 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700561 let mut fails = 0;
562
563 info!("Try non-revert on imgtool generated image");
564
David Brown84b49f72019-03-01 10:58:22 -0700565 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700566
David Vincze2d736ad2019-02-18 11:50:22 +0100567 // This simulates writing an image created by imgtool to
568 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700569 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
570 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100571 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700572 fails += 1;
573 }
574
575 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700576 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700577 if result != 0 {
578 warn!("Failed first boot");
579 fails += 1;
580 }
581
582 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700583 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700584 warn!("Failed image verification");
585 fails += 1;
586 }
David Brown84b49f72019-03-01 10:58:22 -0700587 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
588 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100589 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700590 fails += 1;
591 }
David Brown84b49f72019-03-01 10:58:22 -0700592 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
593 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100594 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700595 fails += 1;
596 }
597
598 if fails > 0 {
599 error!("Expected a non revert with new image");
600 }
601
602 fails > 0
603 }
604
David Vincze2d736ad2019-02-18 11:50:22 +0100605 // Tests a new image written to the primary slot that already has magic and
606 // image_ok set while there is no image on the secondary slot, so no revert
607 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700608 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700609 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700610 let mut fails = 0;
611
612 info!("Try upgrade image with bad signature");
613
David Brown84b49f72019-03-01 10:58:22 -0700614 self.mark_upgrades(&mut flash, 0);
615 self.mark_permanent_upgrades(&mut flash, 0);
616 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700617
David Brown84b49f72019-03-01 10:58:22 -0700618 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
619 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100620 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700621 fails += 1;
622 }
623
624 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700625 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700626 if result != 0 {
627 warn!("Failed first boot");
628 fails += 1;
629 }
630
631 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700632 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700633 warn!("Failed image verification");
634 fails += 1;
635 }
David Brown84b49f72019-03-01 10:58:22 -0700636 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
637 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100638 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700639 fails += 1;
640 }
641
642 if fails > 0 {
643 error!("Expected an upgrade failure when image has bad signature");
644 }
645
646 fails > 0
647 }
648
David Brown5c9e0f12019-01-09 16:34:33 -0700649 fn trailer_sz(&self, align: usize) -> usize {
650 c::boot_trailer_sz(align as u8) as usize
651 }
652
653 // FIXME: could get status sz from bootloader
David Brown5c9e0f12019-01-09 16:34:33 -0700654 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig90f449e2019-10-24 07:43:53 -0300655 let bias = if Caps::EncRsa.present() || Caps::EncKw.present() ||
656 Caps::EncEc256.present() {
David Brown9930a3e2019-01-11 12:28:26 -0700657 32
658 } else {
659 0
660 };
David Brown5c9e0f12019-01-09 16:34:33 -0700661
Christopher Collinsa1c12042019-05-23 14:00:28 -0700662 self.trailer_sz(align) - (16 + 32 + bias)
David Brown5c9e0f12019-01-09 16:34:33 -0700663 }
664
665 /// This test runs a simple upgrade with no fails in the images, but
666 /// allowing for fails in the status area. This should run to the end
667 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700668 pub fn run_with_status_fails_complete(&self) -> bool {
David Vincze2d736ad2019-02-18 11:50:22 +0100669 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700670 return false;
671 }
672
David Brown76101572019-02-28 11:29:03 -0700673 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700674 let mut fails = 0;
675
676 info!("Try swap with status fails");
677
David Brown84b49f72019-03-01 10:58:22 -0700678 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700679 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700680
David Brown76101572019-02-28 11:29:03 -0700681 let (result, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown5c9e0f12019-01-09 16:34:33 -0700682 if result != 0 {
683 warn!("Failed!");
684 fails += 1;
685 }
686
687 // Failed writes to the marked "bad" region don't assert anymore.
688 // Any detected assert() is happening in another part of the code.
689 if asserts != 0 {
690 warn!("At least one assert() was called");
691 fails += 1;
692 }
693
David Brown84b49f72019-03-01 10:58:22 -0700694 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
695 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100696 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700697 fails += 1;
698 }
699
David Brown84b49f72019-03-01 10:58:22 -0700700 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700701 warn!("Failed image verification");
702 fails += 1;
703 }
704
David Vincze2d736ad2019-02-18 11:50:22 +0100705 info!("validate primary slot enabled; \
706 re-run of boot_go should just work");
David Brown76101572019-02-28 11:29:03 -0700707 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700708 if result != 0 {
709 warn!("Failed!");
710 fails += 1;
711 }
712
713 if fails > 0 {
714 error!("Error running upgrade with status write fails");
715 }
716
717 fails > 0
718 }
719
720 /// This test runs a simple upgrade with no fails in the images, but
721 /// allowing for fails in the status area. This should run to the end
722 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700723 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown85904a82019-01-11 13:45:12 -0700724 if Caps::OverwriteUpgrade.present() {
725 false
David Vincze2d736ad2019-02-18 11:50:22 +0100726 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700727
David Brown76101572019-02-28 11:29:03 -0700728 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700729 let mut fails = 0;
730 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700731
David Brown85904a82019-01-11 13:45:12 -0700732 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700733
David Brown85904a82019-01-11 13:45:12 -0700734 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700735
David Brown84b49f72019-03-01 10:58:22 -0700736 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700737 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700738
739 // Should not fail, writing to bad regions does not assert
David Brown76101572019-02-28 11:29:03 -0700740 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true);
David Brown85904a82019-01-11 13:45:12 -0700741 if asserts != 0 {
742 warn!("At least one assert() was called");
743 fails += 1;
744 }
745
David Brown76101572019-02-28 11:29:03 -0700746 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700747
748 info!("Resuming an interrupted swap operation");
David Brown76101572019-02-28 11:29:03 -0700749 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700750
751 // This might throw no asserts, for large sector devices, where
752 // a single failure writing is indistinguishable from no failure,
753 // or throw a single assert for small sector devices that fail
754 // multiple times...
755 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100756 warn!("Expected single assert validating the primary slot, \
757 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700758 fails += 1;
759 }
760
761 if fails > 0 {
762 error!("Error running upgrade with status write fails");
763 }
764
765 fails > 0
766 } else {
David Brown76101572019-02-28 11:29:03 -0700767 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700768 let mut fails = 0;
769
770 info!("Try interrupted swap with status fails");
771
David Brown84b49f72019-03-01 10:58:22 -0700772 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700773 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700774
775 // This is expected to fail while writing to bad regions...
David Brown76101572019-02-28 11:29:03 -0700776 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700777 if asserts == 0 {
778 warn!("No assert() detected");
779 fails += 1;
780 }
781
782 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700783 }
David Brown5c9e0f12019-01-09 16:34:33 -0700784 }
785
786 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -0700787 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -0700788 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -0700789 if Caps::OverwriteUpgrade.present() {
790 return;
791 }
792
David Brown84b49f72019-03-01 10:58:22 -0700793 // Set this for each image.
794 for image in &self.images {
795 let dev_id = &image.slots[slot].dev_id;
796 let dev = flash.get_mut(&dev_id).unwrap();
797 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -0700798 let off = &image.slots[slot].base_off;
799 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -0700800 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -0700801
David Brown84b49f72019-03-01 10:58:22 -0700802 // Mark the status area as a bad area
803 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
804 }
David Brown5c9e0f12019-01-09 16:34:33 -0700805 }
806
David Brown76101572019-02-28 11:29:03 -0700807 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +0100808 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700809 return;
810 }
811
David Brown84b49f72019-03-01 10:58:22 -0700812 for image in &self.images {
813 let dev_id = &image.slots[slot].dev_id;
814 let dev = flash.get_mut(&dev_id).unwrap();
815 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -0700816
David Brown84b49f72019-03-01 10:58:22 -0700817 // Disabling write verification the only assert triggered by
818 // boot_go should be checking for integrity of status bytes.
819 dev.set_verify_writes(false);
820 }
David Brown5c9e0f12019-01-09 16:34:33 -0700821 }
822
David Browndb505822019-03-01 10:04:20 -0700823 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
824 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -0300825 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -0700826 // Clone the flash to have a new copy.
827 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700828
Fabio Utziged4a5362019-07-30 12:43:23 -0300829 if permanent {
830 self.mark_permanent_upgrades(&mut flash, 1);
831 }
David Brown5c9e0f12019-01-09 16:34:33 -0700832
David Browndb505822019-03-01 10:04:20 -0700833 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -0700834
David Browndb505822019-03-01 10:04:20 -0700835 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
836 (-0x13579, _) => (true, stop.unwrap()),
837 (0, _) => (false, -counter),
838 (x, _) => panic!("Unknown return: {}", x),
839 };
David Brown5c9e0f12019-01-09 16:34:33 -0700840
David Browndb505822019-03-01 10:04:20 -0700841 counter = 0;
842 if first_interrupted {
843 // fl.dump();
844 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
845 (-0x13579, _) => panic!("Shouldn't stop again"),
846 (0, _) => (),
847 (x, _) => panic!("Unknown return: {}", x),
848 }
849 }
David Brown5c9e0f12019-01-09 16:34:33 -0700850
David Browndb505822019-03-01 10:04:20 -0700851 (flash, count - counter)
852 }
853
854 fn try_revert(&self, count: usize) -> SimMultiFlash {
855 let mut flash = self.flash.clone();
856
857 // fl.write_file("image0.bin").unwrap();
858 for i in 0 .. count {
859 info!("Running boot pass {}", i + 1);
860 assert_eq!(c::boot_go(&mut flash, &self.areadesc, None, false), (0, 0));
861 }
862 flash
863 }
864
865 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
866 let mut flash = self.flash.clone();
867 let mut fails = 0;
868
869 let mut counter = stop;
870 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
871 if x != -0x13579 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700872 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -0700873 fails += 1;
874 }
875
Fabio Utzig8af7f792019-07-30 12:40:01 -0300876 // In a multi-image setup, copy done might be set if any number of
877 // images was already successfully swapped.
878 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
879 warn!("copy_done should be unset");
880 fails += 1;
881 }
882
David Browndb505822019-03-01 10:04:20 -0700883 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
884 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700885 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -0700886 fails += 1;
887 }
888
David Brown84b49f72019-03-01 10:58:22 -0700889 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -0700890 warn!("Image in the primary slot before revert is invalid at stop={}",
891 stop);
892 fails += 1;
893 }
David Brown84b49f72019-03-01 10:58:22 -0700894 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -0700895 warn!("Image in the secondary slot before revert is invalid at stop={}",
896 stop);
897 fails += 1;
898 }
David Brown84b49f72019-03-01 10:58:22 -0700899 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
900 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -0700901 warn!("Mismatched trailer for the primary slot before revert");
902 fails += 1;
903 }
David Brown84b49f72019-03-01 10:58:22 -0700904 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
905 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -0700906 warn!("Mismatched trailer for the secondary slot before revert");
907 fails += 1;
908 }
909
910 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700911 let mut counter = stop;
912 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
913 if x != -0x13579 {
914 warn!("Should have stopped revert at interruption point");
915 fails += 1;
916 }
917
David Browndb505822019-03-01 10:04:20 -0700918 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
919 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700920 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -0700921 fails += 1;
922 }
923
David Brown84b49f72019-03-01 10:58:22 -0700924 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -0700925 warn!("Image in the primary slot after revert is invalid at stop={}",
926 stop);
927 fails += 1;
928 }
David Brown84b49f72019-03-01 10:58:22 -0700929 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -0700930 warn!("Image in the secondary slot after revert is invalid at stop={}",
931 stop);
932 fails += 1;
933 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700934
David Brown84b49f72019-03-01 10:58:22 -0700935 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
936 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700937 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -0700938 fails += 1;
939 }
David Brown84b49f72019-03-01 10:58:22 -0700940 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
941 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -0700942 warn!("Mismatched trailer for the secondary slot after revert");
943 fails += 1;
944 }
945
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700946 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
947 if x != 0 {
948 warn!("Should have finished 3rd boot");
949 fails += 1;
950 }
951
952 if !self.verify_images(&flash, 0, 0) {
953 warn!("Image in the primary slot is invalid on 1st boot after revert");
954 fails += 1;
955 }
956 if !self.verify_images(&flash, 1, 1) {
957 warn!("Image in the secondary slot is invalid on 1st boot after revert");
958 fails += 1;
959 }
960
David Browndb505822019-03-01 10:04:20 -0700961 fails > 0
962 }
963
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700964
David Browndb505822019-03-01 10:04:20 -0700965 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
966 let mut flash = self.flash.clone();
967
David Brown84b49f72019-03-01 10:58:22 -0700968 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -0700969
970 let mut rng = rand::thread_rng();
971 let mut resets = vec![0i32; count];
972 let mut remaining_ops = total_ops;
973 for i in 0 .. count {
974 let ops = Range::new(1, remaining_ops / 2);
975 let reset_counter = ops.ind_sample(&mut rng);
976 let mut counter = reset_counter;
977 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
978 (0, _) | (-0x13579, _) => (),
979 (x, _) => panic!("Unknown return: {}", x),
980 }
981 remaining_ops -= reset_counter;
982 resets[i] = reset_counter;
983 }
984
985 match c::boot_go(&mut flash, &self.areadesc, None, false) {
986 (-0x13579, _) => panic!("Should not be have been interrupted!"),
David Brown5c9e0f12019-01-09 16:34:33 -0700987 (0, _) => (),
988 (x, _) => panic!("Unknown return: {}", x),
989 }
David Brown5c9e0f12019-01-09 16:34:33 -0700990
David Browndb505822019-03-01 10:04:20 -0700991 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -0700992 }
David Brown84b49f72019-03-01 10:58:22 -0700993
994 /// Verify the image in the given flash device, the specified slot
995 /// against the expected image.
996 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -0600997 self.images.iter().all(|image| {
998 verify_image(flash, &image.slots[slot],
999 match against {
1000 0 => &image.primaries,
1001 1 => &image.upgrades,
1002 _ => panic!("Invalid 'against'")
1003 })
1004 })
David Brown84b49f72019-03-01 10:58:22 -07001005 }
1006
David Brownc3898d62019-08-05 14:20:02 -06001007 /// Verify the images, according to the dependency test.
1008 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1009 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1010 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1011 if !verify_image(flash, &image.slots[0],
1012 match upgrade {
1013 UpgradeInfo::Upgraded => &image.upgrades,
1014 UpgradeInfo::Held => &image.primaries,
1015 }) {
1016 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1017 return true;
1018 }
1019 }
1020
1021 false
1022 }
1023
Fabio Utzig8af7f792019-07-30 12:40:01 -03001024 /// Verify that at least one of the trailers of the images have the
1025 /// specified values.
1026 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1027 magic: Option<u8>, image_ok: Option<u8>,
1028 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001029 self.images.iter().any(|image| {
1030 verify_trailer(flash, &image.slots[slot],
1031 magic, image_ok, copy_done)
1032 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001033 }
1034
David Brown84b49f72019-03-01 10:58:22 -07001035 /// Verify that the trailers of the images have the specified
1036 /// values.
1037 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1038 magic: Option<u8>, image_ok: Option<u8>,
1039 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001040 self.images.iter().all(|image| {
1041 verify_trailer(flash, &image.slots[slot],
1042 magic, image_ok, copy_done)
1043 })
David Brown84b49f72019-03-01 10:58:22 -07001044 }
1045
1046 /// Mark each of the images for permanent upgrade.
1047 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1048 for image in &self.images {
1049 mark_permanent_upgrade(flash, &image.slots[slot]);
1050 }
1051 }
1052
1053 /// Mark each of the images for permanent upgrade.
1054 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1055 for image in &self.images {
1056 mark_upgrade(flash, &image.slots[slot]);
1057 }
1058 }
David Brown297029a2019-08-13 14:29:51 -06001059
1060 /// Dump out the flash image(s) to one or more files for debugging
1061 /// purposes. The names will be written as either "{prefix}.mcubin" or
1062 /// "{prefix}-001.mcubin" depending on how many images there are.
1063 pub fn debug_dump(&self, prefix: &str) {
1064 for (id, fdev) in &self.flash {
1065 let name = if self.flash.len() == 1 {
1066 format!("{}.mcubin", prefix)
1067 } else {
1068 format!("{}-{:>0}.mcubin", prefix, id)
1069 };
1070 fdev.write_file(&name).unwrap();
1071 }
1072 }
David Brown5c9e0f12019-01-09 16:34:33 -07001073}
1074
1075/// Show the flash layout.
1076#[allow(dead_code)]
1077fn show_flash(flash: &dyn Flash) {
1078 println!("---- Flash configuration ----");
1079 for sector in flash.sector_iter() {
1080 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1081 sector.num, sector.base, sector.size);
1082 }
1083 println!("");
1084}
1085
1086/// Install a "program" into the given image. This fakes the image header, or at least all of the
1087/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001088fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownc3898d62019-08-05 14:20:02 -06001089 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001090 let offset = slot.base_off;
1091 let slot_len = slot.len;
1092 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001093
David Brown43643dd2019-01-11 15:43:28 -07001094 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001095
David Brownc3898d62019-08-05 14:20:02 -06001096 // Add the dependencies early to the tlv.
1097 for dep in deps.my_deps(offset, slot.index) {
1098 tlv.add_dependency(deps.other_id(), &dep);
1099 }
1100
David Brown5c9e0f12019-01-09 16:34:33 -07001101 const HDR_SIZE: usize = 32;
1102
1103 // Generate a boot header. Note that the size doesn't include the header.
1104 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001105 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -07001106 load_addr: 0,
1107 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001108 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001109 img_size: len as u32,
1110 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001111 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001112 _pad2: 0,
1113 };
1114
1115 let mut b_header = [0; HDR_SIZE];
1116 b_header[..32].clone_from_slice(header.as_raw());
1117 assert_eq!(b_header.len(), HDR_SIZE);
1118
1119 tlv.add_bytes(&b_header);
1120
1121 // The core of the image itself is just pseudorandom data.
1122 let mut b_img = vec![0; len];
1123 splat(&mut b_img, offset);
1124
David Browncb47dd72019-08-05 14:21:49 -06001125 // Add some information at the start of the payload to make it easier
1126 // to see what it is. This will fail if the image itself is too small.
1127 {
1128 let mut wr = Cursor::new(&mut b_img);
1129 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1130 offset, dev_id, slot).unwrap();
1131 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1132 }
1133
David Brown5c9e0f12019-01-09 16:34:33 -07001134 // TLV signatures work over plain image
1135 tlv.add_bytes(&b_img);
1136
1137 // Generate encrypted images
1138 let flag = TlvFlags::ENCRYPTED as u32;
1139 let is_encrypted = (tlv.get_flags() & flag) == flag;
1140 let mut b_encimg = vec![];
1141 if is_encrypted {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001142 tlv.generate_enc_key();
1143 let enc_key = tlv.get_enc_key();
1144 let key = GenericArray::from_slice(enc_key.as_slice());
David Brown5c9e0f12019-01-09 16:34:33 -07001145 let nonce = GenericArray::from_slice(&[0; 16]);
1146 let mut cipher = Aes128Ctr::new(&key, &nonce);
1147 b_encimg = b_img.clone();
1148 cipher.apply_keystream(&mut b_encimg);
1149 }
1150
1151 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001152 if bad_sig {
1153 tlv.corrupt_sig();
1154 }
1155 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001156
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001157 let dev = flash.get_mut(&dev_id).unwrap();
1158
David Brown5c9e0f12019-01-09 16:34:33 -07001159 let mut buf = vec![];
1160 buf.append(&mut b_header.to_vec());
1161 buf.append(&mut b_img);
1162 buf.append(&mut b_tlv.clone());
1163
David Brown95de4502019-11-15 12:01:34 -07001164 // Pad the buffer to a multiple of the flash alignment.
1165 let align = dev.align();
1166 while buf.len() % align != 0 {
1167 buf.push(dev.erased_val());
1168 }
1169
David Brown5c9e0f12019-01-09 16:34:33 -07001170 let mut encbuf = vec![];
1171 if is_encrypted {
1172 encbuf.append(&mut b_header.to_vec());
1173 encbuf.append(&mut b_encimg);
1174 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001175
1176 while encbuf.len() % align != 0 {
1177 encbuf.push(dev.erased_val());
1178 }
David Brown5c9e0f12019-01-09 16:34:33 -07001179 }
1180
David Vincze2d736ad2019-02-18 11:50:22 +01001181 // Since images are always non-encrypted in the primary slot, we first write
1182 // an encrypted image, re-read to use for verification, erase + flash
1183 // un-encrypted. In the secondary slot the image is written un-encrypted,
1184 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001185
David Brown3b090212019-07-30 15:59:28 -06001186 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001187 let enc_copy: Option<Vec<u8>>;
1188
1189 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001190 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001191
1192 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001193 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001194
1195 enc_copy = Some(enc);
1196
David Brown76101572019-02-28 11:29:03 -07001197 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001198 } else {
1199 enc_copy = None;
1200 }
1201
David Brown76101572019-02-28 11:29:03 -07001202 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001203
1204 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001205 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001206
David Brownca234692019-02-28 11:22:19 -07001207 ImageData {
1208 plain: copy,
1209 cipher: enc_copy,
1210 }
David Brown5c9e0f12019-01-09 16:34:33 -07001211 } else {
1212
David Brown76101572019-02-28 11:29:03 -07001213 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001214
1215 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001216 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001217
1218 let enc_copy: Option<Vec<u8>>;
1219
1220 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001221 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001222
David Brown76101572019-02-28 11:29:03 -07001223 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001224
1225 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001226 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001227
1228 enc_copy = Some(enc);
1229 } else {
1230 enc_copy = None;
1231 }
1232
David Brownca234692019-02-28 11:22:19 -07001233 ImageData {
1234 plain: copy,
1235 cipher: enc_copy,
1236 }
David Brown5c9e0f12019-01-09 16:34:33 -07001237 }
David Brown5c9e0f12019-01-09 16:34:33 -07001238}
1239
David Brown873be312019-09-03 12:22:32 -06001240/// Install no image. This is used when no upgrade happens.
1241fn install_no_image() -> ImageData {
1242 ImageData {
1243 plain: vec![],
1244 cipher: None,
1245 }
1246}
1247
David Brown5c9e0f12019-01-09 16:34:33 -07001248fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001249 if Caps::EcdsaP224.present() {
1250 panic!("Ecdsa P224 not supported in Simulator");
1251 }
David Brown5c9e0f12019-01-09 16:34:33 -07001252
David Brownb8882112019-01-11 14:04:11 -07001253 if Caps::EncKw.present() {
1254 if Caps::RSA2048.present() {
1255 TlvGen::new_rsa_kw()
1256 } else if Caps::EcdsaP256.present() {
1257 TlvGen::new_ecdsa_kw()
1258 } else {
1259 TlvGen::new_enc_kw()
1260 }
1261 } else if Caps::EncRsa.present() {
1262 if Caps::RSA2048.present() {
1263 TlvGen::new_sig_enc_rsa()
1264 } else {
1265 TlvGen::new_enc_rsa()
1266 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001267 } else if Caps::EncEc256.present() {
1268 //FIXME: should fail with RSA signature?
1269 TlvGen::new_ecdsa_ecies_p256()
David Brownb8882112019-01-11 14:04:11 -07001270 } else {
1271 // The non-encrypted configuration.
1272 if Caps::RSA2048.present() {
1273 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001274 } else if Caps::RSA3072.present() {
1275 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001276 } else if Caps::EcdsaP256.present() {
1277 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001278 } else if Caps::Ed25519.present() {
1279 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001280 } else {
1281 TlvGen::new_hash_only()
1282 }
1283 }
David Brown5c9e0f12019-01-09 16:34:33 -07001284}
1285
David Brownca234692019-02-28 11:22:19 -07001286impl ImageData {
1287 /// Find the image contents for the given slot. This assumes that slot 0
1288 /// is unencrypted, and slot 1 is encrypted.
1289 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001290 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
1291 Caps::EncEc256.present();
David Brownca234692019-02-28 11:22:19 -07001292 match (encrypted, slot) {
1293 (false, _) => &self.plain,
1294 (true, 0) => &self.plain,
1295 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1296 _ => panic!("Invalid slot requested"),
1297 }
David Brown5c9e0f12019-01-09 16:34:33 -07001298 }
1299}
1300
David Brown5c9e0f12019-01-09 16:34:33 -07001301/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001302fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1303 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001304 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001305 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001306
1307 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001308 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001309 let dev = flash.get(&dev_id).unwrap();
1310 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001311
1312 if buf != &copy[..] {
1313 for i in 0 .. buf.len() {
1314 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001315 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1316 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001317 break;
1318 }
1319 }
1320 false
1321 } else {
1322 true
1323 }
1324}
1325
David Brown3b090212019-07-30 15:59:28 -06001326fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001327 magic: Option<u8>, image_ok: Option<u8>,
1328 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001329 if Caps::OverwriteUpgrade.present() {
1330 return true;
1331 }
David Brown5c9e0f12019-01-09 16:34:33 -07001332
David Brown3b090212019-07-30 15:59:28 -06001333 let offset = slot.trailer_off + c::boot_max_align();
1334 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001335 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001336 let mut failed = false;
1337
David Brown76101572019-02-28 11:29:03 -07001338 let dev = flash.get(&dev_id).unwrap();
1339 let erased_val = dev.erased_val();
1340 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001341
1342 failed |= match magic {
1343 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001344 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001345 warn!("\"magic\" mismatch at {:#x}", offset);
1346 true
1347 } else if v == 3 {
1348 let expected = [erased_val; 16];
Christopher Collinsa1c12042019-05-23 14:00:28 -07001349 if &copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001350 warn!("\"magic\" mismatch at {:#x}", offset);
1351 true
1352 } else {
1353 false
1354 }
1355 } else {
1356 false
1357 }
1358 },
1359 None => false,
1360 };
1361
1362 failed |= match image_ok {
1363 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001364 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001365 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1366 true
1367 } else {
1368 false
1369 }
1370 },
1371 None => false,
1372 };
1373
1374 failed |= match copy_done {
1375 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001376 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001377 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1378 true
1379 } else {
1380 false
1381 }
1382 },
1383 None => false,
1384 };
1385
1386 !failed
1387}
1388
David Brown297029a2019-08-13 14:29:51 -06001389/// Install a partition table. This is a simplified partition table that
1390/// we write at the beginning of flash so make it easier for external tools
1391/// to analyze these images.
1392fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1393 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1394 for &id in &ids {
1395 // If there are any partitions in this device that start at 0, and
1396 // aren't marked as the BootLoader partition, avoid adding the
1397 // partition table. This makes it harder to view the image, but
1398 // avoids messing up images already written.
1399 if areadesc.iter_areas().any(|area| {
1400 area.device_id == id &&
1401 area.off == 0 &&
1402 area.flash_id != FlashId::BootLoader
1403 }) {
1404 if log_enabled!(Info) {
1405 let special: Vec<FlashId> = areadesc.iter_areas()
1406 .filter(|area| area.device_id == id && area.off == 0)
1407 .map(|area| area.flash_id)
1408 .collect();
1409 info!("Skipping partition table: {:?}", special);
1410 }
1411 break;
1412 }
1413
1414 let mut buf: Vec<u8> = vec![];
1415 write!(&mut buf, "mcuboot\0").unwrap();
1416
1417 // Iterate through all of the partitions in that device, and encode
1418 // into the table.
1419 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1420 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1421
1422 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1423 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1424 buf.write_u32::<LittleEndian>(area.off).unwrap();
1425 buf.write_u32::<LittleEndian>(area.size).unwrap();
1426 buf.write_u32::<LittleEndian>(0).unwrap();
1427 }
1428
1429 let dev = flash.get_mut(&id).unwrap();
1430
1431 // Pad to alignment.
1432 while buf.len() % dev.align() != 0 {
1433 buf.push(0);
1434 }
1435
1436 dev.write(0, &buf).unwrap();
1437 }
1438}
1439
David Brown5c9e0f12019-01-09 16:34:33 -07001440/// The image header
1441#[repr(C)]
1442pub struct ImageHeader {
1443 magic: u32,
1444 load_addr: u32,
1445 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001446 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001447 img_size: u32,
1448 flags: u32,
1449 ver: ImageVersion,
1450 _pad2: u32,
1451}
1452
1453impl AsRaw for ImageHeader {}
1454
1455#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001456#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001457pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001458 pub major: u8,
1459 pub minor: u8,
1460 pub revision: u16,
1461 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001462}
1463
David Brownc3898d62019-08-05 14:20:02 -06001464#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001465pub struct SlotInfo {
1466 pub base_off: usize,
1467 pub trailer_off: usize,
1468 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001469 // Which slot within this device.
1470 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001471 pub dev_id: u8,
1472}
1473
David Brown347dc572019-11-15 11:37:25 -07001474const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1475 0x60, 0xd2, 0xef, 0x7f,
1476 0x35, 0x52, 0x50, 0x0f,
1477 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001478
1479// Replicates defines found in bootutil.h
1480const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1481const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1482
1483const BOOT_FLAG_SET: Option<u8> = Some(1);
1484const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1485
1486/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001487pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1488 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001489 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001490 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001491 if offset % align != 0 || MAGIC.len() % align != 0 {
1492 // The write size is larger than the magic value. Fill a buffer
1493 // with the erased value, put the MAGIC in it, and write it in its
1494 // entirety.
1495 let mut buf = vec![dev.erased_val(); align];
1496 buf[(offset % align)..].copy_from_slice(MAGIC);
1497 dev.write(offset - (offset % align), &buf).unwrap();
1498 } else {
1499 dev.write(offset, MAGIC).unwrap();
1500 }
David Brown5c9e0f12019-01-09 16:34:33 -07001501}
1502
1503/// Writes the image_ok flag which, guess what, tells the bootloader
1504/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001505fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001506 // Overwrite mode always is permanent, and only the magic is used in
1507 // the trailer. To avoid problems with large write sizes, don't try to
1508 // set anything in this case.
1509 if Caps::OverwriteUpgrade.present() {
1510 return;
1511 }
1512
David Brown76101572019-02-28 11:29:03 -07001513 let dev = flash.get_mut(&slot.dev_id).unwrap();
1514 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001515 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001516 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001517 let align = dev.align();
1518 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001519}
1520
1521// Drop some pseudo-random gibberish onto the data.
1522fn splat(data: &mut [u8], seed: usize) {
1523 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
1524 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
1525 rng.fill_bytes(data);
1526}
1527
1528/// Return a read-only view into the raw bytes of this object
1529trait AsRaw : Sized {
1530 fn as_raw<'a>(&'a self) -> &'a [u8] {
1531 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1532 mem::size_of::<Self>()) }
1533 }
1534}
1535
1536pub fn show_sizes() {
1537 // This isn't panic safe.
1538 for min in &[1, 2, 4, 8] {
1539 let msize = c::boot_trailer_sz(*min);
1540 println!("{:2}: {} (0x{:x})", min, msize, msize);
1541 }
1542}
David Brown95de4502019-11-15 12:01:34 -07001543
1544#[cfg(not(feature = "large-write"))]
1545fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001546 &[1, 2, 4, 8]
1547}
1548
1549#[cfg(feature = "large-write")]
1550fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001551 &[1, 2, 4, 8, 128, 512]
1552}