blob: d3cc068ba18539b3af9b4f2e9009187208ab7ccf [file] [log] [blame]
David Brownc8d62012021-10-27 15:03:48 -06001// Copyright (c) 2019-2021 Linaro LTD
David Browne2acfae2020-01-21 16:45:01 -07002// Copyright (c) 2019-2020 JUUL Labs
Salome Thirot6fdbf552021-05-14 16:46:14 +01003// Copyright (c) 2019-2021 Arm Limited
David Browne2acfae2020-01-21 16:45:01 -07004//
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 Brownbf32c272021-06-16 17:11:37 -060022 collections::{BTreeMap, HashSet},
David Browncb47dd72019-08-05 14:21:49 -060023 io::{Cursor, Write},
David Brown5c9e0f12019-01-09 16:34:33 -070024 mem,
25 slice,
26};
David Brown9c6322f2021-08-19 13:03:39 -060027use aes::{
28 Aes128,
David Brown5c9e0f12019-01-09 16:34:33 -070029 Aes128Ctr,
David Brown9c6322f2021-08-19 13:03:39 -060030 Aes256,
Salome Thirot6fdbf552021-05-14 16:46:14 +010031 Aes256Ctr,
David Brown9c6322f2021-08-19 13:03:39 -060032 NewBlockCipher,
David Brown5c9e0f12019-01-09 16:34:33 -070033};
David Brown9c6322f2021-08-19 13:03:39 -060034use cipher::{
35 FromBlockCipher,
36 generic_array::GenericArray,
37 StreamCipher,
38 };
David Brown5c9e0f12019-01-09 16:34:33 -070039
David Brown76101572019-02-28 11:29:03 -070040use simflash::{Flash, SimFlash, SimMultiFlash};
David Brown8a4e23b2021-06-11 10:29:01 -060041use mcuboot_sys::{c, AreaDesc, FlashId, RamBlock};
David Browne5133242019-02-28 11:05:19 -070042use crate::{
43 ALL_DEVICES,
44 DeviceName,
45};
David Brown5c9e0f12019-01-09 16:34:33 -070046use crate::caps::Caps;
David Brownc3898d62019-08-05 14:20:02 -060047use crate::depends::{
48 BoringDep,
49 Depender,
50 DepTest,
David Brown873be312019-09-03 12:22:32 -060051 DepType,
David Brown2ee5f7f2020-01-13 14:04:01 -070052 NO_DEPS,
David Brownc3898d62019-08-05 14:20:02 -060053 PairDep,
54 UpgradeInfo,
55};
Fabio Utzig90f449e2019-10-24 07:43:53 -030056use crate::tlv::{ManifestGen, TlvGen, TlvFlags};
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -030057use crate::utils::align_up;
Salome Thirot6fdbf552021-05-14 16:46:14 +010058use typenum::{U32, U16};
David Brown5c9e0f12019-01-09 16:34:33 -070059
David Brown8a4e23b2021-06-11 10:29:01 -060060/// For testing, use a non-zero offset for the ram-load, to make sure the offset is getting used
61/// properly, but the value is not really that important.
62const RAM_LOAD_ADDR: u32 = 1024;
63
David Browne5133242019-02-28 11:05:19 -070064/// A builder for Images. This describes a single run of the simulator,
65/// capturing the configuration of a particular set of devices, including
66/// the flash simulator(s) and the information about the slots.
67#[derive(Clone)]
68pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070069 flash: SimMultiFlash,
David Browne5133242019-02-28 11:05:19 -070070 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070071 slots: Vec<[SlotInfo; 2]>,
David Brownbf32c272021-06-16 17:11:37 -060072 ram: RamData,
David Browne5133242019-02-28 11:05:19 -070073}
74
David Brown998aa8d2019-02-28 10:54:50 -070075/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070076/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070077/// and upgrades hold the expected contents of these images.
78pub struct Images {
David Brown76101572019-02-28 11:29:03 -070079 flash: SimMultiFlash,
David Brownca234692019-02-28 11:22:19 -070080 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070081 images: Vec<OneImage>,
82 total_count: Option<i32>,
David Brownbf32c272021-06-16 17:11:37 -060083 ram: RamData,
David Brown84b49f72019-03-01 10:58:22 -070084}
85
86/// When doing multi-image, there is an instance of this information for
87/// each of the images. Single image there will be one of these.
88struct OneImage {
David Brownca234692019-02-28 11:22:19 -070089 slots: [SlotInfo; 2],
90 primaries: ImageData,
91 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070092}
93
94/// The Rust-side representation of an image. For unencrypted images, this
95/// is just the unencrypted payload. For encrypted images, we store both
96/// the encrypted and the plaintext.
97struct ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -030098 size: usize,
David Brownca234692019-02-28 11:22:19 -070099 plain: Vec<u8>,
100 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -0700101}
102
David Brownbf32c272021-06-16 17:11:37 -0600103/// For the RamLoad test cases, we need a contiguous area of RAM to load these images into. For
104/// multi-image builds, these may not correspond with the offsets. This has to be computed early,
105/// before images are built, because each image contains the offset where the image is to be loaded
106/// in the header, which is contained within the signature.
107#[derive(Clone, Debug)]
108struct RamData {
109 places: BTreeMap<SlotKey, SlotPlace>,
110 total: u32,
111}
112
113/// Every slot is indexed by this key.
114#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
115struct SlotKey {
116 dev_id: u8,
David Brownf17d3912021-06-23 16:10:51 -0600117 base_off: usize,
David Brownbf32c272021-06-16 17:11:37 -0600118}
119
120#[derive(Clone, Debug)]
121struct SlotPlace {
122 offset: u32,
123 size: u32,
124}
125
David Browne5133242019-02-28 11:05:19 -0700126impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -0700127 /// Construct a new image builder for the given device. Returns
128 /// Some(builder) if is possible to test this configuration, or None if
129 /// not possible (for example, if there aren't enough image slots).
Fabio Utzig114a6472019-11-28 10:24:09 -0300130 pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
131 let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
132
133 for cap in unsupported_caps {
134 if cap.present() {
135 return Err(format!("unsupported {:?}", cap));
136 }
137 }
David Browne5133242019-02-28 11:05:19 -0700138
David Brown06ef06e2019-03-05 12:28:10 -0700139 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -0700140
David Brown06ef06e2019-03-05 12:28:10 -0700141 let mut slots = Vec::with_capacity(num_images);
142 for image in 0..num_images {
143 // This mapping must match that defined in
144 // `boot/zephyr/include/sysflash/sysflash.h`.
145 let id0 = match image {
146 0 => FlashId::Image0,
147 1 => FlashId::Image2,
148 _ => panic!("More than 2 images not supported"),
149 };
150 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
151 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300152 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700153 };
154 let id1 = match image {
155 0 => FlashId::Image1,
156 1 => FlashId::Image3,
157 _ => panic!("More than 2 images not supported"),
158 };
159 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
160 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300161 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700162 };
David Browne5133242019-02-28 11:05:19 -0700163
Christopher Collinsa1c12042019-05-23 14:00:28 -0700164 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700165
David Brown06ef06e2019-03-05 12:28:10 -0700166 // Construct a primary image.
167 let primary = SlotInfo {
168 base_off: primary_base as usize,
169 trailer_off: primary_base + primary_len - offset_from_end,
170 len: primary_len as usize,
171 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600172 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700173 };
174
175 // And an upgrade image.
176 let secondary = SlotInfo {
177 base_off: secondary_base as usize,
178 trailer_off: secondary_base + secondary_len - offset_from_end,
179 len: secondary_len as usize,
180 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600181 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700182 };
183
184 slots.push([primary, secondary]);
185 }
David Browne5133242019-02-28 11:05:19 -0700186
David Brownbf32c272021-06-16 17:11:37 -0600187 let ram = RamData::new(&slots);
188
Fabio Utzig114a6472019-11-28 10:24:09 -0300189 Ok(ImagesBuilder {
David Brown4dfb33c2021-03-10 05:15:45 -0700190 flash,
191 areadesc,
192 slots,
David Brownbf32c272021-06-16 17:11:37 -0600193 ram,
David Brown5bc62c62019-03-05 12:11:48 -0700194 })
David Browne5133242019-02-28 11:05:19 -0700195 }
196
197 pub fn each_device<F>(f: F)
198 where F: Fn(Self)
199 {
200 for &dev in ALL_DEVICES {
David Brown95de4502019-11-15 12:01:34 -0700201 for &align in test_alignments() {
David Browne5133242019-02-28 11:05:19 -0700202 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700203 match Self::new(dev, align, erased_val) {
Fabio Utzig114a6472019-11-28 10:24:09 -0300204 Ok(run) => f(run),
205 Err(msg) => warn!("Skipping {}: {}", dev, msg),
David Brown5bc62c62019-03-05 12:11:48 -0700206 }
David Browne5133242019-02-28 11:05:19 -0700207 }
208 }
209 }
210 }
211
212 /// Construct an `Images` that doesn't expect an upgrade to happen.
David Brownc3898d62019-08-05 14:20:02 -0600213 pub fn make_no_upgrade_image(self, deps: &DepTest) -> Images {
214 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700215 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600216 let ram = self.ram.clone(); // TODO: This is wasteful.
David Brownc3898d62019-08-05 14:20:02 -0600217 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
218 let dep: Box<dyn Depender> = if num_images > 1 {
219 Box::new(PairDep::new(num_images, image_num, deps))
220 } else {
David Brown2ee5f7f2020-01-13 14:04:01 -0700221 Box::new(BoringDep::new(image_num, deps))
David Brownc3898d62019-08-05 14:20:02 -0600222 };
David Browna62c3eb2021-10-25 16:32:40 -0600223 let primaries = install_image(&mut flash, &slots[0],
David Brown07dd5f02021-10-26 16:43:15 -0600224 maximal(42784), &ram, &*dep, false);
David Brown873be312019-09-03 12:22:32 -0600225 let upgrades = match deps.depends[image_num] {
226 DepType::NoUpgrade => install_no_image(),
David Browna62c3eb2021-10-25 16:32:40 -0600227 _ => install_image(&mut flash, &slots[1],
David Brown07dd5f02021-10-26 16:43:15 -0600228 maximal(46928), &ram, &*dep, false)
David Brown873be312019-09-03 12:22:32 -0600229 };
David Brown84b49f72019-03-01 10:58:22 -0700230 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700231 slots,
232 primaries,
233 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700234 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600235 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700236 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700237 flash,
David Browne5133242019-02-28 11:05:19 -0700238 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700239 images,
David Browne5133242019-02-28 11:05:19 -0700240 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600241 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700242 }
243 }
244
David Brownc3898d62019-08-05 14:20:02 -0600245 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
246 let mut images = self.make_no_upgrade_image(deps);
David Brown84b49f72019-03-01 10:58:22 -0700247 for image in &images.images {
248 mark_upgrade(&mut images.flash, &image.slots[1]);
249 }
David Browne5133242019-02-28 11:05:19 -0700250
David Brown6db44d72021-05-26 16:22:58 -0600251 // The count is meaningless if no flash operations are performed.
252 if !Caps::modifies_flash() {
253 return images;
254 }
255
David Browne5133242019-02-28 11:05:19 -0700256 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300257 let total_count = match images.run_basic_upgrade(permanent) {
David Brown8973f552021-03-10 05:21:11 -0700258 Some(v) => v,
259 None =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600260 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
261 0
262 } else {
263 panic!("Unable to perform basic upgrade");
264 }
David Browne5133242019-02-28 11:05:19 -0700265 };
266
267 images.total_count = Some(total_count);
268 images
269 }
270
271 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700272 let mut bad_flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600273 let ram = self.ram.clone(); // TODO: Avoid this clone.
David Brownc3898d62019-08-05 14:20:02 -0600274 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
David Brown2ee5f7f2020-01-13 14:04:01 -0700275 let dep = BoringDep::new(image_num, &NO_DEPS);
David Browna62c3eb2021-10-25 16:32:40 -0600276 let primaries = install_image(&mut bad_flash, &slots[0],
David Brown07dd5f02021-10-26 16:43:15 -0600277 maximal(32784), &ram, &dep, false);
David Browna62c3eb2021-10-25 16:32:40 -0600278 let upgrades = install_image(&mut bad_flash, &slots[1],
David Brown07dd5f02021-10-26 16:43:15 -0600279 maximal(41928), &ram, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700280 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700281 slots,
282 primaries,
283 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700284 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700285 Images {
David Brown76101572019-02-28 11:29:03 -0700286 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700287 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700288 images,
David Browne5133242019-02-28 11:05:19 -0700289 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600290 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700291 }
292 }
293
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300294 pub fn make_erased_secondary_image(self) -> Images {
295 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600296 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300297 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
298 let dep = BoringDep::new(image_num, &NO_DEPS);
David Browna62c3eb2021-10-25 16:32:40 -0600299 let primaries = install_image(&mut flash, &slots[0],
David Brown07dd5f02021-10-26 16:43:15 -0600300 maximal(32784), &ram, &dep, false);
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300301 let upgrades = install_no_image();
302 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700303 slots,
304 primaries,
305 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300306 }}).collect();
307 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700308 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300309 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700310 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300311 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600312 ram: self.ram,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300313 }
314 }
315
Fabio Utzigd0157342020-10-02 15:22:11 -0300316 pub fn make_bootstrap_image(self) -> Images {
317 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600318 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzigd0157342020-10-02 15:22:11 -0300319 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
320 let dep = BoringDep::new(image_num, &NO_DEPS);
321 let primaries = install_no_image();
David Browna62c3eb2021-10-25 16:32:40 -0600322 let upgrades = install_image(&mut flash, &slots[1],
David Brown07dd5f02021-10-26 16:43:15 -0600323 maximal(32784), &ram, &dep, false);
Fabio Utzigd0157342020-10-02 15:22:11 -0300324 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700325 slots,
326 primaries,
327 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300328 }}).collect();
329 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700330 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300331 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700332 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300333 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600334 ram: self.ram,
Fabio Utzigd0157342020-10-02 15:22:11 -0300335 }
336 }
337
David Browne5133242019-02-28 11:05:19 -0700338 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300339 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700340 match device {
341 DeviceName::Stm32f4 => {
342 // STM style flash. Large sectors, with a large scratch area.
Fabio Utzig5577cbd2021-12-10 17:34:28 -0300343 // The flash layout as described is not present in any real STM32F4 device, but it
344 // serves to exercise support for sectors of varying sizes inside a single slot,
345 // as long as they are compatible in both slots and all fit in the scratch.
346 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024, 64 * 1024,
347 32 * 1024, 32 * 1024, 64 * 1024,
348 32 * 1024, 32 * 1024, 64 * 1024,
349 128 * 1024],
David Brown76101572019-02-28 11:29:03 -0700350 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700351 let dev_id = 0;
352 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700353 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700354 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
355 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
356 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
357
David Brown76101572019-02-28 11:29:03 -0700358 let mut flash = SimMultiFlash::new();
359 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300360 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700361 }
362 DeviceName::K64f => {
363 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700364 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700365
366 let dev_id = 0;
367 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700368 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700369 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
370 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
371 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
372
David Brown76101572019-02-28 11:29:03 -0700373 let mut flash = SimMultiFlash::new();
374 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300375 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700376 }
377 DeviceName::K64fBig => {
378 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
379 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700380 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700381
382 let dev_id = 0;
383 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700384 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700385 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
386 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
387 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
388
David Brown76101572019-02-28 11:29:03 -0700389 let mut flash = SimMultiFlash::new();
390 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300391 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700392 }
393 DeviceName::Nrf52840 => {
394 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
395 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700396 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700397
398 let dev_id = 0;
399 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700400 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700401 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
402 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
403 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
404
David Brown76101572019-02-28 11:29:03 -0700405 let mut flash = SimMultiFlash::new();
406 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300407 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700408 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300409 DeviceName::Nrf52840UnequalSlots => {
410 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
411
412 let dev_id = 0;
413 let mut areadesc = AreaDesc::new();
414 areadesc.add_flash_sectors(dev_id, &dev);
415 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
416 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
417
418 let mut flash = SimMultiFlash::new();
419 flash.insert(dev_id, dev);
420 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
421 }
David Browne5133242019-02-28 11:05:19 -0700422 DeviceName::Nrf52840SpiFlash => {
423 // Simulate nrf52840 with external SPI flash. The external SPI flash
424 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700425 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
426 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700427
428 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700429 areadesc.add_flash_sectors(0, &dev0);
430 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700431
432 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
433 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
434 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
435
David Brown76101572019-02-28 11:29:03 -0700436 let mut flash = SimMultiFlash::new();
437 flash.insert(0, dev0);
438 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300439 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700440 }
David Brown2bff6472019-03-05 13:58:35 -0700441 DeviceName::K64fMulti => {
442 // NXP style flash, but larger, to support multiple images.
443 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
444
445 let dev_id = 0;
446 let mut areadesc = AreaDesc::new();
447 areadesc.add_flash_sectors(dev_id, &dev);
448 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
449 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
450 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
451 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
452 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
453
454 let mut flash = SimMultiFlash::new();
455 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300456 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700457 }
David Browne5133242019-02-28 11:05:19 -0700458 }
459 }
David Brownc3898d62019-08-05 14:20:02 -0600460
461 pub fn num_images(&self) -> usize {
462 self.slots.len()
463 }
David Browne5133242019-02-28 11:05:19 -0700464}
465
David Brown5c9e0f12019-01-09 16:34:33 -0700466impl Images {
467 /// A simple upgrade without forced failures.
468 ///
469 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700470 /// inject failures at chosen steps. Returns None if it was unable to
471 /// count the operations in a basic upgrade.
472 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300473 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700474 info!("Total flash operation count={}", total_count);
475
David Brown84b49f72019-03-01 10:58:22 -0700476 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700477 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700478 None
David Brown5c9e0f12019-01-09 16:34:33 -0700479 } else {
David Brown8973f552021-03-10 05:21:11 -0700480 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700481 }
482 }
483
Fabio Utzigd0157342020-10-02 15:22:11 -0300484 pub fn run_bootstrap(&self) -> bool {
485 let mut flash = self.flash.clone();
486 let mut fails = 0;
487
488 if Caps::Bootstrap.present() {
489 info!("Try bootstraping image in the primary");
490
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100491 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigd0157342020-10-02 15:22:11 -0300492 warn!("Failed first boot");
493 fails += 1;
494 }
495
496 if !self.verify_images(&flash, 0, 1) {
497 warn!("Image in the first slot was not bootstrapped");
498 fails += 1;
499 }
500
501 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
502 BOOT_FLAG_SET, BOOT_FLAG_SET) {
503 warn!("Mismatched trailer for the primary slot");
504 fails += 1;
505 }
506 }
507
508 if fails > 0 {
509 error!("Expected trailer on secondary slot to be erased");
510 }
511
512 fails > 0
513 }
514
515
David Brownc3898d62019-08-05 14:20:02 -0600516 /// Test a simple upgrade, with dependencies given, and verify that the
517 /// image does as is described in the test.
518 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600519 if !Caps::modifies_flash() {
520 return false;
521 }
522
David Brownc3898d62019-08-05 14:20:02 -0600523 let (flash, _) = self.try_upgrade(None, true);
524
525 self.verify_dep_images(&flash, deps)
526 }
527
Fabio Utzigf5480c72019-11-28 10:41:57 -0300528 fn is_swap_upgrade(&self) -> bool {
529 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
530 }
531
David Brown5c9e0f12019-01-09 16:34:33 -0700532 pub fn run_basic_revert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600533 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700534 return false;
535 }
David Brown5c9e0f12019-01-09 16:34:33 -0700536
David Brown5c9e0f12019-01-09 16:34:33 -0700537 let mut fails = 0;
538
539 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300540 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700541 for count in 2 .. 5 {
542 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700543 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700544 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700545 error!("Revert failure on count {}", count);
546 fails += 1;
547 }
548 }
549 }
550
551 fails > 0
552 }
553
554 pub fn run_perm_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600555 if !Caps::modifies_flash() {
556 return false;
557 }
558
David Brown5c9e0f12019-01-09 16:34:33 -0700559 let mut fails = 0;
560 let total_flash_ops = self.total_count.unwrap();
561
562 // Let's try an image halfway through.
563 for i in 1 .. total_flash_ops {
564 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300565 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700566 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700567 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700568 warn!("FAIL at step {} of {}", i, total_flash_ops);
569 fails += 1;
570 }
571
David Brown84b49f72019-03-01 10:58:22 -0700572 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
573 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100574 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700575 fails += 1;
576 }
577
David Brown84b49f72019-03-01 10:58:22 -0700578 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
579 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100580 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700581 fails += 1;
582 }
583
David Brownaec56b22021-03-10 05:22:07 -0700584 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
585 warn!("Secondary slot FAIL at step {} of {}",
586 i, total_flash_ops);
587 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700588 }
589 }
590
591 if fails > 0 {
592 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
593 fails as f32 * 100.0 / total_flash_ops as f32);
594 }
595
596 fails > 0
597 }
598
David Brown5c9e0f12019-01-09 16:34:33 -0700599 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600600 if !Caps::modifies_flash() {
601 return false;
602 }
603
David Brown5c9e0f12019-01-09 16:34:33 -0700604 let mut fails = 0;
605 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700606 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700607 info!("Random interruptions at reset points={:?}", total_counts);
608
David Brown84b49f72019-03-01 10:58:22 -0700609 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300610 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700611 // TODO: This result is ignored.
612 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700613 } else {
614 true
615 };
David Vincze2d736ad2019-02-18 11:50:22 +0100616 if !primary_slot_ok || !secondary_slot_ok {
617 error!("Image mismatch after random interrupts: primary slot={} \
618 secondary slot={}",
619 if primary_slot_ok { "ok" } else { "fail" },
620 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700621 fails += 1;
622 }
David Brown84b49f72019-03-01 10:58:22 -0700623 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
624 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100625 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700626 fails += 1;
627 }
David Brown84b49f72019-03-01 10:58:22 -0700628 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
629 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100630 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700631 fails += 1;
632 }
633
634 if fails > 0 {
635 error!("Error testing perm upgrade with {} fails", total_fails);
636 }
637
638 fails > 0
639 }
640
David Brown5c9e0f12019-01-09 16:34:33 -0700641 pub fn run_revert_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600642 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700643 return false;
644 }
David Brown5c9e0f12019-01-09 16:34:33 -0700645
David Brown5c9e0f12019-01-09 16:34:33 -0700646 let mut fails = 0;
647
Fabio Utzigf5480c72019-11-28 10:41:57 -0300648 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300649 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700650 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700651 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700652 error!("Revert failed at interruption {}", i);
653 fails += 1;
654 }
655 }
656 }
657
658 fails > 0
659 }
660
David Brown5c9e0f12019-01-09 16:34:33 -0700661 pub fn run_norevert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600662 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700663 return false;
664 }
David Brown5c9e0f12019-01-09 16:34:33 -0700665
David Brown76101572019-02-28 11:29:03 -0700666 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700667 let mut fails = 0;
668
669 info!("Try norevert");
670
671 // First do a normal upgrade...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100672 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700673 warn!("Failed first boot");
674 fails += 1;
675 }
676
677 //FIXME: copy_done is written by boot_go, is it ok if no copy
678 // was ever done?
679
David Brown84b49f72019-03-01 10:58:22 -0700680 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100681 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700682 fails += 1;
683 }
David Brown84b49f72019-03-01 10:58:22 -0700684 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
685 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100686 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700687 fails += 1;
688 }
David Brown84b49f72019-03-01 10:58:22 -0700689 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
690 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100691 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700692 fails += 1;
693 }
694
David Vincze2d736ad2019-02-18 11:50:22 +0100695 // Marks image in the primary slot as permanent,
696 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700697 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700698
David Brown84b49f72019-03-01 10:58:22 -0700699 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
700 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100701 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700702 fails += 1;
703 }
704
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100705 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700706 warn!("Failed second boot");
707 fails += 1;
708 }
709
David Brown84b49f72019-03-01 10:58:22 -0700710 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
711 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100712 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700713 fails += 1;
714 }
David Brown84b49f72019-03-01 10:58:22 -0700715 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700716 warn!("Failed image verification");
717 fails += 1;
718 }
719
720 if fails > 0 {
721 error!("Error running upgrade without revert");
722 }
723
724 fails > 0
725 }
726
David Brown2ee5f7f2020-01-13 14:04:01 -0700727 // Test that an upgrade is rejected. Assumes that the image was build
728 // such that the upgrade is instead a downgrade.
729 pub fn run_nodowngrade(&self) -> bool {
730 if !Caps::DowngradePrevention.present() {
731 return false;
732 }
733
734 let mut flash = self.flash.clone();
735 let mut fails = 0;
736
737 info!("Try no downgrade");
738
739 // First, do a normal upgrade.
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100740 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700741 warn!("Failed first boot");
742 fails += 1;
743 }
744
745 if !self.verify_images(&flash, 0, 0) {
746 warn!("Failed verification after downgrade rejection");
747 fails += 1;
748 }
749
750 if fails > 0 {
751 error!("Error testing downgrade rejection");
752 }
753
754 fails > 0
755 }
756
David Vincze2d736ad2019-02-18 11:50:22 +0100757 // Tests a new image written to the primary slot that already has magic and
758 // image_ok set while there is no image on the secondary slot, so no revert
759 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700760 pub fn run_norevert_newimage(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600761 if !Caps::modifies_flash() {
762 info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
763 return false;
764 }
765
David Brown76101572019-02-28 11:29:03 -0700766 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700767 let mut fails = 0;
768
769 info!("Try non-revert on imgtool generated image");
770
David Brown84b49f72019-03-01 10:58:22 -0700771 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700772
David Vincze2d736ad2019-02-18 11:50:22 +0100773 // This simulates writing an image created by imgtool to
774 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700775 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
776 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100777 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700778 fails += 1;
779 }
780
781 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100782 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700783 warn!("Failed first boot");
784 fails += 1;
785 }
786
787 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700788 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700789 warn!("Failed image verification");
790 fails += 1;
791 }
David Brown84b49f72019-03-01 10:58:22 -0700792 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
793 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100794 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700795 fails += 1;
796 }
David Brown84b49f72019-03-01 10:58:22 -0700797 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
798 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100799 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700800 fails += 1;
801 }
802
803 if fails > 0 {
804 error!("Expected a non revert with new image");
805 }
806
807 fails > 0
808 }
809
David Vincze2d736ad2019-02-18 11:50:22 +0100810 // Tests a new image written to the primary slot that already has magic and
811 // image_ok set while there is no image on the secondary slot, so no revert
812 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700813 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700814 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700815 let mut fails = 0;
816
817 info!("Try upgrade image with bad signature");
818
David Brown6db44d72021-05-26 16:22:58 -0600819 // Only perform this test if an upgrade is expected to happen.
820 if !Caps::modifies_flash() {
821 info!("Skipping upgrade image with bad signature");
822 return false;
823 }
824
David Brown84b49f72019-03-01 10:58:22 -0700825 self.mark_upgrades(&mut flash, 0);
826 self.mark_permanent_upgrades(&mut flash, 0);
827 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700828
David Brown84b49f72019-03-01 10:58:22 -0700829 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
830 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100831 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700832 fails += 1;
833 }
834
835 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100836 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700837 warn!("Failed first boot");
838 fails += 1;
839 }
840
841 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700842 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700843 warn!("Failed image verification");
844 fails += 1;
845 }
David Brown84b49f72019-03-01 10:58:22 -0700846 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
847 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100848 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700849 fails += 1;
850 }
851
852 if fails > 0 {
853 error!("Expected an upgrade failure when image has bad signature");
854 }
855
856 fails > 0
857 }
858
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300859 // Should detect there is a leftover trailer in an otherwise erased
860 // secondary slot and erase its trailer.
861 pub fn run_secondary_leftover_trailer(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600862 if !Caps::modifies_flash() {
863 return false;
864 }
865
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300866 let mut flash = self.flash.clone();
867 let mut fails = 0;
868
869 info!("Try with a leftover trailer in the secondary; must be erased");
870
871 // Add a trailer on the secondary slot
872 self.mark_permanent_upgrades(&mut flash, 1);
873 self.mark_upgrades(&mut flash, 1);
874
875 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100876 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300877 warn!("Failed first boot");
878 fails += 1;
879 }
880
881 // State should not have changed
882 if !self.verify_images(&flash, 0, 0) {
883 warn!("Failed image verification");
884 fails += 1;
885 }
886 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
887 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
888 warn!("Mismatched trailer for the secondary slot");
889 fails += 1;
890 }
891
892 if fails > 0 {
893 error!("Expected trailer on secondary slot to be erased");
894 }
895
896 fails > 0
897 }
898
David Brown5c9e0f12019-01-09 16:34:33 -0700899 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300900 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700901 }
902
David Brown5c9e0f12019-01-09 16:34:33 -0700903 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300904 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700905 }
906
907 /// This test runs a simple upgrade with no fails in the images, but
908 /// allowing for fails in the status area. This should run to the end
909 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700910 pub fn run_with_status_fails_complete(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600911 if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700912 return false;
913 }
914
David Brown76101572019-02-28 11:29:03 -0700915 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700916 let mut fails = 0;
917
918 info!("Try swap with status fails");
919
David Brown84b49f72019-03-01 10:58:22 -0700920 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700921 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700922
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100923 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brownc423ac42021-06-04 13:47:34 -0600924 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700925 warn!("Failed!");
926 fails += 1;
927 }
928
929 // Failed writes to the marked "bad" region don't assert anymore.
930 // Any detected assert() is happening in another part of the code.
David Brownc423ac42021-06-04 13:47:34 -0600931 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -0700932 warn!("At least one assert() was called");
933 fails += 1;
934 }
935
David Brown84b49f72019-03-01 10:58:22 -0700936 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
937 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100938 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700939 fails += 1;
940 }
941
David Brown84b49f72019-03-01 10:58:22 -0700942 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700943 warn!("Failed image verification");
944 fails += 1;
945 }
946
David Vincze2d736ad2019-02-18 11:50:22 +0100947 info!("validate primary slot enabled; \
948 re-run of boot_go should just work");
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100949 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700950 warn!("Failed!");
951 fails += 1;
952 }
953
954 if fails > 0 {
955 error!("Error running upgrade with status write fails");
956 }
957
958 fails > 0
959 }
960
961 /// This test runs a simple upgrade with no fails in the images, but
962 /// allowing for fails in the status area. This should run to the end
963 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700964 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600965 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700966 false
David Vincze2d736ad2019-02-18 11:50:22 +0100967 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700968
David Brown76101572019-02-28 11:29:03 -0700969 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700970 let mut fails = 0;
971 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700972
David Brown85904a82019-01-11 13:45:12 -0700973 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700974
David Brown85904a82019-01-11 13:45:12 -0700975 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700976
David Brown84b49f72019-03-01 10:58:22 -0700977 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700978 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700979
980 // Should not fail, writing to bad regions does not assert
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100981 let asserts = c::boot_go(&mut flash, &self.areadesc,
982 Some(&mut count), None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700983 if asserts != 0 {
984 warn!("At least one assert() was called");
985 fails += 1;
986 }
987
David Brown76101572019-02-28 11:29:03 -0700988 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700989
990 info!("Resuming an interrupted swap operation");
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100991 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
992 true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700993
994 // This might throw no asserts, for large sector devices, where
995 // a single failure writing is indistinguishable from no failure,
996 // or throw a single assert for small sector devices that fail
997 // multiple times...
998 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100999 warn!("Expected single assert validating the primary slot, \
1000 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -07001001 fails += 1;
1002 }
1003
1004 if fails > 0 {
1005 error!("Error running upgrade with status write fails");
1006 }
1007
1008 fails > 0
1009 } else {
David Brown76101572019-02-28 11:29:03 -07001010 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001011 let mut fails = 0;
1012
1013 info!("Try interrupted swap with status fails");
1014
David Brown84b49f72019-03-01 10:58:22 -07001015 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001016 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -07001017
1018 // This is expected to fail while writing to bad regions...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001019 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1020 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001021 if asserts == 0 {
1022 warn!("No assert() detected");
1023 fails += 1;
1024 }
1025
1026 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -07001027 }
David Brown5c9e0f12019-01-09 16:34:33 -07001028 }
1029
David Brown0dfb8102021-06-03 15:29:11 -06001030 /// Test the direct XIP configuration. With this mode, flash images are never moved, and the
1031 /// bootloader merely selects which partition is the proper one to boot.
1032 pub fn run_direct_xip(&self) -> bool {
1033 if !Caps::DirectXip.present() {
1034 return false;
1035 }
1036
1037 // Clone the flash so we can tell if unchanged.
1038 let mut flash = self.flash.clone();
1039
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001040 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brown0dfb8102021-06-03 15:29:11 -06001041
1042 // Ensure the boot was successful.
1043 let resp = if let Some(resp) = result.resp() {
1044 resp
1045 } else {
1046 panic!("Boot didn't return a valid result");
1047 };
1048
1049 // This configuration should always try booting from the first upgrade slot.
1050 if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
1051 assert_eq!(offset, resp.image_off as usize);
1052 assert_eq!(dev_id, resp.flash_dev_id);
1053 } else {
1054 panic!("Unable to find upgrade image");
1055 }
1056 false
1057 }
1058
David Brown8a4e23b2021-06-11 10:29:01 -06001059 /// Test the ram-loading.
1060 pub fn run_ram_load(&self) -> bool {
1061 if !Caps::RamLoad.present() {
1062 return false;
1063 }
1064
1065 // Clone the flash so we can tell if unchanged.
1066 let mut flash = self.flash.clone();
1067
David Brownf17d3912021-06-23 16:10:51 -06001068 // Setup ram based on the ram configuration we determined earlier for the images.
1069 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
David Brown8a4e23b2021-06-11 10:29:01 -06001070
David Brownf17d3912021-06-23 16:10:51 -06001071 // println!("Ram: {:#?}", self.ram);
David Brown8a4e23b2021-06-11 10:29:01 -06001072
David Brownf17d3912021-06-23 16:10:51 -06001073 // Verify that the images area loaded into this.
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001074 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None,
1075 None, true));
David Brown8a4e23b2021-06-11 10:29:01 -06001076 if !result.success() {
David Brownf17d3912021-06-23 16:10:51 -06001077 error!("Failed to execute ram-load");
David Brown8a4e23b2021-06-11 10:29:01 -06001078 return true;
1079 }
1080
David Brownf17d3912021-06-23 16:10:51 -06001081 // Verify each image.
1082 for image in &self.images {
1083 let place = self.ram.lookup(&image.slots[0]);
1084 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1085 place.size as usize);
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001086 let src_sz = image.upgrades.size();
1087 if src_sz > ram_image.len() {
David Brownf17d3912021-06-23 16:10:51 -06001088 error!("Image ended up too large, nonsensical");
1089 return true;
1090 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001091 let src_image = &image.upgrades.plain[0..src_sz];
1092 let ram_image = &ram_image[0..src_sz];
David Brownf17d3912021-06-23 16:10:51 -06001093 if ram_image != src_image {
1094 error!("Image not loaded correctly");
1095 return true;
1096 }
1097
1098 }
1099
1100 return false;
David Brown8a4e23b2021-06-11 10:29:01 -06001101 }
1102
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001103 /// Test the split ram-loading.
1104 pub fn run_split_ram_load(&self) -> bool {
1105 if !Caps::RamLoad.present() {
1106 return false;
1107 }
1108
1109 // Clone the flash so we can tell if unchanged.
1110 let mut flash = self.flash.clone();
1111
1112 // Setup ram based on the ram configuration we determined earlier for the images.
1113 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1114
1115 for (idx, _image) in (&self.images).iter().enumerate() {
1116 // Verify that the images area loaded into this.
1117 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc,
1118 None, Some(idx as i32), true));
1119 if !result.success() {
1120 error!("Failed to execute ram-load");
1121 return true;
1122 }
1123 }
1124
1125 // Verify each image.
1126 for image in &self.images {
1127 let place = self.ram.lookup(&image.slots[0]);
1128 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1129 place.size as usize);
1130 let src_sz = image.upgrades.size();
1131 if src_sz > ram_image.len() {
1132 error!("Image ended up too large, nonsensical");
1133 return true;
1134 }
1135 let src_image = &image.upgrades.plain[0..src_sz];
1136 let ram_image = &ram_image[0..src_sz];
1137 if ram_image != src_image {
1138 error!("Image not loaded correctly");
1139 return true;
1140 }
1141
1142 }
1143
1144 return false;
1145 }
1146
David Brown5c9e0f12019-01-09 16:34:33 -07001147 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -07001148 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001149 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -07001150 if Caps::OverwriteUpgrade.present() {
1151 return;
1152 }
1153
David Brown84b49f72019-03-01 10:58:22 -07001154 // Set this for each image.
1155 for image in &self.images {
1156 let dev_id = &image.slots[slot].dev_id;
1157 let dev = flash.get_mut(&dev_id).unwrap();
1158 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001159 let off = &image.slots[slot].base_off;
1160 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -07001161 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -07001162
David Brown84b49f72019-03-01 10:58:22 -07001163 // Mark the status area as a bad area
1164 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1165 }
David Brown5c9e0f12019-01-09 16:34:33 -07001166 }
1167
David Brown76101572019-02-28 11:29:03 -07001168 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001169 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001170 return;
1171 }
1172
David Brown84b49f72019-03-01 10:58:22 -07001173 for image in &self.images {
1174 let dev_id = &image.slots[slot].dev_id;
1175 let dev = flash.get_mut(&dev_id).unwrap();
1176 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001177
David Brown84b49f72019-03-01 10:58:22 -07001178 // Disabling write verification the only assert triggered by
1179 // boot_go should be checking for integrity of status bytes.
1180 dev.set_verify_writes(false);
1181 }
David Brown5c9e0f12019-01-09 16:34:33 -07001182 }
1183
David Browndb505822019-03-01 10:04:20 -07001184 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1185 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001186 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001187 // Clone the flash to have a new copy.
1188 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001189
Fabio Utziged4a5362019-07-30 12:43:23 -03001190 if permanent {
1191 self.mark_permanent_upgrades(&mut flash, 1);
1192 }
David Brown5c9e0f12019-01-09 16:34:33 -07001193
David Browndb505822019-03-01 10:04:20 -07001194 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001195
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001196 let (first_interrupted, count) = match c::boot_go(&mut flash,
1197 &self.areadesc,
1198 Some(&mut counter),
1199 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001200 x if x.interrupted() => (true, stop.unwrap()),
1201 x if x.success() => (false, -counter),
1202 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001203 };
David Brown5c9e0f12019-01-09 16:34:33 -07001204
David Browndb505822019-03-01 10:04:20 -07001205 counter = 0;
1206 if first_interrupted {
1207 // fl.dump();
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001208 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1209 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001210 x if x.interrupted() => panic!("Shouldn't stop again"),
1211 x if x.success() => (),
1212 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001213 }
1214 }
David Brown5c9e0f12019-01-09 16:34:33 -07001215
David Browndb505822019-03-01 10:04:20 -07001216 (flash, count - counter)
1217 }
1218
1219 fn try_revert(&self, count: usize) -> SimMultiFlash {
1220 let mut flash = self.flash.clone();
1221
1222 // fl.write_file("image0.bin").unwrap();
1223 for i in 0 .. count {
1224 info!("Running boot pass {}", i + 1);
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001225 assert!(c::boot_go(&mut flash, &self.areadesc, None, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001226 }
1227 flash
1228 }
1229
1230 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1231 let mut flash = self.flash.clone();
1232 let mut fails = 0;
1233
1234 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001235 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1236 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001237 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001238 fails += 1;
1239 }
1240
Fabio Utzig8af7f792019-07-30 12:40:01 -03001241 // In a multi-image setup, copy done might be set if any number of
1242 // images was already successfully swapped.
1243 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1244 warn!("copy_done should be unset");
1245 fails += 1;
1246 }
1247
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001248 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001249 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001250 fails += 1;
1251 }
1252
David Brown84b49f72019-03-01 10:58:22 -07001253 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001254 warn!("Image in the primary slot before revert is invalid at stop={}",
1255 stop);
1256 fails += 1;
1257 }
David Brown84b49f72019-03-01 10:58:22 -07001258 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001259 warn!("Image in the secondary slot before revert is invalid at stop={}",
1260 stop);
1261 fails += 1;
1262 }
David Brown84b49f72019-03-01 10:58:22 -07001263 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1264 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001265 warn!("Mismatched trailer for the primary slot before revert");
1266 fails += 1;
1267 }
David Brown84b49f72019-03-01 10:58:22 -07001268 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1269 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001270 warn!("Mismatched trailer for the secondary slot before revert");
1271 fails += 1;
1272 }
1273
1274 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001275 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001276 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1277 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001278 warn!("Should have stopped revert at interruption point");
1279 fails += 1;
1280 }
1281
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001282 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001283 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001284 fails += 1;
1285 }
1286
David Brown84b49f72019-03-01 10:58:22 -07001287 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001288 warn!("Image in the primary slot after revert is invalid at stop={}",
1289 stop);
1290 fails += 1;
1291 }
David Brown84b49f72019-03-01 10:58:22 -07001292 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001293 warn!("Image in the secondary slot after revert is invalid at stop={}",
1294 stop);
1295 fails += 1;
1296 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001297
David Brown84b49f72019-03-01 10:58:22 -07001298 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1299 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001300 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001301 fails += 1;
1302 }
David Brown84b49f72019-03-01 10:58:22 -07001303 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1304 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001305 warn!("Mismatched trailer for the secondary slot after revert");
1306 fails += 1;
1307 }
1308
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001309 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001310 warn!("Should have finished 3rd boot");
1311 fails += 1;
1312 }
1313
1314 if !self.verify_images(&flash, 0, 0) {
1315 warn!("Image in the primary slot is invalid on 1st boot after revert");
1316 fails += 1;
1317 }
1318 if !self.verify_images(&flash, 1, 1) {
1319 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1320 fails += 1;
1321 }
1322
David Browndb505822019-03-01 10:04:20 -07001323 fails > 0
1324 }
1325
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001326
David Browndb505822019-03-01 10:04:20 -07001327 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1328 let mut flash = self.flash.clone();
1329
David Brown84b49f72019-03-01 10:58:22 -07001330 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001331
1332 let mut rng = rand::thread_rng();
1333 let mut resets = vec![0i32; count];
1334 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001335 for reset in &mut resets {
David Brown9c6322f2021-08-19 13:03:39 -06001336 let reset_counter = rng.gen_range(1 ..= remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001337 let mut counter = reset_counter;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001338 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1339 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001340 x if x.interrupted() => (),
1341 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001342 }
1343 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001344 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001345 }
1346
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001347 match c::boot_go(&mut flash, &self.areadesc, None, None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001348 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1349 x if x.success() => (),
1350 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001351 }
David Brown5c9e0f12019-01-09 16:34:33 -07001352
David Browndb505822019-03-01 10:04:20 -07001353 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001354 }
David Brown84b49f72019-03-01 10:58:22 -07001355
1356 /// Verify the image in the given flash device, the specified slot
1357 /// against the expected image.
1358 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001359 self.images.iter().all(|image| {
1360 verify_image(flash, &image.slots[slot],
1361 match against {
1362 0 => &image.primaries,
1363 1 => &image.upgrades,
1364 _ => panic!("Invalid 'against'")
1365 })
1366 })
David Brown84b49f72019-03-01 10:58:22 -07001367 }
1368
David Brownc3898d62019-08-05 14:20:02 -06001369 /// Verify the images, according to the dependency test.
1370 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1371 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1372 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1373 if !verify_image(flash, &image.slots[0],
1374 match upgrade {
1375 UpgradeInfo::Upgraded => &image.upgrades,
1376 UpgradeInfo::Held => &image.primaries,
1377 }) {
1378 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1379 return true;
1380 }
1381 }
1382
1383 false
1384 }
1385
Fabio Utzig8af7f792019-07-30 12:40:01 -03001386 /// Verify that at least one of the trailers of the images have the
1387 /// specified values.
1388 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1389 magic: Option<u8>, image_ok: Option<u8>,
1390 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001391 self.images.iter().any(|image| {
1392 verify_trailer(flash, &image.slots[slot],
1393 magic, image_ok, copy_done)
1394 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001395 }
1396
David Brown84b49f72019-03-01 10:58:22 -07001397 /// Verify that the trailers of the images have the specified
1398 /// values.
1399 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1400 magic: Option<u8>, image_ok: Option<u8>,
1401 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001402 self.images.iter().all(|image| {
1403 verify_trailer(flash, &image.slots[slot],
1404 magic, image_ok, copy_done)
1405 })
David Brown84b49f72019-03-01 10:58:22 -07001406 }
1407
1408 /// Mark each of the images for permanent upgrade.
1409 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1410 for image in &self.images {
1411 mark_permanent_upgrade(flash, &image.slots[slot]);
1412 }
1413 }
1414
1415 /// Mark each of the images for permanent upgrade.
1416 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1417 for image in &self.images {
1418 mark_upgrade(flash, &image.slots[slot]);
1419 }
1420 }
David Brown297029a2019-08-13 14:29:51 -06001421
1422 /// Dump out the flash image(s) to one or more files for debugging
1423 /// purposes. The names will be written as either "{prefix}.mcubin" or
1424 /// "{prefix}-001.mcubin" depending on how many images there are.
1425 pub fn debug_dump(&self, prefix: &str) {
1426 for (id, fdev) in &self.flash {
1427 let name = if self.flash.len() == 1 {
1428 format!("{}.mcubin", prefix)
1429 } else {
1430 format!("{}-{:>0}.mcubin", prefix, id)
1431 };
1432 fdev.write_file(&name).unwrap();
1433 }
1434 }
David Brown5c9e0f12019-01-09 16:34:33 -07001435}
1436
David Brownbf32c272021-06-16 17:11:37 -06001437impl RamData {
David Brownf17d3912021-06-23 16:10:51 -06001438 // TODO: This is not correct. The second slot of each image should be at the same address as
1439 // the primary.
David Brownbf32c272021-06-16 17:11:37 -06001440 fn new(slots: &[[SlotInfo; 2]]) -> RamData {
1441 let mut addr = RAM_LOAD_ADDR;
1442 let mut places = BTreeMap::new();
David Brownf17d3912021-06-23 16:10:51 -06001443 // println!("Setup:-------------");
David Brownbf32c272021-06-16 17:11:37 -06001444 for imgs in slots {
1445 for si in imgs {
David Brownf17d3912021-06-23 16:10:51 -06001446 // println!("Setup: si: {:?}", si);
David Brownbf32c272021-06-16 17:11:37 -06001447 let offset = addr;
1448 let size = si.len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001449 places.insert(SlotKey {
1450 dev_id: si.dev_id,
David Brownf17d3912021-06-23 16:10:51 -06001451 base_off: si.base_off,
David Brownbf32c272021-06-16 17:11:37 -06001452 }, SlotPlace { offset, size });
David Brownf17d3912021-06-23 16:10:51 -06001453 // println!(" load: offset: {}, size: {}", offset, size);
David Brownbf32c272021-06-16 17:11:37 -06001454 }
David Brownf17d3912021-06-23 16:10:51 -06001455 addr += imgs[0].len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001456 }
1457 RamData {
1458 places,
1459 total: addr,
1460 }
1461 }
David Brownf17d3912021-06-23 16:10:51 -06001462
1463 /// Lookup the ram data associated with a given flash partition. We just panic if not present,
1464 /// because all slots used should be in the map.
1465 fn lookup(&self, slot: &SlotInfo) -> &SlotPlace {
1466 self.places.get(&SlotKey{dev_id: slot.dev_id, base_off: slot.base_off})
1467 .expect("RamData should contain all slots")
1468 }
David Brownbf32c272021-06-16 17:11:37 -06001469}
1470
David Brown5c9e0f12019-01-09 16:34:33 -07001471/// Show the flash layout.
1472#[allow(dead_code)]
1473fn show_flash(flash: &dyn Flash) {
1474 println!("---- Flash configuration ----");
1475 for sector in flash.sector_iter() {
1476 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1477 sector.num, sector.base, sector.size);
1478 }
David Brown599b2db2021-03-10 05:23:26 -07001479 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001480}
1481
David Browna62c3eb2021-10-25 16:32:40 -06001482#[derive(Debug)]
1483enum ImageSize {
1484 /// Make the image the specified given size.
1485 Given(usize),
1486 /// Make the image as large as it can be for the partition/device.
1487 Largest,
1488}
1489
David Brown5c9e0f12019-01-09 16:34:33 -07001490/// Install a "program" into the given image. This fakes the image header, or at least all of the
1491/// fields used by the given code. Returns a copy of the image that was written.
David Browna62c3eb2021-10-25 16:32:40 -06001492fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: ImageSize,
David Brownf17d3912021-06-23 16:10:51 -06001493 ram: &RamData,
David Brownc3898d62019-08-05 14:20:02 -06001494 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001495 let offset = slot.base_off;
1496 let slot_len = slot.len;
1497 let dev_id = slot.dev_id;
David Brown07dd5f02021-10-26 16:43:15 -06001498 let dev = flash.get_mut(&dev_id).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001499
David Brown43643dd2019-01-11 15:43:28 -07001500 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001501
David Brownc3898d62019-08-05 14:20:02 -06001502 // Add the dependencies early to the tlv.
1503 for dep in deps.my_deps(offset, slot.index) {
1504 tlv.add_dependency(deps.other_id(), &dep);
1505 }
1506
David Brown5c9e0f12019-01-09 16:34:33 -07001507 const HDR_SIZE: usize = 32;
1508
David Brownf17d3912021-06-23 16:10:51 -06001509 let place = ram.lookup(&slot);
1510 let load_addr = if Caps::RamLoad.present() {
1511 place.offset
1512 } else {
1513 0
1514 };
1515
David Browna62c3eb2021-10-25 16:32:40 -06001516 let len = match len {
1517 ImageSize::Given(size) => size,
David Brown07dd5f02021-10-26 16:43:15 -06001518 ImageSize::Largest => {
1519 // Using the header size we know, the trailer size, and the slot size, we can compute
1520 // the largest image possible.
1521 let trailer = if Caps::OverwriteUpgrade.present() {
1522 // This computation is incorrect, and we need to figure out the correct size.
1523 // c::boot_status_sz(dev.align() as u32) as usize
1524 16 + 4 * dev.align()
1525 } else {
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03001526 let sector_size = dev.sector_iter().next().unwrap().size as u32;
1527 align_up(c::boot_trailer_sz(dev.align() as u32), sector_size) as usize
David Brown07dd5f02021-10-26 16:43:15 -06001528 };
1529 let tlv_len = tlv.estimate_size();
1530 info!("slot: 0x{:x}, HDR: 0x{:x}, trailer: 0x{:x}",
1531 slot_len, HDR_SIZE, trailer);
1532 slot_len - HDR_SIZE - trailer - tlv_len
1533 }
David Browna62c3eb2021-10-25 16:32:40 -06001534 };
1535
David Brown5c9e0f12019-01-09 16:34:33 -07001536 // Generate a boot header. Note that the size doesn't include the header.
1537 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001538 magic: tlv.get_magic(),
David Brownf17d3912021-06-23 16:10:51 -06001539 load_addr,
David Brown5c9e0f12019-01-09 16:34:33 -07001540 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001541 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001542 img_size: len as u32,
1543 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001544 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001545 _pad2: 0,
1546 };
1547
1548 let mut b_header = [0; HDR_SIZE];
1549 b_header[..32].clone_from_slice(header.as_raw());
1550 assert_eq!(b_header.len(), HDR_SIZE);
1551
1552 tlv.add_bytes(&b_header);
1553
1554 // The core of the image itself is just pseudorandom data.
1555 let mut b_img = vec![0; len];
1556 splat(&mut b_img, offset);
1557
David Browncb47dd72019-08-05 14:21:49 -06001558 // Add some information at the start of the payload to make it easier
1559 // to see what it is. This will fail if the image itself is too small.
1560 {
1561 let mut wr = Cursor::new(&mut b_img);
1562 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1563 offset, dev_id, slot).unwrap();
1564 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1565 }
1566
David Brown5c9e0f12019-01-09 16:34:33 -07001567 // TLV signatures work over plain image
1568 tlv.add_bytes(&b_img);
1569
1570 // Generate encrypted images
Salome Thirot6fdbf552021-05-14 16:46:14 +01001571 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1572 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001573 let mut b_encimg = vec![];
1574 if is_encrypted {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001575 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1576 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001577 tlv.generate_enc_key();
1578 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001579 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001580 b_encimg = b_img.clone();
Salome Thirot6fdbf552021-05-14 16:46:14 +01001581 if aes256 {
1582 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001583 let block = Aes256::new(&key);
1584 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001585 cipher.apply_keystream(&mut b_encimg);
1586 } else {
1587 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001588 let block = Aes128::new(&key);
1589 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001590 cipher.apply_keystream(&mut b_encimg);
1591 }
David Brown5c9e0f12019-01-09 16:34:33 -07001592 }
1593
1594 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001595 if bad_sig {
1596 tlv.corrupt_sig();
1597 }
1598 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001599
David Brown5c9e0f12019-01-09 16:34:33 -07001600 let mut buf = vec![];
1601 buf.append(&mut b_header.to_vec());
1602 buf.append(&mut b_img);
1603 buf.append(&mut b_tlv.clone());
1604
David Brown95de4502019-11-15 12:01:34 -07001605 // Pad the buffer to a multiple of the flash alignment.
1606 let align = dev.align();
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001607 let image_sz = buf.len();
David Brown95de4502019-11-15 12:01:34 -07001608 while buf.len() % align != 0 {
1609 buf.push(dev.erased_val());
1610 }
1611
David Brown5c9e0f12019-01-09 16:34:33 -07001612 let mut encbuf = vec![];
1613 if is_encrypted {
1614 encbuf.append(&mut b_header.to_vec());
1615 encbuf.append(&mut b_encimg);
1616 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001617
1618 while encbuf.len() % align != 0 {
1619 encbuf.push(dev.erased_val());
1620 }
David Brown5c9e0f12019-01-09 16:34:33 -07001621 }
1622
David Vincze2d736ad2019-02-18 11:50:22 +01001623 // Since images are always non-encrypted in the primary slot, we first write
1624 // an encrypted image, re-read to use for verification, erase + flash
1625 // un-encrypted. In the secondary slot the image is written un-encrypted,
1626 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001627
David Brown3b090212019-07-30 15:59:28 -06001628 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001629 let enc_copy: Option<Vec<u8>>;
1630
1631 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001632 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001633
1634 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001635 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001636
1637 enc_copy = Some(enc);
1638
David Brown76101572019-02-28 11:29:03 -07001639 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001640 } else {
1641 enc_copy = None;
1642 }
1643
David Brown76101572019-02-28 11:29:03 -07001644 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001645
1646 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001647 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001648
David Brownca234692019-02-28 11:22:19 -07001649 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001650 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001651 plain: copy,
1652 cipher: enc_copy,
1653 }
David Brown5c9e0f12019-01-09 16:34:33 -07001654 } else {
1655
David Brown76101572019-02-28 11:29:03 -07001656 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001657
1658 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001659 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001660
1661 let enc_copy: Option<Vec<u8>>;
1662
1663 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001664 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001665
David Brown76101572019-02-28 11:29:03 -07001666 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001667
1668 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001669 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001670
1671 enc_copy = Some(enc);
1672 } else {
1673 enc_copy = None;
1674 }
1675
David Brownca234692019-02-28 11:22:19 -07001676 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001677 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001678 plain: copy,
1679 cipher: enc_copy,
1680 }
David Brown5c9e0f12019-01-09 16:34:33 -07001681 }
David Brown5c9e0f12019-01-09 16:34:33 -07001682}
1683
David Brown873be312019-09-03 12:22:32 -06001684/// Install no image. This is used when no upgrade happens.
1685fn install_no_image() -> ImageData {
1686 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001687 size: 0,
David Brown873be312019-09-03 12:22:32 -06001688 plain: vec![],
1689 cipher: None,
1690 }
1691}
1692
David Brown0bd8c6b2021-10-22 16:33:06 -06001693/// Construct a TLV generator based on how MCUboot is currently configured. The returned
1694/// ManifestGen will generate the appropriate entries based on this configuration.
David Brown5c9e0f12019-01-09 16:34:33 -07001695fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001696 if Caps::EcdsaP224.present() {
1697 panic!("Ecdsa P224 not supported in Simulator");
1698 }
David Brownac655bb2021-10-22 16:33:27 -06001699 let aes_key_size = if Caps::Aes256.present() { 256 } else { 128 };
David Brown5c9e0f12019-01-09 16:34:33 -07001700
David Brownb8882112019-01-11 14:04:11 -07001701 if Caps::EncKw.present() {
1702 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001703 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001704 } else if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001705 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001706 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001707 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001708 }
1709 } else if Caps::EncRsa.present() {
1710 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001711 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001712 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001713 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001714 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001715 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001716 if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001717 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001718 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001719 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001720 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001721 } else if Caps::EncX25519.present() {
1722 if Caps::Ed25519.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001723 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001724 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001725 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001726 }
David Brownb8882112019-01-11 14:04:11 -07001727 } else {
1728 // The non-encrypted configuration.
1729 if Caps::RSA2048.present() {
1730 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001731 } else if Caps::RSA3072.present() {
1732 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001733 } else if Caps::EcdsaP256.present() {
1734 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001735 } else if Caps::Ed25519.present() {
1736 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001737 } else {
1738 TlvGen::new_hash_only()
1739 }
1740 }
David Brown5c9e0f12019-01-09 16:34:33 -07001741}
1742
David Brownca234692019-02-28 11:22:19 -07001743impl ImageData {
1744 /// Find the image contents for the given slot. This assumes that slot 0
1745 /// is unencrypted, and slot 1 is encrypted.
1746 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001747 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001748 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001749 match (encrypted, slot) {
1750 (false, _) => &self.plain,
1751 (true, 0) => &self.plain,
1752 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1753 _ => panic!("Invalid slot requested"),
1754 }
David Brown5c9e0f12019-01-09 16:34:33 -07001755 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001756
1757 fn size(&self) -> usize {
1758 self.size
1759 }
David Brown5c9e0f12019-01-09 16:34:33 -07001760}
1761
David Brown5c9e0f12019-01-09 16:34:33 -07001762/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001763fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1764 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001765 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001766 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001767
1768 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001769 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001770 let dev = flash.get(&dev_id).unwrap();
1771 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001772
1773 if buf != &copy[..] {
1774 for i in 0 .. buf.len() {
1775 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001776 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1777 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001778 break;
1779 }
1780 }
1781 false
1782 } else {
1783 true
1784 }
1785}
1786
David Brown3b090212019-07-30 15:59:28 -06001787fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001788 magic: Option<u8>, image_ok: Option<u8>,
1789 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001790 if Caps::OverwriteUpgrade.present() {
1791 return true;
1792 }
David Brown5c9e0f12019-01-09 16:34:33 -07001793
David Brown3b090212019-07-30 15:59:28 -06001794 let offset = slot.trailer_off + c::boot_max_align();
1795 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001796 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001797 let mut failed = false;
1798
David Brown76101572019-02-28 11:29:03 -07001799 let dev = flash.get(&dev_id).unwrap();
1800 let erased_val = dev.erased_val();
1801 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001802
1803 failed |= match magic {
1804 Some(v) => {
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03001805 let magic_off = (c::boot_max_align() * 3) + (c::boot_magic_sz() - MAGIC.len());
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001806 if v == 1 && &copy[magic_off..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001807 warn!("\"magic\" mismatch at {:#x}", offset);
1808 true
1809 } else if v == 3 {
1810 let expected = [erased_val; 16];
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001811 if copy[magic_off..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001812 warn!("\"magic\" mismatch at {:#x}", offset);
1813 true
1814 } else {
1815 false
1816 }
1817 } else {
1818 false
1819 }
1820 },
1821 None => false,
1822 };
1823
1824 failed |= match image_ok {
1825 Some(v) => {
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001826 let image_ok_off = c::boot_max_align() * 2;
1827 if (v == 1 && copy[image_ok_off] != v) || (v == 3 && copy[image_ok_off] != erased_val) {
1828 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[image_ok_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07001829 true
1830 } else {
1831 false
1832 }
1833 },
1834 None => false,
1835 };
1836
1837 failed |= match copy_done {
1838 Some(v) => {
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001839 let copy_done_off = c::boot_max_align();
1840 if (v == 1 && copy[copy_done_off] != v) || (v == 3 && copy[copy_done_off] != erased_val) {
1841 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[copy_done_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07001842 true
1843 } else {
1844 false
1845 }
1846 },
1847 None => false,
1848 };
1849
1850 !failed
1851}
1852
David Brown297029a2019-08-13 14:29:51 -06001853/// Install a partition table. This is a simplified partition table that
1854/// we write at the beginning of flash so make it easier for external tools
1855/// to analyze these images.
1856fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1857 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1858 for &id in &ids {
1859 // If there are any partitions in this device that start at 0, and
1860 // aren't marked as the BootLoader partition, avoid adding the
1861 // partition table. This makes it harder to view the image, but
1862 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07001863 let skip_ptable = areadesc
1864 .iter_areas()
1865 .any(|area| {
1866 area.device_id == id &&
1867 area.off == 0 &&
1868 area.flash_id != FlashId::BootLoader
1869 });
1870 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06001871 if log_enabled!(Info) {
1872 let special: Vec<FlashId> = areadesc.iter_areas()
1873 .filter(|area| area.device_id == id && area.off == 0)
1874 .map(|area| area.flash_id)
1875 .collect();
1876 info!("Skipping partition table: {:?}", special);
1877 }
1878 break;
1879 }
1880
1881 let mut buf: Vec<u8> = vec![];
1882 write!(&mut buf, "mcuboot\0").unwrap();
1883
1884 // Iterate through all of the partitions in that device, and encode
1885 // into the table.
1886 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1887 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1888
1889 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1890 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1891 buf.write_u32::<LittleEndian>(area.off).unwrap();
1892 buf.write_u32::<LittleEndian>(area.size).unwrap();
1893 buf.write_u32::<LittleEndian>(0).unwrap();
1894 }
1895
1896 let dev = flash.get_mut(&id).unwrap();
1897
1898 // Pad to alignment.
1899 while buf.len() % dev.align() != 0 {
1900 buf.push(0);
1901 }
1902
1903 dev.write(0, &buf).unwrap();
1904 }
1905}
1906
David Brown5c9e0f12019-01-09 16:34:33 -07001907/// The image header
1908#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001909#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001910pub struct ImageHeader {
1911 magic: u32,
1912 load_addr: u32,
1913 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001914 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001915 img_size: u32,
1916 flags: u32,
1917 ver: ImageVersion,
1918 _pad2: u32,
1919}
1920
1921impl AsRaw for ImageHeader {}
1922
1923#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001924#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001925pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001926 pub major: u8,
1927 pub minor: u8,
1928 pub revision: u16,
1929 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001930}
1931
David Brownc3898d62019-08-05 14:20:02 -06001932#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001933pub struct SlotInfo {
1934 pub base_off: usize,
1935 pub trailer_off: usize,
1936 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001937 // Which slot within this device.
1938 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001939 pub dev_id: u8,
1940}
1941
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03001942#[cfg(not(feature = "max-align-32"))]
David Brown347dc572019-11-15 11:37:25 -07001943const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1944 0x60, 0xd2, 0xef, 0x7f,
1945 0x35, 0x52, 0x50, 0x0f,
1946 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001947
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03001948#[cfg(feature = "max-align-32")]
1949const MAGIC: &[u8] = &[0x20, 0x00, 0x2d, 0xe1,
1950 0x5d, 0x29, 0x41, 0x0b,
1951 0x8d, 0x77, 0x67, 0x9c,
1952 0x11, 0x0f, 0x1f, 0x8a];
1953
David Brown5c9e0f12019-01-09 16:34:33 -07001954// Replicates defines found in bootutil.h
1955const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1956const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1957
1958const BOOT_FLAG_SET: Option<u8> = Some(1);
1959const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1960
1961/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001962pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1963 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001964 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001965 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001966 if offset % align != 0 || MAGIC.len() % align != 0 {
1967 // The write size is larger than the magic value. Fill a buffer
1968 // with the erased value, put the MAGIC in it, and write it in its
1969 // entirety.
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03001970 let mut buf = vec![dev.erased_val(); c::boot_max_align()];
1971 let magic_off = (offset % align) + (c::boot_magic_sz() - MAGIC.len());
1972 buf[magic_off..].copy_from_slice(MAGIC);
David Brown95de4502019-11-15 12:01:34 -07001973 dev.write(offset - (offset % align), &buf).unwrap();
1974 } else {
1975 dev.write(offset, MAGIC).unwrap();
1976 }
David Brown5c9e0f12019-01-09 16:34:33 -07001977}
1978
1979/// Writes the image_ok flag which, guess what, tells the bootloader
1980/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001981fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001982 // Overwrite mode always is permanent, and only the magic is used in
1983 // the trailer. To avoid problems with large write sizes, don't try to
1984 // set anything in this case.
1985 if Caps::OverwriteUpgrade.present() {
1986 return;
1987 }
1988
David Brown76101572019-02-28 11:29:03 -07001989 let dev = flash.get_mut(&slot.dev_id).unwrap();
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001990 let align = dev.align();
1991 let mut ok = vec![dev.erased_val(); align];
David Brown5c9e0f12019-01-09 16:34:33 -07001992 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001993 let off = slot.trailer_off + c::boot_max_align() * 3;
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001994 dev.write(off, &ok).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001995}
1996
1997// Drop some pseudo-random gibberish onto the data.
1998fn splat(data: &mut [u8], seed: usize) {
David Brown9c6322f2021-08-19 13:03:39 -06001999 let mut seed_block = [0u8; 32];
David Browncd842842020-07-09 15:46:53 -06002000 let mut buf = Cursor::new(&mut seed_block[..]);
2001 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
2002 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
2003 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
2004 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
2005 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07002006 rng.fill_bytes(data);
2007}
2008
2009/// Return a read-only view into the raw bytes of this object
2010trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07002011 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07002012 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
2013 mem::size_of::<Self>()) }
2014 }
2015}
2016
David Brown07dd5f02021-10-26 16:43:15 -06002017/// Determine whether it makes sense to test this configuration with a maximally-sized image.
2018/// Returns an ImageSize representing the best size to test, possibly just with the given size.
2019fn maximal(size: usize) -> ImageSize {
2020 if Caps::OverwriteUpgrade.present() ||
2021 Caps::SwapUsingMove.present()
2022 {
2023 ImageSize::Given(size)
2024 } else {
2025 ImageSize::Largest
2026 }
2027}
2028
David Brown5c9e0f12019-01-09 16:34:33 -07002029pub fn show_sizes() {
2030 // This isn't panic safe.
2031 for min in &[1, 2, 4, 8] {
2032 let msize = c::boot_trailer_sz(*min);
2033 println!("{:2}: {} (0x{:x})", min, msize, msize);
2034 }
2035}
David Brown95de4502019-11-15 12:01:34 -07002036
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002037#[cfg(not(feature = "max-align-32"))]
David Brown95de4502019-11-15 12:01:34 -07002038fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07002039 &[1, 2, 4, 8]
2040}
2041
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002042#[cfg(feature = "max-align-32")]
David Brown95de4502019-11-15 12:01:34 -07002043fn test_alignments() -> &'static [usize] {
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002044 &[32]
David Brown95de4502019-11-15 12:01:34 -07002045}