blob: 9b46ca07df543eabc88c377ee3b5bc084f70da7e [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],
Roland Mikheld6703522023-04-27 14:24:30 +0200224 maximal(42784), &ram, &*dep, false, Some(0));
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],
Roland Mikheld6703522023-04-27 14:24:30 +0200228 maximal(46928), &ram, &*dep, false, Some(0))
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],
Roland Mikheld6703522023-04-27 14:24:30 +0200277 maximal(32784), &ram, &dep, false, Some(0));
David Browna62c3eb2021-10-25 16:32:40 -0600278 let upgrades = install_image(&mut bad_flash, &slots[1],
Roland Mikheld6703522023-04-27 14:24:30 +0200279 maximal(41928), &ram, &dep, true, Some(0));
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],
Roland Mikheld6703522023-04-27 14:24:30 +0200300 maximal(32784), &ram, &dep, false, Some(0));
Andrzej Puzdrowski9324d2b2022-08-11 15:16:56 +0200301 let upgrades = install_image(&mut bad_flash, &slots[1],
Roland Mikheld6703522023-04-27 14:24:30 +0200302 ImageSize::Oversized, &ram, &dep, false, Some(0));
Andrzej Puzdrowski9324d2b2022-08-11 15:16:56 +0200303 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],
Roland Mikheld6703522023-04-27 14:24:30 +0200323 maximal(32784), &ram, &dep, false, Some(0));
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],
Roland Mikheld6703522023-04-27 14:24:30 +0200346 maximal(32784), &ram, &dep, false, Some(0));
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],
Roland Mikheld6703522023-04-27 14:24:30 +0200368 ImageSize::Oversized, &ram, &dep, false, Some(0));
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
383 /// If security_cnt is None then do not add a security counter TLV, otherwise add the specified value.
384 pub fn make_image_with_security_counter(self, security_cnt: Option<u32>) -> Images {
385 let mut flash = self.flash;
386 let ram = self.ram.clone(); // TODO: Avoid this clone.
387 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
388 let dep = BoringDep::new(image_num, &NO_DEPS);
389 let primaries = install_image(&mut flash, &slots[0],
390 maximal(32784), &ram, &dep, false, security_cnt);
391 let upgrades = install_image(&mut flash, &slots[1],
392 maximal(41928), &ram, &dep, false, security_cnt.map(|v| v + 1));
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +0200393 OneImage {
394 slots,
395 primaries,
396 upgrades,
397 }}).collect();
398 Images {
399 flash,
400 areadesc: self.areadesc,
401 images,
402 total_count: None,
403 ram: self.ram,
404 }
405 }
406
David Browne5133242019-02-28 11:05:19 -0700407 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300408 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700409 match device {
410 DeviceName::Stm32f4 => {
411 // STM style flash. Large sectors, with a large scratch area.
Fabio Utzig5577cbd2021-12-10 17:34:28 -0300412 // The flash layout as described is not present in any real STM32F4 device, but it
413 // serves to exercise support for sectors of varying sizes inside a single slot,
414 // as long as they are compatible in both slots and all fit in the scratch.
415 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024, 64 * 1024,
416 32 * 1024, 32 * 1024, 64 * 1024,
417 32 * 1024, 32 * 1024, 64 * 1024,
418 128 * 1024],
David Brown76101572019-02-28 11:29:03 -0700419 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700420 let dev_id = 0;
421 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700422 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700423 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
424 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
425 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
426
David Brown76101572019-02-28 11:29:03 -0700427 let mut flash = SimMultiFlash::new();
428 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300429 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700430 }
431 DeviceName::K64f => {
432 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700433 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700434
435 let dev_id = 0;
436 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700437 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700438 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
439 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
440 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
441
David Brown76101572019-02-28 11:29:03 -0700442 let mut flash = SimMultiFlash::new();
443 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300444 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700445 }
446 DeviceName::K64fBig => {
447 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
448 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700449 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700450
451 let dev_id = 0;
452 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700453 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700454 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
455 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
456 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
457
David Brown76101572019-02-28 11:29:03 -0700458 let mut flash = SimMultiFlash::new();
459 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300460 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700461 }
462 DeviceName::Nrf52840 => {
463 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
464 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700465 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700466
467 let dev_id = 0;
468 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700469 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700470 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
471 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
472 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
473
David Brown76101572019-02-28 11:29:03 -0700474 let mut flash = SimMultiFlash::new();
475 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300476 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700477 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300478 DeviceName::Nrf52840UnequalSlots => {
479 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
480
481 let dev_id = 0;
482 let mut areadesc = AreaDesc::new();
483 areadesc.add_flash_sectors(dev_id, &dev);
484 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
485 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
486
487 let mut flash = SimMultiFlash::new();
488 flash.insert(dev_id, dev);
489 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
490 }
David Browne5133242019-02-28 11:05:19 -0700491 DeviceName::Nrf52840SpiFlash => {
492 // Simulate nrf52840 with external SPI flash. The external SPI flash
493 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700494 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
495 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700496
497 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700498 areadesc.add_flash_sectors(0, &dev0);
499 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700500
501 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
502 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
503 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
504
David Brown76101572019-02-28 11:29:03 -0700505 let mut flash = SimMultiFlash::new();
506 flash.insert(0, dev0);
507 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300508 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700509 }
David Brown2bff6472019-03-05 13:58:35 -0700510 DeviceName::K64fMulti => {
511 // NXP style flash, but larger, to support multiple images.
512 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
513
514 let dev_id = 0;
515 let mut areadesc = AreaDesc::new();
516 areadesc.add_flash_sectors(dev_id, &dev);
517 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
518 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
519 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
520 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
521 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
522
523 let mut flash = SimMultiFlash::new();
524 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300525 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700526 }
David Browne5133242019-02-28 11:05:19 -0700527 }
528 }
David Brownc3898d62019-08-05 14:20:02 -0600529
530 pub fn num_images(&self) -> usize {
531 self.slots.len()
532 }
David Browne5133242019-02-28 11:05:19 -0700533}
534
David Brown5c9e0f12019-01-09 16:34:33 -0700535impl Images {
536 /// A simple upgrade without forced failures.
537 ///
538 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700539 /// inject failures at chosen steps. Returns None if it was unable to
540 /// count the operations in a basic upgrade.
541 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300542 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700543 info!("Total flash operation count={}", total_count);
544
David Brown84b49f72019-03-01 10:58:22 -0700545 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700546 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700547 None
David Brown5c9e0f12019-01-09 16:34:33 -0700548 } else {
David Brown8973f552021-03-10 05:21:11 -0700549 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700550 }
551 }
552
Fabio Utzigd0157342020-10-02 15:22:11 -0300553 pub fn run_bootstrap(&self) -> bool {
554 let mut flash = self.flash.clone();
555 let mut fails = 0;
556
557 if Caps::Bootstrap.present() {
558 info!("Try bootstraping image in the primary");
559
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100560 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigd0157342020-10-02 15:22:11 -0300561 warn!("Failed first boot");
562 fails += 1;
563 }
564
565 if !self.verify_images(&flash, 0, 1) {
566 warn!("Image in the first slot was not bootstrapped");
567 fails += 1;
568 }
569
570 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
571 BOOT_FLAG_SET, BOOT_FLAG_SET) {
572 warn!("Mismatched trailer for the primary slot");
573 fails += 1;
574 }
575 }
576
577 if fails > 0 {
578 error!("Expected trailer on secondary slot to be erased");
579 }
580
581 fails > 0
582 }
583
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +0200584 pub fn run_oversized_bootstrap(&self) -> bool {
585 let mut flash = self.flash.clone();
586 let mut fails = 0;
587
588 if Caps::Bootstrap.present() {
589 info!("Try bootstraping image in the primary");
590
591 let boot_result = c::boot_go(&mut flash, &self.areadesc, None, None, false).interrupted();
592
593 if boot_result {
594 warn!("Failed first boot");
595 fails += 1;
596 }
597
598 if self.verify_images(&flash, 0, 1) {
599 warn!("Image in the first slot was not bootstrapped");
600 fails += 1;
601 }
602
603 if self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
604 BOOT_FLAG_SET, BOOT_FLAG_SET) {
605 warn!("Mismatched trailer for the primary slot");
606 fails += 1;
607 }
608 }
609
610 if fails > 0 {
611 error!("Expected trailer on secondary slot to be erased");
612 }
613
614 fails > 0
615 }
616
Fabio Utzigd0157342020-10-02 15:22:11 -0300617
David Brownc3898d62019-08-05 14:20:02 -0600618 /// Test a simple upgrade, with dependencies given, and verify that the
619 /// image does as is described in the test.
620 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600621 if !Caps::modifies_flash() {
622 return false;
623 }
624
David Brownc3898d62019-08-05 14:20:02 -0600625 let (flash, _) = self.try_upgrade(None, true);
626
627 self.verify_dep_images(&flash, deps)
628 }
629
Fabio Utzigf5480c72019-11-28 10:41:57 -0300630 fn is_swap_upgrade(&self) -> bool {
631 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
632 }
633
David Brown5c9e0f12019-01-09 16:34:33 -0700634 pub fn run_basic_revert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600635 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700636 return false;
637 }
David Brown5c9e0f12019-01-09 16:34:33 -0700638
David Brown5c9e0f12019-01-09 16:34:33 -0700639 let mut fails = 0;
640
641 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300642 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700643 for count in 2 .. 5 {
644 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700645 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700646 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700647 error!("Revert failure on count {}", count);
648 fails += 1;
649 }
650 }
651 }
652
653 fails > 0
654 }
655
656 pub fn run_perm_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600657 if !Caps::modifies_flash() {
658 return false;
659 }
660
David Brown5c9e0f12019-01-09 16:34:33 -0700661 let mut fails = 0;
662 let total_flash_ops = self.total_count.unwrap();
663
664 // Let's try an image halfway through.
665 for i in 1 .. total_flash_ops {
666 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300667 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700668 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700669 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700670 warn!("FAIL at step {} of {}", i, total_flash_ops);
671 fails += 1;
672 }
673
David Brown84b49f72019-03-01 10:58:22 -0700674 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
675 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100676 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700677 fails += 1;
678 }
679
David Brown84b49f72019-03-01 10:58:22 -0700680 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
681 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100682 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700683 fails += 1;
684 }
685
David Brownaec56b22021-03-10 05:22:07 -0700686 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
687 warn!("Secondary slot FAIL at step {} of {}",
688 i, total_flash_ops);
689 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700690 }
691 }
692
693 if fails > 0 {
694 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
695 fails as f32 * 100.0 / total_flash_ops as f32);
696 }
697
698 fails > 0
699 }
700
David Brown5c9e0f12019-01-09 16:34:33 -0700701 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600702 if !Caps::modifies_flash() {
703 return false;
704 }
705
David Brown5c9e0f12019-01-09 16:34:33 -0700706 let mut fails = 0;
707 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700708 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700709 info!("Random interruptions at reset points={:?}", total_counts);
710
David Brown84b49f72019-03-01 10:58:22 -0700711 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300712 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700713 // TODO: This result is ignored.
714 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700715 } else {
716 true
717 };
David Vincze2d736ad2019-02-18 11:50:22 +0100718 if !primary_slot_ok || !secondary_slot_ok {
719 error!("Image mismatch after random interrupts: primary slot={} \
720 secondary slot={}",
721 if primary_slot_ok { "ok" } else { "fail" },
722 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700723 fails += 1;
724 }
David Brown84b49f72019-03-01 10:58:22 -0700725 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
726 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100727 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700728 fails += 1;
729 }
David Brown84b49f72019-03-01 10:58:22 -0700730 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
731 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100732 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700733 fails += 1;
734 }
735
736 if fails > 0 {
737 error!("Error testing perm upgrade with {} fails", total_fails);
738 }
739
740 fails > 0
741 }
742
David Brown5c9e0f12019-01-09 16:34:33 -0700743 pub fn run_revert_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600744 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700745 return false;
746 }
David Brown5c9e0f12019-01-09 16:34:33 -0700747
David Brown5c9e0f12019-01-09 16:34:33 -0700748 let mut fails = 0;
749
Fabio Utzigf5480c72019-11-28 10:41:57 -0300750 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300751 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700752 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700753 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700754 error!("Revert failed at interruption {}", i);
755 fails += 1;
756 }
757 }
758 }
759
760 fails > 0
761 }
762
David Brown5c9e0f12019-01-09 16:34:33 -0700763 pub fn run_norevert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600764 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700765 return false;
766 }
David Brown5c9e0f12019-01-09 16:34:33 -0700767
David Brown76101572019-02-28 11:29:03 -0700768 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700769 let mut fails = 0;
770
771 info!("Try norevert");
772
773 // First do a normal upgrade...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100774 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700775 warn!("Failed first boot");
776 fails += 1;
777 }
778
779 //FIXME: copy_done is written by boot_go, is it ok if no copy
780 // was ever done?
781
David Brown84b49f72019-03-01 10:58:22 -0700782 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100783 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700784 fails += 1;
785 }
David Brown84b49f72019-03-01 10:58:22 -0700786 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
787 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100788 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700789 fails += 1;
790 }
David Brown84b49f72019-03-01 10:58:22 -0700791 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
792 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100793 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700794 fails += 1;
795 }
796
David Vincze2d736ad2019-02-18 11:50:22 +0100797 // Marks image in the primary slot as permanent,
798 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700799 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700800
David Brown84b49f72019-03-01 10:58:22 -0700801 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
802 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100803 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700804 fails += 1;
805 }
806
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100807 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700808 warn!("Failed second boot");
809 fails += 1;
810 }
811
David Brown84b49f72019-03-01 10:58:22 -0700812 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
813 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100814 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700815 fails += 1;
816 }
David Brown84b49f72019-03-01 10:58:22 -0700817 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700818 warn!("Failed image verification");
819 fails += 1;
820 }
821
822 if fails > 0 {
823 error!("Error running upgrade without revert");
824 }
825
826 fails > 0
827 }
828
Andrzej Puzdrowski9324d2b2022-08-11 15:16:56 +0200829 // Test taht too big upgrade image will be rejected
830 pub fn run_oversizefail_upgrade(&self) -> bool {
831 let mut flash = self.flash.clone();
832 let mut fails = 0;
833
834 info!("Try upgrade image with to big size");
835
836 // Only perform this test if an upgrade is expected to happen.
837 if !Caps::modifies_flash() {
838 info!("Skipping upgrade image with bad signature");
839 return false;
840 }
841
842 self.mark_upgrades(&mut flash, 0);
843 self.mark_permanent_upgrades(&mut flash, 0);
844 self.mark_upgrades(&mut flash, 1);
845
846 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
847 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
848 warn!("1. Mismatched trailer for the primary slot");
849 fails += 1;
850 }
851
852 // Run the bootloader...
853 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
854 warn!("Failed first boot");
855 fails += 1;
856 }
857
858 // State should not have changed
859 if !self.verify_images(&flash, 0, 0) {
860 warn!("Failed image verification");
861 fails += 1;
862 }
863 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
864 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
865 warn!("2. Mismatched trailer for the primary slot");
866 fails += 1;
867 }
868
869 if fails > 0 {
870 error!("Expected an upgrade failure when image has to big size");
871 }
872
873 fails > 0
874 }
875
David Brown2ee5f7f2020-01-13 14:04:01 -0700876 // Test that an upgrade is rejected. Assumes that the image was build
877 // such that the upgrade is instead a downgrade.
878 pub fn run_nodowngrade(&self) -> bool {
879 if !Caps::DowngradePrevention.present() {
880 return false;
881 }
882
883 let mut flash = self.flash.clone();
884 let mut fails = 0;
885
886 info!("Try no downgrade");
887
888 // First, do a normal upgrade.
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100889 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700890 warn!("Failed first boot");
891 fails += 1;
892 }
893
894 if !self.verify_images(&flash, 0, 0) {
895 warn!("Failed verification after downgrade rejection");
896 fails += 1;
897 }
898
899 if fails > 0 {
900 error!("Error testing downgrade rejection");
901 }
902
903 fails > 0
904 }
905
David Vincze2d736ad2019-02-18 11:50:22 +0100906 // Tests a new image written to the primary slot that already has magic and
907 // image_ok set while there is no image on the secondary slot, so no revert
908 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700909 pub fn run_norevert_newimage(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600910 if !Caps::modifies_flash() {
911 info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
912 return false;
913 }
914
David Brown76101572019-02-28 11:29:03 -0700915 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700916 let mut fails = 0;
917
918 info!("Try non-revert on imgtool generated image");
919
David Brown84b49f72019-03-01 10:58:22 -0700920 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700921
David Vincze2d736ad2019-02-18 11:50:22 +0100922 // This simulates writing an image created by imgtool to
923 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700924 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
925 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100926 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700927 fails += 1;
928 }
929
930 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100931 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700932 warn!("Failed first boot");
933 fails += 1;
934 }
935
936 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700937 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700938 warn!("Failed image verification");
939 fails += 1;
940 }
David Brown84b49f72019-03-01 10:58:22 -0700941 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
942 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100943 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700944 fails += 1;
945 }
David Brown84b49f72019-03-01 10:58:22 -0700946 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
947 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100948 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700949 fails += 1;
950 }
951
952 if fails > 0 {
953 error!("Expected a non revert with new image");
954 }
955
956 fails > 0
957 }
958
David Vincze2d736ad2019-02-18 11:50:22 +0100959 // Tests a new image written to the primary slot that already has magic and
960 // image_ok set while there is no image on the secondary slot, so no revert
961 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700962 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700963 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700964 let mut fails = 0;
965
966 info!("Try upgrade image with bad signature");
967
David Brown6db44d72021-05-26 16:22:58 -0600968 // Only perform this test if an upgrade is expected to happen.
969 if !Caps::modifies_flash() {
970 info!("Skipping upgrade image with bad signature");
971 return false;
972 }
973
David Brown84b49f72019-03-01 10:58:22 -0700974 self.mark_upgrades(&mut flash, 0);
975 self.mark_permanent_upgrades(&mut flash, 0);
976 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700977
David Brown84b49f72019-03-01 10:58:22 -0700978 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
979 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100980 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700981 fails += 1;
982 }
983
984 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100985 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700986 warn!("Failed first boot");
987 fails += 1;
988 }
989
990 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700991 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700992 warn!("Failed image verification");
993 fails += 1;
994 }
David Brown84b49f72019-03-01 10:58:22 -0700995 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
996 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100997 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700998 fails += 1;
999 }
1000
1001 if fails > 0 {
1002 error!("Expected an upgrade failure when image has bad signature");
1003 }
1004
1005 fails > 0
1006 }
1007
Fabio Utzig2c3be5c2020-07-09 19:54:45 -03001008 // Should detect there is a leftover trailer in an otherwise erased
1009 // secondary slot and erase its trailer.
1010 pub fn run_secondary_leftover_trailer(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -06001011 if !Caps::modifies_flash() {
1012 return false;
1013 }
1014
Fabio Utzig2c3be5c2020-07-09 19:54:45 -03001015 let mut flash = self.flash.clone();
1016 let mut fails = 0;
1017
1018 info!("Try with a leftover trailer in the secondary; must be erased");
1019
1020 // Add a trailer on the secondary slot
1021 self.mark_permanent_upgrades(&mut flash, 1);
1022 self.mark_upgrades(&mut flash, 1);
1023
1024 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001025 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -03001026 warn!("Failed first boot");
1027 fails += 1;
1028 }
1029
1030 // State should not have changed
1031 if !self.verify_images(&flash, 0, 0) {
1032 warn!("Failed image verification");
1033 fails += 1;
1034 }
1035 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1036 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
1037 warn!("Mismatched trailer for the secondary slot");
1038 fails += 1;
1039 }
1040
1041 if fails > 0 {
1042 error!("Expected trailer on secondary slot to be erased");
1043 }
1044
1045 fails > 0
1046 }
1047
David Brown5c9e0f12019-01-09 16:34:33 -07001048 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -03001049 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -07001050 }
1051
David Brown5c9e0f12019-01-09 16:34:33 -07001052 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -03001053 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -07001054 }
1055
1056 /// This test runs a simple upgrade with no fails in the images, but
1057 /// allowing for fails in the status area. This should run to the end
1058 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -07001059 pub fn run_with_status_fails_complete(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -06001060 if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -07001061 return false;
1062 }
1063
David Brown76101572019-02-28 11:29:03 -07001064 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001065 let mut fails = 0;
1066
1067 info!("Try swap with status fails");
1068
David Brown84b49f72019-03-01 10:58:22 -07001069 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001070 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -07001071
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001072 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brownc423ac42021-06-04 13:47:34 -06001073 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -07001074 warn!("Failed!");
1075 fails += 1;
1076 }
1077
1078 // Failed writes to the marked "bad" region don't assert anymore.
1079 // Any detected assert() is happening in another part of the code.
David Brownc423ac42021-06-04 13:47:34 -06001080 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001081 warn!("At least one assert() was called");
1082 fails += 1;
1083 }
1084
David Brown84b49f72019-03-01 10:58:22 -07001085 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1086 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +01001087 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -07001088 fails += 1;
1089 }
1090
David Brown84b49f72019-03-01 10:58:22 -07001091 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -07001092 warn!("Failed image verification");
1093 fails += 1;
1094 }
1095
David Vincze2d736ad2019-02-18 11:50:22 +01001096 info!("validate primary slot enabled; \
1097 re-run of boot_go should just work");
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001098 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -07001099 warn!("Failed!");
1100 fails += 1;
1101 }
1102
1103 if fails > 0 {
1104 error!("Error running upgrade with status write fails");
1105 }
1106
1107 fails > 0
1108 }
1109
1110 /// This test runs a simple upgrade with no fails in the images, but
1111 /// allowing for fails in the status area. This should run to the end
1112 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -07001113 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -06001114 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -07001115 false
David Vincze2d736ad2019-02-18 11:50:22 +01001116 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -07001117
David Brown76101572019-02-28 11:29:03 -07001118 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001119 let mut fails = 0;
1120 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -07001121
David Brown85904a82019-01-11 13:45:12 -07001122 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -07001123
David Brown85904a82019-01-11 13:45:12 -07001124 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -07001125
David Brown84b49f72019-03-01 10:58:22 -07001126 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001127 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -07001128
1129 // Should not fail, writing to bad regions does not assert
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001130 let asserts = c::boot_go(&mut flash, &self.areadesc,
1131 Some(&mut count), None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001132 if asserts != 0 {
1133 warn!("At least one assert() was called");
1134 fails += 1;
1135 }
1136
David Brown76101572019-02-28 11:29:03 -07001137 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -07001138
1139 info!("Resuming an interrupted swap operation");
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001140 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1141 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001142
1143 // This might throw no asserts, for large sector devices, where
1144 // a single failure writing is indistinguishable from no failure,
1145 // or throw a single assert for small sector devices that fail
1146 // multiple times...
1147 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +01001148 warn!("Expected single assert validating the primary slot, \
1149 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -07001150 fails += 1;
1151 }
1152
1153 if fails > 0 {
1154 error!("Error running upgrade with status write fails");
1155 }
1156
1157 fails > 0
1158 } else {
David Brown76101572019-02-28 11:29:03 -07001159 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001160 let mut fails = 0;
1161
1162 info!("Try interrupted swap with status fails");
1163
David Brown84b49f72019-03-01 10:58:22 -07001164 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001165 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -07001166
1167 // This is expected to fail while writing to bad regions...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001168 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1169 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001170 if asserts == 0 {
1171 warn!("No assert() detected");
1172 fails += 1;
1173 }
1174
1175 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -07001176 }
David Brown5c9e0f12019-01-09 16:34:33 -07001177 }
1178
David Brown0dfb8102021-06-03 15:29:11 -06001179 /// Test the direct XIP configuration. With this mode, flash images are never moved, and the
1180 /// bootloader merely selects which partition is the proper one to boot.
1181 pub fn run_direct_xip(&self) -> bool {
1182 if !Caps::DirectXip.present() {
1183 return false;
1184 }
1185
1186 // Clone the flash so we can tell if unchanged.
1187 let mut flash = self.flash.clone();
1188
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001189 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brown0dfb8102021-06-03 15:29:11 -06001190
1191 // Ensure the boot was successful.
1192 let resp = if let Some(resp) = result.resp() {
1193 resp
1194 } else {
1195 panic!("Boot didn't return a valid result");
1196 };
1197
1198 // This configuration should always try booting from the first upgrade slot.
1199 if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
1200 assert_eq!(offset, resp.image_off as usize);
1201 assert_eq!(dev_id, resp.flash_dev_id);
1202 } else {
1203 panic!("Unable to find upgrade image");
1204 }
1205 false
1206 }
1207
David Brown8a4e23b2021-06-11 10:29:01 -06001208 /// Test the ram-loading.
1209 pub fn run_ram_load(&self) -> bool {
1210 if !Caps::RamLoad.present() {
1211 return false;
1212 }
1213
1214 // Clone the flash so we can tell if unchanged.
1215 let mut flash = self.flash.clone();
1216
David Brownf17d3912021-06-23 16:10:51 -06001217 // Setup ram based on the ram configuration we determined earlier for the images.
1218 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
David Brown8a4e23b2021-06-11 10:29:01 -06001219
David Brownf17d3912021-06-23 16:10:51 -06001220 // println!("Ram: {:#?}", self.ram);
David Brown8a4e23b2021-06-11 10:29:01 -06001221
David Brownf17d3912021-06-23 16:10:51 -06001222 // Verify that the images area loaded into this.
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001223 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None,
1224 None, true));
David Brown8a4e23b2021-06-11 10:29:01 -06001225 if !result.success() {
David Brownf17d3912021-06-23 16:10:51 -06001226 error!("Failed to execute ram-load");
David Brown8a4e23b2021-06-11 10:29:01 -06001227 return true;
1228 }
1229
David Brownf17d3912021-06-23 16:10:51 -06001230 // Verify each image.
1231 for image in &self.images {
1232 let place = self.ram.lookup(&image.slots[0]);
1233 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1234 place.size as usize);
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001235 let src_sz = image.upgrades.size();
1236 if src_sz > ram_image.len() {
David Brownf17d3912021-06-23 16:10:51 -06001237 error!("Image ended up too large, nonsensical");
1238 return true;
1239 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001240 let src_image = &image.upgrades.plain[0..src_sz];
1241 let ram_image = &ram_image[0..src_sz];
David Brownf17d3912021-06-23 16:10:51 -06001242 if ram_image != src_image {
1243 error!("Image not loaded correctly");
1244 return true;
1245 }
1246
1247 }
1248
1249 return false;
David Brown8a4e23b2021-06-11 10:29:01 -06001250 }
1251
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001252 /// Test the split ram-loading.
1253 pub fn run_split_ram_load(&self) -> bool {
1254 if !Caps::RamLoad.present() {
1255 return false;
1256 }
1257
1258 // Clone the flash so we can tell if unchanged.
1259 let mut flash = self.flash.clone();
1260
1261 // Setup ram based on the ram configuration we determined earlier for the images.
1262 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1263
1264 for (idx, _image) in (&self.images).iter().enumerate() {
1265 // Verify that the images area loaded into this.
1266 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc,
1267 None, Some(idx as i32), true));
1268 if !result.success() {
1269 error!("Failed to execute ram-load");
1270 return true;
1271 }
1272 }
1273
1274 // Verify each image.
1275 for image in &self.images {
1276 let place = self.ram.lookup(&image.slots[0]);
1277 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1278 place.size as usize);
1279 let src_sz = image.upgrades.size();
1280 if src_sz > ram_image.len() {
1281 error!("Image ended up too large, nonsensical");
1282 return true;
1283 }
1284 let src_image = &image.upgrades.plain[0..src_sz];
1285 let ram_image = &ram_image[0..src_sz];
1286 if ram_image != src_image {
1287 error!("Image not loaded correctly");
1288 return true;
1289 }
1290
1291 }
1292
1293 return false;
1294 }
1295
Roland Mikheld6703522023-04-27 14:24:30 +02001296 pub fn run_hw_rollback_prot(&self) -> bool {
1297 if !Caps::HwRollbackProtection.present() {
1298 return false;
1299 }
1300
1301 let mut flash = self.flash.clone();
1302
1303 // set the "stored" security counter to a fixed value.
1304 c::set_security_counter(0, 30);
1305
1306 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
1307
1308 if result.success() {
1309 warn!("Successful boot when it did not suppose to happen!");
1310 return true;
1311 }
1312 let counter_val = c::get_security_counter(0);
1313 if counter_val != 30 {
1314 warn!("Counter was changed when it did not suppose to!");
1315 return true;
1316 }
1317
1318 false
1319 }
1320
David Brown5c9e0f12019-01-09 16:34:33 -07001321 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -07001322 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001323 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -07001324 if Caps::OverwriteUpgrade.present() {
1325 return;
1326 }
1327
David Brown84b49f72019-03-01 10:58:22 -07001328 // Set this for each image.
1329 for image in &self.images {
1330 let dev_id = &image.slots[slot].dev_id;
1331 let dev = flash.get_mut(&dev_id).unwrap();
1332 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001333 let off = &image.slots[slot].base_off;
1334 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -07001335 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -07001336
David Brown84b49f72019-03-01 10:58:22 -07001337 // Mark the status area as a bad area
1338 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1339 }
David Brown5c9e0f12019-01-09 16:34:33 -07001340 }
1341
David Brown76101572019-02-28 11:29:03 -07001342 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001343 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001344 return;
1345 }
1346
David Brown84b49f72019-03-01 10:58:22 -07001347 for image in &self.images {
1348 let dev_id = &image.slots[slot].dev_id;
1349 let dev = flash.get_mut(&dev_id).unwrap();
1350 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001351
David Brown84b49f72019-03-01 10:58:22 -07001352 // Disabling write verification the only assert triggered by
1353 // boot_go should be checking for integrity of status bytes.
1354 dev.set_verify_writes(false);
1355 }
David Brown5c9e0f12019-01-09 16:34:33 -07001356 }
1357
David Browndb505822019-03-01 10:04:20 -07001358 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1359 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001360 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001361 // Clone the flash to have a new copy.
1362 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001363
Fabio Utziged4a5362019-07-30 12:43:23 -03001364 if permanent {
1365 self.mark_permanent_upgrades(&mut flash, 1);
1366 }
David Brown5c9e0f12019-01-09 16:34:33 -07001367
David Browndb505822019-03-01 10:04:20 -07001368 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001369
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001370 let (first_interrupted, count) = match c::boot_go(&mut flash,
1371 &self.areadesc,
1372 Some(&mut counter),
1373 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001374 x if x.interrupted() => (true, stop.unwrap()),
1375 x if x.success() => (false, -counter),
1376 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001377 };
David Brown5c9e0f12019-01-09 16:34:33 -07001378
David Browndb505822019-03-01 10:04:20 -07001379 counter = 0;
1380 if first_interrupted {
1381 // fl.dump();
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001382 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1383 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001384 x if x.interrupted() => panic!("Shouldn't stop again"),
1385 x if x.success() => (),
1386 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001387 }
1388 }
David Brown5c9e0f12019-01-09 16:34:33 -07001389
David Browndb505822019-03-01 10:04:20 -07001390 (flash, count - counter)
1391 }
1392
1393 fn try_revert(&self, count: usize) -> SimMultiFlash {
1394 let mut flash = self.flash.clone();
1395
1396 // fl.write_file("image0.bin").unwrap();
1397 for i in 0 .. count {
1398 info!("Running boot pass {}", i + 1);
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001399 assert!(c::boot_go(&mut flash, &self.areadesc, None, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001400 }
1401 flash
1402 }
1403
1404 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1405 let mut flash = self.flash.clone();
1406 let mut fails = 0;
1407
1408 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001409 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1410 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001411 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001412 fails += 1;
1413 }
1414
Fabio Utzig8af7f792019-07-30 12:40:01 -03001415 // In a multi-image setup, copy done might be set if any number of
1416 // images was already successfully swapped.
1417 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1418 warn!("copy_done should be unset");
1419 fails += 1;
1420 }
1421
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001422 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001423 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001424 fails += 1;
1425 }
1426
David Brown84b49f72019-03-01 10:58:22 -07001427 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001428 warn!("Image in the primary slot before revert is invalid at stop={}",
1429 stop);
1430 fails += 1;
1431 }
David Brown84b49f72019-03-01 10:58:22 -07001432 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001433 warn!("Image in the secondary slot before revert is invalid at stop={}",
1434 stop);
1435 fails += 1;
1436 }
David Brown84b49f72019-03-01 10:58:22 -07001437 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1438 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001439 warn!("Mismatched trailer for the primary slot before revert");
1440 fails += 1;
1441 }
David Brown84b49f72019-03-01 10:58:22 -07001442 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1443 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001444 warn!("Mismatched trailer for the secondary slot before revert");
1445 fails += 1;
1446 }
1447
1448 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001449 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001450 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1451 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001452 warn!("Should have stopped revert at interruption point");
1453 fails += 1;
1454 }
1455
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001456 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001457 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001458 fails += 1;
1459 }
1460
David Brown84b49f72019-03-01 10:58:22 -07001461 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001462 warn!("Image in the primary slot after revert is invalid at stop={}",
1463 stop);
1464 fails += 1;
1465 }
David Brown84b49f72019-03-01 10:58:22 -07001466 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001467 warn!("Image in the secondary slot after revert is invalid at stop={}",
1468 stop);
1469 fails += 1;
1470 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001471
David Brown84b49f72019-03-01 10:58:22 -07001472 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1473 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001474 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001475 fails += 1;
1476 }
David Brown84b49f72019-03-01 10:58:22 -07001477 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1478 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001479 warn!("Mismatched trailer for the secondary slot after revert");
1480 fails += 1;
1481 }
1482
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001483 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001484 warn!("Should have finished 3rd boot");
1485 fails += 1;
1486 }
1487
1488 if !self.verify_images(&flash, 0, 0) {
1489 warn!("Image in the primary slot is invalid on 1st boot after revert");
1490 fails += 1;
1491 }
1492 if !self.verify_images(&flash, 1, 1) {
1493 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1494 fails += 1;
1495 }
1496
David Browndb505822019-03-01 10:04:20 -07001497 fails > 0
1498 }
1499
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001500
David Browndb505822019-03-01 10:04:20 -07001501 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1502 let mut flash = self.flash.clone();
1503
David Brown84b49f72019-03-01 10:58:22 -07001504 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001505
1506 let mut rng = rand::thread_rng();
1507 let mut resets = vec![0i32; count];
1508 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001509 for reset in &mut resets {
David Brown9c6322f2021-08-19 13:03:39 -06001510 let reset_counter = rng.gen_range(1 ..= remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001511 let mut counter = reset_counter;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001512 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1513 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001514 x if x.interrupted() => (),
1515 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001516 }
1517 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001518 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001519 }
1520
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001521 match c::boot_go(&mut flash, &self.areadesc, None, None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001522 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1523 x if x.success() => (),
1524 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001525 }
David Brown5c9e0f12019-01-09 16:34:33 -07001526
David Browndb505822019-03-01 10:04:20 -07001527 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001528 }
David Brown84b49f72019-03-01 10:58:22 -07001529
1530 /// Verify the image in the given flash device, the specified slot
1531 /// against the expected image.
1532 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001533 self.images.iter().all(|image| {
1534 verify_image(flash, &image.slots[slot],
1535 match against {
1536 0 => &image.primaries,
1537 1 => &image.upgrades,
1538 _ => panic!("Invalid 'against'")
1539 })
1540 })
David Brown84b49f72019-03-01 10:58:22 -07001541 }
1542
David Brownc3898d62019-08-05 14:20:02 -06001543 /// Verify the images, according to the dependency test.
1544 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1545 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1546 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1547 if !verify_image(flash, &image.slots[0],
1548 match upgrade {
1549 UpgradeInfo::Upgraded => &image.upgrades,
1550 UpgradeInfo::Held => &image.primaries,
1551 }) {
1552 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1553 return true;
1554 }
1555 }
1556
1557 false
1558 }
1559
Fabio Utzig8af7f792019-07-30 12:40:01 -03001560 /// Verify that at least one of the trailers of the images have the
1561 /// specified values.
1562 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1563 magic: Option<u8>, image_ok: Option<u8>,
1564 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001565 self.images.iter().any(|image| {
1566 verify_trailer(flash, &image.slots[slot],
1567 magic, image_ok, copy_done)
1568 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001569 }
1570
David Brown84b49f72019-03-01 10:58:22 -07001571 /// Verify that the trailers of the images have the specified
1572 /// values.
1573 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1574 magic: Option<u8>, image_ok: Option<u8>,
1575 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001576 self.images.iter().all(|image| {
1577 verify_trailer(flash, &image.slots[slot],
1578 magic, image_ok, copy_done)
1579 })
David Brown84b49f72019-03-01 10:58:22 -07001580 }
1581
1582 /// Mark each of the images for permanent upgrade.
1583 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1584 for image in &self.images {
1585 mark_permanent_upgrade(flash, &image.slots[slot]);
1586 }
1587 }
1588
1589 /// Mark each of the images for permanent upgrade.
1590 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1591 for image in &self.images {
1592 mark_upgrade(flash, &image.slots[slot]);
1593 }
1594 }
David Brown297029a2019-08-13 14:29:51 -06001595
1596 /// Dump out the flash image(s) to one or more files for debugging
1597 /// purposes. The names will be written as either "{prefix}.mcubin" or
1598 /// "{prefix}-001.mcubin" depending on how many images there are.
1599 pub fn debug_dump(&self, prefix: &str) {
1600 for (id, fdev) in &self.flash {
1601 let name = if self.flash.len() == 1 {
1602 format!("{}.mcubin", prefix)
1603 } else {
1604 format!("{}-{:>0}.mcubin", prefix, id)
1605 };
1606 fdev.write_file(&name).unwrap();
1607 }
1608 }
David Brown5c9e0f12019-01-09 16:34:33 -07001609}
1610
David Brownbf32c272021-06-16 17:11:37 -06001611impl RamData {
David Brownf17d3912021-06-23 16:10:51 -06001612 // TODO: This is not correct. The second slot of each image should be at the same address as
1613 // the primary.
David Brownbf32c272021-06-16 17:11:37 -06001614 fn new(slots: &[[SlotInfo; 2]]) -> RamData {
1615 let mut addr = RAM_LOAD_ADDR;
1616 let mut places = BTreeMap::new();
David Brownf17d3912021-06-23 16:10:51 -06001617 // println!("Setup:-------------");
David Brownbf32c272021-06-16 17:11:37 -06001618 for imgs in slots {
1619 for si in imgs {
David Brownf17d3912021-06-23 16:10:51 -06001620 // println!("Setup: si: {:?}", si);
David Brownbf32c272021-06-16 17:11:37 -06001621 let offset = addr;
1622 let size = si.len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001623 places.insert(SlotKey {
1624 dev_id: si.dev_id,
David Brownf17d3912021-06-23 16:10:51 -06001625 base_off: si.base_off,
David Brownbf32c272021-06-16 17:11:37 -06001626 }, SlotPlace { offset, size });
David Brownf17d3912021-06-23 16:10:51 -06001627 // println!(" load: offset: {}, size: {}", offset, size);
David Brownbf32c272021-06-16 17:11:37 -06001628 }
David Brownf17d3912021-06-23 16:10:51 -06001629 addr += imgs[0].len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001630 }
1631 RamData {
1632 places,
1633 total: addr,
1634 }
1635 }
David Brownf17d3912021-06-23 16:10:51 -06001636
1637 /// Lookup the ram data associated with a given flash partition. We just panic if not present,
1638 /// because all slots used should be in the map.
1639 fn lookup(&self, slot: &SlotInfo) -> &SlotPlace {
1640 self.places.get(&SlotKey{dev_id: slot.dev_id, base_off: slot.base_off})
1641 .expect("RamData should contain all slots")
1642 }
David Brownbf32c272021-06-16 17:11:37 -06001643}
1644
David Brown5c9e0f12019-01-09 16:34:33 -07001645/// Show the flash layout.
1646#[allow(dead_code)]
1647fn show_flash(flash: &dyn Flash) {
1648 println!("---- Flash configuration ----");
1649 for sector in flash.sector_iter() {
1650 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1651 sector.num, sector.base, sector.size);
1652 }
David Brown599b2db2021-03-10 05:23:26 -07001653 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001654}
1655
David Browna62c3eb2021-10-25 16:32:40 -06001656#[derive(Debug)]
1657enum ImageSize {
1658 /// Make the image the specified given size.
1659 Given(usize),
1660 /// Make the image as large as it can be for the partition/device.
1661 Largest,
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001662 /// Make the image quite larger than it can be for the partition/device/
1663 Oversized,
David Browna62c3eb2021-10-25 16:32:40 -06001664}
1665
Andrzej Puzdrowski5b90dc82022-08-08 12:49:24 +02001666#[cfg(not(feature = "max-align-32"))]
1667fn tralier_estimation(dev: &dyn Flash) -> usize {
Andrzej Puzdrowski5b90dc82022-08-08 12:49:24 +02001668 c::boot_trailer_sz(dev.align() as u32) as usize
1669}
1670
1671#[cfg(feature = "max-align-32")]
1672fn tralier_estimation(dev: &dyn Flash) -> usize {
1673
1674 let sector_size = dev.sector_iter().next().unwrap().size as u32;
1675
1676 align_up(c::boot_trailer_sz(dev.align() as u32), sector_size) as usize
1677}
1678
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001679fn image_largest_trailer(dev: &dyn Flash) -> usize {
1680 // Using the header size we know, the trailer size, and the slot size, we can compute
1681 // the largest image possible.
1682 let trailer = if Caps::OverwriteUpgrade.present() {
1683 // This computation is incorrect, and we need to figure out the correct size.
1684 // c::boot_status_sz(dev.align() as u32) as usize
1685 16 + 4 * dev.align()
1686 } else if Caps::SwapUsingMove.present() {
1687 let sector_size = dev.sector_iter().next().unwrap().size as u32;
1688 align_up(c::boot_trailer_sz(dev.align() as u32), sector_size) as usize
1689 } else if Caps::SwapUsingScratch.present() {
1690 tralier_estimation(dev)
1691 } else {
1692 panic!("The maximum image size can't be calculated.")
1693 };
1694
1695 trailer
1696}
1697
David Brown5c9e0f12019-01-09 16:34:33 -07001698/// Install a "program" into the given image. This fakes the image header, or at least all of the
1699/// fields used by the given code. Returns a copy of the image that was written.
David Browna62c3eb2021-10-25 16:32:40 -06001700fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: ImageSize,
David Brownf17d3912021-06-23 16:10:51 -06001701 ram: &RamData,
Roland Mikheld6703522023-04-27 14:24:30 +02001702 deps: &dyn Depender, bad_sig: bool, security_counter:Option<u32>) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001703 let offset = slot.base_off;
1704 let slot_len = slot.len;
1705 let dev_id = slot.dev_id;
David Brown07dd5f02021-10-26 16:43:15 -06001706 let dev = flash.get_mut(&dev_id).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001707
David Brown43643dd2019-01-11 15:43:28 -07001708 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001709
Roland Mikheld6703522023-04-27 14:24:30 +02001710 tlv.set_security_counter(security_counter);
1711
David Brownc3898d62019-08-05 14:20:02 -06001712 // Add the dependencies early to the tlv.
1713 for dep in deps.my_deps(offset, slot.index) {
1714 tlv.add_dependency(deps.other_id(), &dep);
1715 }
1716
David Brown5c9e0f12019-01-09 16:34:33 -07001717 const HDR_SIZE: usize = 32;
1718
David Brownf17d3912021-06-23 16:10:51 -06001719 let place = ram.lookup(&slot);
1720 let load_addr = if Caps::RamLoad.present() {
1721 place.offset
1722 } else {
1723 0
1724 };
1725
David Browna62c3eb2021-10-25 16:32:40 -06001726 let len = match len {
1727 ImageSize::Given(size) => size,
David Brown07dd5f02021-10-26 16:43:15 -06001728 ImageSize::Largest => {
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001729 let trailer = image_largest_trailer(dev);
David Brown07dd5f02021-10-26 16:43:15 -06001730 let tlv_len = tlv.estimate_size();
1731 info!("slot: 0x{:x}, HDR: 0x{:x}, trailer: 0x{:x}",
1732 slot_len, HDR_SIZE, trailer);
1733 slot_len - HDR_SIZE - trailer - tlv_len
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001734 },
1735 ImageSize::Oversized => {
1736 let trailer = image_largest_trailer(dev);
1737 let tlv_len = tlv.estimate_size();
1738 info!("slot: 0x{:x}, HDR: 0x{:x}, trailer: 0x{:x}",
1739 slot_len, HDR_SIZE, trailer);
1740 // the overflow size is rougly estimated to work for all
1741 // configurations. It might be precise if tlv_len will be maked precise.
1742 slot_len - HDR_SIZE - trailer - tlv_len + dev.align()*4
David Brown07dd5f02021-10-26 16:43:15 -06001743 }
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001744
David Browna62c3eb2021-10-25 16:32:40 -06001745 };
1746
David Brown5c9e0f12019-01-09 16:34:33 -07001747 // Generate a boot header. Note that the size doesn't include the header.
1748 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001749 magic: tlv.get_magic(),
David Brownf17d3912021-06-23 16:10:51 -06001750 load_addr,
David Brown5c9e0f12019-01-09 16:34:33 -07001751 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001752 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001753 img_size: len as u32,
1754 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001755 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001756 _pad2: 0,
1757 };
1758
1759 let mut b_header = [0; HDR_SIZE];
1760 b_header[..32].clone_from_slice(header.as_raw());
1761 assert_eq!(b_header.len(), HDR_SIZE);
1762
1763 tlv.add_bytes(&b_header);
1764
1765 // The core of the image itself is just pseudorandom data.
1766 let mut b_img = vec![0; len];
1767 splat(&mut b_img, offset);
1768
David Browncb47dd72019-08-05 14:21:49 -06001769 // Add some information at the start of the payload to make it easier
1770 // to see what it is. This will fail if the image itself is too small.
1771 {
1772 let mut wr = Cursor::new(&mut b_img);
1773 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1774 offset, dev_id, slot).unwrap();
1775 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1776 }
1777
David Brown5c9e0f12019-01-09 16:34:33 -07001778 // TLV signatures work over plain image
1779 tlv.add_bytes(&b_img);
1780
1781 // Generate encrypted images
Salome Thirot6fdbf552021-05-14 16:46:14 +01001782 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1783 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001784 let mut b_encimg = vec![];
1785 if is_encrypted {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001786 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1787 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001788 tlv.generate_enc_key();
1789 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001790 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001791 b_encimg = b_img.clone();
Salome Thirot6fdbf552021-05-14 16:46:14 +01001792 if aes256 {
1793 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001794 let block = Aes256::new(&key);
1795 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001796 cipher.apply_keystream(&mut b_encimg);
1797 } else {
1798 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001799 let block = Aes128::new(&key);
1800 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001801 cipher.apply_keystream(&mut b_encimg);
1802 }
David Brown5c9e0f12019-01-09 16:34:33 -07001803 }
1804
1805 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001806 if bad_sig {
1807 tlv.corrupt_sig();
1808 }
1809 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001810
David Brown5c9e0f12019-01-09 16:34:33 -07001811 let mut buf = vec![];
1812 buf.append(&mut b_header.to_vec());
1813 buf.append(&mut b_img);
1814 buf.append(&mut b_tlv.clone());
1815
David Brown95de4502019-11-15 12:01:34 -07001816 // Pad the buffer to a multiple of the flash alignment.
1817 let align = dev.align();
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001818 let image_sz = buf.len();
David Brown95de4502019-11-15 12:01:34 -07001819 while buf.len() % align != 0 {
1820 buf.push(dev.erased_val());
1821 }
1822
David Brown5c9e0f12019-01-09 16:34:33 -07001823 let mut encbuf = vec![];
1824 if is_encrypted {
1825 encbuf.append(&mut b_header.to_vec());
1826 encbuf.append(&mut b_encimg);
1827 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001828
1829 while encbuf.len() % align != 0 {
1830 encbuf.push(dev.erased_val());
1831 }
David Brown5c9e0f12019-01-09 16:34:33 -07001832 }
1833
David Vincze2d736ad2019-02-18 11:50:22 +01001834 // Since images are always non-encrypted in the primary slot, we first write
1835 // an encrypted image, re-read to use for verification, erase + flash
1836 // un-encrypted. In the secondary slot the image is written un-encrypted,
1837 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001838
David Brown3b090212019-07-30 15:59:28 -06001839 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001840 let enc_copy: Option<Vec<u8>>;
1841
1842 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001843 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001844
1845 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001846 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001847
1848 enc_copy = Some(enc);
1849
David Brown76101572019-02-28 11:29:03 -07001850 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001851 } else {
1852 enc_copy = None;
1853 }
1854
David Brown76101572019-02-28 11:29:03 -07001855 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001856
1857 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001858 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001859
David Brownca234692019-02-28 11:22:19 -07001860 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001861 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001862 plain: copy,
1863 cipher: enc_copy,
1864 }
David Brown5c9e0f12019-01-09 16:34:33 -07001865 } else {
1866
David Brown76101572019-02-28 11:29:03 -07001867 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001868
1869 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001870 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001871
1872 let enc_copy: Option<Vec<u8>>;
1873
1874 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001875 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001876
David Brown76101572019-02-28 11:29:03 -07001877 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001878
1879 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001880 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001881
1882 enc_copy = Some(enc);
1883 } else {
1884 enc_copy = None;
1885 }
1886
David Brownca234692019-02-28 11:22:19 -07001887 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001888 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001889 plain: copy,
1890 cipher: enc_copy,
1891 }
David Brown5c9e0f12019-01-09 16:34:33 -07001892 }
David Brown5c9e0f12019-01-09 16:34:33 -07001893}
1894
David Brown873be312019-09-03 12:22:32 -06001895/// Install no image. This is used when no upgrade happens.
1896fn install_no_image() -> ImageData {
1897 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001898 size: 0,
David Brown873be312019-09-03 12:22:32 -06001899 plain: vec![],
1900 cipher: None,
1901 }
1902}
1903
David Brown0bd8c6b2021-10-22 16:33:06 -06001904/// Construct a TLV generator based on how MCUboot is currently configured. The returned
1905/// ManifestGen will generate the appropriate entries based on this configuration.
David Brown5c9e0f12019-01-09 16:34:33 -07001906fn make_tlv() -> TlvGen {
David Brownac655bb2021-10-22 16:33:27 -06001907 let aes_key_size = if Caps::Aes256.present() { 256 } else { 128 };
David Brown5c9e0f12019-01-09 16:34:33 -07001908
David Brownb8882112019-01-11 14:04:11 -07001909 if Caps::EncKw.present() {
1910 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001911 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001912 } else if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001913 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001914 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001915 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001916 }
1917 } else if Caps::EncRsa.present() {
1918 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001919 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001920 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001921 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001922 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001923 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001924 if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001925 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001926 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001927 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001928 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001929 } else if Caps::EncX25519.present() {
1930 if Caps::Ed25519.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001931 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001932 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001933 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001934 }
David Brownb8882112019-01-11 14:04:11 -07001935 } else {
1936 // The non-encrypted configuration.
1937 if Caps::RSA2048.present() {
1938 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001939 } else if Caps::RSA3072.present() {
1940 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001941 } else if Caps::EcdsaP256.present() {
1942 TlvGen::new_ecdsa()
Roland Mikhel30978512023-02-08 14:06:58 +01001943 } else if Caps::Ed25519.present() {
Fabio Utzig97710282019-05-24 17:44:49 -03001944 TlvGen::new_ed25519()
Roland Mikheld6703522023-04-27 14:24:30 +02001945 } else if Caps::HwRollbackProtection.present() {
1946 TlvGen::new_sec_cnt()
David Brownb8882112019-01-11 14:04:11 -07001947 } else {
1948 TlvGen::new_hash_only()
1949 }
1950 }
David Brown5c9e0f12019-01-09 16:34:33 -07001951}
1952
David Brownca234692019-02-28 11:22:19 -07001953impl ImageData {
1954 /// Find the image contents for the given slot. This assumes that slot 0
1955 /// is unencrypted, and slot 1 is encrypted.
1956 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001957 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001958 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001959 match (encrypted, slot) {
1960 (false, _) => &self.plain,
1961 (true, 0) => &self.plain,
1962 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1963 _ => panic!("Invalid slot requested"),
1964 }
David Brown5c9e0f12019-01-09 16:34:33 -07001965 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001966
1967 fn size(&self) -> usize {
1968 self.size
1969 }
David Brown5c9e0f12019-01-09 16:34:33 -07001970}
1971
David Brown5c9e0f12019-01-09 16:34:33 -07001972/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001973fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1974 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001975 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001976 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001977
1978 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001979 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001980 let dev = flash.get(&dev_id).unwrap();
1981 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001982
1983 if buf != &copy[..] {
1984 for i in 0 .. buf.len() {
1985 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001986 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1987 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001988 break;
1989 }
1990 }
1991 false
1992 } else {
1993 true
1994 }
1995}
1996
David Brown3b090212019-07-30 15:59:28 -06001997fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001998 magic: Option<u8>, image_ok: Option<u8>,
1999 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07002000 if Caps::OverwriteUpgrade.present() {
2001 return true;
2002 }
David Brown5c9e0f12019-01-09 16:34:33 -07002003
David Brown3b090212019-07-30 15:59:28 -06002004 let offset = slot.trailer_off + c::boot_max_align();
2005 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07002006 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07002007 let mut failed = false;
2008
David Brown76101572019-02-28 11:29:03 -07002009 let dev = flash.get(&dev_id).unwrap();
2010 let erased_val = dev.erased_val();
2011 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07002012
2013 failed |= match magic {
2014 Some(v) => {
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002015 let magic_off = (c::boot_max_align() * 3) + (c::boot_magic_sz() - MAGIC.len());
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002016 if v == 1 && &copy[magic_off..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07002017 warn!("\"magic\" mismatch at {:#x}", offset);
2018 true
2019 } else if v == 3 {
2020 let expected = [erased_val; 16];
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002021 if copy[magic_off..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07002022 warn!("\"magic\" mismatch at {:#x}", offset);
2023 true
2024 } else {
2025 false
2026 }
2027 } else {
2028 false
2029 }
2030 },
2031 None => false,
2032 };
2033
2034 failed |= match image_ok {
2035 Some(v) => {
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002036 let image_ok_off = c::boot_max_align() * 2;
2037 if (v == 1 && copy[image_ok_off] != v) || (v == 3 && copy[image_ok_off] != erased_val) {
2038 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[image_ok_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07002039 true
2040 } else {
2041 false
2042 }
2043 },
2044 None => false,
2045 };
2046
2047 failed |= match copy_done {
2048 Some(v) => {
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002049 let copy_done_off = c::boot_max_align();
2050 if (v == 1 && copy[copy_done_off] != v) || (v == 3 && copy[copy_done_off] != erased_val) {
2051 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[copy_done_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07002052 true
2053 } else {
2054 false
2055 }
2056 },
2057 None => false,
2058 };
2059
2060 !failed
2061}
2062
David Brown297029a2019-08-13 14:29:51 -06002063/// Install a partition table. This is a simplified partition table that
2064/// we write at the beginning of flash so make it easier for external tools
2065/// to analyze these images.
2066fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
2067 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
2068 for &id in &ids {
2069 // If there are any partitions in this device that start at 0, and
2070 // aren't marked as the BootLoader partition, avoid adding the
2071 // partition table. This makes it harder to view the image, but
2072 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07002073 let skip_ptable = areadesc
2074 .iter_areas()
2075 .any(|area| {
2076 area.device_id == id &&
2077 area.off == 0 &&
2078 area.flash_id != FlashId::BootLoader
2079 });
2080 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06002081 if log_enabled!(Info) {
2082 let special: Vec<FlashId> = areadesc.iter_areas()
2083 .filter(|area| area.device_id == id && area.off == 0)
2084 .map(|area| area.flash_id)
2085 .collect();
2086 info!("Skipping partition table: {:?}", special);
2087 }
2088 break;
2089 }
2090
2091 let mut buf: Vec<u8> = vec![];
2092 write!(&mut buf, "mcuboot\0").unwrap();
2093
2094 // Iterate through all of the partitions in that device, and encode
2095 // into the table.
2096 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
2097 buf.write_u32::<LittleEndian>(count as u32).unwrap();
2098
2099 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
2100 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
2101 buf.write_u32::<LittleEndian>(area.off).unwrap();
2102 buf.write_u32::<LittleEndian>(area.size).unwrap();
2103 buf.write_u32::<LittleEndian>(0).unwrap();
2104 }
2105
2106 let dev = flash.get_mut(&id).unwrap();
2107
2108 // Pad to alignment.
2109 while buf.len() % dev.align() != 0 {
2110 buf.push(0);
2111 }
2112
2113 dev.write(0, &buf).unwrap();
2114 }
2115}
2116
David Brown5c9e0f12019-01-09 16:34:33 -07002117/// The image header
2118#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07002119#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002120pub struct ImageHeader {
2121 magic: u32,
2122 load_addr: u32,
2123 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06002124 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07002125 img_size: u32,
2126 flags: u32,
2127 ver: ImageVersion,
2128 _pad2: u32,
2129}
2130
2131impl AsRaw for ImageHeader {}
2132
2133#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06002134#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002135pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06002136 pub major: u8,
2137 pub minor: u8,
2138 pub revision: u16,
2139 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07002140}
2141
David Brownc3898d62019-08-05 14:20:02 -06002142#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002143pub struct SlotInfo {
2144 pub base_off: usize,
2145 pub trailer_off: usize,
2146 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06002147 // Which slot within this device.
2148 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07002149 pub dev_id: u8,
2150}
2151
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002152#[cfg(not(feature = "max-align-32"))]
David Brown347dc572019-11-15 11:37:25 -07002153const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
2154 0x60, 0xd2, 0xef, 0x7f,
2155 0x35, 0x52, 0x50, 0x0f,
2156 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07002157
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002158#[cfg(feature = "max-align-32")]
2159const MAGIC: &[u8] = &[0x20, 0x00, 0x2d, 0xe1,
2160 0x5d, 0x29, 0x41, 0x0b,
2161 0x8d, 0x77, 0x67, 0x9c,
2162 0x11, 0x0f, 0x1f, 0x8a];
2163
David Brown5c9e0f12019-01-09 16:34:33 -07002164// Replicates defines found in bootutil.h
2165const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
2166const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
2167
2168const BOOT_FLAG_SET: Option<u8> = Some(1);
2169const BOOT_FLAG_UNSET: Option<u8> = Some(3);
2170
2171/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07002172pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
2173 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07002174 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07002175 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07002176 if offset % align != 0 || MAGIC.len() % align != 0 {
2177 // The write size is larger than the magic value. Fill a buffer
2178 // with the erased value, put the MAGIC in it, and write it in its
2179 // entirety.
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002180 let mut buf = vec![dev.erased_val(); c::boot_max_align()];
2181 let magic_off = (offset % align) + (c::boot_magic_sz() - MAGIC.len());
2182 buf[magic_off..].copy_from_slice(MAGIC);
David Brown95de4502019-11-15 12:01:34 -07002183 dev.write(offset - (offset % align), &buf).unwrap();
2184 } else {
2185 dev.write(offset, MAGIC).unwrap();
2186 }
David Brown5c9e0f12019-01-09 16:34:33 -07002187}
2188
2189/// Writes the image_ok flag which, guess what, tells the bootloader
2190/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07002191fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07002192 // Overwrite mode always is permanent, and only the magic is used in
2193 // the trailer. To avoid problems with large write sizes, don't try to
2194 // set anything in this case.
2195 if Caps::OverwriteUpgrade.present() {
2196 return;
2197 }
2198
David Brown76101572019-02-28 11:29:03 -07002199 let dev = flash.get_mut(&slot.dev_id).unwrap();
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002200 let align = dev.align();
2201 let mut ok = vec![dev.erased_val(); align];
David Brown5c9e0f12019-01-09 16:34:33 -07002202 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07002203 let off = slot.trailer_off + c::boot_max_align() * 3;
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002204 dev.write(off, &ok).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07002205}
2206
2207// Drop some pseudo-random gibberish onto the data.
2208fn splat(data: &mut [u8], seed: usize) {
David Brown9c6322f2021-08-19 13:03:39 -06002209 let mut seed_block = [0u8; 32];
David Browncd842842020-07-09 15:46:53 -06002210 let mut buf = Cursor::new(&mut seed_block[..]);
2211 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
2212 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
2213 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
2214 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
2215 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07002216 rng.fill_bytes(data);
2217}
2218
2219/// Return a read-only view into the raw bytes of this object
2220trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07002221 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07002222 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
2223 mem::size_of::<Self>()) }
2224 }
2225}
2226
David Brown07dd5f02021-10-26 16:43:15 -06002227/// Determine whether it makes sense to test this configuration with a maximally-sized image.
2228/// Returns an ImageSize representing the best size to test, possibly just with the given size.
2229fn maximal(size: usize) -> ImageSize {
2230 if Caps::OverwriteUpgrade.present() ||
2231 Caps::SwapUsingMove.present()
2232 {
2233 ImageSize::Given(size)
2234 } else {
2235 ImageSize::Largest
2236 }
2237}
2238
David Brown5c9e0f12019-01-09 16:34:33 -07002239pub fn show_sizes() {
2240 // This isn't panic safe.
2241 for min in &[1, 2, 4, 8] {
2242 let msize = c::boot_trailer_sz(*min);
2243 println!("{:2}: {} (0x{:x})", min, msize, msize);
2244 }
2245}
David Brown95de4502019-11-15 12:01:34 -07002246
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002247#[cfg(not(feature = "max-align-32"))]
David Brown95de4502019-11-15 12:01:34 -07002248fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07002249 &[1, 2, 4, 8]
2250}
2251
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002252#[cfg(feature = "max-align-32")]
David Brown95de4502019-11-15 12:01:34 -07002253fn test_alignments() -> &'static [usize] {
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002254 &[32]
David Brown95de4502019-11-15 12:01:34 -07002255}