blob: 420a14f68da1a31c859666601988788f99035144 [file] [log] [blame]
David Browne2acfae2020-01-21 16:45:01 -07001// Copyright (c) 2019 Linaro LTD
2// Copyright (c) 2019-2020 JUUL Labs
3// Copyright (c) 2019 Arm Limited
4//
5// SPDX-License-Identifier: Apache-2.0
6
David Brown297029a2019-08-13 14:29:51 -06007use byteorder::{
8 LittleEndian, WriteBytesExt,
9};
10use log::{
11 Level::Info,
12 error,
13 info,
14 log_enabled,
15 warn,
16};
David Brown5c9e0f12019-01-09 16:34:33 -070017use rand::{
18 distributions::{IndependentSample, Range},
19 Rng, SeedableRng, XorShiftRng,
20};
21use std::{
David Brown297029a2019-08-13 14:29:51 -060022 collections::HashSet,
David Browncb47dd72019-08-05 14:21:49 -060023 io::{Cursor, Write},
David Brown5c9e0f12019-01-09 16:34:33 -070024 mem,
25 slice,
26};
27use aes_ctr::{
28 Aes128Ctr,
29 stream_cipher::{
30 generic_array::GenericArray,
31 NewFixStreamCipher,
32 StreamCipherCore,
33 },
34};
35
David Brown76101572019-02-28 11:29:03 -070036use simflash::{Flash, SimFlash, SimMultiFlash};
David Browne5133242019-02-28 11:05:19 -070037use mcuboot_sys::{c, AreaDesc, FlashId};
38use crate::{
39 ALL_DEVICES,
40 DeviceName,
41};
David Brown5c9e0f12019-01-09 16:34:33 -070042use crate::caps::Caps;
David Brownc3898d62019-08-05 14:20:02 -060043use crate::depends::{
44 BoringDep,
45 Depender,
46 DepTest,
David Brown873be312019-09-03 12:22:32 -060047 DepType,
David Brown2ee5f7f2020-01-13 14:04:01 -070048 NO_DEPS,
David Brownc3898d62019-08-05 14:20:02 -060049 PairDep,
50 UpgradeInfo,
51};
Fabio Utzig90f449e2019-10-24 07:43:53 -030052use crate::tlv::{ManifestGen, TlvGen, TlvFlags};
David Brown5c9e0f12019-01-09 16:34:33 -070053
David Browne5133242019-02-28 11:05:19 -070054/// A builder for Images. This describes a single run of the simulator,
55/// capturing the configuration of a particular set of devices, including
56/// the flash simulator(s) and the information about the slots.
57#[derive(Clone)]
58pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070059 flash: SimMultiFlash,
David Browne5133242019-02-28 11:05:19 -070060 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070061 slots: Vec<[SlotInfo; 2]>,
David Browne5133242019-02-28 11:05:19 -070062}
63
David Brown998aa8d2019-02-28 10:54:50 -070064/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070065/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070066/// and upgrades hold the expected contents of these images.
67pub struct Images {
David Brown76101572019-02-28 11:29:03 -070068 flash: SimMultiFlash,
David Brownca234692019-02-28 11:22:19 -070069 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070070 images: Vec<OneImage>,
71 total_count: Option<i32>,
72}
73
74/// When doing multi-image, there is an instance of this information for
75/// each of the images. Single image there will be one of these.
76struct OneImage {
David Brownca234692019-02-28 11:22:19 -070077 slots: [SlotInfo; 2],
78 primaries: ImageData,
79 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070080}
81
82/// The Rust-side representation of an image. For unencrypted images, this
83/// is just the unencrypted payload. For encrypted images, we store both
84/// the encrypted and the plaintext.
85struct ImageData {
86 plain: Vec<u8>,
87 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -070088}
89
David Browne5133242019-02-28 11:05:19 -070090impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -070091 /// Construct a new image builder for the given device. Returns
92 /// Some(builder) if is possible to test this configuration, or None if
93 /// not possible (for example, if there aren't enough image slots).
Fabio Utzig114a6472019-11-28 10:24:09 -030094 pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
95 let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
96
97 for cap in unsupported_caps {
98 if cap.present() {
99 return Err(format!("unsupported {:?}", cap));
100 }
101 }
David Browne5133242019-02-28 11:05:19 -0700102
David Brown06ef06e2019-03-05 12:28:10 -0700103 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -0700104
David Brown06ef06e2019-03-05 12:28:10 -0700105 let mut slots = Vec::with_capacity(num_images);
106 for image in 0..num_images {
107 // This mapping must match that defined in
108 // `boot/zephyr/include/sysflash/sysflash.h`.
109 let id0 = match image {
110 0 => FlashId::Image0,
111 1 => FlashId::Image2,
112 _ => panic!("More than 2 images not supported"),
113 };
114 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
115 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300116 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700117 };
118 let id1 = match image {
119 0 => FlashId::Image1,
120 1 => FlashId::Image3,
121 _ => panic!("More than 2 images not supported"),
122 };
123 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
124 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300125 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700126 };
David Browne5133242019-02-28 11:05:19 -0700127
Christopher Collinsa1c12042019-05-23 14:00:28 -0700128 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700129
David Brown06ef06e2019-03-05 12:28:10 -0700130 // Construct a primary image.
131 let primary = SlotInfo {
132 base_off: primary_base as usize,
133 trailer_off: primary_base + primary_len - offset_from_end,
134 len: primary_len as usize,
135 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600136 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700137 };
138
139 // And an upgrade image.
140 let secondary = SlotInfo {
141 base_off: secondary_base as usize,
142 trailer_off: secondary_base + secondary_len - offset_from_end,
143 len: secondary_len as usize,
144 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600145 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700146 };
147
148 slots.push([primary, secondary]);
149 }
David Browne5133242019-02-28 11:05:19 -0700150
Fabio Utzig114a6472019-11-28 10:24:09 -0300151 Ok(ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -0700152 flash: flash,
David Browne5133242019-02-28 11:05:19 -0700153 areadesc: areadesc,
David Brown06ef06e2019-03-05 12:28:10 -0700154 slots: slots,
David Brown5bc62c62019-03-05 12:11:48 -0700155 })
David Browne5133242019-02-28 11:05:19 -0700156 }
157
158 pub fn each_device<F>(f: F)
159 where F: Fn(Self)
160 {
161 for &dev in ALL_DEVICES {
David Brown95de4502019-11-15 12:01:34 -0700162 for &align in test_alignments() {
David Browne5133242019-02-28 11:05:19 -0700163 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700164 match Self::new(dev, align, erased_val) {
Fabio Utzig114a6472019-11-28 10:24:09 -0300165 Ok(run) => f(run),
166 Err(msg) => warn!("Skipping {}: {}", dev, msg),
David Brown5bc62c62019-03-05 12:11:48 -0700167 }
David Browne5133242019-02-28 11:05:19 -0700168 }
169 }
170 }
171 }
172
173 /// Construct an `Images` that doesn't expect an upgrade to happen.
David Brownc3898d62019-08-05 14:20:02 -0600174 pub fn make_no_upgrade_image(self, deps: &DepTest) -> Images {
175 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700176 let mut flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600177 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
178 let dep: Box<dyn Depender> = if num_images > 1 {
179 Box::new(PairDep::new(num_images, image_num, deps))
180 } else {
David Brown2ee5f7f2020-01-13 14:04:01 -0700181 Box::new(BoringDep::new(image_num, deps))
David Brownc3898d62019-08-05 14:20:02 -0600182 };
183 let primaries = install_image(&mut flash, &slots[0], 42784, &*dep, false);
David Brown873be312019-09-03 12:22:32 -0600184 let upgrades = match deps.depends[image_num] {
185 DepType::NoUpgrade => install_no_image(),
186 _ => install_image(&mut flash, &slots[1], 46928, &*dep, false)
187 };
David Brown84b49f72019-03-01 10:58:22 -0700188 OneImage {
189 slots: slots,
190 primaries: primaries,
191 upgrades: upgrades,
192 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600193 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700194 Images {
David Brown76101572019-02-28 11:29:03 -0700195 flash: flash,
David Browne5133242019-02-28 11:05:19 -0700196 areadesc: self.areadesc,
David Brown84b49f72019-03-01 10:58:22 -0700197 images: images,
David Browne5133242019-02-28 11:05:19 -0700198 total_count: None,
199 }
200 }
201
David Brownc3898d62019-08-05 14:20:02 -0600202 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
203 let mut images = self.make_no_upgrade_image(deps);
David Brown84b49f72019-03-01 10:58:22 -0700204 for image in &images.images {
205 mark_upgrade(&mut images.flash, &image.slots[1]);
206 }
David Browne5133242019-02-28 11:05:19 -0700207
208 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300209 let total_count = match images.run_basic_upgrade(permanent) {
David Browne5133242019-02-28 11:05:19 -0700210 Ok(v) => v,
Fabio Utzig7c1d1552019-08-28 10:59:22 -0300211 Err(_) =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600212 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
213 0
214 } else {
215 panic!("Unable to perform basic upgrade");
216 }
David Browne5133242019-02-28 11:05:19 -0700217 };
218
219 images.total_count = Some(total_count);
220 images
221 }
222
223 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700224 let mut bad_flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600225 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
David Brown2ee5f7f2020-01-13 14:04:01 -0700226 let dep = BoringDep::new(image_num, &NO_DEPS);
David Brownc3898d62019-08-05 14:20:02 -0600227 let primaries = install_image(&mut bad_flash, &slots[0], 32784, &dep, false);
228 let upgrades = install_image(&mut bad_flash, &slots[1], 41928, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700229 OneImage {
230 slots: slots,
231 primaries: primaries,
232 upgrades: upgrades,
233 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700234 Images {
David Brown76101572019-02-28 11:29:03 -0700235 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700236 areadesc: self.areadesc,
David Brown84b49f72019-03-01 10:58:22 -0700237 images: images,
David Browne5133242019-02-28 11:05:19 -0700238 total_count: None,
239 }
240 }
241
242 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300243 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700244 match device {
245 DeviceName::Stm32f4 => {
246 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700247 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
248 64 * 1024,
249 128 * 1024, 128 * 1024, 128 * 1024],
250 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700251 let dev_id = 0;
252 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700253 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700254 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
255 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
256 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
257
David Brown76101572019-02-28 11:29:03 -0700258 let mut flash = SimMultiFlash::new();
259 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300260 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700261 }
262 DeviceName::K64f => {
263 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700264 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700265
266 let dev_id = 0;
267 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700268 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700269 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
270 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
271 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
272
David Brown76101572019-02-28 11:29:03 -0700273 let mut flash = SimMultiFlash::new();
274 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300275 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700276 }
277 DeviceName::K64fBig => {
278 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
279 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700280 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700281
282 let dev_id = 0;
283 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700284 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700285 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
286 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
287 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
288
David Brown76101572019-02-28 11:29:03 -0700289 let mut flash = SimMultiFlash::new();
290 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300291 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700292 }
293 DeviceName::Nrf52840 => {
294 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
295 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700296 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700297
298 let dev_id = 0;
299 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700300 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700301 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
302 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
303 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
304
David Brown76101572019-02-28 11:29:03 -0700305 let mut flash = SimMultiFlash::new();
306 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300307 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700308 }
309 DeviceName::Nrf52840SpiFlash => {
310 // Simulate nrf52840 with external SPI flash. The external SPI flash
311 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700312 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
313 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700314
315 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700316 areadesc.add_flash_sectors(0, &dev0);
317 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700318
319 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
320 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
321 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
322
David Brown76101572019-02-28 11:29:03 -0700323 let mut flash = SimMultiFlash::new();
324 flash.insert(0, dev0);
325 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300326 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700327 }
David Brown2bff6472019-03-05 13:58:35 -0700328 DeviceName::K64fMulti => {
329 // NXP style flash, but larger, to support multiple images.
330 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
331
332 let dev_id = 0;
333 let mut areadesc = AreaDesc::new();
334 areadesc.add_flash_sectors(dev_id, &dev);
335 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
336 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
337 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
338 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
339 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
340
341 let mut flash = SimMultiFlash::new();
342 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300343 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700344 }
David Browne5133242019-02-28 11:05:19 -0700345 }
346 }
David Brownc3898d62019-08-05 14:20:02 -0600347
348 pub fn num_images(&self) -> usize {
349 self.slots.len()
350 }
David Browne5133242019-02-28 11:05:19 -0700351}
352
David Brown5c9e0f12019-01-09 16:34:33 -0700353impl Images {
354 /// A simple upgrade without forced failures.
355 ///
356 /// Returns the number of flash operations which can later be used to
357 /// inject failures at chosen steps.
Fabio Utziged4a5362019-07-30 12:43:23 -0300358 pub fn run_basic_upgrade(&self, permanent: bool) -> Result<i32, ()> {
359 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700360 info!("Total flash operation count={}", total_count);
361
David Brown84b49f72019-03-01 10:58:22 -0700362 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700363 warn!("Image mismatch after first boot");
364 Err(())
365 } else {
366 Ok(total_count)
367 }
368 }
369
David Brownc3898d62019-08-05 14:20:02 -0600370 /// Test a simple upgrade, with dependencies given, and verify that the
371 /// image does as is described in the test.
372 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
373 let (flash, _) = self.try_upgrade(None, true);
374
375 self.verify_dep_images(&flash, deps)
376 }
377
Fabio Utzigf5480c72019-11-28 10:41:57 -0300378 fn is_swap_upgrade(&self) -> bool {
379 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
380 }
381
David Brown5c9e0f12019-01-09 16:34:33 -0700382 pub fn run_basic_revert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700383 if Caps::OverwriteUpgrade.present() {
384 return false;
385 }
David Brown5c9e0f12019-01-09 16:34:33 -0700386
David Brown5c9e0f12019-01-09 16:34:33 -0700387 let mut fails = 0;
388
389 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300390 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700391 for count in 2 .. 5 {
392 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700393 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700394 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700395 error!("Revert failure on count {}", count);
396 fails += 1;
397 }
398 }
399 }
400
401 fails > 0
402 }
403
404 pub fn run_perm_with_fails(&self) -> bool {
405 let mut fails = 0;
406 let total_flash_ops = self.total_count.unwrap();
407
408 // Let's try an image halfway through.
409 for i in 1 .. total_flash_ops {
410 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300411 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700412 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700413 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700414 warn!("FAIL at step {} of {}", i, total_flash_ops);
415 fails += 1;
416 }
417
David Brown84b49f72019-03-01 10:58:22 -0700418 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
419 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100420 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700421 fails += 1;
422 }
423
David Brown84b49f72019-03-01 10:58:22 -0700424 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
425 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100426 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700427 fails += 1;
428 }
429
Fabio Utzigf5480c72019-11-28 10:41:57 -0300430 if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700431 if !self.verify_images(&flash, 1, 0) {
David Vincze2d736ad2019-02-18 11:50:22 +0100432 warn!("Secondary slot FAIL at step {} of {}",
433 i, total_flash_ops);
David Brown5c9e0f12019-01-09 16:34:33 -0700434 fails += 1;
435 }
436 }
437 }
438
439 if fails > 0 {
440 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
441 fails as f32 * 100.0 / total_flash_ops as f32);
442 }
443
444 fails > 0
445 }
446
David Brown5c9e0f12019-01-09 16:34:33 -0700447 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
448 let mut fails = 0;
449 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700450 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700451 info!("Random interruptions at reset points={:?}", total_counts);
452
David Brown84b49f72019-03-01 10:58:22 -0700453 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300454 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700455 // TODO: This result is ignored.
456 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700457 } else {
458 true
459 };
David Vincze2d736ad2019-02-18 11:50:22 +0100460 if !primary_slot_ok || !secondary_slot_ok {
461 error!("Image mismatch after random interrupts: primary slot={} \
462 secondary slot={}",
463 if primary_slot_ok { "ok" } else { "fail" },
464 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700465 fails += 1;
466 }
David Brown84b49f72019-03-01 10:58:22 -0700467 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
468 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100469 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700470 fails += 1;
471 }
David Brown84b49f72019-03-01 10:58:22 -0700472 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
473 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100474 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700475 fails += 1;
476 }
477
478 if fails > 0 {
479 error!("Error testing perm upgrade with {} fails", total_fails);
480 }
481
482 fails > 0
483 }
484
David Brown5c9e0f12019-01-09 16:34:33 -0700485 pub fn run_revert_with_fails(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700486 if Caps::OverwriteUpgrade.present() {
487 return false;
488 }
David Brown5c9e0f12019-01-09 16:34:33 -0700489
David Brown5c9e0f12019-01-09 16:34:33 -0700490 let mut fails = 0;
491
Fabio Utzigf5480c72019-11-28 10:41:57 -0300492 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300493 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700494 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700495 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700496 error!("Revert failed at interruption {}", i);
497 fails += 1;
498 }
499 }
500 }
501
502 fails > 0
503 }
504
David Brown5c9e0f12019-01-09 16:34:33 -0700505 pub fn run_norevert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700506 if Caps::OverwriteUpgrade.present() {
507 return false;
508 }
David Brown5c9e0f12019-01-09 16:34:33 -0700509
David Brown76101572019-02-28 11:29:03 -0700510 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700511 let mut fails = 0;
512
513 info!("Try norevert");
514
515 // First do a normal upgrade...
David Brown76101572019-02-28 11:29:03 -0700516 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700517 if result != 0 {
518 warn!("Failed first boot");
519 fails += 1;
520 }
521
522 //FIXME: copy_done is written by boot_go, is it ok if no copy
523 // was ever done?
524
David Brown84b49f72019-03-01 10:58:22 -0700525 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100526 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700527 fails += 1;
528 }
David Brown84b49f72019-03-01 10:58:22 -0700529 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
530 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100531 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700532 fails += 1;
533 }
David Brown84b49f72019-03-01 10:58:22 -0700534 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
535 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100536 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700537 fails += 1;
538 }
539
David Vincze2d736ad2019-02-18 11:50:22 +0100540 // Marks image in the primary slot as permanent,
541 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700542 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700543
David Brown84b49f72019-03-01 10:58:22 -0700544 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
545 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100546 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700547 fails += 1;
548 }
549
David Brown76101572019-02-28 11:29:03 -0700550 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700551 if result != 0 {
552 warn!("Failed second boot");
553 fails += 1;
554 }
555
David Brown84b49f72019-03-01 10:58:22 -0700556 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
557 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100558 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700559 fails += 1;
560 }
David Brown84b49f72019-03-01 10:58:22 -0700561 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700562 warn!("Failed image verification");
563 fails += 1;
564 }
565
566 if fails > 0 {
567 error!("Error running upgrade without revert");
568 }
569
570 fails > 0
571 }
572
David Brown2ee5f7f2020-01-13 14:04:01 -0700573 // Test that an upgrade is rejected. Assumes that the image was build
574 // such that the upgrade is instead a downgrade.
575 pub fn run_nodowngrade(&self) -> bool {
576 if !Caps::DowngradePrevention.present() {
577 return false;
578 }
579
580 let mut flash = self.flash.clone();
581 let mut fails = 0;
582
583 info!("Try no downgrade");
584
585 // First, do a normal upgrade.
586 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
587 if result != 0 {
588 warn!("Failed first boot");
589 fails += 1;
590 }
591
592 if !self.verify_images(&flash, 0, 0) {
593 warn!("Failed verification after downgrade rejection");
594 fails += 1;
595 }
596
597 if fails > 0 {
598 error!("Error testing downgrade rejection");
599 }
600
601 fails > 0
602 }
603
David Vincze2d736ad2019-02-18 11:50:22 +0100604 // Tests a new image written to the primary slot that already has magic and
605 // image_ok set while there is no image on the secondary slot, so no revert
606 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700607 pub fn run_norevert_newimage(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700608 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700609 let mut fails = 0;
610
611 info!("Try non-revert on imgtool generated image");
612
David Brown84b49f72019-03-01 10:58:22 -0700613 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700614
David Vincze2d736ad2019-02-18 11:50:22 +0100615 // This simulates writing an image created by imgtool to
616 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700617 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
618 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100619 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700620 fails += 1;
621 }
622
623 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700624 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700625 if result != 0 {
626 warn!("Failed first boot");
627 fails += 1;
628 }
629
630 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700631 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700632 warn!("Failed image verification");
633 fails += 1;
634 }
David Brown84b49f72019-03-01 10:58:22 -0700635 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
636 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100637 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700638 fails += 1;
639 }
David Brown84b49f72019-03-01 10:58:22 -0700640 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
641 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100642 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700643 fails += 1;
644 }
645
646 if fails > 0 {
647 error!("Expected a non revert with new image");
648 }
649
650 fails > 0
651 }
652
David Vincze2d736ad2019-02-18 11:50:22 +0100653 // Tests a new image written to the primary slot that already has magic and
654 // image_ok set while there is no image on the secondary slot, so no revert
655 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700656 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700657 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700658 let mut fails = 0;
659
660 info!("Try upgrade image with bad signature");
661
David Brown84b49f72019-03-01 10:58:22 -0700662 self.mark_upgrades(&mut flash, 0);
663 self.mark_permanent_upgrades(&mut flash, 0);
664 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700665
David Brown84b49f72019-03-01 10:58:22 -0700666 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
667 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100668 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700669 fails += 1;
670 }
671
672 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700673 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700674 if result != 0 {
675 warn!("Failed first boot");
676 fails += 1;
677 }
678
679 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700680 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700681 warn!("Failed image verification");
682 fails += 1;
683 }
David Brown84b49f72019-03-01 10:58:22 -0700684 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
685 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100686 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700687 fails += 1;
688 }
689
690 if fails > 0 {
691 error!("Expected an upgrade failure when image has bad signature");
692 }
693
694 fails > 0
695 }
696
David Brown5c9e0f12019-01-09 16:34:33 -0700697 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300698 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700699 }
700
David Brown5c9e0f12019-01-09 16:34:33 -0700701 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300702 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700703 }
704
705 /// This test runs a simple upgrade with no fails in the images, but
706 /// allowing for fails in the status area. This should run to the end
707 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700708 pub fn run_with_status_fails_complete(&self) -> bool {
David Vincze2d736ad2019-02-18 11:50:22 +0100709 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700710 return false;
711 }
712
David Brown76101572019-02-28 11:29:03 -0700713 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700714 let mut fails = 0;
715
716 info!("Try swap with status fails");
717
David Brown84b49f72019-03-01 10:58:22 -0700718 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700719 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700720
David Brown76101572019-02-28 11:29:03 -0700721 let (result, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown5c9e0f12019-01-09 16:34:33 -0700722 if result != 0 {
723 warn!("Failed!");
724 fails += 1;
725 }
726
727 // Failed writes to the marked "bad" region don't assert anymore.
728 // Any detected assert() is happening in another part of the code.
729 if asserts != 0 {
730 warn!("At least one assert() was called");
731 fails += 1;
732 }
733
David Brown84b49f72019-03-01 10:58:22 -0700734 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
735 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100736 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700737 fails += 1;
738 }
739
David Brown84b49f72019-03-01 10:58:22 -0700740 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700741 warn!("Failed image verification");
742 fails += 1;
743 }
744
David Vincze2d736ad2019-02-18 11:50:22 +0100745 info!("validate primary slot enabled; \
746 re-run of boot_go should just work");
David Brown76101572019-02-28 11:29:03 -0700747 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700748 if result != 0 {
749 warn!("Failed!");
750 fails += 1;
751 }
752
753 if fails > 0 {
754 error!("Error running upgrade with status write fails");
755 }
756
757 fails > 0
758 }
759
760 /// This test runs a simple upgrade with no fails in the images, but
761 /// allowing for fails in the status area. This should run to the end
762 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700763 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown85904a82019-01-11 13:45:12 -0700764 if Caps::OverwriteUpgrade.present() {
765 false
David Vincze2d736ad2019-02-18 11:50:22 +0100766 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700767
David Brown76101572019-02-28 11:29:03 -0700768 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700769 let mut fails = 0;
770 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700771
David Brown85904a82019-01-11 13:45:12 -0700772 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700773
David Brown85904a82019-01-11 13:45:12 -0700774 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700775
David Brown84b49f72019-03-01 10:58:22 -0700776 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700777 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700778
779 // Should not fail, writing to bad regions does not assert
David Brown76101572019-02-28 11:29:03 -0700780 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true);
David Brown85904a82019-01-11 13:45:12 -0700781 if asserts != 0 {
782 warn!("At least one assert() was called");
783 fails += 1;
784 }
785
David Brown76101572019-02-28 11:29:03 -0700786 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700787
788 info!("Resuming an interrupted swap operation");
David Brown76101572019-02-28 11:29:03 -0700789 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700790
791 // This might throw no asserts, for large sector devices, where
792 // a single failure writing is indistinguishable from no failure,
793 // or throw a single assert for small sector devices that fail
794 // multiple times...
795 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100796 warn!("Expected single assert validating the primary slot, \
797 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700798 fails += 1;
799 }
800
801 if fails > 0 {
802 error!("Error running upgrade with status write fails");
803 }
804
805 fails > 0
806 } else {
David Brown76101572019-02-28 11:29:03 -0700807 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700808 let mut fails = 0;
809
810 info!("Try interrupted swap with status fails");
811
David Brown84b49f72019-03-01 10:58:22 -0700812 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700813 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700814
815 // This is expected to fail while writing to bad regions...
David Brown76101572019-02-28 11:29:03 -0700816 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700817 if asserts == 0 {
818 warn!("No assert() detected");
819 fails += 1;
820 }
821
822 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700823 }
David Brown5c9e0f12019-01-09 16:34:33 -0700824 }
825
826 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -0700827 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -0700828 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -0700829 if Caps::OverwriteUpgrade.present() {
830 return;
831 }
832
David Brown84b49f72019-03-01 10:58:22 -0700833 // Set this for each image.
834 for image in &self.images {
835 let dev_id = &image.slots[slot].dev_id;
836 let dev = flash.get_mut(&dev_id).unwrap();
837 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -0700838 let off = &image.slots[slot].base_off;
839 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -0700840 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -0700841
David Brown84b49f72019-03-01 10:58:22 -0700842 // Mark the status area as a bad area
843 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
844 }
David Brown5c9e0f12019-01-09 16:34:33 -0700845 }
846
David Brown76101572019-02-28 11:29:03 -0700847 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +0100848 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700849 return;
850 }
851
David Brown84b49f72019-03-01 10:58:22 -0700852 for image in &self.images {
853 let dev_id = &image.slots[slot].dev_id;
854 let dev = flash.get_mut(&dev_id).unwrap();
855 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -0700856
David Brown84b49f72019-03-01 10:58:22 -0700857 // Disabling write verification the only assert triggered by
858 // boot_go should be checking for integrity of status bytes.
859 dev.set_verify_writes(false);
860 }
David Brown5c9e0f12019-01-09 16:34:33 -0700861 }
862
David Browndb505822019-03-01 10:04:20 -0700863 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
864 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -0300865 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -0700866 // Clone the flash to have a new copy.
867 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700868
Fabio Utziged4a5362019-07-30 12:43:23 -0300869 if permanent {
870 self.mark_permanent_upgrades(&mut flash, 1);
871 }
David Brown5c9e0f12019-01-09 16:34:33 -0700872
David Browndb505822019-03-01 10:04:20 -0700873 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -0700874
David Browndb505822019-03-01 10:04:20 -0700875 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
876 (-0x13579, _) => (true, stop.unwrap()),
877 (0, _) => (false, -counter),
878 (x, _) => panic!("Unknown return: {}", x),
879 };
David Brown5c9e0f12019-01-09 16:34:33 -0700880
David Browndb505822019-03-01 10:04:20 -0700881 counter = 0;
882 if first_interrupted {
883 // fl.dump();
884 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
885 (-0x13579, _) => panic!("Shouldn't stop again"),
886 (0, _) => (),
887 (x, _) => panic!("Unknown return: {}", x),
888 }
889 }
David Brown5c9e0f12019-01-09 16:34:33 -0700890
David Browndb505822019-03-01 10:04:20 -0700891 (flash, count - counter)
892 }
893
894 fn try_revert(&self, count: usize) -> SimMultiFlash {
895 let mut flash = self.flash.clone();
896
897 // fl.write_file("image0.bin").unwrap();
898 for i in 0 .. count {
899 info!("Running boot pass {}", i + 1);
900 assert_eq!(c::boot_go(&mut flash, &self.areadesc, None, false), (0, 0));
901 }
902 flash
903 }
904
905 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
906 let mut flash = self.flash.clone();
907 let mut fails = 0;
908
909 let mut counter = stop;
910 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
911 if x != -0x13579 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700912 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -0700913 fails += 1;
914 }
915
Fabio Utzig8af7f792019-07-30 12:40:01 -0300916 // In a multi-image setup, copy done might be set if any number of
917 // images was already successfully swapped.
918 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
919 warn!("copy_done should be unset");
920 fails += 1;
921 }
922
David Browndb505822019-03-01 10:04:20 -0700923 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
924 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700925 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -0700926 fails += 1;
927 }
928
David Brown84b49f72019-03-01 10:58:22 -0700929 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -0700930 warn!("Image in the primary slot before revert is invalid at stop={}",
931 stop);
932 fails += 1;
933 }
David Brown84b49f72019-03-01 10:58:22 -0700934 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -0700935 warn!("Image in the secondary slot before revert is invalid at stop={}",
936 stop);
937 fails += 1;
938 }
David Brown84b49f72019-03-01 10:58:22 -0700939 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
940 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -0700941 warn!("Mismatched trailer for the primary slot before revert");
942 fails += 1;
943 }
David Brown84b49f72019-03-01 10:58:22 -0700944 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
945 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -0700946 warn!("Mismatched trailer for the secondary slot before revert");
947 fails += 1;
948 }
949
950 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700951 let mut counter = stop;
952 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
953 if x != -0x13579 {
954 warn!("Should have stopped revert at interruption point");
955 fails += 1;
956 }
957
David Browndb505822019-03-01 10:04:20 -0700958 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
959 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700960 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -0700961 fails += 1;
962 }
963
David Brown84b49f72019-03-01 10:58:22 -0700964 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -0700965 warn!("Image in the primary slot after revert is invalid at stop={}",
966 stop);
967 fails += 1;
968 }
David Brown84b49f72019-03-01 10:58:22 -0700969 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -0700970 warn!("Image in the secondary slot after revert is invalid at stop={}",
971 stop);
972 fails += 1;
973 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700974
David Brown84b49f72019-03-01 10:58:22 -0700975 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
976 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700977 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -0700978 fails += 1;
979 }
David Brown84b49f72019-03-01 10:58:22 -0700980 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
981 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -0700982 warn!("Mismatched trailer for the secondary slot after revert");
983 fails += 1;
984 }
985
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700986 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
987 if x != 0 {
988 warn!("Should have finished 3rd boot");
989 fails += 1;
990 }
991
992 if !self.verify_images(&flash, 0, 0) {
993 warn!("Image in the primary slot is invalid on 1st boot after revert");
994 fails += 1;
995 }
996 if !self.verify_images(&flash, 1, 1) {
997 warn!("Image in the secondary slot is invalid on 1st boot after revert");
998 fails += 1;
999 }
1000
David Browndb505822019-03-01 10:04:20 -07001001 fails > 0
1002 }
1003
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001004
David Browndb505822019-03-01 10:04:20 -07001005 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1006 let mut flash = self.flash.clone();
1007
David Brown84b49f72019-03-01 10:58:22 -07001008 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001009
1010 let mut rng = rand::thread_rng();
1011 let mut resets = vec![0i32; count];
1012 let mut remaining_ops = total_ops;
1013 for i in 0 .. count {
1014 let ops = Range::new(1, remaining_ops / 2);
1015 let reset_counter = ops.ind_sample(&mut rng);
1016 let mut counter = reset_counter;
1017 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
1018 (0, _) | (-0x13579, _) => (),
1019 (x, _) => panic!("Unknown return: {}", x),
1020 }
1021 remaining_ops -= reset_counter;
1022 resets[i] = reset_counter;
1023 }
1024
1025 match c::boot_go(&mut flash, &self.areadesc, None, false) {
1026 (-0x13579, _) => panic!("Should not be have been interrupted!"),
David Brown5c9e0f12019-01-09 16:34:33 -07001027 (0, _) => (),
1028 (x, _) => panic!("Unknown return: {}", x),
1029 }
David Brown5c9e0f12019-01-09 16:34:33 -07001030
David Browndb505822019-03-01 10:04:20 -07001031 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001032 }
David Brown84b49f72019-03-01 10:58:22 -07001033
1034 /// Verify the image in the given flash device, the specified slot
1035 /// against the expected image.
1036 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001037 self.images.iter().all(|image| {
1038 verify_image(flash, &image.slots[slot],
1039 match against {
1040 0 => &image.primaries,
1041 1 => &image.upgrades,
1042 _ => panic!("Invalid 'against'")
1043 })
1044 })
David Brown84b49f72019-03-01 10:58:22 -07001045 }
1046
David Brownc3898d62019-08-05 14:20:02 -06001047 /// Verify the images, according to the dependency test.
1048 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1049 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1050 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1051 if !verify_image(flash, &image.slots[0],
1052 match upgrade {
1053 UpgradeInfo::Upgraded => &image.upgrades,
1054 UpgradeInfo::Held => &image.primaries,
1055 }) {
1056 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1057 return true;
1058 }
1059 }
1060
1061 false
1062 }
1063
Fabio Utzig8af7f792019-07-30 12:40:01 -03001064 /// Verify that at least one of the trailers of the images have the
1065 /// specified values.
1066 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1067 magic: Option<u8>, image_ok: Option<u8>,
1068 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001069 self.images.iter().any(|image| {
1070 verify_trailer(flash, &image.slots[slot],
1071 magic, image_ok, copy_done)
1072 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001073 }
1074
David Brown84b49f72019-03-01 10:58:22 -07001075 /// Verify that the trailers of the images have the specified
1076 /// values.
1077 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1078 magic: Option<u8>, image_ok: Option<u8>,
1079 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001080 self.images.iter().all(|image| {
1081 verify_trailer(flash, &image.slots[slot],
1082 magic, image_ok, copy_done)
1083 })
David Brown84b49f72019-03-01 10:58:22 -07001084 }
1085
1086 /// Mark each of the images for permanent upgrade.
1087 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1088 for image in &self.images {
1089 mark_permanent_upgrade(flash, &image.slots[slot]);
1090 }
1091 }
1092
1093 /// Mark each of the images for permanent upgrade.
1094 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1095 for image in &self.images {
1096 mark_upgrade(flash, &image.slots[slot]);
1097 }
1098 }
David Brown297029a2019-08-13 14:29:51 -06001099
1100 /// Dump out the flash image(s) to one or more files for debugging
1101 /// purposes. The names will be written as either "{prefix}.mcubin" or
1102 /// "{prefix}-001.mcubin" depending on how many images there are.
1103 pub fn debug_dump(&self, prefix: &str) {
1104 for (id, fdev) in &self.flash {
1105 let name = if self.flash.len() == 1 {
1106 format!("{}.mcubin", prefix)
1107 } else {
1108 format!("{}-{:>0}.mcubin", prefix, id)
1109 };
1110 fdev.write_file(&name).unwrap();
1111 }
1112 }
David Brown5c9e0f12019-01-09 16:34:33 -07001113}
1114
1115/// Show the flash layout.
1116#[allow(dead_code)]
1117fn show_flash(flash: &dyn Flash) {
1118 println!("---- Flash configuration ----");
1119 for sector in flash.sector_iter() {
1120 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1121 sector.num, sector.base, sector.size);
1122 }
1123 println!("");
1124}
1125
1126/// Install a "program" into the given image. This fakes the image header, or at least all of the
1127/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001128fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownc3898d62019-08-05 14:20:02 -06001129 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001130 let offset = slot.base_off;
1131 let slot_len = slot.len;
1132 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001133
David Brown43643dd2019-01-11 15:43:28 -07001134 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001135
David Brownc3898d62019-08-05 14:20:02 -06001136 // Add the dependencies early to the tlv.
1137 for dep in deps.my_deps(offset, slot.index) {
1138 tlv.add_dependency(deps.other_id(), &dep);
1139 }
1140
David Brown5c9e0f12019-01-09 16:34:33 -07001141 const HDR_SIZE: usize = 32;
1142
1143 // Generate a boot header. Note that the size doesn't include the header.
1144 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001145 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -07001146 load_addr: 0,
1147 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001148 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001149 img_size: len as u32,
1150 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001151 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001152 _pad2: 0,
1153 };
1154
1155 let mut b_header = [0; HDR_SIZE];
1156 b_header[..32].clone_from_slice(header.as_raw());
1157 assert_eq!(b_header.len(), HDR_SIZE);
1158
1159 tlv.add_bytes(&b_header);
1160
1161 // The core of the image itself is just pseudorandom data.
1162 let mut b_img = vec![0; len];
1163 splat(&mut b_img, offset);
1164
David Browncb47dd72019-08-05 14:21:49 -06001165 // Add some information at the start of the payload to make it easier
1166 // to see what it is. This will fail if the image itself is too small.
1167 {
1168 let mut wr = Cursor::new(&mut b_img);
1169 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1170 offset, dev_id, slot).unwrap();
1171 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1172 }
1173
David Brown5c9e0f12019-01-09 16:34:33 -07001174 // TLV signatures work over plain image
1175 tlv.add_bytes(&b_img);
1176
1177 // Generate encrypted images
1178 let flag = TlvFlags::ENCRYPTED as u32;
1179 let is_encrypted = (tlv.get_flags() & flag) == flag;
1180 let mut b_encimg = vec![];
1181 if is_encrypted {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001182 tlv.generate_enc_key();
1183 let enc_key = tlv.get_enc_key();
1184 let key = GenericArray::from_slice(enc_key.as_slice());
David Brown5c9e0f12019-01-09 16:34:33 -07001185 let nonce = GenericArray::from_slice(&[0; 16]);
1186 let mut cipher = Aes128Ctr::new(&key, &nonce);
1187 b_encimg = b_img.clone();
1188 cipher.apply_keystream(&mut b_encimg);
1189 }
1190
1191 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001192 if bad_sig {
1193 tlv.corrupt_sig();
1194 }
1195 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001196
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001197 let dev = flash.get_mut(&dev_id).unwrap();
1198
David Brown5c9e0f12019-01-09 16:34:33 -07001199 let mut buf = vec![];
1200 buf.append(&mut b_header.to_vec());
1201 buf.append(&mut b_img);
1202 buf.append(&mut b_tlv.clone());
1203
David Brown95de4502019-11-15 12:01:34 -07001204 // Pad the buffer to a multiple of the flash alignment.
1205 let align = dev.align();
1206 while buf.len() % align != 0 {
1207 buf.push(dev.erased_val());
1208 }
1209
David Brown5c9e0f12019-01-09 16:34:33 -07001210 let mut encbuf = vec![];
1211 if is_encrypted {
1212 encbuf.append(&mut b_header.to_vec());
1213 encbuf.append(&mut b_encimg);
1214 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001215
1216 while encbuf.len() % align != 0 {
1217 encbuf.push(dev.erased_val());
1218 }
David Brown5c9e0f12019-01-09 16:34:33 -07001219 }
1220
David Vincze2d736ad2019-02-18 11:50:22 +01001221 // Since images are always non-encrypted in the primary slot, we first write
1222 // an encrypted image, re-read to use for verification, erase + flash
1223 // un-encrypted. In the secondary slot the image is written un-encrypted,
1224 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001225
David Brown3b090212019-07-30 15:59:28 -06001226 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001227 let enc_copy: Option<Vec<u8>>;
1228
1229 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001230 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001231
1232 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001233 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001234
1235 enc_copy = Some(enc);
1236
David Brown76101572019-02-28 11:29:03 -07001237 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001238 } else {
1239 enc_copy = None;
1240 }
1241
David Brown76101572019-02-28 11:29:03 -07001242 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001243
1244 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001245 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001246
David Brownca234692019-02-28 11:22:19 -07001247 ImageData {
1248 plain: copy,
1249 cipher: enc_copy,
1250 }
David Brown5c9e0f12019-01-09 16:34:33 -07001251 } else {
1252
David Brown76101572019-02-28 11:29:03 -07001253 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001254
1255 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001256 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001257
1258 let enc_copy: Option<Vec<u8>>;
1259
1260 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001261 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001262
David Brown76101572019-02-28 11:29:03 -07001263 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001264
1265 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001266 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001267
1268 enc_copy = Some(enc);
1269 } else {
1270 enc_copy = None;
1271 }
1272
David Brownca234692019-02-28 11:22:19 -07001273 ImageData {
1274 plain: copy,
1275 cipher: enc_copy,
1276 }
David Brown5c9e0f12019-01-09 16:34:33 -07001277 }
David Brown5c9e0f12019-01-09 16:34:33 -07001278}
1279
David Brown873be312019-09-03 12:22:32 -06001280/// Install no image. This is used when no upgrade happens.
1281fn install_no_image() -> ImageData {
1282 ImageData {
1283 plain: vec![],
1284 cipher: None,
1285 }
1286}
1287
David Brown5c9e0f12019-01-09 16:34:33 -07001288fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001289 if Caps::EcdsaP224.present() {
1290 panic!("Ecdsa P224 not supported in Simulator");
1291 }
David Brown5c9e0f12019-01-09 16:34:33 -07001292
David Brownb8882112019-01-11 14:04:11 -07001293 if Caps::EncKw.present() {
1294 if Caps::RSA2048.present() {
1295 TlvGen::new_rsa_kw()
1296 } else if Caps::EcdsaP256.present() {
1297 TlvGen::new_ecdsa_kw()
1298 } else {
1299 TlvGen::new_enc_kw()
1300 }
1301 } else if Caps::EncRsa.present() {
1302 if Caps::RSA2048.present() {
1303 TlvGen::new_sig_enc_rsa()
1304 } else {
1305 TlvGen::new_enc_rsa()
1306 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001307 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001308 if Caps::EcdsaP256.present() {
1309 TlvGen::new_ecdsa_ecies_p256()
1310 } else {
1311 TlvGen::new_ecies_p256()
1312 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001313 } else if Caps::EncX25519.present() {
1314 if Caps::Ed25519.present() {
1315 TlvGen::new_ed25519_ecies_x25519()
1316 } else {
1317 TlvGen::new_ecies_x25519()
1318 }
David Brownb8882112019-01-11 14:04:11 -07001319 } else {
1320 // The non-encrypted configuration.
1321 if Caps::RSA2048.present() {
1322 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001323 } else if Caps::RSA3072.present() {
1324 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001325 } else if Caps::EcdsaP256.present() {
1326 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001327 } else if Caps::Ed25519.present() {
1328 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001329 } else {
1330 TlvGen::new_hash_only()
1331 }
1332 }
David Brown5c9e0f12019-01-09 16:34:33 -07001333}
1334
David Brownca234692019-02-28 11:22:19 -07001335impl ImageData {
1336 /// Find the image contents for the given slot. This assumes that slot 0
1337 /// is unencrypted, and slot 1 is encrypted.
1338 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001339 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001340 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001341 match (encrypted, slot) {
1342 (false, _) => &self.plain,
1343 (true, 0) => &self.plain,
1344 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1345 _ => panic!("Invalid slot requested"),
1346 }
David Brown5c9e0f12019-01-09 16:34:33 -07001347 }
1348}
1349
David Brown5c9e0f12019-01-09 16:34:33 -07001350/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001351fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1352 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001353 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001354 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001355
1356 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001357 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001358 let dev = flash.get(&dev_id).unwrap();
1359 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001360
1361 if buf != &copy[..] {
1362 for i in 0 .. buf.len() {
1363 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001364 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1365 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001366 break;
1367 }
1368 }
1369 false
1370 } else {
1371 true
1372 }
1373}
1374
David Brown3b090212019-07-30 15:59:28 -06001375fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001376 magic: Option<u8>, image_ok: Option<u8>,
1377 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001378 if Caps::OverwriteUpgrade.present() {
1379 return true;
1380 }
David Brown5c9e0f12019-01-09 16:34:33 -07001381
David Brown3b090212019-07-30 15:59:28 -06001382 let offset = slot.trailer_off + c::boot_max_align();
1383 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001384 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001385 let mut failed = false;
1386
David Brown76101572019-02-28 11:29:03 -07001387 let dev = flash.get(&dev_id).unwrap();
1388 let erased_val = dev.erased_val();
1389 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001390
1391 failed |= match magic {
1392 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001393 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001394 warn!("\"magic\" mismatch at {:#x}", offset);
1395 true
1396 } else if v == 3 {
1397 let expected = [erased_val; 16];
Christopher Collinsa1c12042019-05-23 14:00:28 -07001398 if &copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001399 warn!("\"magic\" mismatch at {:#x}", offset);
1400 true
1401 } else {
1402 false
1403 }
1404 } else {
1405 false
1406 }
1407 },
1408 None => false,
1409 };
1410
1411 failed |= match image_ok {
1412 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001413 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001414 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1415 true
1416 } else {
1417 false
1418 }
1419 },
1420 None => false,
1421 };
1422
1423 failed |= match copy_done {
1424 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001425 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001426 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1427 true
1428 } else {
1429 false
1430 }
1431 },
1432 None => false,
1433 };
1434
1435 !failed
1436}
1437
David Brown297029a2019-08-13 14:29:51 -06001438/// Install a partition table. This is a simplified partition table that
1439/// we write at the beginning of flash so make it easier for external tools
1440/// to analyze these images.
1441fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1442 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1443 for &id in &ids {
1444 // If there are any partitions in this device that start at 0, and
1445 // aren't marked as the BootLoader partition, avoid adding the
1446 // partition table. This makes it harder to view the image, but
1447 // avoids messing up images already written.
1448 if areadesc.iter_areas().any(|area| {
1449 area.device_id == id &&
1450 area.off == 0 &&
1451 area.flash_id != FlashId::BootLoader
1452 }) {
1453 if log_enabled!(Info) {
1454 let special: Vec<FlashId> = areadesc.iter_areas()
1455 .filter(|area| area.device_id == id && area.off == 0)
1456 .map(|area| area.flash_id)
1457 .collect();
1458 info!("Skipping partition table: {:?}", special);
1459 }
1460 break;
1461 }
1462
1463 let mut buf: Vec<u8> = vec![];
1464 write!(&mut buf, "mcuboot\0").unwrap();
1465
1466 // Iterate through all of the partitions in that device, and encode
1467 // into the table.
1468 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1469 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1470
1471 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1472 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1473 buf.write_u32::<LittleEndian>(area.off).unwrap();
1474 buf.write_u32::<LittleEndian>(area.size).unwrap();
1475 buf.write_u32::<LittleEndian>(0).unwrap();
1476 }
1477
1478 let dev = flash.get_mut(&id).unwrap();
1479
1480 // Pad to alignment.
1481 while buf.len() % dev.align() != 0 {
1482 buf.push(0);
1483 }
1484
1485 dev.write(0, &buf).unwrap();
1486 }
1487}
1488
David Brown5c9e0f12019-01-09 16:34:33 -07001489/// The image header
1490#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001491#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001492pub struct ImageHeader {
1493 magic: u32,
1494 load_addr: u32,
1495 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001496 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001497 img_size: u32,
1498 flags: u32,
1499 ver: ImageVersion,
1500 _pad2: u32,
1501}
1502
1503impl AsRaw for ImageHeader {}
1504
1505#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001506#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001507pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001508 pub major: u8,
1509 pub minor: u8,
1510 pub revision: u16,
1511 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001512}
1513
David Brownc3898d62019-08-05 14:20:02 -06001514#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001515pub struct SlotInfo {
1516 pub base_off: usize,
1517 pub trailer_off: usize,
1518 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001519 // Which slot within this device.
1520 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001521 pub dev_id: u8,
1522}
1523
David Brown347dc572019-11-15 11:37:25 -07001524const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1525 0x60, 0xd2, 0xef, 0x7f,
1526 0x35, 0x52, 0x50, 0x0f,
1527 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001528
1529// Replicates defines found in bootutil.h
1530const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1531const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1532
1533const BOOT_FLAG_SET: Option<u8> = Some(1);
1534const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1535
1536/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001537pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1538 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001539 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001540 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001541 if offset % align != 0 || MAGIC.len() % align != 0 {
1542 // The write size is larger than the magic value. Fill a buffer
1543 // with the erased value, put the MAGIC in it, and write it in its
1544 // entirety.
1545 let mut buf = vec![dev.erased_val(); align];
1546 buf[(offset % align)..].copy_from_slice(MAGIC);
1547 dev.write(offset - (offset % align), &buf).unwrap();
1548 } else {
1549 dev.write(offset, MAGIC).unwrap();
1550 }
David Brown5c9e0f12019-01-09 16:34:33 -07001551}
1552
1553/// Writes the image_ok flag which, guess what, tells the bootloader
1554/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001555fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001556 // Overwrite mode always is permanent, and only the magic is used in
1557 // the trailer. To avoid problems with large write sizes, don't try to
1558 // set anything in this case.
1559 if Caps::OverwriteUpgrade.present() {
1560 return;
1561 }
1562
David Brown76101572019-02-28 11:29:03 -07001563 let dev = flash.get_mut(&slot.dev_id).unwrap();
1564 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001565 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001566 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001567 let align = dev.align();
1568 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001569}
1570
1571// Drop some pseudo-random gibberish onto the data.
1572fn splat(data: &mut [u8], seed: usize) {
1573 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
1574 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
1575 rng.fill_bytes(data);
1576}
1577
1578/// Return a read-only view into the raw bytes of this object
1579trait AsRaw : Sized {
1580 fn as_raw<'a>(&'a self) -> &'a [u8] {
1581 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1582 mem::size_of::<Self>()) }
1583 }
1584}
1585
1586pub fn show_sizes() {
1587 // This isn't panic safe.
1588 for min in &[1, 2, 4, 8] {
1589 let msize = c::boot_trailer_sz(*min);
1590 println!("{:2}: {} (0x{:x})", min, msize, msize);
1591 }
1592}
David Brown95de4502019-11-15 12:01:34 -07001593
1594#[cfg(not(feature = "large-write"))]
1595fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001596 &[1, 2, 4, 8]
1597}
1598
1599#[cfg(feature = "large-write")]
1600fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001601 &[1, 2, 4, 8, 128, 512]
1602}