blob: 174904fc6f334c9938a009b3d76e8129efdd2b49 [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
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300242 pub fn make_erased_secondary_image(self) -> Images {
243 let mut flash = self.flash;
244 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
245 let dep = BoringDep::new(image_num, &NO_DEPS);
246 let primaries = install_image(&mut flash, &slots[0], 32784, &dep, false);
247 let upgrades = install_no_image();
248 OneImage {
249 slots: slots,
250 primaries: primaries,
251 upgrades: upgrades,
252 }}).collect();
253 Images {
254 flash: flash,
255 areadesc: self.areadesc,
256 images: images,
257 total_count: None,
258 }
259 }
260
David Browne5133242019-02-28 11:05:19 -0700261 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300262 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700263 match device {
264 DeviceName::Stm32f4 => {
265 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700266 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
267 64 * 1024,
268 128 * 1024, 128 * 1024, 128 * 1024],
269 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700270 let dev_id = 0;
271 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700272 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700273 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
274 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
275 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
276
David Brown76101572019-02-28 11:29:03 -0700277 let mut flash = SimMultiFlash::new();
278 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300279 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700280 }
281 DeviceName::K64f => {
282 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700283 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700284
285 let dev_id = 0;
286 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700287 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700288 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
289 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
290 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
291
David Brown76101572019-02-28 11:29:03 -0700292 let mut flash = SimMultiFlash::new();
293 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300294 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700295 }
296 DeviceName::K64fBig => {
297 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
298 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700299 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700300
301 let dev_id = 0;
302 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700303 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700304 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
305 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
306 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
307
David Brown76101572019-02-28 11:29:03 -0700308 let mut flash = SimMultiFlash::new();
309 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300310 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700311 }
312 DeviceName::Nrf52840 => {
313 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
314 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700315 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700316
317 let dev_id = 0;
318 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700319 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700320 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
321 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
322 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
323
David Brown76101572019-02-28 11:29:03 -0700324 let mut flash = SimMultiFlash::new();
325 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300326 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700327 }
328 DeviceName::Nrf52840SpiFlash => {
329 // Simulate nrf52840 with external SPI flash. The external SPI flash
330 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700331 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
332 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700333
334 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700335 areadesc.add_flash_sectors(0, &dev0);
336 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700337
338 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
339 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
340 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
341
David Brown76101572019-02-28 11:29:03 -0700342 let mut flash = SimMultiFlash::new();
343 flash.insert(0, dev0);
344 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300345 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700346 }
David Brown2bff6472019-03-05 13:58:35 -0700347 DeviceName::K64fMulti => {
348 // NXP style flash, but larger, to support multiple images.
349 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
350
351 let dev_id = 0;
352 let mut areadesc = AreaDesc::new();
353 areadesc.add_flash_sectors(dev_id, &dev);
354 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
355 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
356 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
357 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
358 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
359
360 let mut flash = SimMultiFlash::new();
361 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300362 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700363 }
David Browne5133242019-02-28 11:05:19 -0700364 }
365 }
David Brownc3898d62019-08-05 14:20:02 -0600366
367 pub fn num_images(&self) -> usize {
368 self.slots.len()
369 }
David Browne5133242019-02-28 11:05:19 -0700370}
371
David Brown5c9e0f12019-01-09 16:34:33 -0700372impl Images {
373 /// A simple upgrade without forced failures.
374 ///
375 /// Returns the number of flash operations which can later be used to
376 /// inject failures at chosen steps.
Fabio Utziged4a5362019-07-30 12:43:23 -0300377 pub fn run_basic_upgrade(&self, permanent: bool) -> Result<i32, ()> {
378 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700379 info!("Total flash operation count={}", total_count);
380
David Brown84b49f72019-03-01 10:58:22 -0700381 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700382 warn!("Image mismatch after first boot");
383 Err(())
384 } else {
385 Ok(total_count)
386 }
387 }
388
David Brownc3898d62019-08-05 14:20:02 -0600389 /// Test a simple upgrade, with dependencies given, and verify that the
390 /// image does as is described in the test.
391 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
392 let (flash, _) = self.try_upgrade(None, true);
393
394 self.verify_dep_images(&flash, deps)
395 }
396
Fabio Utzigf5480c72019-11-28 10:41:57 -0300397 fn is_swap_upgrade(&self) -> bool {
398 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
399 }
400
David Brown5c9e0f12019-01-09 16:34:33 -0700401 pub fn run_basic_revert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700402 if Caps::OverwriteUpgrade.present() {
403 return false;
404 }
David Brown5c9e0f12019-01-09 16:34:33 -0700405
David Brown5c9e0f12019-01-09 16:34:33 -0700406 let mut fails = 0;
407
408 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300409 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700410 for count in 2 .. 5 {
411 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700412 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700413 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700414 error!("Revert failure on count {}", count);
415 fails += 1;
416 }
417 }
418 }
419
420 fails > 0
421 }
422
423 pub fn run_perm_with_fails(&self) -> bool {
424 let mut fails = 0;
425 let total_flash_ops = self.total_count.unwrap();
426
427 // Let's try an image halfway through.
428 for i in 1 .. total_flash_ops {
429 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300430 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700431 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700432 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700433 warn!("FAIL at step {} of {}", i, total_flash_ops);
434 fails += 1;
435 }
436
David Brown84b49f72019-03-01 10:58:22 -0700437 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
438 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100439 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700440 fails += 1;
441 }
442
David Brown84b49f72019-03-01 10:58:22 -0700443 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
444 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100445 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700446 fails += 1;
447 }
448
Fabio Utzigf5480c72019-11-28 10:41:57 -0300449 if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700450 if !self.verify_images(&flash, 1, 0) {
David Vincze2d736ad2019-02-18 11:50:22 +0100451 warn!("Secondary slot FAIL at step {} of {}",
452 i, total_flash_ops);
David Brown5c9e0f12019-01-09 16:34:33 -0700453 fails += 1;
454 }
455 }
456 }
457
458 if fails > 0 {
459 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
460 fails as f32 * 100.0 / total_flash_ops as f32);
461 }
462
463 fails > 0
464 }
465
David Brown5c9e0f12019-01-09 16:34:33 -0700466 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
467 let mut fails = 0;
468 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700469 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700470 info!("Random interruptions at reset points={:?}", total_counts);
471
David Brown84b49f72019-03-01 10:58:22 -0700472 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300473 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700474 // TODO: This result is ignored.
475 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700476 } else {
477 true
478 };
David Vincze2d736ad2019-02-18 11:50:22 +0100479 if !primary_slot_ok || !secondary_slot_ok {
480 error!("Image mismatch after random interrupts: primary slot={} \
481 secondary slot={}",
482 if primary_slot_ok { "ok" } else { "fail" },
483 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700484 fails += 1;
485 }
David Brown84b49f72019-03-01 10:58:22 -0700486 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
487 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100488 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700489 fails += 1;
490 }
David Brown84b49f72019-03-01 10:58:22 -0700491 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
492 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100493 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700494 fails += 1;
495 }
496
497 if fails > 0 {
498 error!("Error testing perm upgrade with {} fails", total_fails);
499 }
500
501 fails > 0
502 }
503
David Brown5c9e0f12019-01-09 16:34:33 -0700504 pub fn run_revert_with_fails(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700505 if Caps::OverwriteUpgrade.present() {
506 return false;
507 }
David Brown5c9e0f12019-01-09 16:34:33 -0700508
David Brown5c9e0f12019-01-09 16:34:33 -0700509 let mut fails = 0;
510
Fabio Utzigf5480c72019-11-28 10:41:57 -0300511 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300512 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700513 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700514 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700515 error!("Revert failed at interruption {}", i);
516 fails += 1;
517 }
518 }
519 }
520
521 fails > 0
522 }
523
David Brown5c9e0f12019-01-09 16:34:33 -0700524 pub fn run_norevert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700525 if Caps::OverwriteUpgrade.present() {
526 return false;
527 }
David Brown5c9e0f12019-01-09 16:34:33 -0700528
David Brown76101572019-02-28 11:29:03 -0700529 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700530 let mut fails = 0;
531
532 info!("Try norevert");
533
534 // First do a normal upgrade...
David Brown76101572019-02-28 11:29:03 -0700535 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700536 if result != 0 {
537 warn!("Failed first boot");
538 fails += 1;
539 }
540
541 //FIXME: copy_done is written by boot_go, is it ok if no copy
542 // was ever done?
543
David Brown84b49f72019-03-01 10:58:22 -0700544 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100545 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700546 fails += 1;
547 }
David Brown84b49f72019-03-01 10:58:22 -0700548 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
549 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100550 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700551 fails += 1;
552 }
David Brown84b49f72019-03-01 10:58:22 -0700553 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
554 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100555 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700556 fails += 1;
557 }
558
David Vincze2d736ad2019-02-18 11:50:22 +0100559 // Marks image in the primary slot as permanent,
560 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700561 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700562
David Brown84b49f72019-03-01 10:58:22 -0700563 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
564 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100565 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700566 fails += 1;
567 }
568
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 second boot");
572 fails += 1;
573 }
574
David Brown84b49f72019-03-01 10:58:22 -0700575 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
576 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100577 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700578 fails += 1;
579 }
David Brown84b49f72019-03-01 10:58:22 -0700580 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700581 warn!("Failed image verification");
582 fails += 1;
583 }
584
585 if fails > 0 {
586 error!("Error running upgrade without revert");
587 }
588
589 fails > 0
590 }
591
David Brown2ee5f7f2020-01-13 14:04:01 -0700592 // Test that an upgrade is rejected. Assumes that the image was build
593 // such that the upgrade is instead a downgrade.
594 pub fn run_nodowngrade(&self) -> bool {
595 if !Caps::DowngradePrevention.present() {
596 return false;
597 }
598
599 let mut flash = self.flash.clone();
600 let mut fails = 0;
601
602 info!("Try no downgrade");
603
604 // First, do a normal upgrade.
605 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
606 if result != 0 {
607 warn!("Failed first boot");
608 fails += 1;
609 }
610
611 if !self.verify_images(&flash, 0, 0) {
612 warn!("Failed verification after downgrade rejection");
613 fails += 1;
614 }
615
616 if fails > 0 {
617 error!("Error testing downgrade rejection");
618 }
619
620 fails > 0
621 }
622
David Vincze2d736ad2019-02-18 11:50:22 +0100623 // Tests a new image written to the primary slot that already has magic and
624 // image_ok set while there is no image on the secondary slot, so no revert
625 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700626 pub fn run_norevert_newimage(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700627 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700628 let mut fails = 0;
629
630 info!("Try non-revert on imgtool generated image");
631
David Brown84b49f72019-03-01 10:58:22 -0700632 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700633
David Vincze2d736ad2019-02-18 11:50:22 +0100634 // This simulates writing an image created by imgtool to
635 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700636 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
637 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100638 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700639 fails += 1;
640 }
641
642 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700643 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700644 if result != 0 {
645 warn!("Failed first boot");
646 fails += 1;
647 }
648
649 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700650 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700651 warn!("Failed image verification");
652 fails += 1;
653 }
David Brown84b49f72019-03-01 10:58:22 -0700654 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
655 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100656 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700657 fails += 1;
658 }
David Brown84b49f72019-03-01 10:58:22 -0700659 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
660 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100661 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700662 fails += 1;
663 }
664
665 if fails > 0 {
666 error!("Expected a non revert with new image");
667 }
668
669 fails > 0
670 }
671
David Vincze2d736ad2019-02-18 11:50:22 +0100672 // Tests a new image written to the primary slot that already has magic and
673 // image_ok set while there is no image on the secondary slot, so no revert
674 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700675 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700676 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700677 let mut fails = 0;
678
679 info!("Try upgrade image with bad signature");
680
David Brown84b49f72019-03-01 10:58:22 -0700681 self.mark_upgrades(&mut flash, 0);
682 self.mark_permanent_upgrades(&mut flash, 0);
683 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700684
David Brown84b49f72019-03-01 10:58:22 -0700685 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
686 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100687 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700688 fails += 1;
689 }
690
691 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700692 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700693 if result != 0 {
694 warn!("Failed first boot");
695 fails += 1;
696 }
697
698 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700699 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700700 warn!("Failed image verification");
701 fails += 1;
702 }
David Brown84b49f72019-03-01 10:58:22 -0700703 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
704 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100705 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700706 fails += 1;
707 }
708
709 if fails > 0 {
710 error!("Expected an upgrade failure when image has bad signature");
711 }
712
713 fails > 0
714 }
715
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300716 // Should detect there is a leftover trailer in an otherwise erased
717 // secondary slot and erase its trailer.
718 pub fn run_secondary_leftover_trailer(&self) -> bool {
719 let mut flash = self.flash.clone();
720 let mut fails = 0;
721
722 info!("Try with a leftover trailer in the secondary; must be erased");
723
724 // Add a trailer on the secondary slot
725 self.mark_permanent_upgrades(&mut flash, 1);
726 self.mark_upgrades(&mut flash, 1);
727
728 // Run the bootloader...
729 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
730 if result != 0 {
731 warn!("Failed first boot");
732 fails += 1;
733 }
734
735 // State should not have changed
736 if !self.verify_images(&flash, 0, 0) {
737 warn!("Failed image verification");
738 fails += 1;
739 }
740 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
741 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
742 warn!("Mismatched trailer for the secondary slot");
743 fails += 1;
744 }
745
746 if fails > 0 {
747 error!("Expected trailer on secondary slot to be erased");
748 }
749
750 fails > 0
751 }
752
David Brown5c9e0f12019-01-09 16:34:33 -0700753 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300754 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700755 }
756
David Brown5c9e0f12019-01-09 16:34:33 -0700757 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300758 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700759 }
760
761 /// This test runs a simple upgrade with no fails in the images, but
762 /// allowing for fails in the status area. This should run to the end
763 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700764 pub fn run_with_status_fails_complete(&self) -> bool {
David Vincze2d736ad2019-02-18 11:50:22 +0100765 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700766 return false;
767 }
768
David Brown76101572019-02-28 11:29:03 -0700769 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700770 let mut fails = 0;
771
772 info!("Try swap with status fails");
773
David Brown84b49f72019-03-01 10:58:22 -0700774 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700775 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700776
David Brown76101572019-02-28 11:29:03 -0700777 let (result, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown5c9e0f12019-01-09 16:34:33 -0700778 if result != 0 {
779 warn!("Failed!");
780 fails += 1;
781 }
782
783 // Failed writes to the marked "bad" region don't assert anymore.
784 // Any detected assert() is happening in another part of the code.
785 if asserts != 0 {
786 warn!("At least one assert() was called");
787 fails += 1;
788 }
789
David Brown84b49f72019-03-01 10:58:22 -0700790 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
791 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100792 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700793 fails += 1;
794 }
795
David Brown84b49f72019-03-01 10:58:22 -0700796 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700797 warn!("Failed image verification");
798 fails += 1;
799 }
800
David Vincze2d736ad2019-02-18 11:50:22 +0100801 info!("validate primary slot enabled; \
802 re-run of boot_go should just work");
David Brown76101572019-02-28 11:29:03 -0700803 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700804 if result != 0 {
805 warn!("Failed!");
806 fails += 1;
807 }
808
809 if fails > 0 {
810 error!("Error running upgrade with status write fails");
811 }
812
813 fails > 0
814 }
815
816 /// This test runs a simple upgrade with no fails in the images, but
817 /// allowing for fails in the status area. This should run to the end
818 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700819 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown85904a82019-01-11 13:45:12 -0700820 if Caps::OverwriteUpgrade.present() {
821 false
David Vincze2d736ad2019-02-18 11:50:22 +0100822 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700823
David Brown76101572019-02-28 11:29:03 -0700824 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700825 let mut fails = 0;
826 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700827
David Brown85904a82019-01-11 13:45:12 -0700828 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700829
David Brown85904a82019-01-11 13:45:12 -0700830 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700831
David Brown84b49f72019-03-01 10:58:22 -0700832 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700833 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700834
835 // Should not fail, writing to bad regions does not assert
David Brown76101572019-02-28 11:29:03 -0700836 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true);
David Brown85904a82019-01-11 13:45:12 -0700837 if asserts != 0 {
838 warn!("At least one assert() was called");
839 fails += 1;
840 }
841
David Brown76101572019-02-28 11:29:03 -0700842 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700843
844 info!("Resuming an interrupted swap operation");
David Brown76101572019-02-28 11:29:03 -0700845 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700846
847 // This might throw no asserts, for large sector devices, where
848 // a single failure writing is indistinguishable from no failure,
849 // or throw a single assert for small sector devices that fail
850 // multiple times...
851 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100852 warn!("Expected single assert validating the primary slot, \
853 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700854 fails += 1;
855 }
856
857 if fails > 0 {
858 error!("Error running upgrade with status write fails");
859 }
860
861 fails > 0
862 } else {
David Brown76101572019-02-28 11:29:03 -0700863 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700864 let mut fails = 0;
865
866 info!("Try interrupted swap with status fails");
867
David Brown84b49f72019-03-01 10:58:22 -0700868 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700869 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700870
871 // This is expected to fail while writing to bad regions...
David Brown76101572019-02-28 11:29:03 -0700872 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700873 if asserts == 0 {
874 warn!("No assert() detected");
875 fails += 1;
876 }
877
878 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700879 }
David Brown5c9e0f12019-01-09 16:34:33 -0700880 }
881
882 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -0700883 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -0700884 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -0700885 if Caps::OverwriteUpgrade.present() {
886 return;
887 }
888
David Brown84b49f72019-03-01 10:58:22 -0700889 // Set this for each image.
890 for image in &self.images {
891 let dev_id = &image.slots[slot].dev_id;
892 let dev = flash.get_mut(&dev_id).unwrap();
893 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -0700894 let off = &image.slots[slot].base_off;
895 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -0700896 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -0700897
David Brown84b49f72019-03-01 10:58:22 -0700898 // Mark the status area as a bad area
899 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
900 }
David Brown5c9e0f12019-01-09 16:34:33 -0700901 }
902
David Brown76101572019-02-28 11:29:03 -0700903 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +0100904 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700905 return;
906 }
907
David Brown84b49f72019-03-01 10:58:22 -0700908 for image in &self.images {
909 let dev_id = &image.slots[slot].dev_id;
910 let dev = flash.get_mut(&dev_id).unwrap();
911 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -0700912
David Brown84b49f72019-03-01 10:58:22 -0700913 // Disabling write verification the only assert triggered by
914 // boot_go should be checking for integrity of status bytes.
915 dev.set_verify_writes(false);
916 }
David Brown5c9e0f12019-01-09 16:34:33 -0700917 }
918
David Browndb505822019-03-01 10:04:20 -0700919 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
920 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -0300921 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -0700922 // Clone the flash to have a new copy.
923 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700924
Fabio Utziged4a5362019-07-30 12:43:23 -0300925 if permanent {
926 self.mark_permanent_upgrades(&mut flash, 1);
927 }
David Brown5c9e0f12019-01-09 16:34:33 -0700928
David Browndb505822019-03-01 10:04:20 -0700929 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -0700930
David Browndb505822019-03-01 10:04:20 -0700931 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
932 (-0x13579, _) => (true, stop.unwrap()),
933 (0, _) => (false, -counter),
934 (x, _) => panic!("Unknown return: {}", x),
935 };
David Brown5c9e0f12019-01-09 16:34:33 -0700936
David Browndb505822019-03-01 10:04:20 -0700937 counter = 0;
938 if first_interrupted {
939 // fl.dump();
940 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
941 (-0x13579, _) => panic!("Shouldn't stop again"),
942 (0, _) => (),
943 (x, _) => panic!("Unknown return: {}", x),
944 }
945 }
David Brown5c9e0f12019-01-09 16:34:33 -0700946
David Browndb505822019-03-01 10:04:20 -0700947 (flash, count - counter)
948 }
949
950 fn try_revert(&self, count: usize) -> SimMultiFlash {
951 let mut flash = self.flash.clone();
952
953 // fl.write_file("image0.bin").unwrap();
954 for i in 0 .. count {
955 info!("Running boot pass {}", i + 1);
956 assert_eq!(c::boot_go(&mut flash, &self.areadesc, None, false), (0, 0));
957 }
958 flash
959 }
960
961 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
962 let mut flash = self.flash.clone();
963 let mut fails = 0;
964
965 let mut counter = stop;
966 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
967 if x != -0x13579 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700968 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -0700969 fails += 1;
970 }
971
Fabio Utzig8af7f792019-07-30 12:40:01 -0300972 // In a multi-image setup, copy done might be set if any number of
973 // images was already successfully swapped.
974 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
975 warn!("copy_done should be unset");
976 fails += 1;
977 }
978
David Browndb505822019-03-01 10:04:20 -0700979 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
980 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700981 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -0700982 fails += 1;
983 }
984
David Brown84b49f72019-03-01 10:58:22 -0700985 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -0700986 warn!("Image in the primary slot before revert is invalid at stop={}",
987 stop);
988 fails += 1;
989 }
David Brown84b49f72019-03-01 10:58:22 -0700990 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -0700991 warn!("Image in the secondary slot before revert is invalid at stop={}",
992 stop);
993 fails += 1;
994 }
David Brown84b49f72019-03-01 10:58:22 -0700995 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
996 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -0700997 warn!("Mismatched trailer for the primary slot before revert");
998 fails += 1;
999 }
David Brown84b49f72019-03-01 10:58:22 -07001000 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1001 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001002 warn!("Mismatched trailer for the secondary slot before revert");
1003 fails += 1;
1004 }
1005
1006 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001007 let mut counter = stop;
1008 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
1009 if x != -0x13579 {
1010 warn!("Should have stopped revert at interruption point");
1011 fails += 1;
1012 }
1013
David Browndb505822019-03-01 10:04:20 -07001014 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
1015 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001016 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001017 fails += 1;
1018 }
1019
David Brown84b49f72019-03-01 10:58:22 -07001020 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001021 warn!("Image in the primary slot after revert is invalid at stop={}",
1022 stop);
1023 fails += 1;
1024 }
David Brown84b49f72019-03-01 10:58:22 -07001025 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001026 warn!("Image in the secondary slot after revert is invalid at stop={}",
1027 stop);
1028 fails += 1;
1029 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001030
David Brown84b49f72019-03-01 10:58:22 -07001031 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1032 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001033 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001034 fails += 1;
1035 }
David Brown84b49f72019-03-01 10:58:22 -07001036 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1037 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001038 warn!("Mismatched trailer for the secondary slot after revert");
1039 fails += 1;
1040 }
1041
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001042 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
1043 if x != 0 {
1044 warn!("Should have finished 3rd boot");
1045 fails += 1;
1046 }
1047
1048 if !self.verify_images(&flash, 0, 0) {
1049 warn!("Image in the primary slot is invalid on 1st boot after revert");
1050 fails += 1;
1051 }
1052 if !self.verify_images(&flash, 1, 1) {
1053 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1054 fails += 1;
1055 }
1056
David Browndb505822019-03-01 10:04:20 -07001057 fails > 0
1058 }
1059
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001060
David Browndb505822019-03-01 10:04:20 -07001061 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1062 let mut flash = self.flash.clone();
1063
David Brown84b49f72019-03-01 10:58:22 -07001064 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001065
1066 let mut rng = rand::thread_rng();
1067 let mut resets = vec![0i32; count];
1068 let mut remaining_ops = total_ops;
1069 for i in 0 .. count {
1070 let ops = Range::new(1, remaining_ops / 2);
1071 let reset_counter = ops.ind_sample(&mut rng);
1072 let mut counter = reset_counter;
1073 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
1074 (0, _) | (-0x13579, _) => (),
1075 (x, _) => panic!("Unknown return: {}", x),
1076 }
1077 remaining_ops -= reset_counter;
1078 resets[i] = reset_counter;
1079 }
1080
1081 match c::boot_go(&mut flash, &self.areadesc, None, false) {
1082 (-0x13579, _) => panic!("Should not be have been interrupted!"),
David Brown5c9e0f12019-01-09 16:34:33 -07001083 (0, _) => (),
1084 (x, _) => panic!("Unknown return: {}", x),
1085 }
David Brown5c9e0f12019-01-09 16:34:33 -07001086
David Browndb505822019-03-01 10:04:20 -07001087 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001088 }
David Brown84b49f72019-03-01 10:58:22 -07001089
1090 /// Verify the image in the given flash device, the specified slot
1091 /// against the expected image.
1092 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001093 self.images.iter().all(|image| {
1094 verify_image(flash, &image.slots[slot],
1095 match against {
1096 0 => &image.primaries,
1097 1 => &image.upgrades,
1098 _ => panic!("Invalid 'against'")
1099 })
1100 })
David Brown84b49f72019-03-01 10:58:22 -07001101 }
1102
David Brownc3898d62019-08-05 14:20:02 -06001103 /// Verify the images, according to the dependency test.
1104 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1105 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1106 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1107 if !verify_image(flash, &image.slots[0],
1108 match upgrade {
1109 UpgradeInfo::Upgraded => &image.upgrades,
1110 UpgradeInfo::Held => &image.primaries,
1111 }) {
1112 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1113 return true;
1114 }
1115 }
1116
1117 false
1118 }
1119
Fabio Utzig8af7f792019-07-30 12:40:01 -03001120 /// Verify that at least one of the trailers of the images have the
1121 /// specified values.
1122 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1123 magic: Option<u8>, image_ok: Option<u8>,
1124 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001125 self.images.iter().any(|image| {
1126 verify_trailer(flash, &image.slots[slot],
1127 magic, image_ok, copy_done)
1128 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001129 }
1130
David Brown84b49f72019-03-01 10:58:22 -07001131 /// Verify that the trailers of the images have the specified
1132 /// values.
1133 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1134 magic: Option<u8>, image_ok: Option<u8>,
1135 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001136 self.images.iter().all(|image| {
1137 verify_trailer(flash, &image.slots[slot],
1138 magic, image_ok, copy_done)
1139 })
David Brown84b49f72019-03-01 10:58:22 -07001140 }
1141
1142 /// Mark each of the images for permanent upgrade.
1143 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1144 for image in &self.images {
1145 mark_permanent_upgrade(flash, &image.slots[slot]);
1146 }
1147 }
1148
1149 /// Mark each of the images for permanent upgrade.
1150 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1151 for image in &self.images {
1152 mark_upgrade(flash, &image.slots[slot]);
1153 }
1154 }
David Brown297029a2019-08-13 14:29:51 -06001155
1156 /// Dump out the flash image(s) to one or more files for debugging
1157 /// purposes. The names will be written as either "{prefix}.mcubin" or
1158 /// "{prefix}-001.mcubin" depending on how many images there are.
1159 pub fn debug_dump(&self, prefix: &str) {
1160 for (id, fdev) in &self.flash {
1161 let name = if self.flash.len() == 1 {
1162 format!("{}.mcubin", prefix)
1163 } else {
1164 format!("{}-{:>0}.mcubin", prefix, id)
1165 };
1166 fdev.write_file(&name).unwrap();
1167 }
1168 }
David Brown5c9e0f12019-01-09 16:34:33 -07001169}
1170
1171/// Show the flash layout.
1172#[allow(dead_code)]
1173fn show_flash(flash: &dyn Flash) {
1174 println!("---- Flash configuration ----");
1175 for sector in flash.sector_iter() {
1176 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1177 sector.num, sector.base, sector.size);
1178 }
1179 println!("");
1180}
1181
1182/// Install a "program" into the given image. This fakes the image header, or at least all of the
1183/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001184fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownc3898d62019-08-05 14:20:02 -06001185 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001186 let offset = slot.base_off;
1187 let slot_len = slot.len;
1188 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001189
David Brown43643dd2019-01-11 15:43:28 -07001190 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001191
David Brownc3898d62019-08-05 14:20:02 -06001192 // Add the dependencies early to the tlv.
1193 for dep in deps.my_deps(offset, slot.index) {
1194 tlv.add_dependency(deps.other_id(), &dep);
1195 }
1196
David Brown5c9e0f12019-01-09 16:34:33 -07001197 const HDR_SIZE: usize = 32;
1198
1199 // Generate a boot header. Note that the size doesn't include the header.
1200 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001201 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -07001202 load_addr: 0,
1203 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001204 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001205 img_size: len as u32,
1206 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001207 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001208 _pad2: 0,
1209 };
1210
1211 let mut b_header = [0; HDR_SIZE];
1212 b_header[..32].clone_from_slice(header.as_raw());
1213 assert_eq!(b_header.len(), HDR_SIZE);
1214
1215 tlv.add_bytes(&b_header);
1216
1217 // The core of the image itself is just pseudorandom data.
1218 let mut b_img = vec![0; len];
1219 splat(&mut b_img, offset);
1220
David Browncb47dd72019-08-05 14:21:49 -06001221 // Add some information at the start of the payload to make it easier
1222 // to see what it is. This will fail if the image itself is too small.
1223 {
1224 let mut wr = Cursor::new(&mut b_img);
1225 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1226 offset, dev_id, slot).unwrap();
1227 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1228 }
1229
David Brown5c9e0f12019-01-09 16:34:33 -07001230 // TLV signatures work over plain image
1231 tlv.add_bytes(&b_img);
1232
1233 // Generate encrypted images
1234 let flag = TlvFlags::ENCRYPTED as u32;
1235 let is_encrypted = (tlv.get_flags() & flag) == flag;
1236 let mut b_encimg = vec![];
1237 if is_encrypted {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001238 tlv.generate_enc_key();
1239 let enc_key = tlv.get_enc_key();
1240 let key = GenericArray::from_slice(enc_key.as_slice());
David Brown5c9e0f12019-01-09 16:34:33 -07001241 let nonce = GenericArray::from_slice(&[0; 16]);
1242 let mut cipher = Aes128Ctr::new(&key, &nonce);
1243 b_encimg = b_img.clone();
1244 cipher.apply_keystream(&mut b_encimg);
1245 }
1246
1247 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001248 if bad_sig {
1249 tlv.corrupt_sig();
1250 }
1251 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001252
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001253 let dev = flash.get_mut(&dev_id).unwrap();
1254
David Brown5c9e0f12019-01-09 16:34:33 -07001255 let mut buf = vec![];
1256 buf.append(&mut b_header.to_vec());
1257 buf.append(&mut b_img);
1258 buf.append(&mut b_tlv.clone());
1259
David Brown95de4502019-11-15 12:01:34 -07001260 // Pad the buffer to a multiple of the flash alignment.
1261 let align = dev.align();
1262 while buf.len() % align != 0 {
1263 buf.push(dev.erased_val());
1264 }
1265
David Brown5c9e0f12019-01-09 16:34:33 -07001266 let mut encbuf = vec![];
1267 if is_encrypted {
1268 encbuf.append(&mut b_header.to_vec());
1269 encbuf.append(&mut b_encimg);
1270 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001271
1272 while encbuf.len() % align != 0 {
1273 encbuf.push(dev.erased_val());
1274 }
David Brown5c9e0f12019-01-09 16:34:33 -07001275 }
1276
David Vincze2d736ad2019-02-18 11:50:22 +01001277 // Since images are always non-encrypted in the primary slot, we first write
1278 // an encrypted image, re-read to use for verification, erase + flash
1279 // un-encrypted. In the secondary slot the image is written un-encrypted,
1280 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001281
David Brown3b090212019-07-30 15:59:28 -06001282 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001283 let enc_copy: Option<Vec<u8>>;
1284
1285 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001286 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001287
1288 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001289 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001290
1291 enc_copy = Some(enc);
1292
David Brown76101572019-02-28 11:29:03 -07001293 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001294 } else {
1295 enc_copy = None;
1296 }
1297
David Brown76101572019-02-28 11:29:03 -07001298 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001299
1300 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001301 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001302
David Brownca234692019-02-28 11:22:19 -07001303 ImageData {
1304 plain: copy,
1305 cipher: enc_copy,
1306 }
David Brown5c9e0f12019-01-09 16:34:33 -07001307 } else {
1308
David Brown76101572019-02-28 11:29:03 -07001309 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001310
1311 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001312 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001313
1314 let enc_copy: Option<Vec<u8>>;
1315
1316 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001317 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001318
David Brown76101572019-02-28 11:29:03 -07001319 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001320
1321 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001322 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001323
1324 enc_copy = Some(enc);
1325 } else {
1326 enc_copy = None;
1327 }
1328
David Brownca234692019-02-28 11:22:19 -07001329 ImageData {
1330 plain: copy,
1331 cipher: enc_copy,
1332 }
David Brown5c9e0f12019-01-09 16:34:33 -07001333 }
David Brown5c9e0f12019-01-09 16:34:33 -07001334}
1335
David Brown873be312019-09-03 12:22:32 -06001336/// Install no image. This is used when no upgrade happens.
1337fn install_no_image() -> ImageData {
1338 ImageData {
1339 plain: vec![],
1340 cipher: None,
1341 }
1342}
1343
David Brown5c9e0f12019-01-09 16:34:33 -07001344fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001345 if Caps::EcdsaP224.present() {
1346 panic!("Ecdsa P224 not supported in Simulator");
1347 }
David Brown5c9e0f12019-01-09 16:34:33 -07001348
David Brownb8882112019-01-11 14:04:11 -07001349 if Caps::EncKw.present() {
1350 if Caps::RSA2048.present() {
1351 TlvGen::new_rsa_kw()
1352 } else if Caps::EcdsaP256.present() {
1353 TlvGen::new_ecdsa_kw()
1354 } else {
1355 TlvGen::new_enc_kw()
1356 }
1357 } else if Caps::EncRsa.present() {
1358 if Caps::RSA2048.present() {
1359 TlvGen::new_sig_enc_rsa()
1360 } else {
1361 TlvGen::new_enc_rsa()
1362 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001363 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001364 if Caps::EcdsaP256.present() {
1365 TlvGen::new_ecdsa_ecies_p256()
1366 } else {
1367 TlvGen::new_ecies_p256()
1368 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001369 } else if Caps::EncX25519.present() {
1370 if Caps::Ed25519.present() {
1371 TlvGen::new_ed25519_ecies_x25519()
1372 } else {
1373 TlvGen::new_ecies_x25519()
1374 }
David Brownb8882112019-01-11 14:04:11 -07001375 } else {
1376 // The non-encrypted configuration.
1377 if Caps::RSA2048.present() {
1378 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001379 } else if Caps::RSA3072.present() {
1380 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001381 } else if Caps::EcdsaP256.present() {
1382 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001383 } else if Caps::Ed25519.present() {
1384 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001385 } else {
1386 TlvGen::new_hash_only()
1387 }
1388 }
David Brown5c9e0f12019-01-09 16:34:33 -07001389}
1390
David Brownca234692019-02-28 11:22:19 -07001391impl ImageData {
1392 /// Find the image contents for the given slot. This assumes that slot 0
1393 /// is unencrypted, and slot 1 is encrypted.
1394 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001395 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001396 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001397 match (encrypted, slot) {
1398 (false, _) => &self.plain,
1399 (true, 0) => &self.plain,
1400 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1401 _ => panic!("Invalid slot requested"),
1402 }
David Brown5c9e0f12019-01-09 16:34:33 -07001403 }
1404}
1405
David Brown5c9e0f12019-01-09 16:34:33 -07001406/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001407fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1408 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001409 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001410 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001411
1412 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001413 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001414 let dev = flash.get(&dev_id).unwrap();
1415 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001416
1417 if buf != &copy[..] {
1418 for i in 0 .. buf.len() {
1419 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001420 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1421 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001422 break;
1423 }
1424 }
1425 false
1426 } else {
1427 true
1428 }
1429}
1430
David Brown3b090212019-07-30 15:59:28 -06001431fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001432 magic: Option<u8>, image_ok: Option<u8>,
1433 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001434 if Caps::OverwriteUpgrade.present() {
1435 return true;
1436 }
David Brown5c9e0f12019-01-09 16:34:33 -07001437
David Brown3b090212019-07-30 15:59:28 -06001438 let offset = slot.trailer_off + c::boot_max_align();
1439 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001440 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001441 let mut failed = false;
1442
David Brown76101572019-02-28 11:29:03 -07001443 let dev = flash.get(&dev_id).unwrap();
1444 let erased_val = dev.erased_val();
1445 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001446
1447 failed |= match magic {
1448 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001449 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001450 warn!("\"magic\" mismatch at {:#x}", offset);
1451 true
1452 } else if v == 3 {
1453 let expected = [erased_val; 16];
Christopher Collinsa1c12042019-05-23 14:00:28 -07001454 if &copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001455 warn!("\"magic\" mismatch at {:#x}", offset);
1456 true
1457 } else {
1458 false
1459 }
1460 } else {
1461 false
1462 }
1463 },
1464 None => false,
1465 };
1466
1467 failed |= match image_ok {
1468 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001469 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001470 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1471 true
1472 } else {
1473 false
1474 }
1475 },
1476 None => false,
1477 };
1478
1479 failed |= match copy_done {
1480 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001481 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001482 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1483 true
1484 } else {
1485 false
1486 }
1487 },
1488 None => false,
1489 };
1490
1491 !failed
1492}
1493
David Brown297029a2019-08-13 14:29:51 -06001494/// Install a partition table. This is a simplified partition table that
1495/// we write at the beginning of flash so make it easier for external tools
1496/// to analyze these images.
1497fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1498 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1499 for &id in &ids {
1500 // If there are any partitions in this device that start at 0, and
1501 // aren't marked as the BootLoader partition, avoid adding the
1502 // partition table. This makes it harder to view the image, but
1503 // avoids messing up images already written.
1504 if areadesc.iter_areas().any(|area| {
1505 area.device_id == id &&
1506 area.off == 0 &&
1507 area.flash_id != FlashId::BootLoader
1508 }) {
1509 if log_enabled!(Info) {
1510 let special: Vec<FlashId> = areadesc.iter_areas()
1511 .filter(|area| area.device_id == id && area.off == 0)
1512 .map(|area| area.flash_id)
1513 .collect();
1514 info!("Skipping partition table: {:?}", special);
1515 }
1516 break;
1517 }
1518
1519 let mut buf: Vec<u8> = vec![];
1520 write!(&mut buf, "mcuboot\0").unwrap();
1521
1522 // Iterate through all of the partitions in that device, and encode
1523 // into the table.
1524 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1525 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1526
1527 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1528 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1529 buf.write_u32::<LittleEndian>(area.off).unwrap();
1530 buf.write_u32::<LittleEndian>(area.size).unwrap();
1531 buf.write_u32::<LittleEndian>(0).unwrap();
1532 }
1533
1534 let dev = flash.get_mut(&id).unwrap();
1535
1536 // Pad to alignment.
1537 while buf.len() % dev.align() != 0 {
1538 buf.push(0);
1539 }
1540
1541 dev.write(0, &buf).unwrap();
1542 }
1543}
1544
David Brown5c9e0f12019-01-09 16:34:33 -07001545/// The image header
1546#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001547#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001548pub struct ImageHeader {
1549 magic: u32,
1550 load_addr: u32,
1551 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001552 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001553 img_size: u32,
1554 flags: u32,
1555 ver: ImageVersion,
1556 _pad2: u32,
1557}
1558
1559impl AsRaw for ImageHeader {}
1560
1561#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001562#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001563pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001564 pub major: u8,
1565 pub minor: u8,
1566 pub revision: u16,
1567 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001568}
1569
David Brownc3898d62019-08-05 14:20:02 -06001570#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001571pub struct SlotInfo {
1572 pub base_off: usize,
1573 pub trailer_off: usize,
1574 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001575 // Which slot within this device.
1576 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001577 pub dev_id: u8,
1578}
1579
David Brown347dc572019-11-15 11:37:25 -07001580const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1581 0x60, 0xd2, 0xef, 0x7f,
1582 0x35, 0x52, 0x50, 0x0f,
1583 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001584
1585// Replicates defines found in bootutil.h
1586const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1587const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1588
1589const BOOT_FLAG_SET: Option<u8> = Some(1);
1590const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1591
1592/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001593pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1594 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001595 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001596 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001597 if offset % align != 0 || MAGIC.len() % align != 0 {
1598 // The write size is larger than the magic value. Fill a buffer
1599 // with the erased value, put the MAGIC in it, and write it in its
1600 // entirety.
1601 let mut buf = vec![dev.erased_val(); align];
1602 buf[(offset % align)..].copy_from_slice(MAGIC);
1603 dev.write(offset - (offset % align), &buf).unwrap();
1604 } else {
1605 dev.write(offset, MAGIC).unwrap();
1606 }
David Brown5c9e0f12019-01-09 16:34:33 -07001607}
1608
1609/// Writes the image_ok flag which, guess what, tells the bootloader
1610/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001611fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001612 // Overwrite mode always is permanent, and only the magic is used in
1613 // the trailer. To avoid problems with large write sizes, don't try to
1614 // set anything in this case.
1615 if Caps::OverwriteUpgrade.present() {
1616 return;
1617 }
1618
David Brown76101572019-02-28 11:29:03 -07001619 let dev = flash.get_mut(&slot.dev_id).unwrap();
1620 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001621 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001622 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001623 let align = dev.align();
1624 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001625}
1626
1627// Drop some pseudo-random gibberish onto the data.
1628fn splat(data: &mut [u8], seed: usize) {
1629 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
1630 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
1631 rng.fill_bytes(data);
1632}
1633
1634/// Return a read-only view into the raw bytes of this object
1635trait AsRaw : Sized {
1636 fn as_raw<'a>(&'a self) -> &'a [u8] {
1637 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1638 mem::size_of::<Self>()) }
1639 }
1640}
1641
1642pub fn show_sizes() {
1643 // This isn't panic safe.
1644 for min in &[1, 2, 4, 8] {
1645 let msize = c::boot_trailer_sz(*min);
1646 println!("{:2}: {} (0x{:x})", min, msize, msize);
1647 }
1648}
David Brown95de4502019-11-15 12:01:34 -07001649
1650#[cfg(not(feature = "large-write"))]
1651fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001652 &[1, 2, 4, 8]
1653}
1654
1655#[cfg(feature = "large-write")]
1656fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001657 &[1, 2, 4, 8, 128, 512]
1658}