blob: 424f646794abb6e456668df74f32731d390a514c [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
Roland Mikhel75c7c312023-02-23 15:39:14 +01003// Copyright (c) 2019-2023 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
Andrzej Puzdrowski9324d2b2022-08-11 15:16:56 +0200294 pub fn make_oversized_secondary_slot_image(self) -> Images {
295 let mut bad_flash = self.flash;
296 let ram = self.ram.clone(); // TODO: Avoid this clone.
297 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
298 let dep = BoringDep::new(image_num, &NO_DEPS);
299 let primaries = install_image(&mut bad_flash, &slots[0],
300 maximal(32784), &ram, &dep, false);
301 let upgrades = install_image(&mut bad_flash, &slots[1],
302 ImageSize::Oversized, &ram, &dep, false);
303 OneImage {
304 slots,
305 primaries,
306 upgrades,
307 }}).collect();
308 Images {
309 flash: bad_flash,
310 areadesc: self.areadesc,
311 images,
312 total_count: None,
313 ram: self.ram,
314 }
315 }
316
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300317 pub fn make_erased_secondary_image(self) -> Images {
318 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600319 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300320 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
321 let dep = BoringDep::new(image_num, &NO_DEPS);
David Browna62c3eb2021-10-25 16:32:40 -0600322 let primaries = install_image(&mut flash, &slots[0],
David Brown07dd5f02021-10-26 16:43:15 -0600323 maximal(32784), &ram, &dep, false);
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300324 let upgrades = install_no_image();
325 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700326 slots,
327 primaries,
328 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300329 }}).collect();
330 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700331 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300332 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700333 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300334 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600335 ram: self.ram,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300336 }
337 }
338
Fabio Utzigd0157342020-10-02 15:22:11 -0300339 pub fn make_bootstrap_image(self) -> Images {
340 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600341 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzigd0157342020-10-02 15:22:11 -0300342 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
343 let dep = BoringDep::new(image_num, &NO_DEPS);
344 let primaries = install_no_image();
David Browna62c3eb2021-10-25 16:32:40 -0600345 let upgrades = install_image(&mut flash, &slots[1],
David Brown07dd5f02021-10-26 16:43:15 -0600346 maximal(32784), &ram, &dep, false);
Fabio Utzigd0157342020-10-02 15:22:11 -0300347 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700348 slots,
349 primaries,
350 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300351 }}).collect();
352 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700353 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300354 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700355 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300356 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600357 ram: self.ram,
Fabio Utzigd0157342020-10-02 15:22:11 -0300358 }
359 }
360
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +0200361 pub fn make_oversized_bootstrap_image(self) -> Images {
362 let mut flash = self.flash;
363 let ram = self.ram.clone(); // TODO: Avoid this clone.
364 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
365 let dep = BoringDep::new(image_num, &NO_DEPS);
366 let primaries = install_no_image();
367 let upgrades = install_image(&mut flash, &slots[1],
368 ImageSize::Oversized, &ram, &dep, false);
369 OneImage {
370 slots,
371 primaries,
372 upgrades,
373 }}).collect();
374 Images {
375 flash,
376 areadesc: self.areadesc,
377 images,
378 total_count: None,
379 ram: self.ram,
380 }
381 }
382
David Browne5133242019-02-28 11:05:19 -0700383 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300384 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700385 match device {
386 DeviceName::Stm32f4 => {
387 // STM style flash. Large sectors, with a large scratch area.
Fabio Utzig5577cbd2021-12-10 17:34:28 -0300388 // The flash layout as described is not present in any real STM32F4 device, but it
389 // serves to exercise support for sectors of varying sizes inside a single slot,
390 // as long as they are compatible in both slots and all fit in the scratch.
391 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024, 64 * 1024,
392 32 * 1024, 32 * 1024, 64 * 1024,
393 32 * 1024, 32 * 1024, 64 * 1024,
394 128 * 1024],
David Brown76101572019-02-28 11:29:03 -0700395 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700396 let dev_id = 0;
397 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700398 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700399 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
400 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
401 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
402
David Brown76101572019-02-28 11:29:03 -0700403 let mut flash = SimMultiFlash::new();
404 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300405 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700406 }
407 DeviceName::K64f => {
408 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700409 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700410
411 let dev_id = 0;
412 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700413 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700414 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
415 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
416 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
417
David Brown76101572019-02-28 11:29:03 -0700418 let mut flash = SimMultiFlash::new();
419 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300420 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700421 }
422 DeviceName::K64fBig => {
423 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
424 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700425 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700426
427 let dev_id = 0;
428 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700429 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700430 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
431 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
432 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
433
David Brown76101572019-02-28 11:29:03 -0700434 let mut flash = SimMultiFlash::new();
435 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300436 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700437 }
438 DeviceName::Nrf52840 => {
439 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
440 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700441 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700442
443 let dev_id = 0;
444 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700445 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700446 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
447 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
448 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
449
David Brown76101572019-02-28 11:29:03 -0700450 let mut flash = SimMultiFlash::new();
451 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300452 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700453 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300454 DeviceName::Nrf52840UnequalSlots => {
455 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
456
457 let dev_id = 0;
458 let mut areadesc = AreaDesc::new();
459 areadesc.add_flash_sectors(dev_id, &dev);
460 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
461 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
462
463 let mut flash = SimMultiFlash::new();
464 flash.insert(dev_id, dev);
465 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
466 }
David Browne5133242019-02-28 11:05:19 -0700467 DeviceName::Nrf52840SpiFlash => {
468 // Simulate nrf52840 with external SPI flash. The external SPI flash
469 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700470 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
471 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700472
473 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700474 areadesc.add_flash_sectors(0, &dev0);
475 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700476
477 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
478 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
479 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
480
David Brown76101572019-02-28 11:29:03 -0700481 let mut flash = SimMultiFlash::new();
482 flash.insert(0, dev0);
483 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300484 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700485 }
David Brown2bff6472019-03-05 13:58:35 -0700486 DeviceName::K64fMulti => {
487 // NXP style flash, but larger, to support multiple images.
488 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
489
490 let dev_id = 0;
491 let mut areadesc = AreaDesc::new();
492 areadesc.add_flash_sectors(dev_id, &dev);
493 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
494 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
495 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
496 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
497 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
498
499 let mut flash = SimMultiFlash::new();
500 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300501 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700502 }
David Browne5133242019-02-28 11:05:19 -0700503 }
504 }
David Brownc3898d62019-08-05 14:20:02 -0600505
506 pub fn num_images(&self) -> usize {
507 self.slots.len()
508 }
David Browne5133242019-02-28 11:05:19 -0700509}
510
David Brown5c9e0f12019-01-09 16:34:33 -0700511impl Images {
512 /// A simple upgrade without forced failures.
513 ///
514 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700515 /// inject failures at chosen steps. Returns None if it was unable to
516 /// count the operations in a basic upgrade.
517 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300518 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700519 info!("Total flash operation count={}", total_count);
520
David Brown84b49f72019-03-01 10:58:22 -0700521 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700522 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700523 None
David Brown5c9e0f12019-01-09 16:34:33 -0700524 } else {
David Brown8973f552021-03-10 05:21:11 -0700525 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700526 }
527 }
528
Fabio Utzigd0157342020-10-02 15:22:11 -0300529 pub fn run_bootstrap(&self) -> bool {
530 let mut flash = self.flash.clone();
531 let mut fails = 0;
532
533 if Caps::Bootstrap.present() {
534 info!("Try bootstraping image in the primary");
535
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100536 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigd0157342020-10-02 15:22:11 -0300537 warn!("Failed first boot");
538 fails += 1;
539 }
540
541 if !self.verify_images(&flash, 0, 1) {
542 warn!("Image in the first slot was not bootstrapped");
543 fails += 1;
544 }
545
546 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
547 BOOT_FLAG_SET, BOOT_FLAG_SET) {
548 warn!("Mismatched trailer for the primary slot");
549 fails += 1;
550 }
551 }
552
553 if fails > 0 {
554 error!("Expected trailer on secondary slot to be erased");
555 }
556
557 fails > 0
558 }
559
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +0200560 pub fn run_oversized_bootstrap(&self) -> bool {
561 let mut flash = self.flash.clone();
562 let mut fails = 0;
563
564 if Caps::Bootstrap.present() {
565 info!("Try bootstraping image in the primary");
566
567 let boot_result = c::boot_go(&mut flash, &self.areadesc, None, None, false).interrupted();
568
569 if boot_result {
570 warn!("Failed first boot");
571 fails += 1;
572 }
573
574 if self.verify_images(&flash, 0, 1) {
575 warn!("Image in the first slot was not bootstrapped");
576 fails += 1;
577 }
578
579 if self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
580 BOOT_FLAG_SET, BOOT_FLAG_SET) {
581 warn!("Mismatched trailer for the primary slot");
582 fails += 1;
583 }
584 }
585
586 if fails > 0 {
587 error!("Expected trailer on secondary slot to be erased");
588 }
589
590 fails > 0
591 }
592
Fabio Utzigd0157342020-10-02 15:22:11 -0300593
David Brownc3898d62019-08-05 14:20:02 -0600594 /// Test a simple upgrade, with dependencies given, and verify that the
595 /// image does as is described in the test.
596 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600597 if !Caps::modifies_flash() {
598 return false;
599 }
600
David Brownc3898d62019-08-05 14:20:02 -0600601 let (flash, _) = self.try_upgrade(None, true);
602
603 self.verify_dep_images(&flash, deps)
604 }
605
Fabio Utzigf5480c72019-11-28 10:41:57 -0300606 fn is_swap_upgrade(&self) -> bool {
607 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
608 }
609
David Brown5c9e0f12019-01-09 16:34:33 -0700610 pub fn run_basic_revert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600611 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700612 return false;
613 }
David Brown5c9e0f12019-01-09 16:34:33 -0700614
David Brown5c9e0f12019-01-09 16:34:33 -0700615 let mut fails = 0;
616
617 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300618 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700619 for count in 2 .. 5 {
620 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700621 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700622 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700623 error!("Revert failure on count {}", count);
624 fails += 1;
625 }
626 }
627 }
628
629 fails > 0
630 }
631
632 pub fn run_perm_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600633 if !Caps::modifies_flash() {
634 return false;
635 }
636
David Brown5c9e0f12019-01-09 16:34:33 -0700637 let mut fails = 0;
638 let total_flash_ops = self.total_count.unwrap();
639
640 // Let's try an image halfway through.
641 for i in 1 .. total_flash_ops {
642 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300643 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700644 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700645 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700646 warn!("FAIL at step {} of {}", i, total_flash_ops);
647 fails += 1;
648 }
649
David Brown84b49f72019-03-01 10:58:22 -0700650 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
651 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100652 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700653 fails += 1;
654 }
655
David Brown84b49f72019-03-01 10:58:22 -0700656 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
657 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100658 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700659 fails += 1;
660 }
661
David Brownaec56b22021-03-10 05:22:07 -0700662 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
663 warn!("Secondary slot FAIL at step {} of {}",
664 i, total_flash_ops);
665 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700666 }
667 }
668
669 if fails > 0 {
670 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
671 fails as f32 * 100.0 / total_flash_ops as f32);
672 }
673
674 fails > 0
675 }
676
David Brown5c9e0f12019-01-09 16:34:33 -0700677 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600678 if !Caps::modifies_flash() {
679 return false;
680 }
681
David Brown5c9e0f12019-01-09 16:34:33 -0700682 let mut fails = 0;
683 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700684 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700685 info!("Random interruptions at reset points={:?}", total_counts);
686
David Brown84b49f72019-03-01 10:58:22 -0700687 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300688 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700689 // TODO: This result is ignored.
690 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700691 } else {
692 true
693 };
David Vincze2d736ad2019-02-18 11:50:22 +0100694 if !primary_slot_ok || !secondary_slot_ok {
695 error!("Image mismatch after random interrupts: primary slot={} \
696 secondary slot={}",
697 if primary_slot_ok { "ok" } else { "fail" },
698 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700699 fails += 1;
700 }
David Brown84b49f72019-03-01 10:58:22 -0700701 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
702 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100703 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700704 fails += 1;
705 }
David Brown84b49f72019-03-01 10:58:22 -0700706 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
707 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100708 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700709 fails += 1;
710 }
711
712 if fails > 0 {
713 error!("Error testing perm upgrade with {} fails", total_fails);
714 }
715
716 fails > 0
717 }
718
David Brown5c9e0f12019-01-09 16:34:33 -0700719 pub fn run_revert_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600720 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700721 return false;
722 }
David Brown5c9e0f12019-01-09 16:34:33 -0700723
David Brown5c9e0f12019-01-09 16:34:33 -0700724 let mut fails = 0;
725
Fabio Utzigf5480c72019-11-28 10:41:57 -0300726 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300727 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700728 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700729 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700730 error!("Revert failed at interruption {}", i);
731 fails += 1;
732 }
733 }
734 }
735
736 fails > 0
737 }
738
David Brown5c9e0f12019-01-09 16:34:33 -0700739 pub fn run_norevert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600740 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700741 return false;
742 }
David Brown5c9e0f12019-01-09 16:34:33 -0700743
David Brown76101572019-02-28 11:29:03 -0700744 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700745 let mut fails = 0;
746
747 info!("Try norevert");
748
749 // First do a normal upgrade...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100750 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700751 warn!("Failed first boot");
752 fails += 1;
753 }
754
755 //FIXME: copy_done is written by boot_go, is it ok if no copy
756 // was ever done?
757
David Brown84b49f72019-03-01 10:58:22 -0700758 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100759 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700760 fails += 1;
761 }
David Brown84b49f72019-03-01 10:58:22 -0700762 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
763 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100764 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700765 fails += 1;
766 }
David Brown84b49f72019-03-01 10:58:22 -0700767 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
768 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100769 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700770 fails += 1;
771 }
772
David Vincze2d736ad2019-02-18 11:50:22 +0100773 // Marks image in the primary slot as permanent,
774 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700775 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700776
David Brown84b49f72019-03-01 10:58:22 -0700777 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
778 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100779 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700780 fails += 1;
781 }
782
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100783 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700784 warn!("Failed second boot");
785 fails += 1;
786 }
787
David Brown84b49f72019-03-01 10:58:22 -0700788 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
789 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100790 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700791 fails += 1;
792 }
David Brown84b49f72019-03-01 10:58:22 -0700793 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700794 warn!("Failed image verification");
795 fails += 1;
796 }
797
798 if fails > 0 {
799 error!("Error running upgrade without revert");
800 }
801
802 fails > 0
803 }
804
Andrzej Puzdrowski9324d2b2022-08-11 15:16:56 +0200805 // Test taht too big upgrade image will be rejected
806 pub fn run_oversizefail_upgrade(&self) -> bool {
807 let mut flash = self.flash.clone();
808 let mut fails = 0;
809
810 info!("Try upgrade image with to big size");
811
812 // Only perform this test if an upgrade is expected to happen.
813 if !Caps::modifies_flash() {
814 info!("Skipping upgrade image with bad signature");
815 return false;
816 }
817
818 self.mark_upgrades(&mut flash, 0);
819 self.mark_permanent_upgrades(&mut flash, 0);
820 self.mark_upgrades(&mut flash, 1);
821
822 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
823 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
824 warn!("1. Mismatched trailer for the primary slot");
825 fails += 1;
826 }
827
828 // Run the bootloader...
829 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
830 warn!("Failed first boot");
831 fails += 1;
832 }
833
834 // State should not have changed
835 if !self.verify_images(&flash, 0, 0) {
836 warn!("Failed image verification");
837 fails += 1;
838 }
839 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
840 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
841 warn!("2. Mismatched trailer for the primary slot");
842 fails += 1;
843 }
844
845 if fails > 0 {
846 error!("Expected an upgrade failure when image has to big size");
847 }
848
849 fails > 0
850 }
851
David Brown2ee5f7f2020-01-13 14:04:01 -0700852 // Test that an upgrade is rejected. Assumes that the image was build
853 // such that the upgrade is instead a downgrade.
854 pub fn run_nodowngrade(&self) -> bool {
855 if !Caps::DowngradePrevention.present() {
856 return false;
857 }
858
859 let mut flash = self.flash.clone();
860 let mut fails = 0;
861
862 info!("Try no downgrade");
863
864 // First, do a normal upgrade.
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100865 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700866 warn!("Failed first boot");
867 fails += 1;
868 }
869
870 if !self.verify_images(&flash, 0, 0) {
871 warn!("Failed verification after downgrade rejection");
872 fails += 1;
873 }
874
875 if fails > 0 {
876 error!("Error testing downgrade rejection");
877 }
878
879 fails > 0
880 }
881
David Vincze2d736ad2019-02-18 11:50:22 +0100882 // Tests a new image written to the primary slot that already has magic and
883 // image_ok set while there is no image on the secondary slot, so no revert
884 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700885 pub fn run_norevert_newimage(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600886 if !Caps::modifies_flash() {
887 info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
888 return false;
889 }
890
David Brown76101572019-02-28 11:29:03 -0700891 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700892 let mut fails = 0;
893
894 info!("Try non-revert on imgtool generated image");
895
David Brown84b49f72019-03-01 10:58:22 -0700896 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700897
David Vincze2d736ad2019-02-18 11:50:22 +0100898 // This simulates writing an image created by imgtool to
899 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700900 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
901 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100902 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700903 fails += 1;
904 }
905
906 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100907 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700908 warn!("Failed first boot");
909 fails += 1;
910 }
911
912 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700913 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700914 warn!("Failed image verification");
915 fails += 1;
916 }
David Brown84b49f72019-03-01 10:58:22 -0700917 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
918 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100919 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700920 fails += 1;
921 }
David Brown84b49f72019-03-01 10:58:22 -0700922 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
923 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100924 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700925 fails += 1;
926 }
927
928 if fails > 0 {
929 error!("Expected a non revert with new image");
930 }
931
932 fails > 0
933 }
934
David Vincze2d736ad2019-02-18 11:50:22 +0100935 // Tests a new image written to the primary slot that already has magic and
936 // image_ok set while there is no image on the secondary slot, so no revert
937 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700938 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700939 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700940 let mut fails = 0;
941
942 info!("Try upgrade image with bad signature");
943
David Brown6db44d72021-05-26 16:22:58 -0600944 // Only perform this test if an upgrade is expected to happen.
945 if !Caps::modifies_flash() {
946 info!("Skipping upgrade image with bad signature");
947 return false;
948 }
949
David Brown84b49f72019-03-01 10:58:22 -0700950 self.mark_upgrades(&mut flash, 0);
951 self.mark_permanent_upgrades(&mut flash, 0);
952 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700953
David Brown84b49f72019-03-01 10:58:22 -0700954 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
955 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100956 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700957 fails += 1;
958 }
959
960 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100961 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700962 warn!("Failed first boot");
963 fails += 1;
964 }
965
966 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700967 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700968 warn!("Failed image verification");
969 fails += 1;
970 }
David Brown84b49f72019-03-01 10:58:22 -0700971 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
972 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100973 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700974 fails += 1;
975 }
976
977 if fails > 0 {
978 error!("Expected an upgrade failure when image has bad signature");
979 }
980
981 fails > 0
982 }
983
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300984 // Should detect there is a leftover trailer in an otherwise erased
985 // secondary slot and erase its trailer.
986 pub fn run_secondary_leftover_trailer(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600987 if !Caps::modifies_flash() {
988 return false;
989 }
990
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300991 let mut flash = self.flash.clone();
992 let mut fails = 0;
993
994 info!("Try with a leftover trailer in the secondary; must be erased");
995
996 // Add a trailer on the secondary slot
997 self.mark_permanent_upgrades(&mut flash, 1);
998 self.mark_upgrades(&mut flash, 1);
999
1000 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001001 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -03001002 warn!("Failed first boot");
1003 fails += 1;
1004 }
1005
1006 // State should not have changed
1007 if !self.verify_images(&flash, 0, 0) {
1008 warn!("Failed image verification");
1009 fails += 1;
1010 }
1011 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1012 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
1013 warn!("Mismatched trailer for the secondary slot");
1014 fails += 1;
1015 }
1016
1017 if fails > 0 {
1018 error!("Expected trailer on secondary slot to be erased");
1019 }
1020
1021 fails > 0
1022 }
1023
David Brown5c9e0f12019-01-09 16:34:33 -07001024 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -03001025 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -07001026 }
1027
David Brown5c9e0f12019-01-09 16:34:33 -07001028 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -03001029 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -07001030 }
1031
1032 /// This test runs a simple upgrade with no fails in the images, but
1033 /// allowing for fails in the status area. This should run to the end
1034 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -07001035 pub fn run_with_status_fails_complete(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -06001036 if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -07001037 return false;
1038 }
1039
David Brown76101572019-02-28 11:29:03 -07001040 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001041 let mut fails = 0;
1042
1043 info!("Try swap with status fails");
1044
David Brown84b49f72019-03-01 10:58:22 -07001045 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001046 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -07001047
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001048 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brownc423ac42021-06-04 13:47:34 -06001049 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -07001050 warn!("Failed!");
1051 fails += 1;
1052 }
1053
1054 // Failed writes to the marked "bad" region don't assert anymore.
1055 // Any detected assert() is happening in another part of the code.
David Brownc423ac42021-06-04 13:47:34 -06001056 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001057 warn!("At least one assert() was called");
1058 fails += 1;
1059 }
1060
David Brown84b49f72019-03-01 10:58:22 -07001061 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1062 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +01001063 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -07001064 fails += 1;
1065 }
1066
David Brown84b49f72019-03-01 10:58:22 -07001067 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -07001068 warn!("Failed image verification");
1069 fails += 1;
1070 }
1071
David Vincze2d736ad2019-02-18 11:50:22 +01001072 info!("validate primary slot enabled; \
1073 re-run of boot_go should just work");
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001074 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -07001075 warn!("Failed!");
1076 fails += 1;
1077 }
1078
1079 if fails > 0 {
1080 error!("Error running upgrade with status write fails");
1081 }
1082
1083 fails > 0
1084 }
1085
1086 /// This test runs a simple upgrade with no fails in the images, but
1087 /// allowing for fails in the status area. This should run to the end
1088 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -07001089 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -06001090 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -07001091 false
David Vincze2d736ad2019-02-18 11:50:22 +01001092 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -07001093
David Brown76101572019-02-28 11:29:03 -07001094 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001095 let mut fails = 0;
1096 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -07001097
David Brown85904a82019-01-11 13:45:12 -07001098 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -07001099
David Brown85904a82019-01-11 13:45:12 -07001100 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -07001101
David Brown84b49f72019-03-01 10:58:22 -07001102 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001103 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -07001104
1105 // Should not fail, writing to bad regions does not assert
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001106 let asserts = c::boot_go(&mut flash, &self.areadesc,
1107 Some(&mut count), None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001108 if asserts != 0 {
1109 warn!("At least one assert() was called");
1110 fails += 1;
1111 }
1112
David Brown76101572019-02-28 11:29:03 -07001113 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -07001114
1115 info!("Resuming an interrupted swap operation");
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001116 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1117 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001118
1119 // This might throw no asserts, for large sector devices, where
1120 // a single failure writing is indistinguishable from no failure,
1121 // or throw a single assert for small sector devices that fail
1122 // multiple times...
1123 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +01001124 warn!("Expected single assert validating the primary slot, \
1125 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -07001126 fails += 1;
1127 }
1128
1129 if fails > 0 {
1130 error!("Error running upgrade with status write fails");
1131 }
1132
1133 fails > 0
1134 } else {
David Brown76101572019-02-28 11:29:03 -07001135 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001136 let mut fails = 0;
1137
1138 info!("Try interrupted swap with status fails");
1139
David Brown84b49f72019-03-01 10:58:22 -07001140 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001141 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -07001142
1143 // This is expected to fail while writing to bad regions...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001144 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1145 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001146 if asserts == 0 {
1147 warn!("No assert() detected");
1148 fails += 1;
1149 }
1150
1151 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -07001152 }
David Brown5c9e0f12019-01-09 16:34:33 -07001153 }
1154
David Brown0dfb8102021-06-03 15:29:11 -06001155 /// Test the direct XIP configuration. With this mode, flash images are never moved, and the
1156 /// bootloader merely selects which partition is the proper one to boot.
1157 pub fn run_direct_xip(&self) -> bool {
1158 if !Caps::DirectXip.present() {
1159 return false;
1160 }
1161
1162 // Clone the flash so we can tell if unchanged.
1163 let mut flash = self.flash.clone();
1164
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001165 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brown0dfb8102021-06-03 15:29:11 -06001166
1167 // Ensure the boot was successful.
1168 let resp = if let Some(resp) = result.resp() {
1169 resp
1170 } else {
1171 panic!("Boot didn't return a valid result");
1172 };
1173
1174 // This configuration should always try booting from the first upgrade slot.
1175 if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
1176 assert_eq!(offset, resp.image_off as usize);
1177 assert_eq!(dev_id, resp.flash_dev_id);
1178 } else {
1179 panic!("Unable to find upgrade image");
1180 }
1181 false
1182 }
1183
David Brown8a4e23b2021-06-11 10:29:01 -06001184 /// Test the ram-loading.
1185 pub fn run_ram_load(&self) -> bool {
1186 if !Caps::RamLoad.present() {
1187 return false;
1188 }
1189
1190 // Clone the flash so we can tell if unchanged.
1191 let mut flash = self.flash.clone();
1192
David Brownf17d3912021-06-23 16:10:51 -06001193 // Setup ram based on the ram configuration we determined earlier for the images.
1194 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
David Brown8a4e23b2021-06-11 10:29:01 -06001195
David Brownf17d3912021-06-23 16:10:51 -06001196 // println!("Ram: {:#?}", self.ram);
David Brown8a4e23b2021-06-11 10:29:01 -06001197
David Brownf17d3912021-06-23 16:10:51 -06001198 // Verify that the images area loaded into this.
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001199 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None,
1200 None, true));
David Brown8a4e23b2021-06-11 10:29:01 -06001201 if !result.success() {
David Brownf17d3912021-06-23 16:10:51 -06001202 error!("Failed to execute ram-load");
David Brown8a4e23b2021-06-11 10:29:01 -06001203 return true;
1204 }
1205
David Brownf17d3912021-06-23 16:10:51 -06001206 // Verify each image.
1207 for image in &self.images {
1208 let place = self.ram.lookup(&image.slots[0]);
1209 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1210 place.size as usize);
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001211 let src_sz = image.upgrades.size();
1212 if src_sz > ram_image.len() {
David Brownf17d3912021-06-23 16:10:51 -06001213 error!("Image ended up too large, nonsensical");
1214 return true;
1215 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001216 let src_image = &image.upgrades.plain[0..src_sz];
1217 let ram_image = &ram_image[0..src_sz];
David Brownf17d3912021-06-23 16:10:51 -06001218 if ram_image != src_image {
1219 error!("Image not loaded correctly");
1220 return true;
1221 }
1222
1223 }
1224
1225 return false;
David Brown8a4e23b2021-06-11 10:29:01 -06001226 }
1227
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001228 /// Test the split ram-loading.
1229 pub fn run_split_ram_load(&self) -> bool {
1230 if !Caps::RamLoad.present() {
1231 return false;
1232 }
1233
1234 // Clone the flash so we can tell if unchanged.
1235 let mut flash = self.flash.clone();
1236
1237 // Setup ram based on the ram configuration we determined earlier for the images.
1238 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1239
1240 for (idx, _image) in (&self.images).iter().enumerate() {
1241 // Verify that the images area loaded into this.
1242 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc,
1243 None, Some(idx as i32), true));
1244 if !result.success() {
1245 error!("Failed to execute ram-load");
1246 return true;
1247 }
1248 }
1249
1250 // Verify each image.
1251 for image in &self.images {
1252 let place = self.ram.lookup(&image.slots[0]);
1253 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1254 place.size as usize);
1255 let src_sz = image.upgrades.size();
1256 if src_sz > ram_image.len() {
1257 error!("Image ended up too large, nonsensical");
1258 return true;
1259 }
1260 let src_image = &image.upgrades.plain[0..src_sz];
1261 let ram_image = &ram_image[0..src_sz];
1262 if ram_image != src_image {
1263 error!("Image not loaded correctly");
1264 return true;
1265 }
1266
1267 }
1268
1269 return false;
1270 }
1271
David Brown5c9e0f12019-01-09 16:34:33 -07001272 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -07001273 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001274 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -07001275 if Caps::OverwriteUpgrade.present() {
1276 return;
1277 }
1278
David Brown84b49f72019-03-01 10:58:22 -07001279 // Set this for each image.
1280 for image in &self.images {
1281 let dev_id = &image.slots[slot].dev_id;
1282 let dev = flash.get_mut(&dev_id).unwrap();
1283 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001284 let off = &image.slots[slot].base_off;
1285 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -07001286 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -07001287
David Brown84b49f72019-03-01 10:58:22 -07001288 // Mark the status area as a bad area
1289 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1290 }
David Brown5c9e0f12019-01-09 16:34:33 -07001291 }
1292
David Brown76101572019-02-28 11:29:03 -07001293 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001294 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001295 return;
1296 }
1297
David Brown84b49f72019-03-01 10:58:22 -07001298 for image in &self.images {
1299 let dev_id = &image.slots[slot].dev_id;
1300 let dev = flash.get_mut(&dev_id).unwrap();
1301 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001302
David Brown84b49f72019-03-01 10:58:22 -07001303 // Disabling write verification the only assert triggered by
1304 // boot_go should be checking for integrity of status bytes.
1305 dev.set_verify_writes(false);
1306 }
David Brown5c9e0f12019-01-09 16:34:33 -07001307 }
1308
David Browndb505822019-03-01 10:04:20 -07001309 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1310 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001311 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001312 // Clone the flash to have a new copy.
1313 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001314
Fabio Utziged4a5362019-07-30 12:43:23 -03001315 if permanent {
1316 self.mark_permanent_upgrades(&mut flash, 1);
1317 }
David Brown5c9e0f12019-01-09 16:34:33 -07001318
David Browndb505822019-03-01 10:04:20 -07001319 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001320
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001321 let (first_interrupted, count) = match c::boot_go(&mut flash,
1322 &self.areadesc,
1323 Some(&mut counter),
1324 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001325 x if x.interrupted() => (true, stop.unwrap()),
1326 x if x.success() => (false, -counter),
1327 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001328 };
David Brown5c9e0f12019-01-09 16:34:33 -07001329
David Browndb505822019-03-01 10:04:20 -07001330 counter = 0;
1331 if first_interrupted {
1332 // fl.dump();
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001333 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1334 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001335 x if x.interrupted() => panic!("Shouldn't stop again"),
1336 x if x.success() => (),
1337 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001338 }
1339 }
David Brown5c9e0f12019-01-09 16:34:33 -07001340
David Browndb505822019-03-01 10:04:20 -07001341 (flash, count - counter)
1342 }
1343
1344 fn try_revert(&self, count: usize) -> SimMultiFlash {
1345 let mut flash = self.flash.clone();
1346
1347 // fl.write_file("image0.bin").unwrap();
1348 for i in 0 .. count {
1349 info!("Running boot pass {}", i + 1);
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001350 assert!(c::boot_go(&mut flash, &self.areadesc, None, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001351 }
1352 flash
1353 }
1354
1355 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1356 let mut flash = self.flash.clone();
1357 let mut fails = 0;
1358
1359 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001360 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1361 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001362 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001363 fails += 1;
1364 }
1365
Fabio Utzig8af7f792019-07-30 12:40:01 -03001366 // In a multi-image setup, copy done might be set if any number of
1367 // images was already successfully swapped.
1368 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1369 warn!("copy_done should be unset");
1370 fails += 1;
1371 }
1372
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001373 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001374 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001375 fails += 1;
1376 }
1377
David Brown84b49f72019-03-01 10:58:22 -07001378 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001379 warn!("Image in the primary slot before revert is invalid at stop={}",
1380 stop);
1381 fails += 1;
1382 }
David Brown84b49f72019-03-01 10:58:22 -07001383 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001384 warn!("Image in the secondary slot before revert is invalid at stop={}",
1385 stop);
1386 fails += 1;
1387 }
David Brown84b49f72019-03-01 10:58:22 -07001388 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1389 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001390 warn!("Mismatched trailer for the primary slot before revert");
1391 fails += 1;
1392 }
David Brown84b49f72019-03-01 10:58:22 -07001393 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1394 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001395 warn!("Mismatched trailer for the secondary slot before revert");
1396 fails += 1;
1397 }
1398
1399 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001400 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001401 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1402 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001403 warn!("Should have stopped revert at interruption point");
1404 fails += 1;
1405 }
1406
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001407 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001408 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001409 fails += 1;
1410 }
1411
David Brown84b49f72019-03-01 10:58:22 -07001412 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001413 warn!("Image in the primary slot after revert is invalid at stop={}",
1414 stop);
1415 fails += 1;
1416 }
David Brown84b49f72019-03-01 10:58:22 -07001417 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001418 warn!("Image in the secondary slot after revert is invalid at stop={}",
1419 stop);
1420 fails += 1;
1421 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001422
David Brown84b49f72019-03-01 10:58:22 -07001423 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1424 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001425 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001426 fails += 1;
1427 }
David Brown84b49f72019-03-01 10:58:22 -07001428 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1429 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001430 warn!("Mismatched trailer for the secondary slot after revert");
1431 fails += 1;
1432 }
1433
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001434 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001435 warn!("Should have finished 3rd boot");
1436 fails += 1;
1437 }
1438
1439 if !self.verify_images(&flash, 0, 0) {
1440 warn!("Image in the primary slot is invalid on 1st boot after revert");
1441 fails += 1;
1442 }
1443 if !self.verify_images(&flash, 1, 1) {
1444 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1445 fails += 1;
1446 }
1447
David Browndb505822019-03-01 10:04:20 -07001448 fails > 0
1449 }
1450
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001451
David Browndb505822019-03-01 10:04:20 -07001452 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1453 let mut flash = self.flash.clone();
1454
David Brown84b49f72019-03-01 10:58:22 -07001455 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001456
1457 let mut rng = rand::thread_rng();
1458 let mut resets = vec![0i32; count];
1459 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001460 for reset in &mut resets {
David Brown9c6322f2021-08-19 13:03:39 -06001461 let reset_counter = rng.gen_range(1 ..= remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001462 let mut counter = reset_counter;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001463 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1464 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001465 x if x.interrupted() => (),
1466 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001467 }
1468 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001469 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001470 }
1471
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001472 match c::boot_go(&mut flash, &self.areadesc, None, None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001473 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1474 x if x.success() => (),
1475 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001476 }
David Brown5c9e0f12019-01-09 16:34:33 -07001477
David Browndb505822019-03-01 10:04:20 -07001478 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001479 }
David Brown84b49f72019-03-01 10:58:22 -07001480
1481 /// Verify the image in the given flash device, the specified slot
1482 /// against the expected image.
1483 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001484 self.images.iter().all(|image| {
1485 verify_image(flash, &image.slots[slot],
1486 match against {
1487 0 => &image.primaries,
1488 1 => &image.upgrades,
1489 _ => panic!("Invalid 'against'")
1490 })
1491 })
David Brown84b49f72019-03-01 10:58:22 -07001492 }
1493
David Brownc3898d62019-08-05 14:20:02 -06001494 /// Verify the images, according to the dependency test.
1495 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1496 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1497 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1498 if !verify_image(flash, &image.slots[0],
1499 match upgrade {
1500 UpgradeInfo::Upgraded => &image.upgrades,
1501 UpgradeInfo::Held => &image.primaries,
1502 }) {
1503 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1504 return true;
1505 }
1506 }
1507
1508 false
1509 }
1510
Fabio Utzig8af7f792019-07-30 12:40:01 -03001511 /// Verify that at least one of the trailers of the images have the
1512 /// specified values.
1513 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1514 magic: Option<u8>, image_ok: Option<u8>,
1515 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001516 self.images.iter().any(|image| {
1517 verify_trailer(flash, &image.slots[slot],
1518 magic, image_ok, copy_done)
1519 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001520 }
1521
David Brown84b49f72019-03-01 10:58:22 -07001522 /// Verify that the trailers of the images have the specified
1523 /// values.
1524 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1525 magic: Option<u8>, image_ok: Option<u8>,
1526 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001527 self.images.iter().all(|image| {
1528 verify_trailer(flash, &image.slots[slot],
1529 magic, image_ok, copy_done)
1530 })
David Brown84b49f72019-03-01 10:58:22 -07001531 }
1532
1533 /// Mark each of the images for permanent upgrade.
1534 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1535 for image in &self.images {
1536 mark_permanent_upgrade(flash, &image.slots[slot]);
1537 }
1538 }
1539
1540 /// Mark each of the images for permanent upgrade.
1541 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1542 for image in &self.images {
1543 mark_upgrade(flash, &image.slots[slot]);
1544 }
1545 }
David Brown297029a2019-08-13 14:29:51 -06001546
1547 /// Dump out the flash image(s) to one or more files for debugging
1548 /// purposes. The names will be written as either "{prefix}.mcubin" or
1549 /// "{prefix}-001.mcubin" depending on how many images there are.
1550 pub fn debug_dump(&self, prefix: &str) {
1551 for (id, fdev) in &self.flash {
1552 let name = if self.flash.len() == 1 {
1553 format!("{}.mcubin", prefix)
1554 } else {
1555 format!("{}-{:>0}.mcubin", prefix, id)
1556 };
1557 fdev.write_file(&name).unwrap();
1558 }
1559 }
David Brown5c9e0f12019-01-09 16:34:33 -07001560}
1561
David Brownbf32c272021-06-16 17:11:37 -06001562impl RamData {
David Brownf17d3912021-06-23 16:10:51 -06001563 // TODO: This is not correct. The second slot of each image should be at the same address as
1564 // the primary.
David Brownbf32c272021-06-16 17:11:37 -06001565 fn new(slots: &[[SlotInfo; 2]]) -> RamData {
1566 let mut addr = RAM_LOAD_ADDR;
1567 let mut places = BTreeMap::new();
David Brownf17d3912021-06-23 16:10:51 -06001568 // println!("Setup:-------------");
David Brownbf32c272021-06-16 17:11:37 -06001569 for imgs in slots {
1570 for si in imgs {
David Brownf17d3912021-06-23 16:10:51 -06001571 // println!("Setup: si: {:?}", si);
David Brownbf32c272021-06-16 17:11:37 -06001572 let offset = addr;
1573 let size = si.len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001574 places.insert(SlotKey {
1575 dev_id: si.dev_id,
David Brownf17d3912021-06-23 16:10:51 -06001576 base_off: si.base_off,
David Brownbf32c272021-06-16 17:11:37 -06001577 }, SlotPlace { offset, size });
David Brownf17d3912021-06-23 16:10:51 -06001578 // println!(" load: offset: {}, size: {}", offset, size);
David Brownbf32c272021-06-16 17:11:37 -06001579 }
David Brownf17d3912021-06-23 16:10:51 -06001580 addr += imgs[0].len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001581 }
1582 RamData {
1583 places,
1584 total: addr,
1585 }
1586 }
David Brownf17d3912021-06-23 16:10:51 -06001587
1588 /// Lookup the ram data associated with a given flash partition. We just panic if not present,
1589 /// because all slots used should be in the map.
1590 fn lookup(&self, slot: &SlotInfo) -> &SlotPlace {
1591 self.places.get(&SlotKey{dev_id: slot.dev_id, base_off: slot.base_off})
1592 .expect("RamData should contain all slots")
1593 }
David Brownbf32c272021-06-16 17:11:37 -06001594}
1595
David Brown5c9e0f12019-01-09 16:34:33 -07001596/// Show the flash layout.
1597#[allow(dead_code)]
1598fn show_flash(flash: &dyn Flash) {
1599 println!("---- Flash configuration ----");
1600 for sector in flash.sector_iter() {
1601 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1602 sector.num, sector.base, sector.size);
1603 }
David Brown599b2db2021-03-10 05:23:26 -07001604 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001605}
1606
David Browna62c3eb2021-10-25 16:32:40 -06001607#[derive(Debug)]
1608enum ImageSize {
1609 /// Make the image the specified given size.
1610 Given(usize),
1611 /// Make the image as large as it can be for the partition/device.
1612 Largest,
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001613 /// Make the image quite larger than it can be for the partition/device/
1614 Oversized,
David Browna62c3eb2021-10-25 16:32:40 -06001615}
1616
Andrzej Puzdrowski5b90dc82022-08-08 12:49:24 +02001617#[cfg(not(feature = "max-align-32"))]
1618fn tralier_estimation(dev: &dyn Flash) -> usize {
Andrzej Puzdrowski5b90dc82022-08-08 12:49:24 +02001619 c::boot_trailer_sz(dev.align() as u32) as usize
1620}
1621
1622#[cfg(feature = "max-align-32")]
1623fn tralier_estimation(dev: &dyn Flash) -> usize {
1624
1625 let sector_size = dev.sector_iter().next().unwrap().size as u32;
1626
1627 align_up(c::boot_trailer_sz(dev.align() as u32), sector_size) as usize
1628}
1629
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001630fn image_largest_trailer(dev: &dyn Flash) -> usize {
1631 // Using the header size we know, the trailer size, and the slot size, we can compute
1632 // the largest image possible.
1633 let trailer = if Caps::OverwriteUpgrade.present() {
1634 // This computation is incorrect, and we need to figure out the correct size.
1635 // c::boot_status_sz(dev.align() as u32) as usize
1636 16 + 4 * dev.align()
1637 } else if Caps::SwapUsingMove.present() {
1638 let sector_size = dev.sector_iter().next().unwrap().size as u32;
1639 align_up(c::boot_trailer_sz(dev.align() as u32), sector_size) as usize
1640 } else if Caps::SwapUsingScratch.present() {
1641 tralier_estimation(dev)
1642 } else {
1643 panic!("The maximum image size can't be calculated.")
1644 };
1645
1646 trailer
1647}
1648
David Brown5c9e0f12019-01-09 16:34:33 -07001649/// Install a "program" into the given image. This fakes the image header, or at least all of the
1650/// fields used by the given code. Returns a copy of the image that was written.
David Browna62c3eb2021-10-25 16:32:40 -06001651fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: ImageSize,
David Brownf17d3912021-06-23 16:10:51 -06001652 ram: &RamData,
David Brownc3898d62019-08-05 14:20:02 -06001653 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001654 let offset = slot.base_off;
1655 let slot_len = slot.len;
1656 let dev_id = slot.dev_id;
David Brown07dd5f02021-10-26 16:43:15 -06001657 let dev = flash.get_mut(&dev_id).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001658
David Brown43643dd2019-01-11 15:43:28 -07001659 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001660
David Brownc3898d62019-08-05 14:20:02 -06001661 // Add the dependencies early to the tlv.
1662 for dep in deps.my_deps(offset, slot.index) {
1663 tlv.add_dependency(deps.other_id(), &dep);
1664 }
1665
David Brown5c9e0f12019-01-09 16:34:33 -07001666 const HDR_SIZE: usize = 32;
1667
David Brownf17d3912021-06-23 16:10:51 -06001668 let place = ram.lookup(&slot);
1669 let load_addr = if Caps::RamLoad.present() {
1670 place.offset
1671 } else {
1672 0
1673 };
1674
David Browna62c3eb2021-10-25 16:32:40 -06001675 let len = match len {
1676 ImageSize::Given(size) => size,
David Brown07dd5f02021-10-26 16:43:15 -06001677 ImageSize::Largest => {
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001678 let trailer = image_largest_trailer(dev);
David Brown07dd5f02021-10-26 16:43:15 -06001679 let tlv_len = tlv.estimate_size();
1680 info!("slot: 0x{:x}, HDR: 0x{:x}, trailer: 0x{:x}",
1681 slot_len, HDR_SIZE, trailer);
1682 slot_len - HDR_SIZE - trailer - tlv_len
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001683 },
1684 ImageSize::Oversized => {
1685 let trailer = image_largest_trailer(dev);
1686 let tlv_len = tlv.estimate_size();
1687 info!("slot: 0x{:x}, HDR: 0x{:x}, trailer: 0x{:x}",
1688 slot_len, HDR_SIZE, trailer);
1689 // the overflow size is rougly estimated to work for all
1690 // configurations. It might be precise if tlv_len will be maked precise.
1691 slot_len - HDR_SIZE - trailer - tlv_len + dev.align()*4
David Brown07dd5f02021-10-26 16:43:15 -06001692 }
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001693
David Browna62c3eb2021-10-25 16:32:40 -06001694 };
1695
David Brown5c9e0f12019-01-09 16:34:33 -07001696 // Generate a boot header. Note that the size doesn't include the header.
1697 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001698 magic: tlv.get_magic(),
David Brownf17d3912021-06-23 16:10:51 -06001699 load_addr,
David Brown5c9e0f12019-01-09 16:34:33 -07001700 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001701 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001702 img_size: len as u32,
1703 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001704 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001705 _pad2: 0,
1706 };
1707
1708 let mut b_header = [0; HDR_SIZE];
1709 b_header[..32].clone_from_slice(header.as_raw());
1710 assert_eq!(b_header.len(), HDR_SIZE);
1711
1712 tlv.add_bytes(&b_header);
1713
1714 // The core of the image itself is just pseudorandom data.
1715 let mut b_img = vec![0; len];
1716 splat(&mut b_img, offset);
1717
David Browncb47dd72019-08-05 14:21:49 -06001718 // Add some information at the start of the payload to make it easier
1719 // to see what it is. This will fail if the image itself is too small.
1720 {
1721 let mut wr = Cursor::new(&mut b_img);
1722 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1723 offset, dev_id, slot).unwrap();
1724 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1725 }
1726
David Brown5c9e0f12019-01-09 16:34:33 -07001727 // TLV signatures work over plain image
1728 tlv.add_bytes(&b_img);
1729
1730 // Generate encrypted images
Salome Thirot6fdbf552021-05-14 16:46:14 +01001731 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1732 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001733 let mut b_encimg = vec![];
1734 if is_encrypted {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001735 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1736 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001737 tlv.generate_enc_key();
1738 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001739 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001740 b_encimg = b_img.clone();
Salome Thirot6fdbf552021-05-14 16:46:14 +01001741 if aes256 {
1742 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001743 let block = Aes256::new(&key);
1744 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001745 cipher.apply_keystream(&mut b_encimg);
1746 } else {
1747 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001748 let block = Aes128::new(&key);
1749 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001750 cipher.apply_keystream(&mut b_encimg);
1751 }
David Brown5c9e0f12019-01-09 16:34:33 -07001752 }
1753
1754 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001755 if bad_sig {
1756 tlv.corrupt_sig();
1757 }
1758 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001759
David Brown5c9e0f12019-01-09 16:34:33 -07001760 let mut buf = vec![];
1761 buf.append(&mut b_header.to_vec());
1762 buf.append(&mut b_img);
1763 buf.append(&mut b_tlv.clone());
1764
David Brown95de4502019-11-15 12:01:34 -07001765 // Pad the buffer to a multiple of the flash alignment.
1766 let align = dev.align();
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001767 let image_sz = buf.len();
David Brown95de4502019-11-15 12:01:34 -07001768 while buf.len() % align != 0 {
1769 buf.push(dev.erased_val());
1770 }
1771
David Brown5c9e0f12019-01-09 16:34:33 -07001772 let mut encbuf = vec![];
1773 if is_encrypted {
1774 encbuf.append(&mut b_header.to_vec());
1775 encbuf.append(&mut b_encimg);
1776 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001777
1778 while encbuf.len() % align != 0 {
1779 encbuf.push(dev.erased_val());
1780 }
David Brown5c9e0f12019-01-09 16:34:33 -07001781 }
1782
David Vincze2d736ad2019-02-18 11:50:22 +01001783 // Since images are always non-encrypted in the primary slot, we first write
1784 // an encrypted image, re-read to use for verification, erase + flash
1785 // un-encrypted. In the secondary slot the image is written un-encrypted,
1786 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001787
David Brown3b090212019-07-30 15:59:28 -06001788 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001789 let enc_copy: Option<Vec<u8>>;
1790
1791 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001792 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001793
1794 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001795 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001796
1797 enc_copy = Some(enc);
1798
David Brown76101572019-02-28 11:29:03 -07001799 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001800 } else {
1801 enc_copy = None;
1802 }
1803
David Brown76101572019-02-28 11:29:03 -07001804 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001805
1806 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001807 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001808
David Brownca234692019-02-28 11:22:19 -07001809 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001810 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001811 plain: copy,
1812 cipher: enc_copy,
1813 }
David Brown5c9e0f12019-01-09 16:34:33 -07001814 } else {
1815
David Brown76101572019-02-28 11:29:03 -07001816 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001817
1818 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001819 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001820
1821 let enc_copy: Option<Vec<u8>>;
1822
1823 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001824 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001825
David Brown76101572019-02-28 11:29:03 -07001826 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001827
1828 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001829 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001830
1831 enc_copy = Some(enc);
1832 } else {
1833 enc_copy = None;
1834 }
1835
David Brownca234692019-02-28 11:22:19 -07001836 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001837 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001838 plain: copy,
1839 cipher: enc_copy,
1840 }
David Brown5c9e0f12019-01-09 16:34:33 -07001841 }
David Brown5c9e0f12019-01-09 16:34:33 -07001842}
1843
David Brown873be312019-09-03 12:22:32 -06001844/// Install no image. This is used when no upgrade happens.
1845fn install_no_image() -> ImageData {
1846 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001847 size: 0,
David Brown873be312019-09-03 12:22:32 -06001848 plain: vec![],
1849 cipher: None,
1850 }
1851}
1852
David Brown0bd8c6b2021-10-22 16:33:06 -06001853/// Construct a TLV generator based on how MCUboot is currently configured. The returned
1854/// ManifestGen will generate the appropriate entries based on this configuration.
David Brown5c9e0f12019-01-09 16:34:33 -07001855fn make_tlv() -> TlvGen {
David Brownac655bb2021-10-22 16:33:27 -06001856 let aes_key_size = if Caps::Aes256.present() { 256 } else { 128 };
David Brown5c9e0f12019-01-09 16:34:33 -07001857
David Brownb8882112019-01-11 14:04:11 -07001858 if Caps::EncKw.present() {
1859 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001860 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001861 } else if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001862 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001863 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001864 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001865 }
1866 } else if Caps::EncRsa.present() {
1867 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001868 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001869 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001870 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001871 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001872 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001873 if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001874 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001875 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001876 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001877 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001878 } else if Caps::EncX25519.present() {
1879 if Caps::Ed25519.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001880 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001881 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001882 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001883 }
David Brownb8882112019-01-11 14:04:11 -07001884 } else {
1885 // The non-encrypted configuration.
1886 if Caps::RSA2048.present() {
1887 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001888 } else if Caps::RSA3072.present() {
1889 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001890 } else if Caps::EcdsaP256.present() {
1891 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001892 } else if Caps::Ed25519.present() {
1893 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001894 } else {
1895 TlvGen::new_hash_only()
1896 }
1897 }
David Brown5c9e0f12019-01-09 16:34:33 -07001898}
1899
David Brownca234692019-02-28 11:22:19 -07001900impl ImageData {
1901 /// Find the image contents for the given slot. This assumes that slot 0
1902 /// is unencrypted, and slot 1 is encrypted.
1903 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001904 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001905 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001906 match (encrypted, slot) {
1907 (false, _) => &self.plain,
1908 (true, 0) => &self.plain,
1909 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1910 _ => panic!("Invalid slot requested"),
1911 }
David Brown5c9e0f12019-01-09 16:34:33 -07001912 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001913
1914 fn size(&self) -> usize {
1915 self.size
1916 }
David Brown5c9e0f12019-01-09 16:34:33 -07001917}
1918
David Brown5c9e0f12019-01-09 16:34:33 -07001919/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001920fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1921 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001922 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001923 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001924
1925 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001926 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001927 let dev = flash.get(&dev_id).unwrap();
1928 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001929
1930 if buf != &copy[..] {
1931 for i in 0 .. buf.len() {
1932 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001933 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1934 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001935 break;
1936 }
1937 }
1938 false
1939 } else {
1940 true
1941 }
1942}
1943
David Brown3b090212019-07-30 15:59:28 -06001944fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001945 magic: Option<u8>, image_ok: Option<u8>,
1946 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001947 if Caps::OverwriteUpgrade.present() {
1948 return true;
1949 }
David Brown5c9e0f12019-01-09 16:34:33 -07001950
David Brown3b090212019-07-30 15:59:28 -06001951 let offset = slot.trailer_off + c::boot_max_align();
1952 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001953 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001954 let mut failed = false;
1955
David Brown76101572019-02-28 11:29:03 -07001956 let dev = flash.get(&dev_id).unwrap();
1957 let erased_val = dev.erased_val();
1958 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001959
1960 failed |= match magic {
1961 Some(v) => {
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03001962 let magic_off = (c::boot_max_align() * 3) + (c::boot_magic_sz() - MAGIC.len());
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001963 if v == 1 && &copy[magic_off..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001964 warn!("\"magic\" mismatch at {:#x}", offset);
1965 true
1966 } else if v == 3 {
1967 let expected = [erased_val; 16];
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001968 if copy[magic_off..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001969 warn!("\"magic\" mismatch at {:#x}", offset);
1970 true
1971 } else {
1972 false
1973 }
1974 } else {
1975 false
1976 }
1977 },
1978 None => false,
1979 };
1980
1981 failed |= match image_ok {
1982 Some(v) => {
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001983 let image_ok_off = c::boot_max_align() * 2;
1984 if (v == 1 && copy[image_ok_off] != v) || (v == 3 && copy[image_ok_off] != erased_val) {
1985 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[image_ok_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07001986 true
1987 } else {
1988 false
1989 }
1990 },
1991 None => false,
1992 };
1993
1994 failed |= match copy_done {
1995 Some(v) => {
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001996 let copy_done_off = c::boot_max_align();
1997 if (v == 1 && copy[copy_done_off] != v) || (v == 3 && copy[copy_done_off] != erased_val) {
1998 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[copy_done_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07001999 true
2000 } else {
2001 false
2002 }
2003 },
2004 None => false,
2005 };
2006
2007 !failed
2008}
2009
David Brown297029a2019-08-13 14:29:51 -06002010/// Install a partition table. This is a simplified partition table that
2011/// we write at the beginning of flash so make it easier for external tools
2012/// to analyze these images.
2013fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
2014 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
2015 for &id in &ids {
2016 // If there are any partitions in this device that start at 0, and
2017 // aren't marked as the BootLoader partition, avoid adding the
2018 // partition table. This makes it harder to view the image, but
2019 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07002020 let skip_ptable = areadesc
2021 .iter_areas()
2022 .any(|area| {
2023 area.device_id == id &&
2024 area.off == 0 &&
2025 area.flash_id != FlashId::BootLoader
2026 });
2027 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06002028 if log_enabled!(Info) {
2029 let special: Vec<FlashId> = areadesc.iter_areas()
2030 .filter(|area| area.device_id == id && area.off == 0)
2031 .map(|area| area.flash_id)
2032 .collect();
2033 info!("Skipping partition table: {:?}", special);
2034 }
2035 break;
2036 }
2037
2038 let mut buf: Vec<u8> = vec![];
2039 write!(&mut buf, "mcuboot\0").unwrap();
2040
2041 // Iterate through all of the partitions in that device, and encode
2042 // into the table.
2043 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
2044 buf.write_u32::<LittleEndian>(count as u32).unwrap();
2045
2046 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
2047 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
2048 buf.write_u32::<LittleEndian>(area.off).unwrap();
2049 buf.write_u32::<LittleEndian>(area.size).unwrap();
2050 buf.write_u32::<LittleEndian>(0).unwrap();
2051 }
2052
2053 let dev = flash.get_mut(&id).unwrap();
2054
2055 // Pad to alignment.
2056 while buf.len() % dev.align() != 0 {
2057 buf.push(0);
2058 }
2059
2060 dev.write(0, &buf).unwrap();
2061 }
2062}
2063
David Brown5c9e0f12019-01-09 16:34:33 -07002064/// The image header
2065#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07002066#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002067pub struct ImageHeader {
2068 magic: u32,
2069 load_addr: u32,
2070 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06002071 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07002072 img_size: u32,
2073 flags: u32,
2074 ver: ImageVersion,
2075 _pad2: u32,
2076}
2077
2078impl AsRaw for ImageHeader {}
2079
2080#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06002081#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002082pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06002083 pub major: u8,
2084 pub minor: u8,
2085 pub revision: u16,
2086 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07002087}
2088
David Brownc3898d62019-08-05 14:20:02 -06002089#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002090pub struct SlotInfo {
2091 pub base_off: usize,
2092 pub trailer_off: usize,
2093 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06002094 // Which slot within this device.
2095 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07002096 pub dev_id: u8,
2097}
2098
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002099#[cfg(not(feature = "max-align-32"))]
David Brown347dc572019-11-15 11:37:25 -07002100const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
2101 0x60, 0xd2, 0xef, 0x7f,
2102 0x35, 0x52, 0x50, 0x0f,
2103 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07002104
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002105#[cfg(feature = "max-align-32")]
2106const MAGIC: &[u8] = &[0x20, 0x00, 0x2d, 0xe1,
2107 0x5d, 0x29, 0x41, 0x0b,
2108 0x8d, 0x77, 0x67, 0x9c,
2109 0x11, 0x0f, 0x1f, 0x8a];
2110
David Brown5c9e0f12019-01-09 16:34:33 -07002111// Replicates defines found in bootutil.h
2112const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
2113const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
2114
2115const BOOT_FLAG_SET: Option<u8> = Some(1);
2116const BOOT_FLAG_UNSET: Option<u8> = Some(3);
2117
2118/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07002119pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
2120 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07002121 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07002122 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07002123 if offset % align != 0 || MAGIC.len() % align != 0 {
2124 // The write size is larger than the magic value. Fill a buffer
2125 // with the erased value, put the MAGIC in it, and write it in its
2126 // entirety.
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002127 let mut buf = vec![dev.erased_val(); c::boot_max_align()];
2128 let magic_off = (offset % align) + (c::boot_magic_sz() - MAGIC.len());
2129 buf[magic_off..].copy_from_slice(MAGIC);
David Brown95de4502019-11-15 12:01:34 -07002130 dev.write(offset - (offset % align), &buf).unwrap();
2131 } else {
2132 dev.write(offset, MAGIC).unwrap();
2133 }
David Brown5c9e0f12019-01-09 16:34:33 -07002134}
2135
2136/// Writes the image_ok flag which, guess what, tells the bootloader
2137/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07002138fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07002139 // Overwrite mode always is permanent, and only the magic is used in
2140 // the trailer. To avoid problems with large write sizes, don't try to
2141 // set anything in this case.
2142 if Caps::OverwriteUpgrade.present() {
2143 return;
2144 }
2145
David Brown76101572019-02-28 11:29:03 -07002146 let dev = flash.get_mut(&slot.dev_id).unwrap();
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002147 let align = dev.align();
2148 let mut ok = vec![dev.erased_val(); align];
David Brown5c9e0f12019-01-09 16:34:33 -07002149 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07002150 let off = slot.trailer_off + c::boot_max_align() * 3;
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002151 dev.write(off, &ok).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07002152}
2153
2154// Drop some pseudo-random gibberish onto the data.
2155fn splat(data: &mut [u8], seed: usize) {
David Brown9c6322f2021-08-19 13:03:39 -06002156 let mut seed_block = [0u8; 32];
David Browncd842842020-07-09 15:46:53 -06002157 let mut buf = Cursor::new(&mut seed_block[..]);
2158 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
2159 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
2160 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
2161 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
2162 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07002163 rng.fill_bytes(data);
2164}
2165
2166/// Return a read-only view into the raw bytes of this object
2167trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07002168 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07002169 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
2170 mem::size_of::<Self>()) }
2171 }
2172}
2173
David Brown07dd5f02021-10-26 16:43:15 -06002174/// Determine whether it makes sense to test this configuration with a maximally-sized image.
2175/// Returns an ImageSize representing the best size to test, possibly just with the given size.
2176fn maximal(size: usize) -> ImageSize {
2177 if Caps::OverwriteUpgrade.present() ||
2178 Caps::SwapUsingMove.present()
2179 {
2180 ImageSize::Given(size)
2181 } else {
2182 ImageSize::Largest
2183 }
2184}
2185
David Brown5c9e0f12019-01-09 16:34:33 -07002186pub fn show_sizes() {
2187 // This isn't panic safe.
2188 for min in &[1, 2, 4, 8] {
2189 let msize = c::boot_trailer_sz(*min);
2190 println!("{:2}: {} (0x{:x})", min, msize, msize);
2191 }
2192}
David Brown95de4502019-11-15 12:01:34 -07002193
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002194#[cfg(not(feature = "max-align-32"))]
David Brown95de4502019-11-15 12:01:34 -07002195fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07002196 &[1, 2, 4, 8]
2197}
2198
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002199#[cfg(feature = "max-align-32")]
David Brown95de4502019-11-15 12:01:34 -07002200fn test_alignments() -> &'static [usize] {
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002201 &[32]
David Brown95de4502019-11-15 12:01:34 -07002202}