blob: 4a39010d2c389e0b1af7b287bc86bc0d1ef43013 [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::{
David Browncd842842020-07-09 15:46:53 -060018 Rng, RngCore, SeedableRng,
19 rngs::SmallRng,
David Brown5c9e0f12019-01-09 16:34:33 -070020};
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,
David Brown8a99adf2020-07-09 16:52:38 -060031 NewStreamCipher,
32 SyncStreamCipher,
David Brown5c9e0f12019-01-09 16:34:33 -070033 },
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 {
David Browncd842842020-07-09 15:46:53 -06001070 let reset_counter = rng.gen_range(1, remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001071 let mut counter = reset_counter;
1072 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
1073 (0, _) | (-0x13579, _) => (),
1074 (x, _) => panic!("Unknown return: {}", x),
1075 }
1076 remaining_ops -= reset_counter;
1077 resets[i] = reset_counter;
1078 }
1079
1080 match c::boot_go(&mut flash, &self.areadesc, None, false) {
1081 (-0x13579, _) => panic!("Should not be have been interrupted!"),
David Brown5c9e0f12019-01-09 16:34:33 -07001082 (0, _) => (),
1083 (x, _) => panic!("Unknown return: {}", x),
1084 }
David Brown5c9e0f12019-01-09 16:34:33 -07001085
David Browndb505822019-03-01 10:04:20 -07001086 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001087 }
David Brown84b49f72019-03-01 10:58:22 -07001088
1089 /// Verify the image in the given flash device, the specified slot
1090 /// against the expected image.
1091 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001092 self.images.iter().all(|image| {
1093 verify_image(flash, &image.slots[slot],
1094 match against {
1095 0 => &image.primaries,
1096 1 => &image.upgrades,
1097 _ => panic!("Invalid 'against'")
1098 })
1099 })
David Brown84b49f72019-03-01 10:58:22 -07001100 }
1101
David Brownc3898d62019-08-05 14:20:02 -06001102 /// Verify the images, according to the dependency test.
1103 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1104 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1105 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1106 if !verify_image(flash, &image.slots[0],
1107 match upgrade {
1108 UpgradeInfo::Upgraded => &image.upgrades,
1109 UpgradeInfo::Held => &image.primaries,
1110 }) {
1111 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1112 return true;
1113 }
1114 }
1115
1116 false
1117 }
1118
Fabio Utzig8af7f792019-07-30 12:40:01 -03001119 /// Verify that at least one of the trailers of the images have the
1120 /// specified values.
1121 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1122 magic: Option<u8>, image_ok: Option<u8>,
1123 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001124 self.images.iter().any(|image| {
1125 verify_trailer(flash, &image.slots[slot],
1126 magic, image_ok, copy_done)
1127 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001128 }
1129
David Brown84b49f72019-03-01 10:58:22 -07001130 /// Verify that the trailers of the images have the specified
1131 /// values.
1132 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1133 magic: Option<u8>, image_ok: Option<u8>,
1134 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001135 self.images.iter().all(|image| {
1136 verify_trailer(flash, &image.slots[slot],
1137 magic, image_ok, copy_done)
1138 })
David Brown84b49f72019-03-01 10:58:22 -07001139 }
1140
1141 /// Mark each of the images for permanent upgrade.
1142 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1143 for image in &self.images {
1144 mark_permanent_upgrade(flash, &image.slots[slot]);
1145 }
1146 }
1147
1148 /// Mark each of the images for permanent upgrade.
1149 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1150 for image in &self.images {
1151 mark_upgrade(flash, &image.slots[slot]);
1152 }
1153 }
David Brown297029a2019-08-13 14:29:51 -06001154
1155 /// Dump out the flash image(s) to one or more files for debugging
1156 /// purposes. The names will be written as either "{prefix}.mcubin" or
1157 /// "{prefix}-001.mcubin" depending on how many images there are.
1158 pub fn debug_dump(&self, prefix: &str) {
1159 for (id, fdev) in &self.flash {
1160 let name = if self.flash.len() == 1 {
1161 format!("{}.mcubin", prefix)
1162 } else {
1163 format!("{}-{:>0}.mcubin", prefix, id)
1164 };
1165 fdev.write_file(&name).unwrap();
1166 }
1167 }
David Brown5c9e0f12019-01-09 16:34:33 -07001168}
1169
1170/// Show the flash layout.
1171#[allow(dead_code)]
1172fn show_flash(flash: &dyn Flash) {
1173 println!("---- Flash configuration ----");
1174 for sector in flash.sector_iter() {
1175 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1176 sector.num, sector.base, sector.size);
1177 }
1178 println!("");
1179}
1180
1181/// Install a "program" into the given image. This fakes the image header, or at least all of the
1182/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001183fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownc3898d62019-08-05 14:20:02 -06001184 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001185 let offset = slot.base_off;
1186 let slot_len = slot.len;
1187 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001188
David Brown43643dd2019-01-11 15:43:28 -07001189 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001190
David Brownc3898d62019-08-05 14:20:02 -06001191 // Add the dependencies early to the tlv.
1192 for dep in deps.my_deps(offset, slot.index) {
1193 tlv.add_dependency(deps.other_id(), &dep);
1194 }
1195
David Brown5c9e0f12019-01-09 16:34:33 -07001196 const HDR_SIZE: usize = 32;
1197
1198 // Generate a boot header. Note that the size doesn't include the header.
1199 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001200 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -07001201 load_addr: 0,
1202 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001203 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001204 img_size: len as u32,
1205 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001206 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001207 _pad2: 0,
1208 };
1209
1210 let mut b_header = [0; HDR_SIZE];
1211 b_header[..32].clone_from_slice(header.as_raw());
1212 assert_eq!(b_header.len(), HDR_SIZE);
1213
1214 tlv.add_bytes(&b_header);
1215
1216 // The core of the image itself is just pseudorandom data.
1217 let mut b_img = vec![0; len];
1218 splat(&mut b_img, offset);
1219
David Browncb47dd72019-08-05 14:21:49 -06001220 // Add some information at the start of the payload to make it easier
1221 // to see what it is. This will fail if the image itself is too small.
1222 {
1223 let mut wr = Cursor::new(&mut b_img);
1224 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1225 offset, dev_id, slot).unwrap();
1226 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1227 }
1228
David Brown5c9e0f12019-01-09 16:34:33 -07001229 // TLV signatures work over plain image
1230 tlv.add_bytes(&b_img);
1231
1232 // Generate encrypted images
1233 let flag = TlvFlags::ENCRYPTED as u32;
1234 let is_encrypted = (tlv.get_flags() & flag) == flag;
1235 let mut b_encimg = vec![];
1236 if is_encrypted {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001237 tlv.generate_enc_key();
1238 let enc_key = tlv.get_enc_key();
1239 let key = GenericArray::from_slice(enc_key.as_slice());
David Brown5c9e0f12019-01-09 16:34:33 -07001240 let nonce = GenericArray::from_slice(&[0; 16]);
1241 let mut cipher = Aes128Ctr::new(&key, &nonce);
1242 b_encimg = b_img.clone();
1243 cipher.apply_keystream(&mut b_encimg);
1244 }
1245
1246 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001247 if bad_sig {
1248 tlv.corrupt_sig();
1249 }
1250 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001251
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001252 let dev = flash.get_mut(&dev_id).unwrap();
1253
David Brown5c9e0f12019-01-09 16:34:33 -07001254 let mut buf = vec![];
1255 buf.append(&mut b_header.to_vec());
1256 buf.append(&mut b_img);
1257 buf.append(&mut b_tlv.clone());
1258
David Brown95de4502019-11-15 12:01:34 -07001259 // Pad the buffer to a multiple of the flash alignment.
1260 let align = dev.align();
1261 while buf.len() % align != 0 {
1262 buf.push(dev.erased_val());
1263 }
1264
David Brown5c9e0f12019-01-09 16:34:33 -07001265 let mut encbuf = vec![];
1266 if is_encrypted {
1267 encbuf.append(&mut b_header.to_vec());
1268 encbuf.append(&mut b_encimg);
1269 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001270
1271 while encbuf.len() % align != 0 {
1272 encbuf.push(dev.erased_val());
1273 }
David Brown5c9e0f12019-01-09 16:34:33 -07001274 }
1275
David Vincze2d736ad2019-02-18 11:50:22 +01001276 // Since images are always non-encrypted in the primary slot, we first write
1277 // an encrypted image, re-read to use for verification, erase + flash
1278 // un-encrypted. In the secondary slot the image is written un-encrypted,
1279 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001280
David Brown3b090212019-07-30 15:59:28 -06001281 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001282 let enc_copy: Option<Vec<u8>>;
1283
1284 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001285 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001286
1287 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001288 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001289
1290 enc_copy = Some(enc);
1291
David Brown76101572019-02-28 11:29:03 -07001292 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001293 } else {
1294 enc_copy = None;
1295 }
1296
David Brown76101572019-02-28 11:29:03 -07001297 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001298
1299 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001300 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001301
David Brownca234692019-02-28 11:22:19 -07001302 ImageData {
1303 plain: copy,
1304 cipher: enc_copy,
1305 }
David Brown5c9e0f12019-01-09 16:34:33 -07001306 } else {
1307
David Brown76101572019-02-28 11:29:03 -07001308 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001309
1310 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001311 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001312
1313 let enc_copy: Option<Vec<u8>>;
1314
1315 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001316 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001317
David Brown76101572019-02-28 11:29:03 -07001318 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001319
1320 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001321 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001322
1323 enc_copy = Some(enc);
1324 } else {
1325 enc_copy = None;
1326 }
1327
David Brownca234692019-02-28 11:22:19 -07001328 ImageData {
1329 plain: copy,
1330 cipher: enc_copy,
1331 }
David Brown5c9e0f12019-01-09 16:34:33 -07001332 }
David Brown5c9e0f12019-01-09 16:34:33 -07001333}
1334
David Brown873be312019-09-03 12:22:32 -06001335/// Install no image. This is used when no upgrade happens.
1336fn install_no_image() -> ImageData {
1337 ImageData {
1338 plain: vec![],
1339 cipher: None,
1340 }
1341}
1342
David Brown5c9e0f12019-01-09 16:34:33 -07001343fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001344 if Caps::EcdsaP224.present() {
1345 panic!("Ecdsa P224 not supported in Simulator");
1346 }
David Brown5c9e0f12019-01-09 16:34:33 -07001347
David Brownb8882112019-01-11 14:04:11 -07001348 if Caps::EncKw.present() {
1349 if Caps::RSA2048.present() {
1350 TlvGen::new_rsa_kw()
1351 } else if Caps::EcdsaP256.present() {
1352 TlvGen::new_ecdsa_kw()
1353 } else {
1354 TlvGen::new_enc_kw()
1355 }
1356 } else if Caps::EncRsa.present() {
1357 if Caps::RSA2048.present() {
1358 TlvGen::new_sig_enc_rsa()
1359 } else {
1360 TlvGen::new_enc_rsa()
1361 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001362 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001363 if Caps::EcdsaP256.present() {
1364 TlvGen::new_ecdsa_ecies_p256()
1365 } else {
1366 TlvGen::new_ecies_p256()
1367 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001368 } else if Caps::EncX25519.present() {
1369 if Caps::Ed25519.present() {
1370 TlvGen::new_ed25519_ecies_x25519()
1371 } else {
1372 TlvGen::new_ecies_x25519()
1373 }
David Brownb8882112019-01-11 14:04:11 -07001374 } else {
1375 // The non-encrypted configuration.
1376 if Caps::RSA2048.present() {
1377 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001378 } else if Caps::RSA3072.present() {
1379 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001380 } else if Caps::EcdsaP256.present() {
1381 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001382 } else if Caps::Ed25519.present() {
1383 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001384 } else {
1385 TlvGen::new_hash_only()
1386 }
1387 }
David Brown5c9e0f12019-01-09 16:34:33 -07001388}
1389
David Brownca234692019-02-28 11:22:19 -07001390impl ImageData {
1391 /// Find the image contents for the given slot. This assumes that slot 0
1392 /// is unencrypted, and slot 1 is encrypted.
1393 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001394 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001395 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001396 match (encrypted, slot) {
1397 (false, _) => &self.plain,
1398 (true, 0) => &self.plain,
1399 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1400 _ => panic!("Invalid slot requested"),
1401 }
David Brown5c9e0f12019-01-09 16:34:33 -07001402 }
1403}
1404
David Brown5c9e0f12019-01-09 16:34:33 -07001405/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001406fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1407 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001408 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001409 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001410
1411 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001412 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001413 let dev = flash.get(&dev_id).unwrap();
1414 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001415
1416 if buf != &copy[..] {
1417 for i in 0 .. buf.len() {
1418 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001419 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1420 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001421 break;
1422 }
1423 }
1424 false
1425 } else {
1426 true
1427 }
1428}
1429
David Brown3b090212019-07-30 15:59:28 -06001430fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001431 magic: Option<u8>, image_ok: Option<u8>,
1432 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001433 if Caps::OverwriteUpgrade.present() {
1434 return true;
1435 }
David Brown5c9e0f12019-01-09 16:34:33 -07001436
David Brown3b090212019-07-30 15:59:28 -06001437 let offset = slot.trailer_off + c::boot_max_align();
1438 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001439 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001440 let mut failed = false;
1441
David Brown76101572019-02-28 11:29:03 -07001442 let dev = flash.get(&dev_id).unwrap();
1443 let erased_val = dev.erased_val();
1444 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001445
1446 failed |= match magic {
1447 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001448 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001449 warn!("\"magic\" mismatch at {:#x}", offset);
1450 true
1451 } else if v == 3 {
1452 let expected = [erased_val; 16];
Christopher Collinsa1c12042019-05-23 14:00:28 -07001453 if &copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001454 warn!("\"magic\" mismatch at {:#x}", offset);
1455 true
1456 } else {
1457 false
1458 }
1459 } else {
1460 false
1461 }
1462 },
1463 None => false,
1464 };
1465
1466 failed |= match image_ok {
1467 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001468 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001469 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1470 true
1471 } else {
1472 false
1473 }
1474 },
1475 None => false,
1476 };
1477
1478 failed |= match copy_done {
1479 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001480 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001481 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1482 true
1483 } else {
1484 false
1485 }
1486 },
1487 None => false,
1488 };
1489
1490 !failed
1491}
1492
David Brown297029a2019-08-13 14:29:51 -06001493/// Install a partition table. This is a simplified partition table that
1494/// we write at the beginning of flash so make it easier for external tools
1495/// to analyze these images.
1496fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1497 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1498 for &id in &ids {
1499 // If there are any partitions in this device that start at 0, and
1500 // aren't marked as the BootLoader partition, avoid adding the
1501 // partition table. This makes it harder to view the image, but
1502 // avoids messing up images already written.
1503 if areadesc.iter_areas().any(|area| {
1504 area.device_id == id &&
1505 area.off == 0 &&
1506 area.flash_id != FlashId::BootLoader
1507 }) {
1508 if log_enabled!(Info) {
1509 let special: Vec<FlashId> = areadesc.iter_areas()
1510 .filter(|area| area.device_id == id && area.off == 0)
1511 .map(|area| area.flash_id)
1512 .collect();
1513 info!("Skipping partition table: {:?}", special);
1514 }
1515 break;
1516 }
1517
1518 let mut buf: Vec<u8> = vec![];
1519 write!(&mut buf, "mcuboot\0").unwrap();
1520
1521 // Iterate through all of the partitions in that device, and encode
1522 // into the table.
1523 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1524 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1525
1526 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1527 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1528 buf.write_u32::<LittleEndian>(area.off).unwrap();
1529 buf.write_u32::<LittleEndian>(area.size).unwrap();
1530 buf.write_u32::<LittleEndian>(0).unwrap();
1531 }
1532
1533 let dev = flash.get_mut(&id).unwrap();
1534
1535 // Pad to alignment.
1536 while buf.len() % dev.align() != 0 {
1537 buf.push(0);
1538 }
1539
1540 dev.write(0, &buf).unwrap();
1541 }
1542}
1543
David Brown5c9e0f12019-01-09 16:34:33 -07001544/// The image header
1545#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001546#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001547pub struct ImageHeader {
1548 magic: u32,
1549 load_addr: u32,
1550 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001551 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001552 img_size: u32,
1553 flags: u32,
1554 ver: ImageVersion,
1555 _pad2: u32,
1556}
1557
1558impl AsRaw for ImageHeader {}
1559
1560#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001561#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001562pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001563 pub major: u8,
1564 pub minor: u8,
1565 pub revision: u16,
1566 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001567}
1568
David Brownc3898d62019-08-05 14:20:02 -06001569#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001570pub struct SlotInfo {
1571 pub base_off: usize,
1572 pub trailer_off: usize,
1573 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001574 // Which slot within this device.
1575 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001576 pub dev_id: u8,
1577}
1578
David Brown347dc572019-11-15 11:37:25 -07001579const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1580 0x60, 0xd2, 0xef, 0x7f,
1581 0x35, 0x52, 0x50, 0x0f,
1582 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001583
1584// Replicates defines found in bootutil.h
1585const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1586const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1587
1588const BOOT_FLAG_SET: Option<u8> = Some(1);
1589const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1590
1591/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001592pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1593 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001594 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001595 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001596 if offset % align != 0 || MAGIC.len() % align != 0 {
1597 // The write size is larger than the magic value. Fill a buffer
1598 // with the erased value, put the MAGIC in it, and write it in its
1599 // entirety.
1600 let mut buf = vec![dev.erased_val(); align];
1601 buf[(offset % align)..].copy_from_slice(MAGIC);
1602 dev.write(offset - (offset % align), &buf).unwrap();
1603 } else {
1604 dev.write(offset, MAGIC).unwrap();
1605 }
David Brown5c9e0f12019-01-09 16:34:33 -07001606}
1607
1608/// Writes the image_ok flag which, guess what, tells the bootloader
1609/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001610fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001611 // Overwrite mode always is permanent, and only the magic is used in
1612 // the trailer. To avoid problems with large write sizes, don't try to
1613 // set anything in this case.
1614 if Caps::OverwriteUpgrade.present() {
1615 return;
1616 }
1617
David Brown76101572019-02-28 11:29:03 -07001618 let dev = flash.get_mut(&slot.dev_id).unwrap();
1619 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001620 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001621 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001622 let align = dev.align();
1623 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001624}
1625
1626// Drop some pseudo-random gibberish onto the data.
1627fn splat(data: &mut [u8], seed: usize) {
David Browncd842842020-07-09 15:46:53 -06001628 let mut seed_block = [0u8; 16];
1629 let mut buf = Cursor::new(&mut seed_block[..]);
1630 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
1631 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
1632 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
1633 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
1634 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07001635 rng.fill_bytes(data);
1636}
1637
1638/// Return a read-only view into the raw bytes of this object
1639trait AsRaw : Sized {
1640 fn as_raw<'a>(&'a self) -> &'a [u8] {
1641 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1642 mem::size_of::<Self>()) }
1643 }
1644}
1645
1646pub fn show_sizes() {
1647 // This isn't panic safe.
1648 for min in &[1, 2, 4, 8] {
1649 let msize = c::boot_trailer_sz(*min);
1650 println!("{:2}: {} (0x{:x})", min, msize, msize);
1651 }
1652}
David Brown95de4502019-11-15 12:01:34 -07001653
1654#[cfg(not(feature = "large-write"))]
1655fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001656 &[1, 2, 4, 8]
1657}
1658
1659#[cfg(feature = "large-write")]
1660fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001661 &[1, 2, 4, 8, 128, 512]
1662}