blob: 4cd648832afcff82843ca0ebef4738854475270b [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 Brown9cc8dac2024-06-12 14:33:59 -060022 collections::{BTreeMap, HashSet}, io::{Cursor, Write}, mem, rc::Rc, slice
David Brown5c9e0f12019-01-09 16:34:33 -070023};
David Brown9c6322f2021-08-19 13:03:39 -060024use aes::{
25 Aes128,
David Brown5c9e0f12019-01-09 16:34:33 -070026 Aes128Ctr,
David Brown9c6322f2021-08-19 13:03:39 -060027 Aes256,
Salome Thirot6fdbf552021-05-14 16:46:14 +010028 Aes256Ctr,
David Brown9c6322f2021-08-19 13:03:39 -060029 NewBlockCipher,
David Brown5c9e0f12019-01-09 16:34:33 -070030};
David Brown9c6322f2021-08-19 13:03:39 -060031use cipher::{
32 FromBlockCipher,
33 generic_array::GenericArray,
34 StreamCipher,
35 };
David Brown5c9e0f12019-01-09 16:34:33 -070036
David Brown76101572019-02-28 11:29:03 -070037use simflash::{Flash, SimFlash, SimMultiFlash};
David Brown8a4e23b2021-06-11 10:29:01 -060038use mcuboot_sys::{c, AreaDesc, FlashId, RamBlock};
David Browne5133242019-02-28 11:05:19 -070039use crate::{
40 ALL_DEVICES,
41 DeviceName,
42};
David Brown5c9e0f12019-01-09 16:34:33 -070043use crate::caps::Caps;
David Brownc3898d62019-08-05 14:20:02 -060044use crate::depends::{
45 BoringDep,
46 Depender,
47 DepTest,
David Brown873be312019-09-03 12:22:32 -060048 DepType,
David Brown2ee5f7f2020-01-13 14:04:01 -070049 NO_DEPS,
David Brownc3898d62019-08-05 14:20:02 -060050 PairDep,
51 UpgradeInfo,
52};
Fabio Utzig90f449e2019-10-24 07:43:53 -030053use crate::tlv::{ManifestGen, TlvGen, TlvFlags};
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -030054use crate::utils::align_up;
Salome Thirot6fdbf552021-05-14 16:46:14 +010055use typenum::{U32, U16};
David Brown5c9e0f12019-01-09 16:34:33 -070056
David Brown8a4e23b2021-06-11 10:29:01 -060057/// For testing, use a non-zero offset for the ram-load, to make sure the offset is getting used
58/// properly, but the value is not really that important.
59const RAM_LOAD_ADDR: u32 = 1024;
60
David Browne5133242019-02-28 11:05:19 -070061/// A builder for Images. This describes a single run of the simulator,
62/// capturing the configuration of a particular set of devices, including
63/// the flash simulator(s) and the information about the slots.
64#[derive(Clone)]
65pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070066 flash: SimMultiFlash,
David Brown9cc8dac2024-06-12 14:33:59 -060067 areadesc: Rc<AreaDesc>,
David Brown84b49f72019-03-01 10:58:22 -070068 slots: Vec<[SlotInfo; 2]>,
David Brownbf32c272021-06-16 17:11:37 -060069 ram: RamData,
David Browne5133242019-02-28 11:05:19 -070070}
71
David Brown998aa8d2019-02-28 10:54:50 -070072/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070073/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070074/// and upgrades hold the expected contents of these images.
75pub struct Images {
David Brown76101572019-02-28 11:29:03 -070076 flash: SimMultiFlash,
David Brown9cc8dac2024-06-12 14:33:59 -060077 areadesc: Rc<AreaDesc>,
David Brown84b49f72019-03-01 10:58:22 -070078 images: Vec<OneImage>,
79 total_count: Option<i32>,
David Brownbf32c272021-06-16 17:11:37 -060080 ram: RamData,
David Brown84b49f72019-03-01 10:58:22 -070081}
82
83/// When doing multi-image, there is an instance of this information for
84/// each of the images. Single image there will be one of these.
85struct OneImage {
David Brownca234692019-02-28 11:22:19 -070086 slots: [SlotInfo; 2],
87 primaries: ImageData,
88 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070089}
90
91/// The Rust-side representation of an image. For unencrypted images, this
92/// is just the unencrypted payload. For encrypted images, we store both
93/// the encrypted and the plaintext.
94struct ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -030095 size: usize,
David Brownca234692019-02-28 11:22:19 -070096 plain: Vec<u8>,
97 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -070098}
99
David Brownbf32c272021-06-16 17:11:37 -0600100/// For the RamLoad test cases, we need a contiguous area of RAM to load these images into. For
101/// multi-image builds, these may not correspond with the offsets. This has to be computed early,
102/// before images are built, because each image contains the offset where the image is to be loaded
103/// in the header, which is contained within the signature.
104#[derive(Clone, Debug)]
105struct RamData {
106 places: BTreeMap<SlotKey, SlotPlace>,
107 total: u32,
108}
109
110/// Every slot is indexed by this key.
111#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
112struct SlotKey {
113 dev_id: u8,
David Brownf17d3912021-06-23 16:10:51 -0600114 base_off: usize,
David Brownbf32c272021-06-16 17:11:37 -0600115}
116
117#[derive(Clone, Debug)]
118struct SlotPlace {
119 offset: u32,
120 size: u32,
121}
122
Roland Mikhel6945bb62023-04-11 15:57:49 +0200123#[derive(Copy, Clone, Debug, Eq, PartialEq)]
124pub enum ImageManipulation {
125 None,
126 BadSignature,
127 WrongOffset,
128 IgnoreRamLoadFlag,
129 /// True to use same address,
130 /// false to overlap by 1 byte
131 OverlapImages(bool),
132 CorruptHigherVersionImage,
133}
134
135
David Browne5133242019-02-28 11:05:19 -0700136impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -0700137 /// Construct a new image builder for the given device. Returns
138 /// Some(builder) if is possible to test this configuration, or None if
139 /// not possible (for example, if there aren't enough image slots).
Fabio Utzig114a6472019-11-28 10:24:09 -0300140 pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
141 let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
142
143 for cap in unsupported_caps {
144 if cap.present() {
145 return Err(format!("unsupported {:?}", cap));
146 }
147 }
David Browne5133242019-02-28 11:05:19 -0700148
David Brown06ef06e2019-03-05 12:28:10 -0700149 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -0700150
David Brown06ef06e2019-03-05 12:28:10 -0700151 let mut slots = Vec::with_capacity(num_images);
152 for image in 0..num_images {
153 // This mapping must match that defined in
154 // `boot/zephyr/include/sysflash/sysflash.h`.
155 let id0 = match image {
156 0 => FlashId::Image0,
157 1 => FlashId::Image2,
158 _ => panic!("More than 2 images not supported"),
159 };
160 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
161 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300162 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700163 };
164 let id1 = match image {
165 0 => FlashId::Image1,
166 1 => FlashId::Image3,
167 _ => panic!("More than 2 images not supported"),
168 };
169 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
170 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300171 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700172 };
David Browne5133242019-02-28 11:05:19 -0700173
Christopher Collinsa1c12042019-05-23 14:00:28 -0700174 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700175
David Brown06ef06e2019-03-05 12:28:10 -0700176 // Construct a primary image.
177 let primary = SlotInfo {
178 base_off: primary_base as usize,
179 trailer_off: primary_base + primary_len - offset_from_end,
180 len: primary_len as usize,
181 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600182 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700183 };
184
185 // And an upgrade image.
186 let secondary = SlotInfo {
187 base_off: secondary_base as usize,
188 trailer_off: secondary_base + secondary_len - offset_from_end,
189 len: secondary_len as usize,
190 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600191 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700192 };
193
194 slots.push([primary, secondary]);
195 }
David Browne5133242019-02-28 11:05:19 -0700196
David Brownbf32c272021-06-16 17:11:37 -0600197 let ram = RamData::new(&slots);
198
Fabio Utzig114a6472019-11-28 10:24:09 -0300199 Ok(ImagesBuilder {
David Brown4dfb33c2021-03-10 05:15:45 -0700200 flash,
201 areadesc,
202 slots,
David Brownbf32c272021-06-16 17:11:37 -0600203 ram,
David Brown5bc62c62019-03-05 12:11:48 -0700204 })
David Browne5133242019-02-28 11:05:19 -0700205 }
206
207 pub fn each_device<F>(f: F)
208 where F: Fn(Self)
209 {
210 for &dev in ALL_DEVICES {
David Brown95de4502019-11-15 12:01:34 -0700211 for &align in test_alignments() {
David Browne5133242019-02-28 11:05:19 -0700212 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700213 match Self::new(dev, align, erased_val) {
Fabio Utzig114a6472019-11-28 10:24:09 -0300214 Ok(run) => f(run),
215 Err(msg) => warn!("Skipping {}: {}", dev, msg),
David Brown5bc62c62019-03-05 12:11:48 -0700216 }
David Browne5133242019-02-28 11:05:19 -0700217 }
218 }
219 }
220 }
221
222 /// Construct an `Images` that doesn't expect an upgrade to happen.
Roland Mikhel6945bb62023-04-11 15:57:49 +0200223 pub fn make_no_upgrade_image(self, deps: &DepTest, img_manipulation: ImageManipulation) -> Images {
David Brownc3898d62019-08-05 14:20:02 -0600224 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700225 let mut flash = self.flash;
Roland Mikhel6945bb62023-04-11 15:57:49 +0200226 let ram = self.ram.clone(); // TODO: Avoid this clone.
227 let mut higher_version_corrupted = false;
David Brownc3898d62019-08-05 14:20:02 -0600228 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
229 let dep: Box<dyn Depender> = if num_images > 1 {
230 Box::new(PairDep::new(num_images, image_num, deps))
231 } else {
David Brown2ee5f7f2020-01-13 14:04:01 -0700232 Box::new(BoringDep::new(image_num, deps))
David Brownc3898d62019-08-05 14:20:02 -0600233 };
Roland Mikhel6945bb62023-04-11 15:57:49 +0200234
235 let (primaries,upgrades) = if img_manipulation == ImageManipulation::CorruptHigherVersionImage && !higher_version_corrupted {
236 higher_version_corrupted = true;
237 let prim = install_image(&mut flash, &slots[0],
238 maximal(42784), &ram, &*dep, ImageManipulation::None, Some(0));
239 let upgr = match deps.depends[image_num] {
240 DepType::NoUpgrade => install_no_image(),
241 _ => install_image(&mut flash, &slots[1],
242 maximal(46928), &ram, &*dep, ImageManipulation::BadSignature, Some(0))
243 };
244 (prim, upgr)
245 } else {
246 let prim = install_image(&mut flash, &slots[0],
247 maximal(42784), &ram, &*dep, img_manipulation, Some(0));
248 let upgr = match deps.depends[image_num] {
249 DepType::NoUpgrade => install_no_image(),
250 _ => install_image(&mut flash, &slots[1],
251 maximal(46928), &ram, &*dep, img_manipulation, Some(0))
252 };
253 (prim, upgr)
David Brown873be312019-09-03 12:22:32 -0600254 };
David Brown84b49f72019-03-01 10:58:22 -0700255 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700256 slots,
257 primaries,
258 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700259 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600260 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700261 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700262 flash,
David Browne5133242019-02-28 11:05:19 -0700263 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700264 images,
David Browne5133242019-02-28 11:05:19 -0700265 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600266 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700267 }
268 }
269
David Brownc3898d62019-08-05 14:20:02 -0600270 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
Roland Mikhel6945bb62023-04-11 15:57:49 +0200271 let mut images = self.make_no_upgrade_image(deps, ImageManipulation::None);
David Brown84b49f72019-03-01 10:58:22 -0700272 for image in &images.images {
273 mark_upgrade(&mut images.flash, &image.slots[1]);
274 }
David Browne5133242019-02-28 11:05:19 -0700275
David Brown6db44d72021-05-26 16:22:58 -0600276 // The count is meaningless if no flash operations are performed.
277 if !Caps::modifies_flash() {
278 return images;
279 }
280
David Browne5133242019-02-28 11:05:19 -0700281 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300282 let total_count = match images.run_basic_upgrade(permanent) {
David Brown8973f552021-03-10 05:21:11 -0700283 Some(v) => v,
284 None =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600285 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
286 0
287 } else {
288 panic!("Unable to perform basic upgrade");
289 }
David Browne5133242019-02-28 11:05:19 -0700290 };
291
292 images.total_count = Some(total_count);
293 images
294 }
295
296 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700297 let mut bad_flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600298 let ram = self.ram.clone(); // TODO: Avoid this clone.
David Brownc3898d62019-08-05 14:20:02 -0600299 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
David Brown2ee5f7f2020-01-13 14:04:01 -0700300 let dep = BoringDep::new(image_num, &NO_DEPS);
David Browna62c3eb2021-10-25 16:32:40 -0600301 let primaries = install_image(&mut bad_flash, &slots[0],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200302 maximal(32784), &ram, &dep, ImageManipulation::None, Some(0));
David Browna62c3eb2021-10-25 16:32:40 -0600303 let upgrades = install_image(&mut bad_flash, &slots[1],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200304 maximal(41928), &ram, &dep, ImageManipulation::BadSignature, Some(0));
David Brown84b49f72019-03-01 10:58:22 -0700305 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700306 slots,
307 primaries,
308 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700309 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700310 Images {
David Brown76101572019-02-28 11:29:03 -0700311 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700312 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700313 images,
David Browne5133242019-02-28 11:05:19 -0700314 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600315 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700316 }
317 }
318
Andrzej Puzdrowski9324d2b2022-08-11 15:16:56 +0200319 pub fn make_oversized_secondary_slot_image(self) -> Images {
320 let mut bad_flash = self.flash;
321 let ram = self.ram.clone(); // TODO: Avoid this clone.
322 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
323 let dep = BoringDep::new(image_num, &NO_DEPS);
324 let primaries = install_image(&mut bad_flash, &slots[0],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200325 maximal(32784), &ram, &dep, ImageManipulation::None, Some(0));
Andrzej Puzdrowski9324d2b2022-08-11 15:16:56 +0200326 let upgrades = install_image(&mut bad_flash, &slots[1],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200327 ImageSize::Oversized, &ram, &dep, ImageManipulation::None, Some(0));
Andrzej Puzdrowski9324d2b2022-08-11 15:16:56 +0200328 OneImage {
329 slots,
330 primaries,
331 upgrades,
332 }}).collect();
333 Images {
334 flash: bad_flash,
335 areadesc: self.areadesc,
336 images,
337 total_count: None,
338 ram: self.ram,
339 }
340 }
341
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300342 pub fn make_erased_secondary_image(self) -> Images {
343 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600344 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300345 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
346 let dep = BoringDep::new(image_num, &NO_DEPS);
David Browna62c3eb2021-10-25 16:32:40 -0600347 let primaries = install_image(&mut flash, &slots[0],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200348 maximal(32784), &ram, &dep,ImageManipulation::None, Some(0));
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300349 let upgrades = install_no_image();
350 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700351 slots,
352 primaries,
353 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300354 }}).collect();
355 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700356 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300357 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700358 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300359 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600360 ram: self.ram,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300361 }
362 }
363
Fabio Utzigd0157342020-10-02 15:22:11 -0300364 pub fn make_bootstrap_image(self) -> Images {
365 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600366 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzigd0157342020-10-02 15:22:11 -0300367 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
368 let dep = BoringDep::new(image_num, &NO_DEPS);
369 let primaries = install_no_image();
David Browna62c3eb2021-10-25 16:32:40 -0600370 let upgrades = install_image(&mut flash, &slots[1],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200371 maximal(32784), &ram, &dep, ImageManipulation::None, Some(0));
Fabio Utzigd0157342020-10-02 15:22:11 -0300372 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700373 slots,
374 primaries,
375 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300376 }}).collect();
377 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700378 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300379 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700380 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300381 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600382 ram: self.ram,
Fabio Utzigd0157342020-10-02 15:22:11 -0300383 }
384 }
385
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +0200386 pub fn make_oversized_bootstrap_image(self) -> Images {
387 let mut flash = self.flash;
388 let ram = self.ram.clone(); // TODO: Avoid this clone.
389 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
390 let dep = BoringDep::new(image_num, &NO_DEPS);
391 let primaries = install_no_image();
392 let upgrades = install_image(&mut flash, &slots[1],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200393 ImageSize::Oversized, &ram, &dep, ImageManipulation::None, Some(0));
Roland Mikheld6703522023-04-27 14:24:30 +0200394 OneImage {
395 slots,
396 primaries,
397 upgrades,
398 }}).collect();
399 Images {
400 flash,
401 areadesc: self.areadesc,
402 images,
403 total_count: None,
404 ram: self.ram,
405 }
406 }
407
408 /// If security_cnt is None then do not add a security counter TLV, otherwise add the specified value.
409 pub fn make_image_with_security_counter(self, security_cnt: Option<u32>) -> Images {
410 let mut flash = self.flash;
411 let ram = self.ram.clone(); // TODO: Avoid this clone.
412 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
413 let dep = BoringDep::new(image_num, &NO_DEPS);
414 let primaries = install_image(&mut flash, &slots[0],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200415 maximal(32784), &ram, &dep, ImageManipulation::None, security_cnt);
Roland Mikheld6703522023-04-27 14:24:30 +0200416 let upgrades = install_image(&mut flash, &slots[1],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200417 maximal(41928), &ram, &dep, ImageManipulation::None, security_cnt.map(|v| v + 1));
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +0200418 OneImage {
419 slots,
420 primaries,
421 upgrades,
422 }}).collect();
423 Images {
424 flash,
425 areadesc: self.areadesc,
426 images,
427 total_count: None,
428 ram: self.ram,
429 }
430 }
431
David Browne5133242019-02-28 11:05:19 -0700432 /// Build the Flash and area descriptor for a given device.
David Brown9cc8dac2024-06-12 14:33:59 -0600433 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, Rc<AreaDesc>, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700434 match device {
435 DeviceName::Stm32f4 => {
436 // STM style flash. Large sectors, with a large scratch area.
Fabio Utzig5577cbd2021-12-10 17:34:28 -0300437 // The flash layout as described is not present in any real STM32F4 device, but it
438 // serves to exercise support for sectors of varying sizes inside a single slot,
439 // as long as they are compatible in both slots and all fit in the scratch.
440 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024, 64 * 1024,
441 32 * 1024, 32 * 1024, 64 * 1024,
442 32 * 1024, 32 * 1024, 64 * 1024,
443 128 * 1024],
David Brown76101572019-02-28 11:29:03 -0700444 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700445 let dev_id = 0;
446 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700447 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700448 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
449 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
450 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
451
David Brown76101572019-02-28 11:29:03 -0700452 let mut flash = SimMultiFlash::new();
453 flash.insert(dev_id, dev);
David Brown9cc8dac2024-06-12 14:33:59 -0600454 (flash, Rc::new(areadesc), &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700455 }
456 DeviceName::K64f => {
457 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700458 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700459
460 let dev_id = 0;
461 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700462 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700463 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
464 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
465 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
466
David Brown76101572019-02-28 11:29:03 -0700467 let mut flash = SimMultiFlash::new();
468 flash.insert(dev_id, dev);
David Brown9cc8dac2024-06-12 14:33:59 -0600469 (flash, Rc::new(areadesc), &[])
David Browne5133242019-02-28 11:05:19 -0700470 }
471 DeviceName::K64fBig => {
472 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
473 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700474 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700475
476 let dev_id = 0;
477 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700478 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700479 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
480 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
481 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
482
David Brown76101572019-02-28 11:29:03 -0700483 let mut flash = SimMultiFlash::new();
484 flash.insert(dev_id, dev);
David Brown9cc8dac2024-06-12 14:33:59 -0600485 (flash, Rc::new(areadesc), &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700486 }
487 DeviceName::Nrf52840 => {
488 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
489 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700490 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700491
492 let dev_id = 0;
493 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700494 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700495 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
496 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
497 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
498
David Brown76101572019-02-28 11:29:03 -0700499 let mut flash = SimMultiFlash::new();
500 flash.insert(dev_id, dev);
David Brown9cc8dac2024-06-12 14:33:59 -0600501 (flash, Rc::new(areadesc), &[])
David Browne5133242019-02-28 11:05:19 -0700502 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300503 DeviceName::Nrf52840UnequalSlots => {
504 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
505
506 let dev_id = 0;
507 let mut areadesc = AreaDesc::new();
508 areadesc.add_flash_sectors(dev_id, &dev);
509 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
510 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
511
512 let mut flash = SimMultiFlash::new();
513 flash.insert(dev_id, dev);
David Brown9cc8dac2024-06-12 14:33:59 -0600514 (flash, Rc::new(areadesc), &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
Fabio Utzigc659ec52020-07-13 21:18:48 -0300515 }
David Browne5133242019-02-28 11:05:19 -0700516 DeviceName::Nrf52840SpiFlash => {
517 // Simulate nrf52840 with external SPI flash. The external SPI flash
518 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700519 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
520 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700521
522 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700523 areadesc.add_flash_sectors(0, &dev0);
524 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700525
526 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
527 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
528 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
529
David Brown76101572019-02-28 11:29:03 -0700530 let mut flash = SimMultiFlash::new();
531 flash.insert(0, dev0);
532 flash.insert(1, dev1);
David Brown9cc8dac2024-06-12 14:33:59 -0600533 (flash, Rc::new(areadesc), &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700534 }
David Brown2bff6472019-03-05 13:58:35 -0700535 DeviceName::K64fMulti => {
536 // NXP style flash, but larger, to support multiple images.
537 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
538
539 let dev_id = 0;
540 let mut areadesc = AreaDesc::new();
541 areadesc.add_flash_sectors(dev_id, &dev);
542 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
543 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
544 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
545 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
546 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
547
548 let mut flash = SimMultiFlash::new();
549 flash.insert(dev_id, dev);
David Brown9cc8dac2024-06-12 14:33:59 -0600550 (flash, Rc::new(areadesc), &[])
David Brown2bff6472019-03-05 13:58:35 -0700551 }
David Browne5133242019-02-28 11:05:19 -0700552 }
553 }
David Brownc3898d62019-08-05 14:20:02 -0600554
555 pub fn num_images(&self) -> usize {
556 self.slots.len()
557 }
David Browne5133242019-02-28 11:05:19 -0700558}
559
David Brown5c9e0f12019-01-09 16:34:33 -0700560impl Images {
561 /// A simple upgrade without forced failures.
562 ///
563 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700564 /// inject failures at chosen steps. Returns None if it was unable to
565 /// count the operations in a basic upgrade.
566 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300567 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700568 info!("Total flash operation count={}", total_count);
569
David Brown84b49f72019-03-01 10:58:22 -0700570 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700571 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700572 None
David Brown5c9e0f12019-01-09 16:34:33 -0700573 } else {
David Brown8973f552021-03-10 05:21:11 -0700574 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700575 }
576 }
577
Fabio Utzigd0157342020-10-02 15:22:11 -0300578 pub fn run_bootstrap(&self) -> bool {
579 let mut flash = self.flash.clone();
580 let mut fails = 0;
581
582 if Caps::Bootstrap.present() {
583 info!("Try bootstraping image in the primary");
584
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100585 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigd0157342020-10-02 15:22:11 -0300586 warn!("Failed first boot");
587 fails += 1;
588 }
589
590 if !self.verify_images(&flash, 0, 1) {
591 warn!("Image in the first slot was not bootstrapped");
592 fails += 1;
593 }
594
595 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
596 BOOT_FLAG_SET, BOOT_FLAG_SET) {
597 warn!("Mismatched trailer for the primary slot");
598 fails += 1;
599 }
600 }
601
602 if fails > 0 {
603 error!("Expected trailer on secondary slot to be erased");
604 }
605
606 fails > 0
607 }
608
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +0200609 pub fn run_oversized_bootstrap(&self) -> bool {
610 let mut flash = self.flash.clone();
611 let mut fails = 0;
612
613 if Caps::Bootstrap.present() {
614 info!("Try bootstraping image in the primary");
615
616 let boot_result = c::boot_go(&mut flash, &self.areadesc, None, None, false).interrupted();
617
618 if boot_result {
619 warn!("Failed first boot");
620 fails += 1;
621 }
622
623 if self.verify_images(&flash, 0, 1) {
624 warn!("Image in the first slot was not bootstrapped");
625 fails += 1;
626 }
627
628 if self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
629 BOOT_FLAG_SET, BOOT_FLAG_SET) {
630 warn!("Mismatched trailer for the primary slot");
631 fails += 1;
632 }
633 }
634
635 if fails > 0 {
636 error!("Expected trailer on secondary slot to be erased");
637 }
638
639 fails > 0
640 }
641
Fabio Utzigd0157342020-10-02 15:22:11 -0300642
David Brownc3898d62019-08-05 14:20:02 -0600643 /// Test a simple upgrade, with dependencies given, and verify that the
644 /// image does as is described in the test.
645 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600646 if !Caps::modifies_flash() {
647 return false;
648 }
649
David Brownc3898d62019-08-05 14:20:02 -0600650 let (flash, _) = self.try_upgrade(None, true);
651
652 self.verify_dep_images(&flash, deps)
653 }
654
Fabio Utzigf5480c72019-11-28 10:41:57 -0300655 fn is_swap_upgrade(&self) -> bool {
656 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
657 }
658
David Brown5c9e0f12019-01-09 16:34:33 -0700659 pub fn run_basic_revert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600660 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700661 return false;
662 }
David Brown5c9e0f12019-01-09 16:34:33 -0700663
David Brown5c9e0f12019-01-09 16:34:33 -0700664 let mut fails = 0;
665
666 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300667 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700668 for count in 2 .. 5 {
669 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700670 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700671 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700672 error!("Revert failure on count {}", count);
673 fails += 1;
674 }
675 }
676 }
677
678 fails > 0
679 }
680
681 pub fn run_perm_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600682 if !Caps::modifies_flash() {
683 return false;
684 }
685
David Brown5c9e0f12019-01-09 16:34:33 -0700686 let mut fails = 0;
687 let total_flash_ops = self.total_count.unwrap();
688
David Brown80704f82024-04-11 10:42:10 -0600689 if skip_slow_test() {
690 return false;
691 }
692
David Brown5c9e0f12019-01-09 16:34:33 -0700693 // Let's try an image halfway through.
694 for i in 1 .. total_flash_ops {
695 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300696 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700697 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700698 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700699 warn!("FAIL at step {} of {}", i, total_flash_ops);
700 fails += 1;
701 }
702
David Brown84b49f72019-03-01 10:58:22 -0700703 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
704 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100705 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700706 fails += 1;
707 }
708
David Brown84b49f72019-03-01 10:58:22 -0700709 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
710 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100711 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700712 fails += 1;
713 }
714
David Brownaec56b22021-03-10 05:22:07 -0700715 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
716 warn!("Secondary slot FAIL at step {} of {}",
717 i, total_flash_ops);
718 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700719 }
720 }
721
722 if fails > 0 {
723 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
724 fails as f32 * 100.0 / total_flash_ops as f32);
725 }
726
727 fails > 0
728 }
729
David Brown5c9e0f12019-01-09 16:34:33 -0700730 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600731 if !Caps::modifies_flash() {
732 return false;
733 }
734
David Brown5c9e0f12019-01-09 16:34:33 -0700735 let mut fails = 0;
736 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700737 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700738 info!("Random interruptions at reset points={:?}", total_counts);
739
David Brown84b49f72019-03-01 10:58:22 -0700740 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300741 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700742 // TODO: This result is ignored.
743 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700744 } else {
745 true
746 };
David Vincze2d736ad2019-02-18 11:50:22 +0100747 if !primary_slot_ok || !secondary_slot_ok {
748 error!("Image mismatch after random interrupts: primary slot={} \
749 secondary slot={}",
750 if primary_slot_ok { "ok" } else { "fail" },
751 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700752 fails += 1;
753 }
David Brown84b49f72019-03-01 10:58:22 -0700754 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
755 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100756 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700757 fails += 1;
758 }
David Brown84b49f72019-03-01 10:58:22 -0700759 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
760 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100761 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700762 fails += 1;
763 }
764
765 if fails > 0 {
766 error!("Error testing perm upgrade with {} fails", total_fails);
767 }
768
769 fails > 0
770 }
771
David Brown5c9e0f12019-01-09 16:34:33 -0700772 pub fn run_revert_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600773 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700774 return false;
775 }
David Brown5c9e0f12019-01-09 16:34:33 -0700776
David Brown5c9e0f12019-01-09 16:34:33 -0700777 let mut fails = 0;
778
David Brown80704f82024-04-11 10:42:10 -0600779 if skip_slow_test() {
780 return false;
781 }
782
Fabio Utzigf5480c72019-11-28 10:41:57 -0300783 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300784 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700785 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700786 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700787 error!("Revert failed at interruption {}", i);
788 fails += 1;
789 }
790 }
791 }
792
793 fails > 0
794 }
795
David Brown5c9e0f12019-01-09 16:34:33 -0700796 pub fn run_norevert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600797 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700798 return false;
799 }
David Brown5c9e0f12019-01-09 16:34:33 -0700800
David Brown76101572019-02-28 11:29:03 -0700801 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700802 let mut fails = 0;
803
804 info!("Try norevert");
805
806 // First do a normal upgrade...
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 first boot");
809 fails += 1;
810 }
811
812 //FIXME: copy_done is written by boot_go, is it ok if no copy
813 // was ever done?
814
David Brown84b49f72019-03-01 10:58:22 -0700815 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100816 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700817 fails += 1;
818 }
David Brown84b49f72019-03-01 10:58:22 -0700819 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
820 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100821 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700822 fails += 1;
823 }
David Brown84b49f72019-03-01 10:58:22 -0700824 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
825 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100826 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700827 fails += 1;
828 }
829
David Vincze2d736ad2019-02-18 11:50:22 +0100830 // Marks image in the primary slot as permanent,
831 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700832 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700833
David Brown84b49f72019-03-01 10:58:22 -0700834 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
835 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100836 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700837 fails += 1;
838 }
839
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100840 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700841 warn!("Failed second boot");
842 fails += 1;
843 }
844
David Brown84b49f72019-03-01 10:58:22 -0700845 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
846 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100847 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700848 fails += 1;
849 }
David Brown84b49f72019-03-01 10:58:22 -0700850 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700851 warn!("Failed image verification");
852 fails += 1;
853 }
854
855 if fails > 0 {
856 error!("Error running upgrade without revert");
857 }
858
859 fails > 0
860 }
861
Andrzej Puzdrowski9324d2b2022-08-11 15:16:56 +0200862 // Test taht too big upgrade image will be rejected
863 pub fn run_oversizefail_upgrade(&self) -> bool {
864 let mut flash = self.flash.clone();
865 let mut fails = 0;
866
867 info!("Try upgrade image with to big size");
868
869 // Only perform this test if an upgrade is expected to happen.
870 if !Caps::modifies_flash() {
871 info!("Skipping upgrade image with bad signature");
872 return false;
873 }
874
875 self.mark_upgrades(&mut flash, 0);
876 self.mark_permanent_upgrades(&mut flash, 0);
877 self.mark_upgrades(&mut flash, 1);
878
879 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
880 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
881 warn!("1. Mismatched trailer for the primary slot");
882 fails += 1;
883 }
884
885 // Run the bootloader...
886 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
887 warn!("Failed first boot");
888 fails += 1;
889 }
890
891 // State should not have changed
892 if !self.verify_images(&flash, 0, 0) {
893 warn!("Failed image verification");
894 fails += 1;
895 }
896 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
897 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
898 warn!("2. Mismatched trailer for the primary slot");
899 fails += 1;
900 }
901
902 if fails > 0 {
903 error!("Expected an upgrade failure when image has to big size");
904 }
905
906 fails > 0
907 }
908
David Brown2ee5f7f2020-01-13 14:04:01 -0700909 // Test that an upgrade is rejected. Assumes that the image was build
910 // such that the upgrade is instead a downgrade.
911 pub fn run_nodowngrade(&self) -> bool {
912 if !Caps::DowngradePrevention.present() {
913 return false;
914 }
915
916 let mut flash = self.flash.clone();
917 let mut fails = 0;
918
919 info!("Try no downgrade");
920
921 // First, do a normal upgrade.
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100922 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700923 warn!("Failed first boot");
924 fails += 1;
925 }
926
927 if !self.verify_images(&flash, 0, 0) {
928 warn!("Failed verification after downgrade rejection");
929 fails += 1;
930 }
931
932 if fails > 0 {
933 error!("Error testing downgrade rejection");
934 }
935
936 fails > 0
937 }
938
David Vincze2d736ad2019-02-18 11:50:22 +0100939 // Tests a new image written to the primary slot that already has magic and
940 // image_ok set while there is no image on the secondary slot, so no revert
941 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700942 pub fn run_norevert_newimage(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600943 if !Caps::modifies_flash() {
944 info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
945 return false;
946 }
947
David Brown76101572019-02-28 11:29:03 -0700948 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700949 let mut fails = 0;
950
951 info!("Try non-revert on imgtool generated image");
952
David Brown84b49f72019-03-01 10:58:22 -0700953 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700954
David Vincze2d736ad2019-02-18 11:50:22 +0100955 // This simulates writing an image created by imgtool to
956 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700957 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
958 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100959 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700960 fails += 1;
961 }
962
963 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100964 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700965 warn!("Failed first boot");
966 fails += 1;
967 }
968
969 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700970 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700971 warn!("Failed image verification");
972 fails += 1;
973 }
David Brown84b49f72019-03-01 10:58:22 -0700974 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
975 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100976 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700977 fails += 1;
978 }
David Brown84b49f72019-03-01 10:58:22 -0700979 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
980 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100981 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700982 fails += 1;
983 }
984
985 if fails > 0 {
986 error!("Expected a non revert with new image");
987 }
988
989 fails > 0
990 }
991
David Vincze2d736ad2019-02-18 11:50:22 +0100992 // Tests a new image written to the primary slot that already has magic and
993 // image_ok set while there is no image on the secondary slot, so no revert
994 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700995 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700996 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700997 let mut fails = 0;
998
999 info!("Try upgrade image with bad signature");
1000
David Brown6db44d72021-05-26 16:22:58 -06001001 // Only perform this test if an upgrade is expected to happen.
1002 if !Caps::modifies_flash() {
1003 info!("Skipping upgrade image with bad signature");
1004 return false;
1005 }
1006
David Brown84b49f72019-03-01 10:58:22 -07001007 self.mark_upgrades(&mut flash, 0);
1008 self.mark_permanent_upgrades(&mut flash, 0);
1009 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -07001010
David Brown84b49f72019-03-01 10:58:22 -07001011 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1012 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +01001013 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -07001014 fails += 1;
1015 }
1016
1017 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001018 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -07001019 warn!("Failed first boot");
1020 fails += 1;
1021 }
1022
1023 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -07001024 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -07001025 warn!("Failed image verification");
1026 fails += 1;
1027 }
David Brown84b49f72019-03-01 10:58:22 -07001028 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1029 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +01001030 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -07001031 fails += 1;
1032 }
1033
1034 if fails > 0 {
1035 error!("Expected an upgrade failure when image has bad signature");
1036 }
1037
1038 fails > 0
1039 }
1040
Fabio Utzig2c3be5c2020-07-09 19:54:45 -03001041 // Should detect there is a leftover trailer in an otherwise erased
1042 // secondary slot and erase its trailer.
1043 pub fn run_secondary_leftover_trailer(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -06001044 if !Caps::modifies_flash() {
1045 return false;
1046 }
1047
Fabio Utzig2c3be5c2020-07-09 19:54:45 -03001048 let mut flash = self.flash.clone();
1049 let mut fails = 0;
1050
1051 info!("Try with a leftover trailer in the secondary; must be erased");
1052
1053 // Add a trailer on the secondary slot
1054 self.mark_permanent_upgrades(&mut flash, 1);
1055 self.mark_upgrades(&mut flash, 1);
1056
1057 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001058 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -03001059 warn!("Failed first boot");
1060 fails += 1;
1061 }
1062
1063 // State should not have changed
1064 if !self.verify_images(&flash, 0, 0) {
1065 warn!("Failed image verification");
1066 fails += 1;
1067 }
1068 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1069 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
1070 warn!("Mismatched trailer for the secondary slot");
1071 fails += 1;
1072 }
1073
1074 if fails > 0 {
1075 error!("Expected trailer on secondary slot to be erased");
1076 }
1077
1078 fails > 0
1079 }
1080
David Brown5c9e0f12019-01-09 16:34:33 -07001081 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -03001082 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -07001083 }
1084
David Brown5c9e0f12019-01-09 16:34:33 -07001085 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -03001086 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -07001087 }
1088
1089 /// This test runs a simple upgrade with no fails in the images, but
1090 /// allowing for fails in the status area. This should run to the end
1091 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -07001092 pub fn run_with_status_fails_complete(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -06001093 if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -07001094 return false;
1095 }
1096
David Brown76101572019-02-28 11:29:03 -07001097 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001098 let mut fails = 0;
1099
1100 info!("Try swap with status fails");
1101
David Brown84b49f72019-03-01 10:58:22 -07001102 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001103 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -07001104
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001105 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brownc423ac42021-06-04 13:47:34 -06001106 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -07001107 warn!("Failed!");
1108 fails += 1;
1109 }
1110
1111 // Failed writes to the marked "bad" region don't assert anymore.
1112 // Any detected assert() is happening in another part of the code.
David Brownc423ac42021-06-04 13:47:34 -06001113 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001114 warn!("At least one assert() was called");
1115 fails += 1;
1116 }
1117
David Brown84b49f72019-03-01 10:58:22 -07001118 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1119 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +01001120 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -07001121 fails += 1;
1122 }
1123
David Brown84b49f72019-03-01 10:58:22 -07001124 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -07001125 warn!("Failed image verification");
1126 fails += 1;
1127 }
1128
David Vincze2d736ad2019-02-18 11:50:22 +01001129 info!("validate primary slot enabled; \
1130 re-run of boot_go should just work");
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001131 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -07001132 warn!("Failed!");
1133 fails += 1;
1134 }
1135
1136 if fails > 0 {
1137 error!("Error running upgrade with status write fails");
1138 }
1139
1140 fails > 0
1141 }
1142
1143 /// This test runs a simple upgrade with no fails in the images, but
1144 /// allowing for fails in the status area. This should run to the end
1145 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -07001146 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -06001147 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -07001148 false
David Vincze2d736ad2019-02-18 11:50:22 +01001149 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -07001150
David Brown76101572019-02-28 11:29:03 -07001151 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001152 let mut fails = 0;
1153 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -07001154
David Brown85904a82019-01-11 13:45:12 -07001155 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -07001156
David Brown85904a82019-01-11 13:45:12 -07001157 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -07001158
David Brown84b49f72019-03-01 10:58:22 -07001159 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001160 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -07001161
1162 // Should not fail, writing to bad regions does not assert
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001163 let asserts = c::boot_go(&mut flash, &self.areadesc,
1164 Some(&mut count), None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001165 if asserts != 0 {
1166 warn!("At least one assert() was called");
1167 fails += 1;
1168 }
1169
David Brown76101572019-02-28 11:29:03 -07001170 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -07001171
1172 info!("Resuming an interrupted swap operation");
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001173 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1174 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001175
1176 // This might throw no asserts, for large sector devices, where
1177 // a single failure writing is indistinguishable from no failure,
1178 // or throw a single assert for small sector devices that fail
1179 // multiple times...
1180 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +01001181 warn!("Expected single assert validating the primary slot, \
1182 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -07001183 fails += 1;
1184 }
1185
1186 if fails > 0 {
1187 error!("Error running upgrade with status write fails");
1188 }
1189
1190 fails > 0
1191 } else {
David Brown76101572019-02-28 11:29:03 -07001192 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001193 let mut fails = 0;
1194
1195 info!("Try interrupted swap with status fails");
1196
David Brown84b49f72019-03-01 10:58:22 -07001197 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001198 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -07001199
1200 // This is expected to fail while writing to bad regions...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001201 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1202 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001203 if asserts == 0 {
1204 warn!("No assert() detected");
1205 fails += 1;
1206 }
1207
1208 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -07001209 }
David Brown5c9e0f12019-01-09 16:34:33 -07001210 }
1211
David Brown0dfb8102021-06-03 15:29:11 -06001212 /// Test the direct XIP configuration. With this mode, flash images are never moved, and the
1213 /// bootloader merely selects which partition is the proper one to boot.
1214 pub fn run_direct_xip(&self) -> bool {
1215 if !Caps::DirectXip.present() {
1216 return false;
1217 }
1218
1219 // Clone the flash so we can tell if unchanged.
1220 let mut flash = self.flash.clone();
1221
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001222 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brown0dfb8102021-06-03 15:29:11 -06001223
1224 // Ensure the boot was successful.
1225 let resp = if let Some(resp) = result.resp() {
1226 resp
1227 } else {
1228 panic!("Boot didn't return a valid result");
1229 };
1230
1231 // This configuration should always try booting from the first upgrade slot.
1232 if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
1233 assert_eq!(offset, resp.image_off as usize);
1234 assert_eq!(dev_id, resp.flash_dev_id);
1235 } else {
1236 panic!("Unable to find upgrade image");
1237 }
1238 false
1239 }
1240
David Brown8a4e23b2021-06-11 10:29:01 -06001241 /// Test the ram-loading.
1242 pub fn run_ram_load(&self) -> bool {
1243 if !Caps::RamLoad.present() {
1244 return false;
1245 }
1246
1247 // Clone the flash so we can tell if unchanged.
1248 let mut flash = self.flash.clone();
1249
David Brownf17d3912021-06-23 16:10:51 -06001250 // Setup ram based on the ram configuration we determined earlier for the images.
1251 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
David Brown8a4e23b2021-06-11 10:29:01 -06001252
David Brownf17d3912021-06-23 16:10:51 -06001253 // println!("Ram: {:#?}", self.ram);
David Brown8a4e23b2021-06-11 10:29:01 -06001254
David Brownf17d3912021-06-23 16:10:51 -06001255 // Verify that the images area loaded into this.
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001256 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None,
1257 None, true));
David Brown8a4e23b2021-06-11 10:29:01 -06001258 if !result.success() {
David Brownf17d3912021-06-23 16:10:51 -06001259 error!("Failed to execute ram-load");
David Brown8a4e23b2021-06-11 10:29:01 -06001260 return true;
1261 }
1262
David Brownf17d3912021-06-23 16:10:51 -06001263 // Verify each image.
1264 for image in &self.images {
1265 let place = self.ram.lookup(&image.slots[0]);
1266 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1267 place.size as usize);
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001268 let src_sz = image.upgrades.size();
1269 if src_sz > ram_image.len() {
David Brownf17d3912021-06-23 16:10:51 -06001270 error!("Image ended up too large, nonsensical");
1271 return true;
1272 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001273 let src_image = &image.upgrades.plain[0..src_sz];
1274 let ram_image = &ram_image[0..src_sz];
David Brownf17d3912021-06-23 16:10:51 -06001275 if ram_image != src_image {
1276 error!("Image not loaded correctly");
1277 return true;
1278 }
1279
1280 }
1281
1282 return false;
David Brown8a4e23b2021-06-11 10:29:01 -06001283 }
1284
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001285 /// Test the split ram-loading.
1286 pub fn run_split_ram_load(&self) -> bool {
1287 if !Caps::RamLoad.present() {
1288 return false;
1289 }
1290
1291 // Clone the flash so we can tell if unchanged.
1292 let mut flash = self.flash.clone();
1293
1294 // Setup ram based on the ram configuration we determined earlier for the images.
1295 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1296
1297 for (idx, _image) in (&self.images).iter().enumerate() {
1298 // Verify that the images area loaded into this.
1299 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc,
1300 None, Some(idx as i32), true));
1301 if !result.success() {
1302 error!("Failed to execute ram-load");
1303 return true;
1304 }
1305 }
1306
1307 // Verify each image.
1308 for image in &self.images {
1309 let place = self.ram.lookup(&image.slots[0]);
1310 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1311 place.size as usize);
1312 let src_sz = image.upgrades.size();
1313 if src_sz > ram_image.len() {
1314 error!("Image ended up too large, nonsensical");
1315 return true;
1316 }
1317 let src_image = &image.upgrades.plain[0..src_sz];
1318 let ram_image = &ram_image[0..src_sz];
1319 if ram_image != src_image {
1320 error!("Image not loaded correctly");
1321 return true;
1322 }
1323
1324 }
1325
1326 return false;
1327 }
1328
Roland Mikheld6703522023-04-27 14:24:30 +02001329 pub fn run_hw_rollback_prot(&self) -> bool {
1330 if !Caps::HwRollbackProtection.present() {
1331 return false;
1332 }
1333
1334 let mut flash = self.flash.clone();
1335
1336 // set the "stored" security counter to a fixed value.
1337 c::set_security_counter(0, 30);
1338
1339 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
1340
1341 if result.success() {
1342 warn!("Successful boot when it did not suppose to happen!");
1343 return true;
1344 }
1345 let counter_val = c::get_security_counter(0);
1346 if counter_val != 30 {
1347 warn!("Counter was changed when it did not suppose to!");
1348 return true;
1349 }
1350
1351 false
1352 }
1353
Roland Mikhel6945bb62023-04-11 15:57:49 +02001354 pub fn run_ram_load_boot_with_result(&self, expected_result: bool) -> bool {
1355 if !Caps::RamLoad.present() {
1356 return false;
1357 }
1358 // Clone the flash so we can tell if unchanged.
1359 let mut flash = self.flash.clone();
1360
1361 // Create RAM config.
1362 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1363
1364 // Run the bootloader, and verify that it couldn't run to completion.
1365 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None,
1366 None, true));
1367
1368 if result.success() != expected_result {
1369 error!("RAM load boot result was not of the expected value! (was: {}, expected: {})", result.success(), expected_result);
1370 return true;
1371 }
1372
1373 false
1374 }
1375
David Brown5c9e0f12019-01-09 16:34:33 -07001376 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -07001377 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001378 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -07001379 if Caps::OverwriteUpgrade.present() {
1380 return;
1381 }
1382
David Brown84b49f72019-03-01 10:58:22 -07001383 // Set this for each image.
1384 for image in &self.images {
1385 let dev_id = &image.slots[slot].dev_id;
1386 let dev = flash.get_mut(&dev_id).unwrap();
1387 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001388 let off = &image.slots[slot].base_off;
1389 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -07001390 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -07001391
David Brown84b49f72019-03-01 10:58:22 -07001392 // Mark the status area as a bad area
1393 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1394 }
David Brown5c9e0f12019-01-09 16:34:33 -07001395 }
1396
David Brown76101572019-02-28 11:29:03 -07001397 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001398 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001399 return;
1400 }
1401
David Brown84b49f72019-03-01 10:58:22 -07001402 for image in &self.images {
1403 let dev_id = &image.slots[slot].dev_id;
1404 let dev = flash.get_mut(&dev_id).unwrap();
1405 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001406
David Brown84b49f72019-03-01 10:58:22 -07001407 // Disabling write verification the only assert triggered by
1408 // boot_go should be checking for integrity of status bytes.
1409 dev.set_verify_writes(false);
1410 }
David Brown5c9e0f12019-01-09 16:34:33 -07001411 }
1412
David Browndb505822019-03-01 10:04:20 -07001413 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1414 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001415 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001416 // Clone the flash to have a new copy.
1417 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001418
Fabio Utziged4a5362019-07-30 12:43:23 -03001419 if permanent {
1420 self.mark_permanent_upgrades(&mut flash, 1);
1421 }
David Brown5c9e0f12019-01-09 16:34:33 -07001422
David Browndb505822019-03-01 10:04:20 -07001423 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001424
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001425 let (first_interrupted, count) = match c::boot_go(&mut flash,
1426 &self.areadesc,
1427 Some(&mut counter),
1428 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001429 x if x.interrupted() => (true, stop.unwrap()),
1430 x if x.success() => (false, -counter),
1431 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001432 };
David Brown5c9e0f12019-01-09 16:34:33 -07001433
David Browndb505822019-03-01 10:04:20 -07001434 counter = 0;
1435 if first_interrupted {
1436 // fl.dump();
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001437 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1438 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001439 x if x.interrupted() => panic!("Shouldn't stop again"),
1440 x if x.success() => (),
1441 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001442 }
1443 }
David Brown5c9e0f12019-01-09 16:34:33 -07001444
David Browndb505822019-03-01 10:04:20 -07001445 (flash, count - counter)
1446 }
1447
1448 fn try_revert(&self, count: usize) -> SimMultiFlash {
1449 let mut flash = self.flash.clone();
1450
1451 // fl.write_file("image0.bin").unwrap();
1452 for i in 0 .. count {
1453 info!("Running boot pass {}", i + 1);
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001454 assert!(c::boot_go(&mut flash, &self.areadesc, None, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001455 }
1456 flash
1457 }
1458
1459 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1460 let mut flash = self.flash.clone();
1461 let mut fails = 0;
1462
1463 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001464 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1465 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001466 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001467 fails += 1;
1468 }
1469
Fabio Utzig8af7f792019-07-30 12:40:01 -03001470 // In a multi-image setup, copy done might be set if any number of
1471 // images was already successfully swapped.
1472 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1473 warn!("copy_done should be unset");
1474 fails += 1;
1475 }
1476
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001477 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001478 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001479 fails += 1;
1480 }
1481
David Brown84b49f72019-03-01 10:58:22 -07001482 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001483 warn!("Image in the primary slot before revert is invalid at stop={}",
1484 stop);
1485 fails += 1;
1486 }
David Brown84b49f72019-03-01 10:58:22 -07001487 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001488 warn!("Image in the secondary slot before revert is invalid at stop={}",
1489 stop);
1490 fails += 1;
1491 }
David Brown84b49f72019-03-01 10:58:22 -07001492 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1493 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001494 warn!("Mismatched trailer for the primary slot before revert");
1495 fails += 1;
1496 }
David Brown84b49f72019-03-01 10:58:22 -07001497 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1498 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001499 warn!("Mismatched trailer for the secondary slot before revert");
1500 fails += 1;
1501 }
1502
1503 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001504 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001505 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1506 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001507 warn!("Should have stopped revert at interruption point");
1508 fails += 1;
1509 }
1510
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001511 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001512 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001513 fails += 1;
1514 }
1515
David Brown84b49f72019-03-01 10:58:22 -07001516 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001517 warn!("Image in the primary slot after revert is invalid at stop={}",
1518 stop);
1519 fails += 1;
1520 }
David Brown84b49f72019-03-01 10:58:22 -07001521 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001522 warn!("Image in the secondary slot after revert is invalid at stop={}",
1523 stop);
1524 fails += 1;
1525 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001526
David Brown84b49f72019-03-01 10:58:22 -07001527 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1528 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001529 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001530 fails += 1;
1531 }
David Brown84b49f72019-03-01 10:58:22 -07001532 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1533 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001534 warn!("Mismatched trailer for the secondary slot after revert");
1535 fails += 1;
1536 }
1537
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001538 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001539 warn!("Should have finished 3rd boot");
1540 fails += 1;
1541 }
1542
1543 if !self.verify_images(&flash, 0, 0) {
1544 warn!("Image in the primary slot is invalid on 1st boot after revert");
1545 fails += 1;
1546 }
1547 if !self.verify_images(&flash, 1, 1) {
1548 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1549 fails += 1;
1550 }
1551
David Browndb505822019-03-01 10:04:20 -07001552 fails > 0
1553 }
1554
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001555
David Browndb505822019-03-01 10:04:20 -07001556 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1557 let mut flash = self.flash.clone();
1558
David Brown84b49f72019-03-01 10:58:22 -07001559 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001560
1561 let mut rng = rand::thread_rng();
1562 let mut resets = vec![0i32; count];
1563 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001564 for reset in &mut resets {
David Brown9c6322f2021-08-19 13:03:39 -06001565 let reset_counter = rng.gen_range(1 ..= remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001566 let mut counter = reset_counter;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001567 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1568 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001569 x if x.interrupted() => (),
1570 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001571 }
1572 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001573 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001574 }
1575
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001576 match c::boot_go(&mut flash, &self.areadesc, None, None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001577 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1578 x if x.success() => (),
1579 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001580 }
David Brown5c9e0f12019-01-09 16:34:33 -07001581
David Browndb505822019-03-01 10:04:20 -07001582 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001583 }
David Brown84b49f72019-03-01 10:58:22 -07001584
1585 /// Verify the image in the given flash device, the specified slot
1586 /// against the expected image.
1587 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001588 self.images.iter().all(|image| {
1589 verify_image(flash, &image.slots[slot],
1590 match against {
1591 0 => &image.primaries,
1592 1 => &image.upgrades,
1593 _ => panic!("Invalid 'against'")
1594 })
1595 })
David Brown84b49f72019-03-01 10:58:22 -07001596 }
1597
David Brownc3898d62019-08-05 14:20:02 -06001598 /// Verify the images, according to the dependency test.
1599 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1600 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1601 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1602 if !verify_image(flash, &image.slots[0],
1603 match upgrade {
1604 UpgradeInfo::Upgraded => &image.upgrades,
1605 UpgradeInfo::Held => &image.primaries,
1606 }) {
1607 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1608 return true;
1609 }
1610 }
1611
1612 false
1613 }
1614
Fabio Utzig8af7f792019-07-30 12:40:01 -03001615 /// Verify that at least one of the trailers of the images have the
1616 /// specified values.
1617 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1618 magic: Option<u8>, image_ok: Option<u8>,
1619 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001620 self.images.iter().any(|image| {
1621 verify_trailer(flash, &image.slots[slot],
1622 magic, image_ok, copy_done)
1623 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001624 }
1625
David Brown84b49f72019-03-01 10:58:22 -07001626 /// Verify that the trailers of the images have the specified
1627 /// values.
1628 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1629 magic: Option<u8>, image_ok: Option<u8>,
1630 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001631 self.images.iter().all(|image| {
1632 verify_trailer(flash, &image.slots[slot],
1633 magic, image_ok, copy_done)
1634 })
David Brown84b49f72019-03-01 10:58:22 -07001635 }
1636
1637 /// Mark each of the images for permanent upgrade.
1638 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1639 for image in &self.images {
1640 mark_permanent_upgrade(flash, &image.slots[slot]);
1641 }
1642 }
1643
1644 /// Mark each of the images for permanent upgrade.
1645 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1646 for image in &self.images {
1647 mark_upgrade(flash, &image.slots[slot]);
1648 }
1649 }
David Brown297029a2019-08-13 14:29:51 -06001650
1651 /// Dump out the flash image(s) to one or more files for debugging
1652 /// purposes. The names will be written as either "{prefix}.mcubin" or
1653 /// "{prefix}-001.mcubin" depending on how many images there are.
1654 pub fn debug_dump(&self, prefix: &str) {
1655 for (id, fdev) in &self.flash {
1656 let name = if self.flash.len() == 1 {
1657 format!("{}.mcubin", prefix)
1658 } else {
1659 format!("{}-{:>0}.mcubin", prefix, id)
1660 };
1661 fdev.write_file(&name).unwrap();
1662 }
1663 }
David Brown5c9e0f12019-01-09 16:34:33 -07001664}
1665
David Brownbf32c272021-06-16 17:11:37 -06001666impl RamData {
David Brownf17d3912021-06-23 16:10:51 -06001667 // TODO: This is not correct. The second slot of each image should be at the same address as
1668 // the primary.
David Brownbf32c272021-06-16 17:11:37 -06001669 fn new(slots: &[[SlotInfo; 2]]) -> RamData {
1670 let mut addr = RAM_LOAD_ADDR;
1671 let mut places = BTreeMap::new();
David Brownf17d3912021-06-23 16:10:51 -06001672 // println!("Setup:-------------");
David Brownbf32c272021-06-16 17:11:37 -06001673 for imgs in slots {
1674 for si in imgs {
David Brownf17d3912021-06-23 16:10:51 -06001675 // println!("Setup: si: {:?}", si);
David Brownbf32c272021-06-16 17:11:37 -06001676 let offset = addr;
1677 let size = si.len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001678 places.insert(SlotKey {
1679 dev_id: si.dev_id,
David Brownf17d3912021-06-23 16:10:51 -06001680 base_off: si.base_off,
David Brownbf32c272021-06-16 17:11:37 -06001681 }, SlotPlace { offset, size });
David Brownf17d3912021-06-23 16:10:51 -06001682 // println!(" load: offset: {}, size: {}", offset, size);
David Brownbf32c272021-06-16 17:11:37 -06001683 }
David Brownf17d3912021-06-23 16:10:51 -06001684 addr += imgs[0].len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001685 }
1686 RamData {
1687 places,
1688 total: addr,
1689 }
1690 }
David Brownf17d3912021-06-23 16:10:51 -06001691
1692 /// Lookup the ram data associated with a given flash partition. We just panic if not present,
1693 /// because all slots used should be in the map.
1694 fn lookup(&self, slot: &SlotInfo) -> &SlotPlace {
1695 self.places.get(&SlotKey{dev_id: slot.dev_id, base_off: slot.base_off})
1696 .expect("RamData should contain all slots")
1697 }
David Brownbf32c272021-06-16 17:11:37 -06001698}
1699
David Brown5c9e0f12019-01-09 16:34:33 -07001700/// Show the flash layout.
1701#[allow(dead_code)]
1702fn show_flash(flash: &dyn Flash) {
1703 println!("---- Flash configuration ----");
1704 for sector in flash.sector_iter() {
1705 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1706 sector.num, sector.base, sector.size);
1707 }
David Brown599b2db2021-03-10 05:23:26 -07001708 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001709}
1710
David Browna62c3eb2021-10-25 16:32:40 -06001711#[derive(Debug)]
1712enum ImageSize {
1713 /// Make the image the specified given size.
1714 Given(usize),
1715 /// Make the image as large as it can be for the partition/device.
1716 Largest,
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001717 /// Make the image quite larger than it can be for the partition/device/
1718 Oversized,
David Browna62c3eb2021-10-25 16:32:40 -06001719}
1720
Andrzej Puzdrowski5b90dc82022-08-08 12:49:24 +02001721#[cfg(not(feature = "max-align-32"))]
1722fn tralier_estimation(dev: &dyn Flash) -> usize {
Andrzej Puzdrowski5b90dc82022-08-08 12:49:24 +02001723 c::boot_trailer_sz(dev.align() as u32) as usize
1724}
1725
1726#[cfg(feature = "max-align-32")]
1727fn tralier_estimation(dev: &dyn Flash) -> usize {
1728
1729 let sector_size = dev.sector_iter().next().unwrap().size as u32;
1730
1731 align_up(c::boot_trailer_sz(dev.align() as u32), sector_size) as usize
1732}
1733
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001734fn image_largest_trailer(dev: &dyn Flash) -> usize {
1735 // Using the header size we know, the trailer size, and the slot size, we can compute
1736 // the largest image possible.
1737 let trailer = if Caps::OverwriteUpgrade.present() {
1738 // This computation is incorrect, and we need to figure out the correct size.
1739 // c::boot_status_sz(dev.align() as u32) as usize
1740 16 + 4 * dev.align()
1741 } else if Caps::SwapUsingMove.present() {
1742 let sector_size = dev.sector_iter().next().unwrap().size as u32;
1743 align_up(c::boot_trailer_sz(dev.align() as u32), sector_size) as usize
1744 } else if Caps::SwapUsingScratch.present() {
1745 tralier_estimation(dev)
1746 } else {
1747 panic!("The maximum image size can't be calculated.")
1748 };
1749
1750 trailer
1751}
1752
David Brown5c9e0f12019-01-09 16:34:33 -07001753/// Install a "program" into the given image. This fakes the image header, or at least all of the
1754/// fields used by the given code. Returns a copy of the image that was written.
David Browna62c3eb2021-10-25 16:32:40 -06001755fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: ImageSize,
David Brownf17d3912021-06-23 16:10:51 -06001756 ram: &RamData,
Roland Mikhel6945bb62023-04-11 15:57:49 +02001757 deps: &dyn Depender, img_manipulation: ImageManipulation, security_counter:Option<u32>) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001758 let offset = slot.base_off;
1759 let slot_len = slot.len;
1760 let dev_id = slot.dev_id;
David Brown07dd5f02021-10-26 16:43:15 -06001761 let dev = flash.get_mut(&dev_id).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001762
David Brown43643dd2019-01-11 15:43:28 -07001763 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
Roland Mikhel6945bb62023-04-11 15:57:49 +02001764 if img_manipulation == ImageManipulation::IgnoreRamLoadFlag {
1765 tlv.set_ignore_ram_load_flag();
1766 }
David Brown5c9e0f12019-01-09 16:34:33 -07001767
Roland Mikheld6703522023-04-27 14:24:30 +02001768 tlv.set_security_counter(security_counter);
1769
Roland Mikhel6945bb62023-04-11 15:57:49 +02001770
David Brownc3898d62019-08-05 14:20:02 -06001771 // Add the dependencies early to the tlv.
1772 for dep in deps.my_deps(offset, slot.index) {
1773 tlv.add_dependency(deps.other_id(), &dep);
1774 }
1775
David Brown5c9e0f12019-01-09 16:34:33 -07001776 const HDR_SIZE: usize = 32;
David Brownf17d3912021-06-23 16:10:51 -06001777 let place = ram.lookup(&slot);
1778 let load_addr = if Caps::RamLoad.present() {
Roland Mikhel6945bb62023-04-11 15:57:49 +02001779 match img_manipulation {
1780 ImageManipulation::WrongOffset => u32::MAX,
1781 ImageManipulation::OverlapImages(true) => RAM_LOAD_ADDR,
1782 ImageManipulation::OverlapImages(false) => place.offset - 1,
1783 _ => place.offset
1784 }
David Brownf17d3912021-06-23 16:10:51 -06001785 } else {
1786 0
1787 };
1788
David Browna62c3eb2021-10-25 16:32:40 -06001789 let len = match len {
1790 ImageSize::Given(size) => size,
David Brown07dd5f02021-10-26 16:43:15 -06001791 ImageSize::Largest => {
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001792 let trailer = image_largest_trailer(dev);
David Brown07dd5f02021-10-26 16:43:15 -06001793 let tlv_len = tlv.estimate_size();
1794 info!("slot: 0x{:x}, HDR: 0x{:x}, trailer: 0x{:x}",
1795 slot_len, HDR_SIZE, trailer);
1796 slot_len - HDR_SIZE - trailer - tlv_len
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001797 },
1798 ImageSize::Oversized => {
1799 let trailer = image_largest_trailer(dev);
1800 let tlv_len = tlv.estimate_size();
1801 info!("slot: 0x{:x}, HDR: 0x{:x}, trailer: 0x{:x}",
1802 slot_len, HDR_SIZE, trailer);
1803 // the overflow size is rougly estimated to work for all
1804 // configurations. It might be precise if tlv_len will be maked precise.
1805 slot_len - HDR_SIZE - trailer - tlv_len + dev.align()*4
David Brown07dd5f02021-10-26 16:43:15 -06001806 }
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001807
David Browna62c3eb2021-10-25 16:32:40 -06001808 };
1809
David Brown5c9e0f12019-01-09 16:34:33 -07001810 // Generate a boot header. Note that the size doesn't include the header.
1811 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001812 magic: tlv.get_magic(),
David Brownf17d3912021-06-23 16:10:51 -06001813 load_addr,
David Brown5c9e0f12019-01-09 16:34:33 -07001814 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001815 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001816 img_size: len as u32,
1817 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001818 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001819 _pad2: 0,
1820 };
1821
1822 let mut b_header = [0; HDR_SIZE];
1823 b_header[..32].clone_from_slice(header.as_raw());
1824 assert_eq!(b_header.len(), HDR_SIZE);
1825
1826 tlv.add_bytes(&b_header);
1827
1828 // The core of the image itself is just pseudorandom data.
1829 let mut b_img = vec![0; len];
1830 splat(&mut b_img, offset);
1831
David Browncb47dd72019-08-05 14:21:49 -06001832 // Add some information at the start of the payload to make it easier
1833 // to see what it is. This will fail if the image itself is too small.
1834 {
1835 let mut wr = Cursor::new(&mut b_img);
1836 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1837 offset, dev_id, slot).unwrap();
1838 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1839 }
1840
David Brown5c9e0f12019-01-09 16:34:33 -07001841 // TLV signatures work over plain image
1842 tlv.add_bytes(&b_img);
1843
1844 // Generate encrypted images
Salome Thirot6fdbf552021-05-14 16:46:14 +01001845 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1846 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001847 let mut b_encimg = vec![];
1848 if is_encrypted {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001849 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1850 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001851 tlv.generate_enc_key();
1852 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001853 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001854 b_encimg = b_img.clone();
Salome Thirot6fdbf552021-05-14 16:46:14 +01001855 if aes256 {
1856 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001857 let block = Aes256::new(&key);
1858 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001859 cipher.apply_keystream(&mut b_encimg);
1860 } else {
1861 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001862 let block = Aes128::new(&key);
1863 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001864 cipher.apply_keystream(&mut b_encimg);
1865 }
David Brown5c9e0f12019-01-09 16:34:33 -07001866 }
1867
1868 // Build the TLV itself.
Roland Mikhel6945bb62023-04-11 15:57:49 +02001869 if img_manipulation == ImageManipulation::BadSignature {
David Browne90b13f2019-12-06 15:04:00 -07001870 tlv.corrupt_sig();
1871 }
1872 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001873
David Brown5c9e0f12019-01-09 16:34:33 -07001874 let mut buf = vec![];
1875 buf.append(&mut b_header.to_vec());
1876 buf.append(&mut b_img);
1877 buf.append(&mut b_tlv.clone());
1878
David Brown95de4502019-11-15 12:01:34 -07001879 // Pad the buffer to a multiple of the flash alignment.
1880 let align = dev.align();
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001881 let image_sz = buf.len();
David Brown95de4502019-11-15 12:01:34 -07001882 while buf.len() % align != 0 {
1883 buf.push(dev.erased_val());
1884 }
1885
David Brown5c9e0f12019-01-09 16:34:33 -07001886 let mut encbuf = vec![];
1887 if is_encrypted {
1888 encbuf.append(&mut b_header.to_vec());
1889 encbuf.append(&mut b_encimg);
1890 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001891
1892 while encbuf.len() % align != 0 {
1893 encbuf.push(dev.erased_val());
1894 }
David Brown5c9e0f12019-01-09 16:34:33 -07001895 }
1896
David Vincze2d736ad2019-02-18 11:50:22 +01001897 // Since images are always non-encrypted in the primary slot, we first write
1898 // an encrypted image, re-read to use for verification, erase + flash
1899 // un-encrypted. In the secondary slot the image is written un-encrypted,
1900 // and if encryption is requested, it follows an erase + flash encrypted.
Roland Mikhel820e9cc2023-05-09 14:30:16 +02001901 //
1902 // In the case of ram-load when encryption is enabled both slots have to
1903 // be encrypted so in the event when the image is in the primary slot
1904 // the verification will fail as the image is not encrypted.
1905 if slot.index == 0 && !Caps::RamLoad.present() {
David Brown5c9e0f12019-01-09 16:34:33 -07001906 let enc_copy: Option<Vec<u8>>;
1907
1908 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001909 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001910
1911 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001912 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001913
1914 enc_copy = Some(enc);
1915
David Brown76101572019-02-28 11:29:03 -07001916 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001917 } else {
1918 enc_copy = None;
1919 }
1920
David Brown76101572019-02-28 11:29:03 -07001921 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001922
1923 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001924 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001925
David Brownca234692019-02-28 11:22:19 -07001926 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001927 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001928 plain: copy,
1929 cipher: enc_copy,
1930 }
David Brown5c9e0f12019-01-09 16:34:33 -07001931 } else {
1932
David Brown76101572019-02-28 11:29:03 -07001933 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001934
1935 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001936 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001937
1938 let enc_copy: Option<Vec<u8>>;
1939
1940 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001941 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001942
David Brown76101572019-02-28 11:29:03 -07001943 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001944
1945 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001946 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001947
1948 enc_copy = Some(enc);
1949 } else {
1950 enc_copy = None;
1951 }
1952
David Brownca234692019-02-28 11:22:19 -07001953 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001954 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001955 plain: copy,
1956 cipher: enc_copy,
1957 }
David Brown5c9e0f12019-01-09 16:34:33 -07001958 }
David Brown5c9e0f12019-01-09 16:34:33 -07001959}
1960
David Brown873be312019-09-03 12:22:32 -06001961/// Install no image. This is used when no upgrade happens.
1962fn install_no_image() -> ImageData {
1963 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001964 size: 0,
David Brown873be312019-09-03 12:22:32 -06001965 plain: vec![],
1966 cipher: None,
1967 }
1968}
1969
David Brown0bd8c6b2021-10-22 16:33:06 -06001970/// Construct a TLV generator based on how MCUboot is currently configured. The returned
1971/// ManifestGen will generate the appropriate entries based on this configuration.
David Brown5c9e0f12019-01-09 16:34:33 -07001972fn make_tlv() -> TlvGen {
David Brownac655bb2021-10-22 16:33:27 -06001973 let aes_key_size = if Caps::Aes256.present() { 256 } else { 128 };
David Brown5c9e0f12019-01-09 16:34:33 -07001974
David Brownb8882112019-01-11 14:04:11 -07001975 if Caps::EncKw.present() {
1976 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001977 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001978 } else if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001979 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001980 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001981 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001982 }
1983 } else if Caps::EncRsa.present() {
1984 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001985 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001986 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001987 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001988 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001989 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001990 if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001991 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001992 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001993 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001994 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001995 } else if Caps::EncX25519.present() {
1996 if Caps::Ed25519.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001997 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001998 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001999 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03002000 }
David Brownb8882112019-01-11 14:04:11 -07002001 } else {
2002 // The non-encrypted configuration.
2003 if Caps::RSA2048.present() {
2004 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03002005 } else if Caps::RSA3072.present() {
2006 TlvGen::new_rsa3072_pss()
Roland Mikhel5899fac2023-03-14 13:59:55 +01002007 } else if Caps::EcdsaP256.present() || Caps::EcdsaP384.present() {
David Brownb8882112019-01-11 14:04:11 -07002008 TlvGen::new_ecdsa()
Roland Mikhel30978512023-02-08 14:06:58 +01002009 } else if Caps::Ed25519.present() {
Fabio Utzig97710282019-05-24 17:44:49 -03002010 TlvGen::new_ed25519()
Roland Mikheld6703522023-04-27 14:24:30 +02002011 } else if Caps::HwRollbackProtection.present() {
2012 TlvGen::new_sec_cnt()
David Brownb8882112019-01-11 14:04:11 -07002013 } else {
2014 TlvGen::new_hash_only()
2015 }
2016 }
David Brown5c9e0f12019-01-09 16:34:33 -07002017}
2018
David Brownca234692019-02-28 11:22:19 -07002019impl ImageData {
2020 /// Find the image contents for the given slot. This assumes that slot 0
2021 /// is unencrypted, and slot 1 is encrypted.
2022 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03002023 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03002024 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07002025 match (encrypted, slot) {
2026 (false, _) => &self.plain,
2027 (true, 0) => &self.plain,
2028 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
2029 _ => panic!("Invalid slot requested"),
2030 }
David Brown5c9e0f12019-01-09 16:34:33 -07002031 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03002032
2033 fn size(&self) -> usize {
2034 self.size
2035 }
David Brown5c9e0f12019-01-09 16:34:33 -07002036}
2037
David Brown5c9e0f12019-01-09 16:34:33 -07002038/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06002039fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
2040 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07002041 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06002042 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07002043
2044 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06002045 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07002046 let dev = flash.get(&dev_id).unwrap();
2047 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07002048
2049 if buf != &copy[..] {
2050 for i in 0 .. buf.len() {
2051 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06002052 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
2053 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07002054 break;
2055 }
2056 }
2057 false
2058 } else {
2059 true
2060 }
2061}
2062
David Brown3b090212019-07-30 15:59:28 -06002063fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07002064 magic: Option<u8>, image_ok: Option<u8>,
2065 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07002066 if Caps::OverwriteUpgrade.present() {
2067 return true;
2068 }
David Brown5c9e0f12019-01-09 16:34:33 -07002069
David Brown3b090212019-07-30 15:59:28 -06002070 let offset = slot.trailer_off + c::boot_max_align();
2071 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07002072 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07002073 let mut failed = false;
2074
David Brown76101572019-02-28 11:29:03 -07002075 let dev = flash.get(&dev_id).unwrap();
2076 let erased_val = dev.erased_val();
2077 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07002078
2079 failed |= match magic {
2080 Some(v) => {
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002081 let magic_off = (c::boot_max_align() * 3) + (c::boot_magic_sz() - MAGIC.len());
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002082 if v == 1 && &copy[magic_off..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07002083 warn!("\"magic\" mismatch at {:#x}", offset);
2084 true
2085 } else if v == 3 {
2086 let expected = [erased_val; 16];
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002087 if copy[magic_off..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07002088 warn!("\"magic\" mismatch at {:#x}", offset);
2089 true
2090 } else {
2091 false
2092 }
2093 } else {
2094 false
2095 }
2096 },
2097 None => false,
2098 };
2099
2100 failed |= match image_ok {
2101 Some(v) => {
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002102 let image_ok_off = c::boot_max_align() * 2;
2103 if (v == 1 && copy[image_ok_off] != v) || (v == 3 && copy[image_ok_off] != erased_val) {
2104 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[image_ok_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07002105 true
2106 } else {
2107 false
2108 }
2109 },
2110 None => false,
2111 };
2112
2113 failed |= match copy_done {
2114 Some(v) => {
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002115 let copy_done_off = c::boot_max_align();
2116 if (v == 1 && copy[copy_done_off] != v) || (v == 3 && copy[copy_done_off] != erased_val) {
2117 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[copy_done_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07002118 true
2119 } else {
2120 false
2121 }
2122 },
2123 None => false,
2124 };
2125
2126 !failed
2127}
2128
David Brown297029a2019-08-13 14:29:51 -06002129/// Install a partition table. This is a simplified partition table that
2130/// we write at the beginning of flash so make it easier for external tools
2131/// to analyze these images.
2132fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
2133 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
2134 for &id in &ids {
2135 // If there are any partitions in this device that start at 0, and
2136 // aren't marked as the BootLoader partition, avoid adding the
2137 // partition table. This makes it harder to view the image, but
2138 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07002139 let skip_ptable = areadesc
2140 .iter_areas()
2141 .any(|area| {
2142 area.device_id == id &&
2143 area.off == 0 &&
2144 area.flash_id != FlashId::BootLoader
2145 });
2146 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06002147 if log_enabled!(Info) {
2148 let special: Vec<FlashId> = areadesc.iter_areas()
2149 .filter(|area| area.device_id == id && area.off == 0)
2150 .map(|area| area.flash_id)
2151 .collect();
2152 info!("Skipping partition table: {:?}", special);
2153 }
2154 break;
2155 }
2156
2157 let mut buf: Vec<u8> = vec![];
2158 write!(&mut buf, "mcuboot\0").unwrap();
2159
2160 // Iterate through all of the partitions in that device, and encode
2161 // into the table.
2162 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
2163 buf.write_u32::<LittleEndian>(count as u32).unwrap();
2164
2165 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
2166 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
2167 buf.write_u32::<LittleEndian>(area.off).unwrap();
2168 buf.write_u32::<LittleEndian>(area.size).unwrap();
2169 buf.write_u32::<LittleEndian>(0).unwrap();
2170 }
2171
2172 let dev = flash.get_mut(&id).unwrap();
2173
2174 // Pad to alignment.
2175 while buf.len() % dev.align() != 0 {
2176 buf.push(0);
2177 }
2178
2179 dev.write(0, &buf).unwrap();
2180 }
2181}
2182
David Brown5c9e0f12019-01-09 16:34:33 -07002183/// The image header
2184#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07002185#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002186pub struct ImageHeader {
2187 magic: u32,
2188 load_addr: u32,
2189 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06002190 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07002191 img_size: u32,
2192 flags: u32,
2193 ver: ImageVersion,
2194 _pad2: u32,
2195}
2196
2197impl AsRaw for ImageHeader {}
2198
2199#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06002200#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002201pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06002202 pub major: u8,
2203 pub minor: u8,
2204 pub revision: u16,
2205 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07002206}
2207
David Brownc3898d62019-08-05 14:20:02 -06002208#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002209pub struct SlotInfo {
2210 pub base_off: usize,
2211 pub trailer_off: usize,
2212 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06002213 // Which slot within this device.
2214 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07002215 pub dev_id: u8,
2216}
2217
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002218#[cfg(not(feature = "max-align-32"))]
David Brown347dc572019-11-15 11:37:25 -07002219const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
2220 0x60, 0xd2, 0xef, 0x7f,
2221 0x35, 0x52, 0x50, 0x0f,
2222 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07002223
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002224#[cfg(feature = "max-align-32")]
2225const MAGIC: &[u8] = &[0x20, 0x00, 0x2d, 0xe1,
2226 0x5d, 0x29, 0x41, 0x0b,
2227 0x8d, 0x77, 0x67, 0x9c,
2228 0x11, 0x0f, 0x1f, 0x8a];
2229
David Brown5c9e0f12019-01-09 16:34:33 -07002230// Replicates defines found in bootutil.h
2231const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
2232const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
2233
2234const BOOT_FLAG_SET: Option<u8> = Some(1);
2235const BOOT_FLAG_UNSET: Option<u8> = Some(3);
2236
2237/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07002238pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
2239 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07002240 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07002241 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07002242 if offset % align != 0 || MAGIC.len() % align != 0 {
2243 // The write size is larger than the magic value. Fill a buffer
2244 // with the erased value, put the MAGIC in it, and write it in its
2245 // entirety.
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002246 let mut buf = vec![dev.erased_val(); c::boot_max_align()];
2247 let magic_off = (offset % align) + (c::boot_magic_sz() - MAGIC.len());
2248 buf[magic_off..].copy_from_slice(MAGIC);
David Brown95de4502019-11-15 12:01:34 -07002249 dev.write(offset - (offset % align), &buf).unwrap();
2250 } else {
2251 dev.write(offset, MAGIC).unwrap();
2252 }
David Brown5c9e0f12019-01-09 16:34:33 -07002253}
2254
2255/// Writes the image_ok flag which, guess what, tells the bootloader
2256/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07002257fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07002258 // Overwrite mode always is permanent, and only the magic is used in
2259 // the trailer. To avoid problems with large write sizes, don't try to
2260 // set anything in this case.
2261 if Caps::OverwriteUpgrade.present() {
2262 return;
2263 }
2264
David Brown76101572019-02-28 11:29:03 -07002265 let dev = flash.get_mut(&slot.dev_id).unwrap();
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002266 let align = dev.align();
2267 let mut ok = vec![dev.erased_val(); align];
David Brown5c9e0f12019-01-09 16:34:33 -07002268 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07002269 let off = slot.trailer_off + c::boot_max_align() * 3;
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002270 dev.write(off, &ok).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07002271}
2272
2273// Drop some pseudo-random gibberish onto the data.
2274fn splat(data: &mut [u8], seed: usize) {
David Brown9c6322f2021-08-19 13:03:39 -06002275 let mut seed_block = [0u8; 32];
David Browncd842842020-07-09 15:46:53 -06002276 let mut buf = Cursor::new(&mut seed_block[..]);
2277 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
2278 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
2279 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
2280 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
2281 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07002282 rng.fill_bytes(data);
2283}
2284
2285/// Return a read-only view into the raw bytes of this object
2286trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07002287 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07002288 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
2289 mem::size_of::<Self>()) }
2290 }
2291}
2292
David Brown07dd5f02021-10-26 16:43:15 -06002293/// Determine whether it makes sense to test this configuration with a maximally-sized image.
2294/// Returns an ImageSize representing the best size to test, possibly just with the given size.
2295fn maximal(size: usize) -> ImageSize {
2296 if Caps::OverwriteUpgrade.present() ||
2297 Caps::SwapUsingMove.present()
2298 {
2299 ImageSize::Given(size)
2300 } else {
2301 ImageSize::Largest
2302 }
2303}
2304
David Brown5c9e0f12019-01-09 16:34:33 -07002305pub fn show_sizes() {
2306 // This isn't panic safe.
2307 for min in &[1, 2, 4, 8] {
2308 let msize = c::boot_trailer_sz(*min);
2309 println!("{:2}: {} (0x{:x})", min, msize, msize);
2310 }
2311}
David Brown95de4502019-11-15 12:01:34 -07002312
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002313#[cfg(not(feature = "max-align-32"))]
David Brown95de4502019-11-15 12:01:34 -07002314fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07002315 &[1, 2, 4, 8]
2316}
2317
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002318#[cfg(feature = "max-align-32")]
David Brown95de4502019-11-15 12:01:34 -07002319fn test_alignments() -> &'static [usize] {
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002320 &[32]
David Brown95de4502019-11-15 12:01:34 -07002321}
David Brown80704f82024-04-11 10:42:10 -06002322
2323/// For testing, some of the tests are quite slow. This will query for an
2324/// environment variable `MCUBOOT_SKIP_SLOW_TESTS`, which can be set to avoid
2325/// running these tests.
2326fn skip_slow_test() -> bool {
2327 if let Ok(_) = std::env::var("MCUBOOT_SKIP_SLOW_TESTS") {
2328 true
2329 } else {
2330 false
2331 }
2332}