blob: 663835b443eb7c8473d11179201eb407e805c995 [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,
194 Err(_) => {
195 panic!("Unable to perform basic upgrade");
196 },
197 };
198
199 images.total_count = Some(total_count);
200 images
201 }
202
203 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700204 let mut bad_flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600205 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
206 let dep = BoringDep(image_num);
207 let primaries = install_image(&mut bad_flash, &slots[0], 32784, &dep, false);
208 let upgrades = install_image(&mut bad_flash, &slots[1], 41928, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700209 OneImage {
210 slots: slots,
211 primaries: primaries,
212 upgrades: upgrades,
213 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700214 Images {
David Brown76101572019-02-28 11:29:03 -0700215 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700216 areadesc: self.areadesc,
David Brown84b49f72019-03-01 10:58:22 -0700217 images: images,
David Browne5133242019-02-28 11:05:19 -0700218 total_count: None,
219 }
220 }
221
222 /// Build the Flash and area descriptor for a given device.
David Brown76101572019-02-28 11:29:03 -0700223 pub fn make_device(device: DeviceName, align: u8, erased_val: u8) -> (SimMultiFlash, AreaDesc) {
David Browne5133242019-02-28 11:05:19 -0700224 match device {
225 DeviceName::Stm32f4 => {
226 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700227 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
228 64 * 1024,
229 128 * 1024, 128 * 1024, 128 * 1024],
230 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700231 let dev_id = 0;
232 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700233 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700234 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
235 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
236 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
237
David Brown76101572019-02-28 11:29:03 -0700238 let mut flash = SimMultiFlash::new();
239 flash.insert(dev_id, dev);
240 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700241 }
242 DeviceName::K64f => {
243 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700244 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700245
246 let dev_id = 0;
247 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700248 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700249 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
250 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
251 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
252
David Brown76101572019-02-28 11:29:03 -0700253 let mut flash = SimMultiFlash::new();
254 flash.insert(dev_id, dev);
255 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700256 }
257 DeviceName::K64fBig => {
258 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
259 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700260 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700261
262 let dev_id = 0;
263 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700264 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700265 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
266 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
267 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
268
David Brown76101572019-02-28 11:29:03 -0700269 let mut flash = SimMultiFlash::new();
270 flash.insert(dev_id, dev);
271 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700272 }
273 DeviceName::Nrf52840 => {
274 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
275 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700276 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700277
278 let dev_id = 0;
279 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700280 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700281 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
282 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
283 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
284
David Brown76101572019-02-28 11:29:03 -0700285 let mut flash = SimMultiFlash::new();
286 flash.insert(dev_id, dev);
287 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700288 }
289 DeviceName::Nrf52840SpiFlash => {
290 // Simulate nrf52840 with external SPI flash. The external SPI flash
291 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700292 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
293 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700294
295 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700296 areadesc.add_flash_sectors(0, &dev0);
297 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700298
299 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
300 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
301 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
302
David Brown76101572019-02-28 11:29:03 -0700303 let mut flash = SimMultiFlash::new();
304 flash.insert(0, dev0);
305 flash.insert(1, dev1);
306 (flash, areadesc)
David Browne5133242019-02-28 11:05:19 -0700307 }
David Brown2bff6472019-03-05 13:58:35 -0700308 DeviceName::K64fMulti => {
309 // NXP style flash, but larger, to support multiple images.
310 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
311
312 let dev_id = 0;
313 let mut areadesc = AreaDesc::new();
314 areadesc.add_flash_sectors(dev_id, &dev);
315 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
316 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
317 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
318 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
319 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
320
321 let mut flash = SimMultiFlash::new();
322 flash.insert(dev_id, dev);
323 (flash, areadesc)
324 }
David Browne5133242019-02-28 11:05:19 -0700325 }
326 }
David Brownc3898d62019-08-05 14:20:02 -0600327
328 pub fn num_images(&self) -> usize {
329 self.slots.len()
330 }
David Browne5133242019-02-28 11:05:19 -0700331}
332
David Brown5c9e0f12019-01-09 16:34:33 -0700333impl Images {
334 /// A simple upgrade without forced failures.
335 ///
336 /// Returns the number of flash operations which can later be used to
337 /// inject failures at chosen steps.
Fabio Utziged4a5362019-07-30 12:43:23 -0300338 pub fn run_basic_upgrade(&self, permanent: bool) -> Result<i32, ()> {
339 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700340 info!("Total flash operation count={}", total_count);
341
David Brown84b49f72019-03-01 10:58:22 -0700342 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700343 warn!("Image mismatch after first boot");
344 Err(())
345 } else {
346 Ok(total_count)
347 }
348 }
349
David Brownc3898d62019-08-05 14:20:02 -0600350 /// Test a simple upgrade, with dependencies given, and verify that the
351 /// image does as is described in the test.
352 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
353 let (flash, _) = self.try_upgrade(None, true);
354
355 self.verify_dep_images(&flash, deps)
356 }
357
David Brown5c9e0f12019-01-09 16:34:33 -0700358 pub fn run_basic_revert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700359 if Caps::OverwriteUpgrade.present() {
360 return false;
361 }
David Brown5c9e0f12019-01-09 16:34:33 -0700362
David Brown5c9e0f12019-01-09 16:34:33 -0700363 let mut fails = 0;
364
365 // FIXME: this test would also pass if no swap is ever performed???
366 if Caps::SwapUpgrade.present() {
367 for count in 2 .. 5 {
368 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700369 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700370 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700371 error!("Revert failure on count {}", count);
372 fails += 1;
373 }
374 }
375 }
376
377 fails > 0
378 }
379
380 pub fn run_perm_with_fails(&self) -> bool {
381 let mut fails = 0;
382 let total_flash_ops = self.total_count.unwrap();
383
384 // Let's try an image halfway through.
385 for i in 1 .. total_flash_ops {
386 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300387 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700388 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700389 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700390 warn!("FAIL at step {} of {}", i, total_flash_ops);
391 fails += 1;
392 }
393
David Brown84b49f72019-03-01 10:58:22 -0700394 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
395 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100396 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700397 fails += 1;
398 }
399
David Brown84b49f72019-03-01 10:58:22 -0700400 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
401 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100402 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700403 fails += 1;
404 }
405
406 if Caps::SwapUpgrade.present() {
David Brown84b49f72019-03-01 10:58:22 -0700407 if !self.verify_images(&flash, 1, 0) {
David Vincze2d736ad2019-02-18 11:50:22 +0100408 warn!("Secondary slot FAIL at step {} of {}",
409 i, total_flash_ops);
David Brown5c9e0f12019-01-09 16:34:33 -0700410 fails += 1;
411 }
412 }
413 }
414
415 if fails > 0 {
416 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
417 fails as f32 * 100.0 / total_flash_ops as f32);
418 }
419
420 fails > 0
421 }
422
David Brown5c9e0f12019-01-09 16:34:33 -0700423 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
424 let mut fails = 0;
425 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700426 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700427 info!("Random interruptions at reset points={:?}", total_counts);
428
David Brown84b49f72019-03-01 10:58:22 -0700429 let primary_slot_ok = self.verify_images(&flash, 0, 1);
David Vincze2d736ad2019-02-18 11:50:22 +0100430 let secondary_slot_ok = if Caps::SwapUpgrade.present() {
David Brown84b49f72019-03-01 10:58:22 -0700431 // TODO: This result is ignored.
432 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700433 } else {
434 true
435 };
David Vincze2d736ad2019-02-18 11:50:22 +0100436 if !primary_slot_ok || !secondary_slot_ok {
437 error!("Image mismatch after random interrupts: primary slot={} \
438 secondary slot={}",
439 if primary_slot_ok { "ok" } else { "fail" },
440 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700441 fails += 1;
442 }
David Brown84b49f72019-03-01 10:58:22 -0700443 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
444 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100445 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700446 fails += 1;
447 }
David Brown84b49f72019-03-01 10:58:22 -0700448 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
449 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100450 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700451 fails += 1;
452 }
453
454 if fails > 0 {
455 error!("Error testing perm upgrade with {} fails", total_fails);
456 }
457
458 fails > 0
459 }
460
David Brown5c9e0f12019-01-09 16:34:33 -0700461 pub fn run_revert_with_fails(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700462 if Caps::OverwriteUpgrade.present() {
463 return false;
464 }
David Brown5c9e0f12019-01-09 16:34:33 -0700465
David Brown5c9e0f12019-01-09 16:34:33 -0700466 let mut fails = 0;
467
468 if Caps::SwapUpgrade.present() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300469 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700470 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700471 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700472 error!("Revert failed at interruption {}", i);
473 fails += 1;
474 }
475 }
476 }
477
478 fails > 0
479 }
480
David Brown5c9e0f12019-01-09 16:34:33 -0700481 pub fn run_norevert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700482 if Caps::OverwriteUpgrade.present() {
483 return false;
484 }
David Brown5c9e0f12019-01-09 16:34:33 -0700485
David Brown76101572019-02-28 11:29:03 -0700486 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700487 let mut fails = 0;
488
489 info!("Try norevert");
490
491 // First do a normal upgrade...
David Brown76101572019-02-28 11:29:03 -0700492 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700493 if result != 0 {
494 warn!("Failed first boot");
495 fails += 1;
496 }
497
498 //FIXME: copy_done is written by boot_go, is it ok if no copy
499 // was ever done?
500
David Brown84b49f72019-03-01 10:58:22 -0700501 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100502 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700503 fails += 1;
504 }
David Brown84b49f72019-03-01 10:58:22 -0700505 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
506 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100507 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700508 fails += 1;
509 }
David Brown84b49f72019-03-01 10:58:22 -0700510 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
511 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100512 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700513 fails += 1;
514 }
515
David Vincze2d736ad2019-02-18 11:50:22 +0100516 // Marks image in the primary slot as permanent,
517 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700518 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700519
David Brown84b49f72019-03-01 10:58:22 -0700520 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
521 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100522 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700523 fails += 1;
524 }
525
David Brown76101572019-02-28 11:29:03 -0700526 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700527 if result != 0 {
528 warn!("Failed second boot");
529 fails += 1;
530 }
531
David Brown84b49f72019-03-01 10:58:22 -0700532 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
533 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100534 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700535 fails += 1;
536 }
David Brown84b49f72019-03-01 10:58:22 -0700537 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700538 warn!("Failed image verification");
539 fails += 1;
540 }
541
542 if fails > 0 {
543 error!("Error running upgrade without revert");
544 }
545
546 fails > 0
547 }
548
David Vincze2d736ad2019-02-18 11:50:22 +0100549 // Tests a new image written to the primary slot that already has magic and
550 // image_ok set while there is no image on the secondary slot, so no revert
551 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700552 pub fn run_norevert_newimage(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700553 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700554 let mut fails = 0;
555
556 info!("Try non-revert on imgtool generated image");
557
David Brown84b49f72019-03-01 10:58:22 -0700558 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700559
David Vincze2d736ad2019-02-18 11:50:22 +0100560 // This simulates writing an image created by imgtool to
561 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700562 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
563 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100564 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700565 fails += 1;
566 }
567
568 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700569 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700570 if result != 0 {
571 warn!("Failed first boot");
572 fails += 1;
573 }
574
575 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700576 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700577 warn!("Failed image verification");
578 fails += 1;
579 }
David Brown84b49f72019-03-01 10:58:22 -0700580 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
581 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100582 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700583 fails += 1;
584 }
David Brown84b49f72019-03-01 10:58:22 -0700585 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
586 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100587 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700588 fails += 1;
589 }
590
591 if fails > 0 {
592 error!("Expected a non revert with new image");
593 }
594
595 fails > 0
596 }
597
David Vincze2d736ad2019-02-18 11:50:22 +0100598 // Tests a new image written to the primary slot that already has magic and
599 // image_ok set while there is no image on the secondary slot, so no revert
600 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700601 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700602 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700603 let mut fails = 0;
604
605 info!("Try upgrade image with bad signature");
606
David Brown84b49f72019-03-01 10:58:22 -0700607 self.mark_upgrades(&mut flash, 0);
608 self.mark_permanent_upgrades(&mut flash, 0);
609 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700610
David Brown84b49f72019-03-01 10:58:22 -0700611 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
612 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100613 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700614 fails += 1;
615 }
616
617 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700618 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700619 if result != 0 {
620 warn!("Failed first boot");
621 fails += 1;
622 }
623
624 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700625 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700626 warn!("Failed image verification");
627 fails += 1;
628 }
David Brown84b49f72019-03-01 10:58:22 -0700629 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
630 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100631 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700632 fails += 1;
633 }
634
635 if fails > 0 {
636 error!("Expected an upgrade failure when image has bad signature");
637 }
638
639 fails > 0
640 }
641
David Brown5c9e0f12019-01-09 16:34:33 -0700642 fn trailer_sz(&self, align: usize) -> usize {
643 c::boot_trailer_sz(align as u8) as usize
644 }
645
646 // FIXME: could get status sz from bootloader
David Brown5c9e0f12019-01-09 16:34:33 -0700647 fn status_sz(&self, align: usize) -> usize {
David Brown9930a3e2019-01-11 12:28:26 -0700648 let bias = if Caps::EncRsa.present() || Caps::EncKw.present() {
649 32
650 } else {
651 0
652 };
David Brown5c9e0f12019-01-09 16:34:33 -0700653
Christopher Collinsa1c12042019-05-23 14:00:28 -0700654 self.trailer_sz(align) - (16 + 32 + bias)
David Brown5c9e0f12019-01-09 16:34:33 -0700655 }
656
657 /// This test runs a simple upgrade with no fails in the images, but
658 /// allowing for fails in the status area. This should run to the end
659 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700660 pub fn run_with_status_fails_complete(&self) -> bool {
David Vincze2d736ad2019-02-18 11:50:22 +0100661 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700662 return false;
663 }
664
David Brown76101572019-02-28 11:29:03 -0700665 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700666 let mut fails = 0;
667
668 info!("Try swap with status fails");
669
David Brown84b49f72019-03-01 10:58:22 -0700670 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700671 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700672
David Brown76101572019-02-28 11:29:03 -0700673 let (result, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown5c9e0f12019-01-09 16:34:33 -0700674 if result != 0 {
675 warn!("Failed!");
676 fails += 1;
677 }
678
679 // Failed writes to the marked "bad" region don't assert anymore.
680 // Any detected assert() is happening in another part of the code.
681 if asserts != 0 {
682 warn!("At least one assert() was called");
683 fails += 1;
684 }
685
David Brown84b49f72019-03-01 10:58:22 -0700686 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
687 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100688 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700689 fails += 1;
690 }
691
David Brown84b49f72019-03-01 10:58:22 -0700692 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700693 warn!("Failed image verification");
694 fails += 1;
695 }
696
David Vincze2d736ad2019-02-18 11:50:22 +0100697 info!("validate primary slot enabled; \
698 re-run of boot_go should just work");
David Brown76101572019-02-28 11:29:03 -0700699 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700700 if result != 0 {
701 warn!("Failed!");
702 fails += 1;
703 }
704
705 if fails > 0 {
706 error!("Error running upgrade with status write fails");
707 }
708
709 fails > 0
710 }
711
712 /// This test runs a simple upgrade with no fails in the images, but
713 /// allowing for fails in the status area. This should run to the end
714 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700715 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown85904a82019-01-11 13:45:12 -0700716 if Caps::OverwriteUpgrade.present() {
717 false
David Vincze2d736ad2019-02-18 11:50:22 +0100718 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700719
David Brown76101572019-02-28 11:29:03 -0700720 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700721 let mut fails = 0;
722 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700723
David Brown85904a82019-01-11 13:45:12 -0700724 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700725
David Brown85904a82019-01-11 13:45:12 -0700726 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700727
David Brown84b49f72019-03-01 10:58:22 -0700728 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700729 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700730
731 // Should not fail, writing to bad regions does not assert
David Brown76101572019-02-28 11:29:03 -0700732 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true);
David Brown85904a82019-01-11 13:45:12 -0700733 if asserts != 0 {
734 warn!("At least one assert() was called");
735 fails += 1;
736 }
737
David Brown76101572019-02-28 11:29:03 -0700738 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700739
740 info!("Resuming an interrupted swap operation");
David Brown76101572019-02-28 11:29:03 -0700741 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700742
743 // This might throw no asserts, for large sector devices, where
744 // a single failure writing is indistinguishable from no failure,
745 // or throw a single assert for small sector devices that fail
746 // multiple times...
747 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100748 warn!("Expected single assert validating the primary slot, \
749 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700750 fails += 1;
751 }
752
753 if fails > 0 {
754 error!("Error running upgrade with status write fails");
755 }
756
757 fails > 0
758 } else {
David Brown76101572019-02-28 11:29:03 -0700759 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700760 let mut fails = 0;
761
762 info!("Try interrupted swap with status fails");
763
David Brown84b49f72019-03-01 10:58:22 -0700764 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700765 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700766
767 // This is expected to fail while writing to bad regions...
David Brown76101572019-02-28 11:29:03 -0700768 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700769 if asserts == 0 {
770 warn!("No assert() detected");
771 fails += 1;
772 }
773
774 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700775 }
David Brown5c9e0f12019-01-09 16:34:33 -0700776 }
777
778 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -0700779 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -0700780 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -0700781 if Caps::OverwriteUpgrade.present() {
782 return;
783 }
784
David Brown84b49f72019-03-01 10:58:22 -0700785 // Set this for each image.
786 for image in &self.images {
787 let dev_id = &image.slots[slot].dev_id;
788 let dev = flash.get_mut(&dev_id).unwrap();
789 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -0700790 let off = &image.slots[slot].base_off;
791 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -0700792 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -0700793
David Brown84b49f72019-03-01 10:58:22 -0700794 // Mark the status area as a bad area
795 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
796 }
David Brown5c9e0f12019-01-09 16:34:33 -0700797 }
798
David Brown76101572019-02-28 11:29:03 -0700799 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +0100800 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700801 return;
802 }
803
David Brown84b49f72019-03-01 10:58:22 -0700804 for image in &self.images {
805 let dev_id = &image.slots[slot].dev_id;
806 let dev = flash.get_mut(&dev_id).unwrap();
807 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -0700808
David Brown84b49f72019-03-01 10:58:22 -0700809 // Disabling write verification the only assert triggered by
810 // boot_go should be checking for integrity of status bytes.
811 dev.set_verify_writes(false);
812 }
David Brown5c9e0f12019-01-09 16:34:33 -0700813 }
814
David Browndb505822019-03-01 10:04:20 -0700815 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
816 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -0300817 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -0700818 // Clone the flash to have a new copy.
819 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700820
Fabio Utziged4a5362019-07-30 12:43:23 -0300821 if permanent {
822 self.mark_permanent_upgrades(&mut flash, 1);
823 }
David Brown5c9e0f12019-01-09 16:34:33 -0700824
David Browndb505822019-03-01 10:04:20 -0700825 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -0700826
David Browndb505822019-03-01 10:04:20 -0700827 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
828 (-0x13579, _) => (true, stop.unwrap()),
829 (0, _) => (false, -counter),
830 (x, _) => panic!("Unknown return: {}", x),
831 };
David Brown5c9e0f12019-01-09 16:34:33 -0700832
David Browndb505822019-03-01 10:04:20 -0700833 counter = 0;
834 if first_interrupted {
835 // fl.dump();
836 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
837 (-0x13579, _) => panic!("Shouldn't stop again"),
838 (0, _) => (),
839 (x, _) => panic!("Unknown return: {}", x),
840 }
841 }
David Brown5c9e0f12019-01-09 16:34:33 -0700842
David Browndb505822019-03-01 10:04:20 -0700843 (flash, count - counter)
844 }
845
846 fn try_revert(&self, count: usize) -> SimMultiFlash {
847 let mut flash = self.flash.clone();
848
849 // fl.write_file("image0.bin").unwrap();
850 for i in 0 .. count {
851 info!("Running boot pass {}", i + 1);
852 assert_eq!(c::boot_go(&mut flash, &self.areadesc, None, false), (0, 0));
853 }
854 flash
855 }
856
857 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
858 let mut flash = self.flash.clone();
859 let mut fails = 0;
860
861 let mut counter = stop;
862 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
863 if x != -0x13579 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700864 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -0700865 fails += 1;
866 }
867
Fabio Utzig8af7f792019-07-30 12:40:01 -0300868 // In a multi-image setup, copy done might be set if any number of
869 // images was already successfully swapped.
870 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
871 warn!("copy_done should be unset");
872 fails += 1;
873 }
874
David Browndb505822019-03-01 10:04:20 -0700875 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
876 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700877 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -0700878 fails += 1;
879 }
880
David Brown84b49f72019-03-01 10:58:22 -0700881 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -0700882 warn!("Image in the primary slot before revert is invalid at stop={}",
883 stop);
884 fails += 1;
885 }
David Brown84b49f72019-03-01 10:58:22 -0700886 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -0700887 warn!("Image in the secondary slot before revert is invalid at stop={}",
888 stop);
889 fails += 1;
890 }
David Brown84b49f72019-03-01 10:58:22 -0700891 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
892 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -0700893 warn!("Mismatched trailer for the primary slot before revert");
894 fails += 1;
895 }
David Brown84b49f72019-03-01 10:58:22 -0700896 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
897 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -0700898 warn!("Mismatched trailer for the secondary slot before revert");
899 fails += 1;
900 }
901
902 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700903 let mut counter = stop;
904 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
905 if x != -0x13579 {
906 warn!("Should have stopped revert at interruption point");
907 fails += 1;
908 }
909
David Browndb505822019-03-01 10:04:20 -0700910 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
911 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700912 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -0700913 fails += 1;
914 }
915
David Brown84b49f72019-03-01 10:58:22 -0700916 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -0700917 warn!("Image in the primary slot after revert is invalid at stop={}",
918 stop);
919 fails += 1;
920 }
David Brown84b49f72019-03-01 10:58:22 -0700921 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -0700922 warn!("Image in the secondary slot after revert is invalid at stop={}",
923 stop);
924 fails += 1;
925 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700926
David Brown84b49f72019-03-01 10:58:22 -0700927 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
928 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700929 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -0700930 fails += 1;
931 }
David Brown84b49f72019-03-01 10:58:22 -0700932 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
933 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -0700934 warn!("Mismatched trailer for the secondary slot after revert");
935 fails += 1;
936 }
937
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700938 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
939 if x != 0 {
940 warn!("Should have finished 3rd boot");
941 fails += 1;
942 }
943
944 if !self.verify_images(&flash, 0, 0) {
945 warn!("Image in the primary slot is invalid on 1st boot after revert");
946 fails += 1;
947 }
948 if !self.verify_images(&flash, 1, 1) {
949 warn!("Image in the secondary slot is invalid on 1st boot after revert");
950 fails += 1;
951 }
952
David Browndb505822019-03-01 10:04:20 -0700953 fails > 0
954 }
955
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700956
David Browndb505822019-03-01 10:04:20 -0700957 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
958 let mut flash = self.flash.clone();
959
David Brown84b49f72019-03-01 10:58:22 -0700960 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -0700961
962 let mut rng = rand::thread_rng();
963 let mut resets = vec![0i32; count];
964 let mut remaining_ops = total_ops;
965 for i in 0 .. count {
966 let ops = Range::new(1, remaining_ops / 2);
967 let reset_counter = ops.ind_sample(&mut rng);
968 let mut counter = reset_counter;
969 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
970 (0, _) | (-0x13579, _) => (),
971 (x, _) => panic!("Unknown return: {}", x),
972 }
973 remaining_ops -= reset_counter;
974 resets[i] = reset_counter;
975 }
976
977 match c::boot_go(&mut flash, &self.areadesc, None, false) {
978 (-0x13579, _) => panic!("Should not be have been interrupted!"),
David Brown5c9e0f12019-01-09 16:34:33 -0700979 (0, _) => (),
980 (x, _) => panic!("Unknown return: {}", x),
981 }
David Brown5c9e0f12019-01-09 16:34:33 -0700982
David Browndb505822019-03-01 10:04:20 -0700983 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -0700984 }
David Brown84b49f72019-03-01 10:58:22 -0700985
986 /// Verify the image in the given flash device, the specified slot
987 /// against the expected image.
988 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -0600989 self.images.iter().all(|image| {
990 verify_image(flash, &image.slots[slot],
991 match against {
992 0 => &image.primaries,
993 1 => &image.upgrades,
994 _ => panic!("Invalid 'against'")
995 })
996 })
David Brown84b49f72019-03-01 10:58:22 -0700997 }
998
David Brownc3898d62019-08-05 14:20:02 -0600999 /// Verify the images, according to the dependency test.
1000 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1001 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1002 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1003 if !verify_image(flash, &image.slots[0],
1004 match upgrade {
1005 UpgradeInfo::Upgraded => &image.upgrades,
1006 UpgradeInfo::Held => &image.primaries,
1007 }) {
1008 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1009 return true;
1010 }
1011 }
1012
1013 false
1014 }
1015
Fabio Utzig8af7f792019-07-30 12:40:01 -03001016 /// Verify that at least one of the trailers of the images have the
1017 /// specified values.
1018 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1019 magic: Option<u8>, image_ok: Option<u8>,
1020 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001021 self.images.iter().any(|image| {
1022 verify_trailer(flash, &image.slots[slot],
1023 magic, image_ok, copy_done)
1024 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001025 }
1026
David Brown84b49f72019-03-01 10:58:22 -07001027 /// Verify that the trailers of the images have the specified
1028 /// values.
1029 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1030 magic: Option<u8>, image_ok: Option<u8>,
1031 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001032 self.images.iter().all(|image| {
1033 verify_trailer(flash, &image.slots[slot],
1034 magic, image_ok, copy_done)
1035 })
David Brown84b49f72019-03-01 10:58:22 -07001036 }
1037
1038 /// Mark each of the images for permanent upgrade.
1039 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1040 for image in &self.images {
1041 mark_permanent_upgrade(flash, &image.slots[slot]);
1042 }
1043 }
1044
1045 /// Mark each of the images for permanent upgrade.
1046 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1047 for image in &self.images {
1048 mark_upgrade(flash, &image.slots[slot]);
1049 }
1050 }
David Brown297029a2019-08-13 14:29:51 -06001051
1052 /// Dump out the flash image(s) to one or more files for debugging
1053 /// purposes. The names will be written as either "{prefix}.mcubin" or
1054 /// "{prefix}-001.mcubin" depending on how many images there are.
1055 pub fn debug_dump(&self, prefix: &str) {
1056 for (id, fdev) in &self.flash {
1057 let name = if self.flash.len() == 1 {
1058 format!("{}.mcubin", prefix)
1059 } else {
1060 format!("{}-{:>0}.mcubin", prefix, id)
1061 };
1062 fdev.write_file(&name).unwrap();
1063 }
1064 }
David Brown5c9e0f12019-01-09 16:34:33 -07001065}
1066
1067/// Show the flash layout.
1068#[allow(dead_code)]
1069fn show_flash(flash: &dyn Flash) {
1070 println!("---- Flash configuration ----");
1071 for sector in flash.sector_iter() {
1072 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1073 sector.num, sector.base, sector.size);
1074 }
1075 println!("");
1076}
1077
1078/// Install a "program" into the given image. This fakes the image header, or at least all of the
1079/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001080fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownc3898d62019-08-05 14:20:02 -06001081 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001082 let offset = slot.base_off;
1083 let slot_len = slot.len;
1084 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001085
David Brown43643dd2019-01-11 15:43:28 -07001086 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001087
David Brownc3898d62019-08-05 14:20:02 -06001088 // Add the dependencies early to the tlv.
1089 for dep in deps.my_deps(offset, slot.index) {
1090 tlv.add_dependency(deps.other_id(), &dep);
1091 }
1092
David Brown5c9e0f12019-01-09 16:34:33 -07001093 const HDR_SIZE: usize = 32;
1094
1095 // Generate a boot header. Note that the size doesn't include the header.
1096 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001097 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -07001098 load_addr: 0,
1099 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001100 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001101 img_size: len as u32,
1102 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001103 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001104 _pad2: 0,
1105 };
1106
1107 let mut b_header = [0; HDR_SIZE];
1108 b_header[..32].clone_from_slice(header.as_raw());
1109 assert_eq!(b_header.len(), HDR_SIZE);
1110
1111 tlv.add_bytes(&b_header);
1112
1113 // The core of the image itself is just pseudorandom data.
1114 let mut b_img = vec![0; len];
1115 splat(&mut b_img, offset);
1116
David Browncb47dd72019-08-05 14:21:49 -06001117 // Add some information at the start of the payload to make it easier
1118 // to see what it is. This will fail if the image itself is too small.
1119 {
1120 let mut wr = Cursor::new(&mut b_img);
1121 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1122 offset, dev_id, slot).unwrap();
1123 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1124 }
1125
David Brown5c9e0f12019-01-09 16:34:33 -07001126 // TLV signatures work over plain image
1127 tlv.add_bytes(&b_img);
1128
1129 // Generate encrypted images
1130 let flag = TlvFlags::ENCRYPTED as u32;
1131 let is_encrypted = (tlv.get_flags() & flag) == flag;
1132 let mut b_encimg = vec![];
1133 if is_encrypted {
1134 let key = GenericArray::from_slice(AES_SEC_KEY);
1135 let nonce = GenericArray::from_slice(&[0; 16]);
1136 let mut cipher = Aes128Ctr::new(&key, &nonce);
1137 b_encimg = b_img.clone();
1138 cipher.apply_keystream(&mut b_encimg);
1139 }
1140
1141 // Build the TLV itself.
1142 let mut b_tlv = if bad_sig {
1143 let good_sig = &mut tlv.make_tlv();
1144 vec![0; good_sig.len()]
1145 } else {
1146 tlv.make_tlv()
1147 };
1148
1149 // Pad the block to a flash alignment (8 bytes).
1150 while b_tlv.len() % 8 != 0 {
1151 //FIXME: should be erase_val?
1152 b_tlv.push(0xFF);
1153 }
1154
1155 let mut buf = vec![];
1156 buf.append(&mut b_header.to_vec());
1157 buf.append(&mut b_img);
1158 buf.append(&mut b_tlv.clone());
1159
1160 let mut encbuf = vec![];
1161 if is_encrypted {
1162 encbuf.append(&mut b_header.to_vec());
1163 encbuf.append(&mut b_encimg);
1164 encbuf.append(&mut b_tlv);
1165 }
1166
David Vincze2d736ad2019-02-18 11:50:22 +01001167 // Since images are always non-encrypted in the primary slot, we first write
1168 // an encrypted image, re-read to use for verification, erase + flash
1169 // un-encrypted. In the secondary slot the image is written un-encrypted,
1170 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001171
David Brown76101572019-02-28 11:29:03 -07001172 let dev = flash.get_mut(&dev_id).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001173
David Brown3b090212019-07-30 15:59:28 -06001174 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001175 let enc_copy: Option<Vec<u8>>;
1176
1177 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001178 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001179
1180 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001181 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001182
1183 enc_copy = Some(enc);
1184
David Brown76101572019-02-28 11:29:03 -07001185 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001186 } else {
1187 enc_copy = None;
1188 }
1189
David Brown76101572019-02-28 11:29:03 -07001190 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001191
1192 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001193 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001194
David Brownca234692019-02-28 11:22:19 -07001195 ImageData {
1196 plain: copy,
1197 cipher: enc_copy,
1198 }
David Brown5c9e0f12019-01-09 16:34:33 -07001199 } else {
1200
David Brown76101572019-02-28 11:29:03 -07001201 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001202
1203 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001204 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001205
1206 let enc_copy: Option<Vec<u8>>;
1207
1208 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001209 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001210
David Brown76101572019-02-28 11:29:03 -07001211 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001212
1213 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001214 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001215
1216 enc_copy = Some(enc);
1217 } else {
1218 enc_copy = None;
1219 }
1220
David Brownca234692019-02-28 11:22:19 -07001221 ImageData {
1222 plain: copy,
1223 cipher: enc_copy,
1224 }
David Brown5c9e0f12019-01-09 16:34:33 -07001225 }
David Brown5c9e0f12019-01-09 16:34:33 -07001226}
1227
David Brown5c9e0f12019-01-09 16:34:33 -07001228fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001229 if Caps::EcdsaP224.present() {
1230 panic!("Ecdsa P224 not supported in Simulator");
1231 }
David Brown5c9e0f12019-01-09 16:34:33 -07001232
David Brownb8882112019-01-11 14:04:11 -07001233 if Caps::EncKw.present() {
1234 if Caps::RSA2048.present() {
1235 TlvGen::new_rsa_kw()
1236 } else if Caps::EcdsaP256.present() {
1237 TlvGen::new_ecdsa_kw()
1238 } else {
1239 TlvGen::new_enc_kw()
1240 }
1241 } else if Caps::EncRsa.present() {
1242 if Caps::RSA2048.present() {
1243 TlvGen::new_sig_enc_rsa()
1244 } else {
1245 TlvGen::new_enc_rsa()
1246 }
1247 } else {
1248 // The non-encrypted configuration.
1249 if Caps::RSA2048.present() {
1250 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001251 } else if Caps::RSA3072.present() {
1252 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001253 } else if Caps::EcdsaP256.present() {
1254 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001255 } else if Caps::Ed25519.present() {
1256 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001257 } else {
1258 TlvGen::new_hash_only()
1259 }
1260 }
David Brown5c9e0f12019-01-09 16:34:33 -07001261}
1262
David Brownca234692019-02-28 11:22:19 -07001263impl ImageData {
1264 /// Find the image contents for the given slot. This assumes that slot 0
1265 /// is unencrypted, and slot 1 is encrypted.
1266 fn find(&self, slot: usize) -> &Vec<u8> {
1267 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present();
1268 match (encrypted, slot) {
1269 (false, _) => &self.plain,
1270 (true, 0) => &self.plain,
1271 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1272 _ => panic!("Invalid slot requested"),
1273 }
David Brown5c9e0f12019-01-09 16:34:33 -07001274 }
1275}
1276
David Brown5c9e0f12019-01-09 16:34:33 -07001277/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001278fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1279 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001280 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001281 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001282
1283 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001284 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001285 let dev = flash.get(&dev_id).unwrap();
1286 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001287
1288 if buf != &copy[..] {
1289 for i in 0 .. buf.len() {
1290 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001291 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1292 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001293 break;
1294 }
1295 }
1296 false
1297 } else {
1298 true
1299 }
1300}
1301
David Brown3b090212019-07-30 15:59:28 -06001302fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001303 magic: Option<u8>, image_ok: Option<u8>,
1304 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001305 if Caps::OverwriteUpgrade.present() {
1306 return true;
1307 }
David Brown5c9e0f12019-01-09 16:34:33 -07001308
David Brown3b090212019-07-30 15:59:28 -06001309 let offset = slot.trailer_off + c::boot_max_align();
1310 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001311 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001312 let mut failed = false;
1313
David Brown76101572019-02-28 11:29:03 -07001314 let dev = flash.get(&dev_id).unwrap();
1315 let erased_val = dev.erased_val();
1316 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001317
1318 failed |= match magic {
1319 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001320 if v == 1 && &copy[24..] != MAGIC.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -07001321 warn!("\"magic\" mismatch at {:#x}", offset);
1322 true
1323 } else if v == 3 {
1324 let expected = [erased_val; 16];
Christopher Collinsa1c12042019-05-23 14:00:28 -07001325 if &copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001326 warn!("\"magic\" mismatch at {:#x}", offset);
1327 true
1328 } else {
1329 false
1330 }
1331 } else {
1332 false
1333 }
1334 },
1335 None => false,
1336 };
1337
1338 failed |= match image_ok {
1339 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001340 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001341 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1342 true
1343 } else {
1344 false
1345 }
1346 },
1347 None => false,
1348 };
1349
1350 failed |= match copy_done {
1351 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001352 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001353 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1354 true
1355 } else {
1356 false
1357 }
1358 },
1359 None => false,
1360 };
1361
1362 !failed
1363}
1364
David Brown297029a2019-08-13 14:29:51 -06001365/// Install a partition table. This is a simplified partition table that
1366/// we write at the beginning of flash so make it easier for external tools
1367/// to analyze these images.
1368fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1369 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1370 for &id in &ids {
1371 // If there are any partitions in this device that start at 0, and
1372 // aren't marked as the BootLoader partition, avoid adding the
1373 // partition table. This makes it harder to view the image, but
1374 // avoids messing up images already written.
1375 if areadesc.iter_areas().any(|area| {
1376 area.device_id == id &&
1377 area.off == 0 &&
1378 area.flash_id != FlashId::BootLoader
1379 }) {
1380 if log_enabled!(Info) {
1381 let special: Vec<FlashId> = areadesc.iter_areas()
1382 .filter(|area| area.device_id == id && area.off == 0)
1383 .map(|area| area.flash_id)
1384 .collect();
1385 info!("Skipping partition table: {:?}", special);
1386 }
1387 break;
1388 }
1389
1390 let mut buf: Vec<u8> = vec![];
1391 write!(&mut buf, "mcuboot\0").unwrap();
1392
1393 // Iterate through all of the partitions in that device, and encode
1394 // into the table.
1395 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1396 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1397
1398 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1399 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1400 buf.write_u32::<LittleEndian>(area.off).unwrap();
1401 buf.write_u32::<LittleEndian>(area.size).unwrap();
1402 buf.write_u32::<LittleEndian>(0).unwrap();
1403 }
1404
1405 let dev = flash.get_mut(&id).unwrap();
1406
1407 // Pad to alignment.
1408 while buf.len() % dev.align() != 0 {
1409 buf.push(0);
1410 }
1411
1412 dev.write(0, &buf).unwrap();
1413 }
1414}
1415
David Brown5c9e0f12019-01-09 16:34:33 -07001416/// The image header
1417#[repr(C)]
1418pub struct ImageHeader {
1419 magic: u32,
1420 load_addr: u32,
1421 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001422 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001423 img_size: u32,
1424 flags: u32,
1425 ver: ImageVersion,
1426 _pad2: u32,
1427}
1428
1429impl AsRaw for ImageHeader {}
1430
1431#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001432#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001433pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001434 pub major: u8,
1435 pub minor: u8,
1436 pub revision: u16,
1437 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001438}
1439
David Brownc3898d62019-08-05 14:20:02 -06001440#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001441pub struct SlotInfo {
1442 pub base_off: usize,
1443 pub trailer_off: usize,
1444 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001445 // Which slot within this device.
1446 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001447 pub dev_id: u8,
1448}
1449
David Brown5c9e0f12019-01-09 16:34:33 -07001450const MAGIC: Option<&[u8]> = Some(&[0x77, 0xc2, 0x95, 0xf3,
1451 0x60, 0xd2, 0xef, 0x7f,
1452 0x35, 0x52, 0x50, 0x0f,
1453 0x2c, 0xb6, 0x79, 0x80]);
1454
1455// Replicates defines found in bootutil.h
1456const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1457const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1458
1459const BOOT_FLAG_SET: Option<u8> = Some(1);
1460const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1461
1462/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001463pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1464 let dev = flash.get_mut(&slot.dev_id).unwrap();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001465 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown76101572019-02-28 11:29:03 -07001466 dev.write(offset, MAGIC.unwrap()).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001467}
1468
1469/// Writes the image_ok flag which, guess what, tells the bootloader
1470/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001471fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1472 let dev = flash.get_mut(&slot.dev_id).unwrap();
1473 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001474 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001475 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001476 let align = dev.align();
1477 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001478}
1479
1480// Drop some pseudo-random gibberish onto the data.
1481fn splat(data: &mut [u8], seed: usize) {
1482 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
1483 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
1484 rng.fill_bytes(data);
1485}
1486
1487/// Return a read-only view into the raw bytes of this object
1488trait AsRaw : Sized {
1489 fn as_raw<'a>(&'a self) -> &'a [u8] {
1490 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1491 mem::size_of::<Self>()) }
1492 }
1493}
1494
1495pub fn show_sizes() {
1496 // This isn't panic safe.
1497 for min in &[1, 2, 4, 8] {
1498 let msize = c::boot_trailer_sz(*min);
1499 println!("{:2}: {} (0x{:x})", min, msize, msize);
1500 }
1501}