blob: 63cd86227a896a59ab3aa9d681b9bdb84c56caa1 [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 Brown4dfb33c2021-03-10 05:15:45 -0700152 flash,
153 areadesc,
154 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 {
David Brown4dfb33c2021-03-10 05:15:45 -0700189 slots,
190 primaries,
191 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700192 }}).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 Brown4dfb33c2021-03-10 05:15:45 -0700195 flash,
David Browne5133242019-02-28 11:05:19 -0700196 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700197 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 {
David Brown4dfb33c2021-03-10 05:15:45 -0700230 slots,
231 primaries,
232 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700233 }}).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 Brown4dfb33c2021-03-10 05:15:45 -0700237 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 {
David Brown4dfb33c2021-03-10 05:15:45 -0700249 slots,
250 primaries,
251 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300252 }}).collect();
253 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700254 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300255 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700256 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300257 total_count: None,
258 }
259 }
260
Fabio Utzigd0157342020-10-02 15:22:11 -0300261 pub fn make_bootstrap_image(self) -> Images {
262 let mut flash = self.flash;
263 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
264 let dep = BoringDep::new(image_num, &NO_DEPS);
265 let primaries = install_no_image();
266 let upgrades = install_image(&mut flash, &slots[1], 32784, &dep, false);
267 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700268 slots,
269 primaries,
270 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300271 }}).collect();
272 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700273 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300274 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700275 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300276 total_count: None,
277 }
278 }
279
David Browne5133242019-02-28 11:05:19 -0700280 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300281 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700282 match device {
283 DeviceName::Stm32f4 => {
284 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700285 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
286 64 * 1024,
287 128 * 1024, 128 * 1024, 128 * 1024],
288 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700289 let dev_id = 0;
290 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700291 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700292 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
293 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
294 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
295
David Brown76101572019-02-28 11:29:03 -0700296 let mut flash = SimMultiFlash::new();
297 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300298 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700299 }
300 DeviceName::K64f => {
301 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700302 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700303
304 let dev_id = 0;
305 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700306 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700307 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
308 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
309 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
310
David Brown76101572019-02-28 11:29:03 -0700311 let mut flash = SimMultiFlash::new();
312 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300313 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700314 }
315 DeviceName::K64fBig => {
316 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
317 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700318 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700319
320 let dev_id = 0;
321 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700322 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700323 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
324 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
325 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
326
David Brown76101572019-02-28 11:29:03 -0700327 let mut flash = SimMultiFlash::new();
328 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300329 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700330 }
331 DeviceName::Nrf52840 => {
332 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
333 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700334 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700335
336 let dev_id = 0;
337 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700338 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700339 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
340 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
341 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
342
David Brown76101572019-02-28 11:29:03 -0700343 let mut flash = SimMultiFlash::new();
344 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300345 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700346 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300347 DeviceName::Nrf52840UnequalSlots => {
348 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
349
350 let dev_id = 0;
351 let mut areadesc = AreaDesc::new();
352 areadesc.add_flash_sectors(dev_id, &dev);
353 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
354 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
355
356 let mut flash = SimMultiFlash::new();
357 flash.insert(dev_id, dev);
358 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
359 }
David Browne5133242019-02-28 11:05:19 -0700360 DeviceName::Nrf52840SpiFlash => {
361 // Simulate nrf52840 with external SPI flash. The external SPI flash
362 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700363 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
364 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700365
366 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700367 areadesc.add_flash_sectors(0, &dev0);
368 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700369
370 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
371 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
372 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
373
David Brown76101572019-02-28 11:29:03 -0700374 let mut flash = SimMultiFlash::new();
375 flash.insert(0, dev0);
376 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300377 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700378 }
David Brown2bff6472019-03-05 13:58:35 -0700379 DeviceName::K64fMulti => {
380 // NXP style flash, but larger, to support multiple images.
381 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
382
383 let dev_id = 0;
384 let mut areadesc = AreaDesc::new();
385 areadesc.add_flash_sectors(dev_id, &dev);
386 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
387 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
388 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
389 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
390 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
391
392 let mut flash = SimMultiFlash::new();
393 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300394 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700395 }
David Browne5133242019-02-28 11:05:19 -0700396 }
397 }
David Brownc3898d62019-08-05 14:20:02 -0600398
399 pub fn num_images(&self) -> usize {
400 self.slots.len()
401 }
David Browne5133242019-02-28 11:05:19 -0700402}
403
David Brown5c9e0f12019-01-09 16:34:33 -0700404impl Images {
405 /// A simple upgrade without forced failures.
406 ///
407 /// Returns the number of flash operations which can later be used to
408 /// inject failures at chosen steps.
Fabio Utziged4a5362019-07-30 12:43:23 -0300409 pub fn run_basic_upgrade(&self, permanent: bool) -> Result<i32, ()> {
410 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700411 info!("Total flash operation count={}", total_count);
412
David Brown84b49f72019-03-01 10:58:22 -0700413 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700414 warn!("Image mismatch after first boot");
415 Err(())
416 } else {
417 Ok(total_count)
418 }
419 }
420
Fabio Utzigd0157342020-10-02 15:22:11 -0300421 pub fn run_bootstrap(&self) -> bool {
422 let mut flash = self.flash.clone();
423 let mut fails = 0;
424
425 if Caps::Bootstrap.present() {
426 info!("Try bootstraping image in the primary");
427
428 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
429 if result != 0 {
430 warn!("Failed first boot");
431 fails += 1;
432 }
433
434 if !self.verify_images(&flash, 0, 1) {
435 warn!("Image in the first slot was not bootstrapped");
436 fails += 1;
437 }
438
439 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
440 BOOT_FLAG_SET, BOOT_FLAG_SET) {
441 warn!("Mismatched trailer for the primary slot");
442 fails += 1;
443 }
444 }
445
446 if fails > 0 {
447 error!("Expected trailer on secondary slot to be erased");
448 }
449
450 fails > 0
451 }
452
453
David Brownc3898d62019-08-05 14:20:02 -0600454 /// Test a simple upgrade, with dependencies given, and verify that the
455 /// image does as is described in the test.
456 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
457 let (flash, _) = self.try_upgrade(None, true);
458
459 self.verify_dep_images(&flash, deps)
460 }
461
Fabio Utzigf5480c72019-11-28 10:41:57 -0300462 fn is_swap_upgrade(&self) -> bool {
463 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
464 }
465
David Brown5c9e0f12019-01-09 16:34:33 -0700466 pub fn run_basic_revert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700467 if Caps::OverwriteUpgrade.present() {
468 return false;
469 }
David Brown5c9e0f12019-01-09 16:34:33 -0700470
David Brown5c9e0f12019-01-09 16:34:33 -0700471 let mut fails = 0;
472
473 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300474 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700475 for count in 2 .. 5 {
476 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700477 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700478 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700479 error!("Revert failure on count {}", count);
480 fails += 1;
481 }
482 }
483 }
484
485 fails > 0
486 }
487
488 pub fn run_perm_with_fails(&self) -> bool {
489 let mut fails = 0;
490 let total_flash_ops = self.total_count.unwrap();
491
492 // Let's try an image halfway through.
493 for i in 1 .. total_flash_ops {
494 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300495 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700496 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700497 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700498 warn!("FAIL at step {} of {}", i, total_flash_ops);
499 fails += 1;
500 }
501
David Brown84b49f72019-03-01 10:58:22 -0700502 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
503 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100504 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700505 fails += 1;
506 }
507
David Brown84b49f72019-03-01 10:58:22 -0700508 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
509 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100510 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700511 fails += 1;
512 }
513
Fabio Utzigf5480c72019-11-28 10:41:57 -0300514 if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700515 if !self.verify_images(&flash, 1, 0) {
David Vincze2d736ad2019-02-18 11:50:22 +0100516 warn!("Secondary slot FAIL at step {} of {}",
517 i, total_flash_ops);
David Brown5c9e0f12019-01-09 16:34:33 -0700518 fails += 1;
519 }
520 }
521 }
522
523 if fails > 0 {
524 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
525 fails as f32 * 100.0 / total_flash_ops as f32);
526 }
527
528 fails > 0
529 }
530
David Brown5c9e0f12019-01-09 16:34:33 -0700531 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
532 let mut fails = 0;
533 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700534 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700535 info!("Random interruptions at reset points={:?}", total_counts);
536
David Brown84b49f72019-03-01 10:58:22 -0700537 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300538 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700539 // TODO: This result is ignored.
540 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700541 } else {
542 true
543 };
David Vincze2d736ad2019-02-18 11:50:22 +0100544 if !primary_slot_ok || !secondary_slot_ok {
545 error!("Image mismatch after random interrupts: primary slot={} \
546 secondary slot={}",
547 if primary_slot_ok { "ok" } else { "fail" },
548 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700549 fails += 1;
550 }
David Brown84b49f72019-03-01 10:58:22 -0700551 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
552 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100553 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700554 fails += 1;
555 }
David Brown84b49f72019-03-01 10:58:22 -0700556 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
557 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100558 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700559 fails += 1;
560 }
561
562 if fails > 0 {
563 error!("Error testing perm upgrade with {} fails", total_fails);
564 }
565
566 fails > 0
567 }
568
David Brown5c9e0f12019-01-09 16:34:33 -0700569 pub fn run_revert_with_fails(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700570 if Caps::OverwriteUpgrade.present() {
571 return false;
572 }
David Brown5c9e0f12019-01-09 16:34:33 -0700573
David Brown5c9e0f12019-01-09 16:34:33 -0700574 let mut fails = 0;
575
Fabio Utzigf5480c72019-11-28 10:41:57 -0300576 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300577 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700578 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700579 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700580 error!("Revert failed at interruption {}", i);
581 fails += 1;
582 }
583 }
584 }
585
586 fails > 0
587 }
588
David Brown5c9e0f12019-01-09 16:34:33 -0700589 pub fn run_norevert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700590 if Caps::OverwriteUpgrade.present() {
591 return false;
592 }
David Brown5c9e0f12019-01-09 16:34:33 -0700593
David Brown76101572019-02-28 11:29:03 -0700594 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700595 let mut fails = 0;
596
597 info!("Try norevert");
598
599 // First do a normal upgrade...
David Brown76101572019-02-28 11:29:03 -0700600 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700601 if result != 0 {
602 warn!("Failed first boot");
603 fails += 1;
604 }
605
606 //FIXME: copy_done is written by boot_go, is it ok if no copy
607 // was ever done?
608
David Brown84b49f72019-03-01 10:58:22 -0700609 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100610 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700611 fails += 1;
612 }
David Brown84b49f72019-03-01 10:58:22 -0700613 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
614 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100615 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700616 fails += 1;
617 }
David Brown84b49f72019-03-01 10:58:22 -0700618 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
619 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100620 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700621 fails += 1;
622 }
623
David Vincze2d736ad2019-02-18 11:50:22 +0100624 // Marks image in the primary slot as permanent,
625 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700626 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700627
David Brown84b49f72019-03-01 10:58:22 -0700628 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
629 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100630 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700631 fails += 1;
632 }
633
David Brown76101572019-02-28 11:29:03 -0700634 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700635 if result != 0 {
636 warn!("Failed second boot");
637 fails += 1;
638 }
639
David Brown84b49f72019-03-01 10:58:22 -0700640 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
641 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100642 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700643 fails += 1;
644 }
David Brown84b49f72019-03-01 10:58:22 -0700645 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700646 warn!("Failed image verification");
647 fails += 1;
648 }
649
650 if fails > 0 {
651 error!("Error running upgrade without revert");
652 }
653
654 fails > 0
655 }
656
David Brown2ee5f7f2020-01-13 14:04:01 -0700657 // Test that an upgrade is rejected. Assumes that the image was build
658 // such that the upgrade is instead a downgrade.
659 pub fn run_nodowngrade(&self) -> bool {
660 if !Caps::DowngradePrevention.present() {
661 return false;
662 }
663
664 let mut flash = self.flash.clone();
665 let mut fails = 0;
666
667 info!("Try no downgrade");
668
669 // First, do a normal upgrade.
670 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
671 if result != 0 {
672 warn!("Failed first boot");
673 fails += 1;
674 }
675
676 if !self.verify_images(&flash, 0, 0) {
677 warn!("Failed verification after downgrade rejection");
678 fails += 1;
679 }
680
681 if fails > 0 {
682 error!("Error testing downgrade rejection");
683 }
684
685 fails > 0
686 }
687
David Vincze2d736ad2019-02-18 11:50:22 +0100688 // Tests a new image written to the primary slot that already has magic and
689 // image_ok set while there is no image on the secondary slot, so no revert
690 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700691 pub fn run_norevert_newimage(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700692 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700693 let mut fails = 0;
694
695 info!("Try non-revert on imgtool generated image");
696
David Brown84b49f72019-03-01 10:58:22 -0700697 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700698
David Vincze2d736ad2019-02-18 11:50:22 +0100699 // This simulates writing an image created by imgtool to
700 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700701 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
702 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100703 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700704 fails += 1;
705 }
706
707 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700708 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700709 if result != 0 {
710 warn!("Failed first boot");
711 fails += 1;
712 }
713
714 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700715 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700716 warn!("Failed image verification");
717 fails += 1;
718 }
David Brown84b49f72019-03-01 10:58:22 -0700719 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
720 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100721 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700722 fails += 1;
723 }
David Brown84b49f72019-03-01 10:58:22 -0700724 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
725 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100726 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700727 fails += 1;
728 }
729
730 if fails > 0 {
731 error!("Expected a non revert with new image");
732 }
733
734 fails > 0
735 }
736
David Vincze2d736ad2019-02-18 11:50:22 +0100737 // Tests a new image written to the primary slot that already has magic and
738 // image_ok set while there is no image on the secondary slot, so no revert
739 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700740 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700741 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700742 let mut fails = 0;
743
744 info!("Try upgrade image with bad signature");
745
David Brown84b49f72019-03-01 10:58:22 -0700746 self.mark_upgrades(&mut flash, 0);
747 self.mark_permanent_upgrades(&mut flash, 0);
748 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700749
David Brown84b49f72019-03-01 10:58:22 -0700750 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
751 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100752 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700753 fails += 1;
754 }
755
756 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700757 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700758 if result != 0 {
759 warn!("Failed first boot");
760 fails += 1;
761 }
762
763 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700764 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700765 warn!("Failed image verification");
766 fails += 1;
767 }
David Brown84b49f72019-03-01 10:58:22 -0700768 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
769 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100770 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700771 fails += 1;
772 }
773
774 if fails > 0 {
775 error!("Expected an upgrade failure when image has bad signature");
776 }
777
778 fails > 0
779 }
780
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300781 // Should detect there is a leftover trailer in an otherwise erased
782 // secondary slot and erase its trailer.
783 pub fn run_secondary_leftover_trailer(&self) -> bool {
784 let mut flash = self.flash.clone();
785 let mut fails = 0;
786
787 info!("Try with a leftover trailer in the secondary; must be erased");
788
789 // Add a trailer on the secondary slot
790 self.mark_permanent_upgrades(&mut flash, 1);
791 self.mark_upgrades(&mut flash, 1);
792
793 // Run the bootloader...
794 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
795 if result != 0 {
796 warn!("Failed first boot");
797 fails += 1;
798 }
799
800 // State should not have changed
801 if !self.verify_images(&flash, 0, 0) {
802 warn!("Failed image verification");
803 fails += 1;
804 }
805 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
806 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
807 warn!("Mismatched trailer for the secondary slot");
808 fails += 1;
809 }
810
811 if fails > 0 {
812 error!("Expected trailer on secondary slot to be erased");
813 }
814
815 fails > 0
816 }
817
David Brown5c9e0f12019-01-09 16:34:33 -0700818 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300819 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700820 }
821
David Brown5c9e0f12019-01-09 16:34:33 -0700822 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300823 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700824 }
825
826 /// This test runs a simple upgrade with no fails in the images, but
827 /// allowing for fails in the status area. This should run to the end
828 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700829 pub fn run_with_status_fails_complete(&self) -> bool {
David Vincze2d736ad2019-02-18 11:50:22 +0100830 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700831 return false;
832 }
833
David Brown76101572019-02-28 11:29:03 -0700834 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700835 let mut fails = 0;
836
837 info!("Try swap with status fails");
838
David Brown84b49f72019-03-01 10:58:22 -0700839 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700840 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700841
David Brown76101572019-02-28 11:29:03 -0700842 let (result, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown5c9e0f12019-01-09 16:34:33 -0700843 if result != 0 {
844 warn!("Failed!");
845 fails += 1;
846 }
847
848 // Failed writes to the marked "bad" region don't assert anymore.
849 // Any detected assert() is happening in another part of the code.
850 if asserts != 0 {
851 warn!("At least one assert() was called");
852 fails += 1;
853 }
854
David Brown84b49f72019-03-01 10:58:22 -0700855 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
856 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100857 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700858 fails += 1;
859 }
860
David Brown84b49f72019-03-01 10:58:22 -0700861 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700862 warn!("Failed image verification");
863 fails += 1;
864 }
865
David Vincze2d736ad2019-02-18 11:50:22 +0100866 info!("validate primary slot enabled; \
867 re-run of boot_go should just work");
David Brown76101572019-02-28 11:29:03 -0700868 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700869 if result != 0 {
870 warn!("Failed!");
871 fails += 1;
872 }
873
874 if fails > 0 {
875 error!("Error running upgrade with status write fails");
876 }
877
878 fails > 0
879 }
880
881 /// This test runs a simple upgrade with no fails in the images, but
882 /// allowing for fails in the status area. This should run to the end
883 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700884 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown85904a82019-01-11 13:45:12 -0700885 if Caps::OverwriteUpgrade.present() {
886 false
David Vincze2d736ad2019-02-18 11:50:22 +0100887 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700888
David Brown76101572019-02-28 11:29:03 -0700889 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700890 let mut fails = 0;
891 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700892
David Brown85904a82019-01-11 13:45:12 -0700893 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700894
David Brown85904a82019-01-11 13:45:12 -0700895 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700896
David Brown84b49f72019-03-01 10:58:22 -0700897 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700898 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700899
900 // Should not fail, writing to bad regions does not assert
David Brown76101572019-02-28 11:29:03 -0700901 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true);
David Brown85904a82019-01-11 13:45:12 -0700902 if asserts != 0 {
903 warn!("At least one assert() was called");
904 fails += 1;
905 }
906
David Brown76101572019-02-28 11:29:03 -0700907 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700908
909 info!("Resuming an interrupted swap operation");
David Brown76101572019-02-28 11:29:03 -0700910 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700911
912 // This might throw no asserts, for large sector devices, where
913 // a single failure writing is indistinguishable from no failure,
914 // or throw a single assert for small sector devices that fail
915 // multiple times...
916 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100917 warn!("Expected single assert validating the primary slot, \
918 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700919 fails += 1;
920 }
921
922 if fails > 0 {
923 error!("Error running upgrade with status write fails");
924 }
925
926 fails > 0
927 } else {
David Brown76101572019-02-28 11:29:03 -0700928 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700929 let mut fails = 0;
930
931 info!("Try interrupted swap with status fails");
932
David Brown84b49f72019-03-01 10:58:22 -0700933 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700934 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700935
936 // This is expected to fail while writing to bad regions...
David Brown76101572019-02-28 11:29:03 -0700937 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700938 if asserts == 0 {
939 warn!("No assert() detected");
940 fails += 1;
941 }
942
943 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700944 }
David Brown5c9e0f12019-01-09 16:34:33 -0700945 }
946
947 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -0700948 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -0700949 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -0700950 if Caps::OverwriteUpgrade.present() {
951 return;
952 }
953
David Brown84b49f72019-03-01 10:58:22 -0700954 // Set this for each image.
955 for image in &self.images {
956 let dev_id = &image.slots[slot].dev_id;
957 let dev = flash.get_mut(&dev_id).unwrap();
958 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -0700959 let off = &image.slots[slot].base_off;
960 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -0700961 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -0700962
David Brown84b49f72019-03-01 10:58:22 -0700963 // Mark the status area as a bad area
964 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
965 }
David Brown5c9e0f12019-01-09 16:34:33 -0700966 }
967
David Brown76101572019-02-28 11:29:03 -0700968 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +0100969 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700970 return;
971 }
972
David Brown84b49f72019-03-01 10:58:22 -0700973 for image in &self.images {
974 let dev_id = &image.slots[slot].dev_id;
975 let dev = flash.get_mut(&dev_id).unwrap();
976 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -0700977
David Brown84b49f72019-03-01 10:58:22 -0700978 // Disabling write verification the only assert triggered by
979 // boot_go should be checking for integrity of status bytes.
980 dev.set_verify_writes(false);
981 }
David Brown5c9e0f12019-01-09 16:34:33 -0700982 }
983
David Browndb505822019-03-01 10:04:20 -0700984 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
985 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -0300986 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -0700987 // Clone the flash to have a new copy.
988 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700989
Fabio Utziged4a5362019-07-30 12:43:23 -0300990 if permanent {
991 self.mark_permanent_upgrades(&mut flash, 1);
992 }
David Brown5c9e0f12019-01-09 16:34:33 -0700993
David Browndb505822019-03-01 10:04:20 -0700994 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -0700995
David Browndb505822019-03-01 10:04:20 -0700996 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
997 (-0x13579, _) => (true, stop.unwrap()),
998 (0, _) => (false, -counter),
999 (x, _) => panic!("Unknown return: {}", x),
1000 };
David Brown5c9e0f12019-01-09 16:34:33 -07001001
David Browndb505822019-03-01 10:04:20 -07001002 counter = 0;
1003 if first_interrupted {
1004 // fl.dump();
1005 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
1006 (-0x13579, _) => panic!("Shouldn't stop again"),
1007 (0, _) => (),
1008 (x, _) => panic!("Unknown return: {}", x),
1009 }
1010 }
David Brown5c9e0f12019-01-09 16:34:33 -07001011
David Browndb505822019-03-01 10:04:20 -07001012 (flash, count - counter)
1013 }
1014
1015 fn try_revert(&self, count: usize) -> SimMultiFlash {
1016 let mut flash = self.flash.clone();
1017
1018 // fl.write_file("image0.bin").unwrap();
1019 for i in 0 .. count {
1020 info!("Running boot pass {}", i + 1);
1021 assert_eq!(c::boot_go(&mut flash, &self.areadesc, None, false), (0, 0));
1022 }
1023 flash
1024 }
1025
1026 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1027 let mut flash = self.flash.clone();
1028 let mut fails = 0;
1029
1030 let mut counter = stop;
1031 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
1032 if x != -0x13579 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001033 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001034 fails += 1;
1035 }
1036
Fabio Utzig8af7f792019-07-30 12:40:01 -03001037 // In a multi-image setup, copy done might be set if any number of
1038 // images was already successfully swapped.
1039 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1040 warn!("copy_done should be unset");
1041 fails += 1;
1042 }
1043
David Browndb505822019-03-01 10:04:20 -07001044 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
1045 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001046 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001047 fails += 1;
1048 }
1049
David Brown84b49f72019-03-01 10:58:22 -07001050 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001051 warn!("Image in the primary slot before revert is invalid at stop={}",
1052 stop);
1053 fails += 1;
1054 }
David Brown84b49f72019-03-01 10:58:22 -07001055 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001056 warn!("Image in the secondary slot before revert is invalid at stop={}",
1057 stop);
1058 fails += 1;
1059 }
David Brown84b49f72019-03-01 10:58:22 -07001060 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1061 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001062 warn!("Mismatched trailer for the primary slot before revert");
1063 fails += 1;
1064 }
David Brown84b49f72019-03-01 10:58:22 -07001065 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1066 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001067 warn!("Mismatched trailer for the secondary slot before revert");
1068 fails += 1;
1069 }
1070
1071 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001072 let mut counter = stop;
1073 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
1074 if x != -0x13579 {
1075 warn!("Should have stopped revert at interruption point");
1076 fails += 1;
1077 }
1078
David Browndb505822019-03-01 10:04:20 -07001079 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
1080 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001081 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001082 fails += 1;
1083 }
1084
David Brown84b49f72019-03-01 10:58:22 -07001085 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001086 warn!("Image in the primary slot after revert is invalid at stop={}",
1087 stop);
1088 fails += 1;
1089 }
David Brown84b49f72019-03-01 10:58:22 -07001090 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001091 warn!("Image in the secondary slot after revert is invalid at stop={}",
1092 stop);
1093 fails += 1;
1094 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001095
David Brown84b49f72019-03-01 10:58:22 -07001096 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1097 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001098 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001099 fails += 1;
1100 }
David Brown84b49f72019-03-01 10:58:22 -07001101 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1102 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001103 warn!("Mismatched trailer for the secondary slot after revert");
1104 fails += 1;
1105 }
1106
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001107 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
1108 if x != 0 {
1109 warn!("Should have finished 3rd boot");
1110 fails += 1;
1111 }
1112
1113 if !self.verify_images(&flash, 0, 0) {
1114 warn!("Image in the primary slot is invalid on 1st boot after revert");
1115 fails += 1;
1116 }
1117 if !self.verify_images(&flash, 1, 1) {
1118 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1119 fails += 1;
1120 }
1121
David Browndb505822019-03-01 10:04:20 -07001122 fails > 0
1123 }
1124
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001125
David Browndb505822019-03-01 10:04:20 -07001126 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1127 let mut flash = self.flash.clone();
1128
David Brown84b49f72019-03-01 10:58:22 -07001129 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001130
1131 let mut rng = rand::thread_rng();
1132 let mut resets = vec![0i32; count];
1133 let mut remaining_ops = total_ops;
1134 for i in 0 .. count {
David Browncd842842020-07-09 15:46:53 -06001135 let reset_counter = rng.gen_range(1, remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001136 let mut counter = reset_counter;
1137 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
1138 (0, _) | (-0x13579, _) => (),
1139 (x, _) => panic!("Unknown return: {}", x),
1140 }
1141 remaining_ops -= reset_counter;
1142 resets[i] = reset_counter;
1143 }
1144
1145 match c::boot_go(&mut flash, &self.areadesc, None, false) {
1146 (-0x13579, _) => panic!("Should not be have been interrupted!"),
David Brown5c9e0f12019-01-09 16:34:33 -07001147 (0, _) => (),
1148 (x, _) => panic!("Unknown return: {}", x),
1149 }
David Brown5c9e0f12019-01-09 16:34:33 -07001150
David Browndb505822019-03-01 10:04:20 -07001151 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001152 }
David Brown84b49f72019-03-01 10:58:22 -07001153
1154 /// Verify the image in the given flash device, the specified slot
1155 /// against the expected image.
1156 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001157 self.images.iter().all(|image| {
1158 verify_image(flash, &image.slots[slot],
1159 match against {
1160 0 => &image.primaries,
1161 1 => &image.upgrades,
1162 _ => panic!("Invalid 'against'")
1163 })
1164 })
David Brown84b49f72019-03-01 10:58:22 -07001165 }
1166
David Brownc3898d62019-08-05 14:20:02 -06001167 /// Verify the images, according to the dependency test.
1168 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1169 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1170 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1171 if !verify_image(flash, &image.slots[0],
1172 match upgrade {
1173 UpgradeInfo::Upgraded => &image.upgrades,
1174 UpgradeInfo::Held => &image.primaries,
1175 }) {
1176 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1177 return true;
1178 }
1179 }
1180
1181 false
1182 }
1183
Fabio Utzig8af7f792019-07-30 12:40:01 -03001184 /// Verify that at least one of the trailers of the images have the
1185 /// specified values.
1186 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1187 magic: Option<u8>, image_ok: Option<u8>,
1188 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001189 self.images.iter().any(|image| {
1190 verify_trailer(flash, &image.slots[slot],
1191 magic, image_ok, copy_done)
1192 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001193 }
1194
David Brown84b49f72019-03-01 10:58:22 -07001195 /// Verify that the trailers of the images have the specified
1196 /// values.
1197 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1198 magic: Option<u8>, image_ok: Option<u8>,
1199 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001200 self.images.iter().all(|image| {
1201 verify_trailer(flash, &image.slots[slot],
1202 magic, image_ok, copy_done)
1203 })
David Brown84b49f72019-03-01 10:58:22 -07001204 }
1205
1206 /// Mark each of the images for permanent upgrade.
1207 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1208 for image in &self.images {
1209 mark_permanent_upgrade(flash, &image.slots[slot]);
1210 }
1211 }
1212
1213 /// Mark each of the images for permanent upgrade.
1214 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1215 for image in &self.images {
1216 mark_upgrade(flash, &image.slots[slot]);
1217 }
1218 }
David Brown297029a2019-08-13 14:29:51 -06001219
1220 /// Dump out the flash image(s) to one or more files for debugging
1221 /// purposes. The names will be written as either "{prefix}.mcubin" or
1222 /// "{prefix}-001.mcubin" depending on how many images there are.
1223 pub fn debug_dump(&self, prefix: &str) {
1224 for (id, fdev) in &self.flash {
1225 let name = if self.flash.len() == 1 {
1226 format!("{}.mcubin", prefix)
1227 } else {
1228 format!("{}-{:>0}.mcubin", prefix, id)
1229 };
1230 fdev.write_file(&name).unwrap();
1231 }
1232 }
David Brown5c9e0f12019-01-09 16:34:33 -07001233}
1234
1235/// Show the flash layout.
1236#[allow(dead_code)]
1237fn show_flash(flash: &dyn Flash) {
1238 println!("---- Flash configuration ----");
1239 for sector in flash.sector_iter() {
1240 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1241 sector.num, sector.base, sector.size);
1242 }
1243 println!("");
1244}
1245
1246/// Install a "program" into the given image. This fakes the image header, or at least all of the
1247/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001248fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownc3898d62019-08-05 14:20:02 -06001249 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001250 let offset = slot.base_off;
1251 let slot_len = slot.len;
1252 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001253
David Brown43643dd2019-01-11 15:43:28 -07001254 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001255
David Brownc3898d62019-08-05 14:20:02 -06001256 // Add the dependencies early to the tlv.
1257 for dep in deps.my_deps(offset, slot.index) {
1258 tlv.add_dependency(deps.other_id(), &dep);
1259 }
1260
David Brown5c9e0f12019-01-09 16:34:33 -07001261 const HDR_SIZE: usize = 32;
1262
1263 // Generate a boot header. Note that the size doesn't include the header.
1264 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001265 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -07001266 load_addr: 0,
1267 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001268 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001269 img_size: len as u32,
1270 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001271 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001272 _pad2: 0,
1273 };
1274
1275 let mut b_header = [0; HDR_SIZE];
1276 b_header[..32].clone_from_slice(header.as_raw());
1277 assert_eq!(b_header.len(), HDR_SIZE);
1278
1279 tlv.add_bytes(&b_header);
1280
1281 // The core of the image itself is just pseudorandom data.
1282 let mut b_img = vec![0; len];
1283 splat(&mut b_img, offset);
1284
David Browncb47dd72019-08-05 14:21:49 -06001285 // Add some information at the start of the payload to make it easier
1286 // to see what it is. This will fail if the image itself is too small.
1287 {
1288 let mut wr = Cursor::new(&mut b_img);
1289 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1290 offset, dev_id, slot).unwrap();
1291 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1292 }
1293
David Brown5c9e0f12019-01-09 16:34:33 -07001294 // TLV signatures work over plain image
1295 tlv.add_bytes(&b_img);
1296
1297 // Generate encrypted images
1298 let flag = TlvFlags::ENCRYPTED as u32;
1299 let is_encrypted = (tlv.get_flags() & flag) == flag;
1300 let mut b_encimg = vec![];
1301 if is_encrypted {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001302 tlv.generate_enc_key();
1303 let enc_key = tlv.get_enc_key();
1304 let key = GenericArray::from_slice(enc_key.as_slice());
David Brown5c9e0f12019-01-09 16:34:33 -07001305 let nonce = GenericArray::from_slice(&[0; 16]);
1306 let mut cipher = Aes128Ctr::new(&key, &nonce);
1307 b_encimg = b_img.clone();
1308 cipher.apply_keystream(&mut b_encimg);
1309 }
1310
1311 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001312 if bad_sig {
1313 tlv.corrupt_sig();
1314 }
1315 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001316
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001317 let dev = flash.get_mut(&dev_id).unwrap();
1318
David Brown5c9e0f12019-01-09 16:34:33 -07001319 let mut buf = vec![];
1320 buf.append(&mut b_header.to_vec());
1321 buf.append(&mut b_img);
1322 buf.append(&mut b_tlv.clone());
1323
David Brown95de4502019-11-15 12:01:34 -07001324 // Pad the buffer to a multiple of the flash alignment.
1325 let align = dev.align();
1326 while buf.len() % align != 0 {
1327 buf.push(dev.erased_val());
1328 }
1329
David Brown5c9e0f12019-01-09 16:34:33 -07001330 let mut encbuf = vec![];
1331 if is_encrypted {
1332 encbuf.append(&mut b_header.to_vec());
1333 encbuf.append(&mut b_encimg);
1334 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001335
1336 while encbuf.len() % align != 0 {
1337 encbuf.push(dev.erased_val());
1338 }
David Brown5c9e0f12019-01-09 16:34:33 -07001339 }
1340
David Vincze2d736ad2019-02-18 11:50:22 +01001341 // Since images are always non-encrypted in the primary slot, we first write
1342 // an encrypted image, re-read to use for verification, erase + flash
1343 // un-encrypted. In the secondary slot the image is written un-encrypted,
1344 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001345
David Brown3b090212019-07-30 15:59:28 -06001346 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001347 let enc_copy: Option<Vec<u8>>;
1348
1349 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001350 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001351
1352 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001353 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001354
1355 enc_copy = Some(enc);
1356
David Brown76101572019-02-28 11:29:03 -07001357 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001358 } else {
1359 enc_copy = None;
1360 }
1361
David Brown76101572019-02-28 11:29:03 -07001362 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001363
1364 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001365 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001366
David Brownca234692019-02-28 11:22:19 -07001367 ImageData {
1368 plain: copy,
1369 cipher: enc_copy,
1370 }
David Brown5c9e0f12019-01-09 16:34:33 -07001371 } else {
1372
David Brown76101572019-02-28 11:29:03 -07001373 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001374
1375 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001376 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001377
1378 let enc_copy: Option<Vec<u8>>;
1379
1380 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001381 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001382
David Brown76101572019-02-28 11:29:03 -07001383 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001384
1385 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001386 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001387
1388 enc_copy = Some(enc);
1389 } else {
1390 enc_copy = None;
1391 }
1392
David Brownca234692019-02-28 11:22:19 -07001393 ImageData {
1394 plain: copy,
1395 cipher: enc_copy,
1396 }
David Brown5c9e0f12019-01-09 16:34:33 -07001397 }
David Brown5c9e0f12019-01-09 16:34:33 -07001398}
1399
David Brown873be312019-09-03 12:22:32 -06001400/// Install no image. This is used when no upgrade happens.
1401fn install_no_image() -> ImageData {
1402 ImageData {
1403 plain: vec![],
1404 cipher: None,
1405 }
1406}
1407
David Brown5c9e0f12019-01-09 16:34:33 -07001408fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001409 if Caps::EcdsaP224.present() {
1410 panic!("Ecdsa P224 not supported in Simulator");
1411 }
David Brown5c9e0f12019-01-09 16:34:33 -07001412
David Brownb8882112019-01-11 14:04:11 -07001413 if Caps::EncKw.present() {
1414 if Caps::RSA2048.present() {
1415 TlvGen::new_rsa_kw()
1416 } else if Caps::EcdsaP256.present() {
1417 TlvGen::new_ecdsa_kw()
1418 } else {
1419 TlvGen::new_enc_kw()
1420 }
1421 } else if Caps::EncRsa.present() {
1422 if Caps::RSA2048.present() {
1423 TlvGen::new_sig_enc_rsa()
1424 } else {
1425 TlvGen::new_enc_rsa()
1426 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001427 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001428 if Caps::EcdsaP256.present() {
1429 TlvGen::new_ecdsa_ecies_p256()
1430 } else {
1431 TlvGen::new_ecies_p256()
1432 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001433 } else if Caps::EncX25519.present() {
1434 if Caps::Ed25519.present() {
1435 TlvGen::new_ed25519_ecies_x25519()
1436 } else {
1437 TlvGen::new_ecies_x25519()
1438 }
David Brownb8882112019-01-11 14:04:11 -07001439 } else {
1440 // The non-encrypted configuration.
1441 if Caps::RSA2048.present() {
1442 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001443 } else if Caps::RSA3072.present() {
1444 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001445 } else if Caps::EcdsaP256.present() {
1446 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001447 } else if Caps::Ed25519.present() {
1448 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001449 } else {
1450 TlvGen::new_hash_only()
1451 }
1452 }
David Brown5c9e0f12019-01-09 16:34:33 -07001453}
1454
David Brownca234692019-02-28 11:22:19 -07001455impl ImageData {
1456 /// Find the image contents for the given slot. This assumes that slot 0
1457 /// is unencrypted, and slot 1 is encrypted.
1458 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001459 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001460 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001461 match (encrypted, slot) {
1462 (false, _) => &self.plain,
1463 (true, 0) => &self.plain,
1464 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1465 _ => panic!("Invalid slot requested"),
1466 }
David Brown5c9e0f12019-01-09 16:34:33 -07001467 }
1468}
1469
David Brown5c9e0f12019-01-09 16:34:33 -07001470/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001471fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1472 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001473 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001474 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001475
1476 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001477 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001478 let dev = flash.get(&dev_id).unwrap();
1479 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001480
1481 if buf != &copy[..] {
1482 for i in 0 .. buf.len() {
1483 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001484 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1485 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001486 break;
1487 }
1488 }
1489 false
1490 } else {
1491 true
1492 }
1493}
1494
David Brown3b090212019-07-30 15:59:28 -06001495fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001496 magic: Option<u8>, image_ok: Option<u8>,
1497 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001498 if Caps::OverwriteUpgrade.present() {
1499 return true;
1500 }
David Brown5c9e0f12019-01-09 16:34:33 -07001501
David Brown3b090212019-07-30 15:59:28 -06001502 let offset = slot.trailer_off + c::boot_max_align();
1503 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001504 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001505 let mut failed = false;
1506
David Brown76101572019-02-28 11:29:03 -07001507 let dev = flash.get(&dev_id).unwrap();
1508 let erased_val = dev.erased_val();
1509 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001510
1511 failed |= match magic {
1512 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001513 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001514 warn!("\"magic\" mismatch at {:#x}", offset);
1515 true
1516 } else if v == 3 {
1517 let expected = [erased_val; 16];
Christopher Collinsa1c12042019-05-23 14:00:28 -07001518 if &copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001519 warn!("\"magic\" mismatch at {:#x}", offset);
1520 true
1521 } else {
1522 false
1523 }
1524 } else {
1525 false
1526 }
1527 },
1528 None => false,
1529 };
1530
1531 failed |= match image_ok {
1532 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001533 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001534 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1535 true
1536 } else {
1537 false
1538 }
1539 },
1540 None => false,
1541 };
1542
1543 failed |= match copy_done {
1544 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001545 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001546 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1547 true
1548 } else {
1549 false
1550 }
1551 },
1552 None => false,
1553 };
1554
1555 !failed
1556}
1557
David Brown297029a2019-08-13 14:29:51 -06001558/// Install a partition table. This is a simplified partition table that
1559/// we write at the beginning of flash so make it easier for external tools
1560/// to analyze these images.
1561fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1562 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1563 for &id in &ids {
1564 // If there are any partitions in this device that start at 0, and
1565 // aren't marked as the BootLoader partition, avoid adding the
1566 // partition table. This makes it harder to view the image, but
1567 // avoids messing up images already written.
1568 if areadesc.iter_areas().any(|area| {
1569 area.device_id == id &&
1570 area.off == 0 &&
1571 area.flash_id != FlashId::BootLoader
1572 }) {
1573 if log_enabled!(Info) {
1574 let special: Vec<FlashId> = areadesc.iter_areas()
1575 .filter(|area| area.device_id == id && area.off == 0)
1576 .map(|area| area.flash_id)
1577 .collect();
1578 info!("Skipping partition table: {:?}", special);
1579 }
1580 break;
1581 }
1582
1583 let mut buf: Vec<u8> = vec![];
1584 write!(&mut buf, "mcuboot\0").unwrap();
1585
1586 // Iterate through all of the partitions in that device, and encode
1587 // into the table.
1588 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1589 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1590
1591 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1592 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1593 buf.write_u32::<LittleEndian>(area.off).unwrap();
1594 buf.write_u32::<LittleEndian>(area.size).unwrap();
1595 buf.write_u32::<LittleEndian>(0).unwrap();
1596 }
1597
1598 let dev = flash.get_mut(&id).unwrap();
1599
1600 // Pad to alignment.
1601 while buf.len() % dev.align() != 0 {
1602 buf.push(0);
1603 }
1604
1605 dev.write(0, &buf).unwrap();
1606 }
1607}
1608
David Brown5c9e0f12019-01-09 16:34:33 -07001609/// The image header
1610#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001611#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001612pub struct ImageHeader {
1613 magic: u32,
1614 load_addr: u32,
1615 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001616 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001617 img_size: u32,
1618 flags: u32,
1619 ver: ImageVersion,
1620 _pad2: u32,
1621}
1622
1623impl AsRaw for ImageHeader {}
1624
1625#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001626#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001627pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001628 pub major: u8,
1629 pub minor: u8,
1630 pub revision: u16,
1631 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001632}
1633
David Brownc3898d62019-08-05 14:20:02 -06001634#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001635pub struct SlotInfo {
1636 pub base_off: usize,
1637 pub trailer_off: usize,
1638 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001639 // Which slot within this device.
1640 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001641 pub dev_id: u8,
1642}
1643
David Brown347dc572019-11-15 11:37:25 -07001644const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1645 0x60, 0xd2, 0xef, 0x7f,
1646 0x35, 0x52, 0x50, 0x0f,
1647 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001648
1649// Replicates defines found in bootutil.h
1650const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1651const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1652
1653const BOOT_FLAG_SET: Option<u8> = Some(1);
1654const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1655
1656/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001657pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1658 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001659 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001660 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001661 if offset % align != 0 || MAGIC.len() % align != 0 {
1662 // The write size is larger than the magic value. Fill a buffer
1663 // with the erased value, put the MAGIC in it, and write it in its
1664 // entirety.
1665 let mut buf = vec![dev.erased_val(); align];
1666 buf[(offset % align)..].copy_from_slice(MAGIC);
1667 dev.write(offset - (offset % align), &buf).unwrap();
1668 } else {
1669 dev.write(offset, MAGIC).unwrap();
1670 }
David Brown5c9e0f12019-01-09 16:34:33 -07001671}
1672
1673/// Writes the image_ok flag which, guess what, tells the bootloader
1674/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001675fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001676 // Overwrite mode always is permanent, and only the magic is used in
1677 // the trailer. To avoid problems with large write sizes, don't try to
1678 // set anything in this case.
1679 if Caps::OverwriteUpgrade.present() {
1680 return;
1681 }
1682
David Brown76101572019-02-28 11:29:03 -07001683 let dev = flash.get_mut(&slot.dev_id).unwrap();
1684 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001685 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001686 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001687 let align = dev.align();
1688 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001689}
1690
1691// Drop some pseudo-random gibberish onto the data.
1692fn splat(data: &mut [u8], seed: usize) {
David Browncd842842020-07-09 15:46:53 -06001693 let mut seed_block = [0u8; 16];
1694 let mut buf = Cursor::new(&mut seed_block[..]);
1695 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
1696 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
1697 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
1698 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
1699 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07001700 rng.fill_bytes(data);
1701}
1702
1703/// Return a read-only view into the raw bytes of this object
1704trait AsRaw : Sized {
1705 fn as_raw<'a>(&'a self) -> &'a [u8] {
1706 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1707 mem::size_of::<Self>()) }
1708 }
1709}
1710
1711pub fn show_sizes() {
1712 // This isn't panic safe.
1713 for min in &[1, 2, 4, 8] {
1714 let msize = c::boot_trailer_sz(*min);
1715 println!("{:2}: {} (0x{:x})", min, msize, msize);
1716 }
1717}
David Brown95de4502019-11-15 12:01:34 -07001718
1719#[cfg(not(feature = "large-write"))]
1720fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001721 &[1, 2, 4, 8]
1722}
1723
1724#[cfg(feature = "large-write")]
1725fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001726 &[1, 2, 4, 8, 128, 512]
1727}