blob: 270ef248a3d8d4ca5b0dfb768067fa0524601c4d [file] [log] [blame]
David Brownc8d62012021-10-27 15:03:48 -06001// Copyright (c) 2019-2021 Linaro LTD
David Browne2acfae2020-01-21 16:45:01 -07002// Copyright (c) 2019-2020 JUUL Labs
Roland Mikhel75c7c312023-02-23 15:39:14 +01003// Copyright (c) 2019-2023 Arm Limited
David Browne2acfae2020-01-21 16:45:01 -07004//
5// SPDX-License-Identifier: Apache-2.0
6
David Brown297029a2019-08-13 14:29:51 -06007use byteorder::{
8 LittleEndian, WriteBytesExt,
9};
10use log::{
11 Level::Info,
12 error,
13 info,
14 log_enabled,
15 warn,
16};
David Brown5c9e0f12019-01-09 16:34:33 -070017use rand::{
David Browncd842842020-07-09 15:46:53 -060018 Rng, RngCore, SeedableRng,
19 rngs::SmallRng,
David Brown5c9e0f12019-01-09 16:34:33 -070020};
21use std::{
David Brownbf32c272021-06-16 17:11:37 -060022 collections::{BTreeMap, HashSet},
David Browncb47dd72019-08-05 14:21:49 -060023 io::{Cursor, Write},
David Brown5c9e0f12019-01-09 16:34:33 -070024 mem,
25 slice,
26};
David Brown9c6322f2021-08-19 13:03:39 -060027use aes::{
28 Aes128,
David Brown5c9e0f12019-01-09 16:34:33 -070029 Aes128Ctr,
David Brown9c6322f2021-08-19 13:03:39 -060030 Aes256,
Salome Thirot6fdbf552021-05-14 16:46:14 +010031 Aes256Ctr,
David Brown9c6322f2021-08-19 13:03:39 -060032 NewBlockCipher,
David Brown5c9e0f12019-01-09 16:34:33 -070033};
David Brown9c6322f2021-08-19 13:03:39 -060034use cipher::{
35 FromBlockCipher,
36 generic_array::GenericArray,
37 StreamCipher,
38 };
David Brown5c9e0f12019-01-09 16:34:33 -070039
David Brown76101572019-02-28 11:29:03 -070040use simflash::{Flash, SimFlash, SimMultiFlash};
David Brown8a4e23b2021-06-11 10:29:01 -060041use mcuboot_sys::{c, AreaDesc, FlashId, RamBlock};
David Browne5133242019-02-28 11:05:19 -070042use crate::{
43 ALL_DEVICES,
44 DeviceName,
45};
David Brown5c9e0f12019-01-09 16:34:33 -070046use crate::caps::Caps;
David Brownc3898d62019-08-05 14:20:02 -060047use crate::depends::{
48 BoringDep,
49 Depender,
50 DepTest,
David Brown873be312019-09-03 12:22:32 -060051 DepType,
David Brown2ee5f7f2020-01-13 14:04:01 -070052 NO_DEPS,
David Brownc3898d62019-08-05 14:20:02 -060053 PairDep,
54 UpgradeInfo,
55};
Fabio Utzig90f449e2019-10-24 07:43:53 -030056use crate::tlv::{ManifestGen, TlvGen, TlvFlags};
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -030057use crate::utils::align_up;
Salome Thirot6fdbf552021-05-14 16:46:14 +010058use typenum::{U32, U16};
David Brown5c9e0f12019-01-09 16:34:33 -070059
David Brown8a4e23b2021-06-11 10:29:01 -060060/// For testing, use a non-zero offset for the ram-load, to make sure the offset is getting used
61/// properly, but the value is not really that important.
62const RAM_LOAD_ADDR: u32 = 1024;
63
David Browne5133242019-02-28 11:05:19 -070064/// A builder for Images. This describes a single run of the simulator,
65/// capturing the configuration of a particular set of devices, including
66/// the flash simulator(s) and the information about the slots.
67#[derive(Clone)]
68pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070069 flash: SimMultiFlash,
David Browne5133242019-02-28 11:05:19 -070070 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070071 slots: Vec<[SlotInfo; 2]>,
David Brownbf32c272021-06-16 17:11:37 -060072 ram: RamData,
David Browne5133242019-02-28 11:05:19 -070073}
74
David Brown998aa8d2019-02-28 10:54:50 -070075/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070076/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070077/// and upgrades hold the expected contents of these images.
78pub struct Images {
David Brown76101572019-02-28 11:29:03 -070079 flash: SimMultiFlash,
David Brownca234692019-02-28 11:22:19 -070080 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070081 images: Vec<OneImage>,
82 total_count: Option<i32>,
David Brownbf32c272021-06-16 17:11:37 -060083 ram: RamData,
David Brown84b49f72019-03-01 10:58:22 -070084}
85
86/// When doing multi-image, there is an instance of this information for
87/// each of the images. Single image there will be one of these.
88struct OneImage {
David Brownca234692019-02-28 11:22:19 -070089 slots: [SlotInfo; 2],
90 primaries: ImageData,
91 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070092}
93
94/// The Rust-side representation of an image. For unencrypted images, this
95/// is just the unencrypted payload. For encrypted images, we store both
96/// the encrypted and the plaintext.
97struct ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -030098 size: usize,
David Brownca234692019-02-28 11:22:19 -070099 plain: Vec<u8>,
100 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -0700101}
102
David Brownbf32c272021-06-16 17:11:37 -0600103/// For the RamLoad test cases, we need a contiguous area of RAM to load these images into. For
104/// multi-image builds, these may not correspond with the offsets. This has to be computed early,
105/// before images are built, because each image contains the offset where the image is to be loaded
106/// in the header, which is contained within the signature.
107#[derive(Clone, Debug)]
108struct RamData {
109 places: BTreeMap<SlotKey, SlotPlace>,
110 total: u32,
111}
112
113/// Every slot is indexed by this key.
114#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
115struct SlotKey {
116 dev_id: u8,
David Brownf17d3912021-06-23 16:10:51 -0600117 base_off: usize,
David Brownbf32c272021-06-16 17:11:37 -0600118}
119
120#[derive(Clone, Debug)]
121struct SlotPlace {
122 offset: u32,
123 size: u32,
124}
125
Roland Mikhel6945bb62023-04-11 15:57:49 +0200126#[derive(Copy, Clone, Debug, Eq, PartialEq)]
127pub enum ImageManipulation {
128 None,
129 BadSignature,
130 WrongOffset,
131 IgnoreRamLoadFlag,
132 /// True to use same address,
133 /// false to overlap by 1 byte
134 OverlapImages(bool),
135 CorruptHigherVersionImage,
136}
137
138
David Browne5133242019-02-28 11:05:19 -0700139impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -0700140 /// Construct a new image builder for the given device. Returns
141 /// Some(builder) if is possible to test this configuration, or None if
142 /// not possible (for example, if there aren't enough image slots).
Fabio Utzig114a6472019-11-28 10:24:09 -0300143 pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
144 let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
145
146 for cap in unsupported_caps {
147 if cap.present() {
148 return Err(format!("unsupported {:?}", cap));
149 }
150 }
David Browne5133242019-02-28 11:05:19 -0700151
David Brown06ef06e2019-03-05 12:28:10 -0700152 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -0700153
David Brown06ef06e2019-03-05 12:28:10 -0700154 let mut slots = Vec::with_capacity(num_images);
155 for image in 0..num_images {
156 // This mapping must match that defined in
157 // `boot/zephyr/include/sysflash/sysflash.h`.
158 let id0 = match image {
159 0 => FlashId::Image0,
160 1 => FlashId::Image2,
161 _ => panic!("More than 2 images not supported"),
162 };
163 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
164 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300165 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700166 };
167 let id1 = match image {
168 0 => FlashId::Image1,
169 1 => FlashId::Image3,
170 _ => panic!("More than 2 images not supported"),
171 };
172 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
173 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300174 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700175 };
David Browne5133242019-02-28 11:05:19 -0700176
Christopher Collinsa1c12042019-05-23 14:00:28 -0700177 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700178
David Brown06ef06e2019-03-05 12:28:10 -0700179 // Construct a primary image.
180 let primary = SlotInfo {
181 base_off: primary_base as usize,
182 trailer_off: primary_base + primary_len - offset_from_end,
183 len: primary_len as usize,
184 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600185 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700186 };
187
188 // And an upgrade image.
189 let secondary = SlotInfo {
190 base_off: secondary_base as usize,
191 trailer_off: secondary_base + secondary_len - offset_from_end,
192 len: secondary_len as usize,
193 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600194 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700195 };
196
197 slots.push([primary, secondary]);
198 }
David Browne5133242019-02-28 11:05:19 -0700199
David Brownbf32c272021-06-16 17:11:37 -0600200 let ram = RamData::new(&slots);
201
Fabio Utzig114a6472019-11-28 10:24:09 -0300202 Ok(ImagesBuilder {
David Brown4dfb33c2021-03-10 05:15:45 -0700203 flash,
204 areadesc,
205 slots,
David Brownbf32c272021-06-16 17:11:37 -0600206 ram,
David Brown5bc62c62019-03-05 12:11:48 -0700207 })
David Browne5133242019-02-28 11:05:19 -0700208 }
209
210 pub fn each_device<F>(f: F)
211 where F: Fn(Self)
212 {
213 for &dev in ALL_DEVICES {
David Brown95de4502019-11-15 12:01:34 -0700214 for &align in test_alignments() {
David Browne5133242019-02-28 11:05:19 -0700215 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700216 match Self::new(dev, align, erased_val) {
Fabio Utzig114a6472019-11-28 10:24:09 -0300217 Ok(run) => f(run),
218 Err(msg) => warn!("Skipping {}: {}", dev, msg),
David Brown5bc62c62019-03-05 12:11:48 -0700219 }
David Browne5133242019-02-28 11:05:19 -0700220 }
221 }
222 }
223 }
224
225 /// Construct an `Images` that doesn't expect an upgrade to happen.
Roland Mikhel6945bb62023-04-11 15:57:49 +0200226 pub fn make_no_upgrade_image(self, deps: &DepTest, img_manipulation: ImageManipulation) -> Images {
David Brownc3898d62019-08-05 14:20:02 -0600227 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700228 let mut flash = self.flash;
Roland Mikhel6945bb62023-04-11 15:57:49 +0200229 let ram = self.ram.clone(); // TODO: Avoid this clone.
230 let mut higher_version_corrupted = false;
David Brownc3898d62019-08-05 14:20:02 -0600231 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
232 let dep: Box<dyn Depender> = if num_images > 1 {
233 Box::new(PairDep::new(num_images, image_num, deps))
234 } else {
David Brown2ee5f7f2020-01-13 14:04:01 -0700235 Box::new(BoringDep::new(image_num, deps))
David Brownc3898d62019-08-05 14:20:02 -0600236 };
Roland Mikhel6945bb62023-04-11 15:57:49 +0200237
238 let (primaries,upgrades) = if img_manipulation == ImageManipulation::CorruptHigherVersionImage && !higher_version_corrupted {
239 higher_version_corrupted = true;
240 let prim = install_image(&mut flash, &slots[0],
241 maximal(42784), &ram, &*dep, ImageManipulation::None, Some(0));
242 let upgr = match deps.depends[image_num] {
243 DepType::NoUpgrade => install_no_image(),
244 _ => install_image(&mut flash, &slots[1],
245 maximal(46928), &ram, &*dep, ImageManipulation::BadSignature, Some(0))
246 };
247 (prim, upgr)
248 } else {
249 let prim = install_image(&mut flash, &slots[0],
250 maximal(42784), &ram, &*dep, img_manipulation, Some(0));
251 let upgr = match deps.depends[image_num] {
252 DepType::NoUpgrade => install_no_image(),
253 _ => install_image(&mut flash, &slots[1],
254 maximal(46928), &ram, &*dep, img_manipulation, Some(0))
255 };
256 (prim, upgr)
David Brown873be312019-09-03 12:22:32 -0600257 };
David Brown84b49f72019-03-01 10:58:22 -0700258 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700259 slots,
260 primaries,
261 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700262 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600263 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700264 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700265 flash,
David Browne5133242019-02-28 11:05:19 -0700266 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700267 images,
David Browne5133242019-02-28 11:05:19 -0700268 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600269 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700270 }
271 }
272
David Brownc3898d62019-08-05 14:20:02 -0600273 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
Roland Mikhel6945bb62023-04-11 15:57:49 +0200274 let mut images = self.make_no_upgrade_image(deps, ImageManipulation::None);
David Brown84b49f72019-03-01 10:58:22 -0700275 for image in &images.images {
276 mark_upgrade(&mut images.flash, &image.slots[1]);
277 }
David Browne5133242019-02-28 11:05:19 -0700278
David Brown6db44d72021-05-26 16:22:58 -0600279 // The count is meaningless if no flash operations are performed.
280 if !Caps::modifies_flash() {
281 return images;
282 }
283
David Browne5133242019-02-28 11:05:19 -0700284 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300285 let total_count = match images.run_basic_upgrade(permanent) {
David Brown8973f552021-03-10 05:21:11 -0700286 Some(v) => v,
287 None =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600288 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
289 0
290 } else {
291 panic!("Unable to perform basic upgrade");
292 }
David Browne5133242019-02-28 11:05:19 -0700293 };
294
295 images.total_count = Some(total_count);
296 images
297 }
298
299 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700300 let mut bad_flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600301 let ram = self.ram.clone(); // TODO: Avoid this clone.
David Brownc3898d62019-08-05 14:20:02 -0600302 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
David Brown2ee5f7f2020-01-13 14:04:01 -0700303 let dep = BoringDep::new(image_num, &NO_DEPS);
David Browna62c3eb2021-10-25 16:32:40 -0600304 let primaries = install_image(&mut bad_flash, &slots[0],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200305 maximal(32784), &ram, &dep, ImageManipulation::None, Some(0));
David Browna62c3eb2021-10-25 16:32:40 -0600306 let upgrades = install_image(&mut bad_flash, &slots[1],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200307 maximal(41928), &ram, &dep, ImageManipulation::BadSignature, Some(0));
David Brown84b49f72019-03-01 10:58:22 -0700308 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700309 slots,
310 primaries,
311 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700312 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700313 Images {
David Brown76101572019-02-28 11:29:03 -0700314 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700315 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700316 images,
David Browne5133242019-02-28 11:05:19 -0700317 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600318 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700319 }
320 }
321
Andrzej Puzdrowski9324d2b2022-08-11 15:16:56 +0200322 pub fn make_oversized_secondary_slot_image(self) -> Images {
323 let mut bad_flash = self.flash;
324 let ram = self.ram.clone(); // TODO: Avoid this clone.
325 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
326 let dep = BoringDep::new(image_num, &NO_DEPS);
327 let primaries = install_image(&mut bad_flash, &slots[0],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200328 maximal(32784), &ram, &dep, ImageManipulation::None, Some(0));
Andrzej Puzdrowski9324d2b2022-08-11 15:16:56 +0200329 let upgrades = install_image(&mut bad_flash, &slots[1],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200330 ImageSize::Oversized, &ram, &dep, ImageManipulation::None, Some(0));
Andrzej Puzdrowski9324d2b2022-08-11 15:16:56 +0200331 OneImage {
332 slots,
333 primaries,
334 upgrades,
335 }}).collect();
336 Images {
337 flash: bad_flash,
338 areadesc: self.areadesc,
339 images,
340 total_count: None,
341 ram: self.ram,
342 }
343 }
344
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300345 pub fn make_erased_secondary_image(self) -> Images {
346 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600347 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300348 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
349 let dep = BoringDep::new(image_num, &NO_DEPS);
David Browna62c3eb2021-10-25 16:32:40 -0600350 let primaries = install_image(&mut flash, &slots[0],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200351 maximal(32784), &ram, &dep,ImageManipulation::None, Some(0));
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300352 let upgrades = install_no_image();
353 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700354 slots,
355 primaries,
356 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300357 }}).collect();
358 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700359 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300360 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700361 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300362 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600363 ram: self.ram,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300364 }
365 }
366
Fabio Utzigd0157342020-10-02 15:22:11 -0300367 pub fn make_bootstrap_image(self) -> Images {
368 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600369 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzigd0157342020-10-02 15:22:11 -0300370 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
371 let dep = BoringDep::new(image_num, &NO_DEPS);
372 let primaries = install_no_image();
David Browna62c3eb2021-10-25 16:32:40 -0600373 let upgrades = install_image(&mut flash, &slots[1],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200374 maximal(32784), &ram, &dep, ImageManipulation::None, Some(0));
Fabio Utzigd0157342020-10-02 15:22:11 -0300375 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700376 slots,
377 primaries,
378 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300379 }}).collect();
380 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700381 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300382 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700383 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300384 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600385 ram: self.ram,
Fabio Utzigd0157342020-10-02 15:22:11 -0300386 }
387 }
388
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +0200389 pub fn make_oversized_bootstrap_image(self) -> Images {
390 let mut flash = self.flash;
391 let ram = self.ram.clone(); // TODO: Avoid this clone.
392 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
393 let dep = BoringDep::new(image_num, &NO_DEPS);
394 let primaries = install_no_image();
395 let upgrades = install_image(&mut flash, &slots[1],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200396 ImageSize::Oversized, &ram, &dep, ImageManipulation::None, Some(0));
Roland Mikheld6703522023-04-27 14:24:30 +0200397 OneImage {
398 slots,
399 primaries,
400 upgrades,
401 }}).collect();
402 Images {
403 flash,
404 areadesc: self.areadesc,
405 images,
406 total_count: None,
407 ram: self.ram,
408 }
409 }
410
411 /// If security_cnt is None then do not add a security counter TLV, otherwise add the specified value.
412 pub fn make_image_with_security_counter(self, security_cnt: Option<u32>) -> Images {
413 let mut flash = self.flash;
414 let ram = self.ram.clone(); // TODO: Avoid this clone.
415 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
416 let dep = BoringDep::new(image_num, &NO_DEPS);
417 let primaries = install_image(&mut flash, &slots[0],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200418 maximal(32784), &ram, &dep, ImageManipulation::None, security_cnt);
Roland Mikheld6703522023-04-27 14:24:30 +0200419 let upgrades = install_image(&mut flash, &slots[1],
Roland Mikhel6945bb62023-04-11 15:57:49 +0200420 maximal(41928), &ram, &dep, ImageManipulation::None, security_cnt.map(|v| v + 1));
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +0200421 OneImage {
422 slots,
423 primaries,
424 upgrades,
425 }}).collect();
426 Images {
427 flash,
428 areadesc: self.areadesc,
429 images,
430 total_count: None,
431 ram: self.ram,
432 }
433 }
434
David Browne5133242019-02-28 11:05:19 -0700435 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300436 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700437 match device {
438 DeviceName::Stm32f4 => {
439 // STM style flash. Large sectors, with a large scratch area.
Fabio Utzig5577cbd2021-12-10 17:34:28 -0300440 // The flash layout as described is not present in any real STM32F4 device, but it
441 // serves to exercise support for sectors of varying sizes inside a single slot,
442 // as long as they are compatible in both slots and all fit in the scratch.
443 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024, 64 * 1024,
444 32 * 1024, 32 * 1024, 64 * 1024,
445 32 * 1024, 32 * 1024, 64 * 1024,
446 128 * 1024],
David Brown76101572019-02-28 11:29:03 -0700447 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700448 let dev_id = 0;
449 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700450 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700451 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
452 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
453 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
454
David Brown76101572019-02-28 11:29:03 -0700455 let mut flash = SimMultiFlash::new();
456 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300457 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700458 }
459 DeviceName::K64f => {
460 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700461 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700462
463 let dev_id = 0;
464 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700465 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700466 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
467 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
468 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
469
David Brown76101572019-02-28 11:29:03 -0700470 let mut flash = SimMultiFlash::new();
471 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300472 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700473 }
474 DeviceName::K64fBig => {
475 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
476 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700477 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700478
479 let dev_id = 0;
480 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700481 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700482 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
483 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
484 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
485
David Brown76101572019-02-28 11:29:03 -0700486 let mut flash = SimMultiFlash::new();
487 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300488 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700489 }
490 DeviceName::Nrf52840 => {
491 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
492 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700493 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700494
495 let dev_id = 0;
496 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700497 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700498 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
499 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
500 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
501
David Brown76101572019-02-28 11:29:03 -0700502 let mut flash = SimMultiFlash::new();
503 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300504 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700505 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300506 DeviceName::Nrf52840UnequalSlots => {
507 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
508
509 let dev_id = 0;
510 let mut areadesc = AreaDesc::new();
511 areadesc.add_flash_sectors(dev_id, &dev);
512 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
513 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
514
515 let mut flash = SimMultiFlash::new();
516 flash.insert(dev_id, dev);
517 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
518 }
David Browne5133242019-02-28 11:05:19 -0700519 DeviceName::Nrf52840SpiFlash => {
520 // Simulate nrf52840 with external SPI flash. The external SPI flash
521 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700522 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
523 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700524
525 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700526 areadesc.add_flash_sectors(0, &dev0);
527 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700528
529 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
530 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
531 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
532
David Brown76101572019-02-28 11:29:03 -0700533 let mut flash = SimMultiFlash::new();
534 flash.insert(0, dev0);
535 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300536 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700537 }
David Brown2bff6472019-03-05 13:58:35 -0700538 DeviceName::K64fMulti => {
539 // NXP style flash, but larger, to support multiple images.
540 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
541
542 let dev_id = 0;
543 let mut areadesc = AreaDesc::new();
544 areadesc.add_flash_sectors(dev_id, &dev);
545 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
546 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
547 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
548 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
549 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
550
551 let mut flash = SimMultiFlash::new();
552 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300553 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700554 }
David Browne5133242019-02-28 11:05:19 -0700555 }
556 }
David Brownc3898d62019-08-05 14:20:02 -0600557
558 pub fn num_images(&self) -> usize {
559 self.slots.len()
560 }
David Browne5133242019-02-28 11:05:19 -0700561}
562
David Brown5c9e0f12019-01-09 16:34:33 -0700563impl Images {
564 /// A simple upgrade without forced failures.
565 ///
566 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700567 /// inject failures at chosen steps. Returns None if it was unable to
568 /// count the operations in a basic upgrade.
569 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300570 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700571 info!("Total flash operation count={}", total_count);
572
David Brown84b49f72019-03-01 10:58:22 -0700573 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700574 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700575 None
David Brown5c9e0f12019-01-09 16:34:33 -0700576 } else {
David Brown8973f552021-03-10 05:21:11 -0700577 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700578 }
579 }
580
Fabio Utzigd0157342020-10-02 15:22:11 -0300581 pub fn run_bootstrap(&self) -> bool {
582 let mut flash = self.flash.clone();
583 let mut fails = 0;
584
585 if Caps::Bootstrap.present() {
586 info!("Try bootstraping image in the primary");
587
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100588 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigd0157342020-10-02 15:22:11 -0300589 warn!("Failed first boot");
590 fails += 1;
591 }
592
593 if !self.verify_images(&flash, 0, 1) {
594 warn!("Image in the first slot was not bootstrapped");
595 fails += 1;
596 }
597
598 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
599 BOOT_FLAG_SET, BOOT_FLAG_SET) {
600 warn!("Mismatched trailer for the primary slot");
601 fails += 1;
602 }
603 }
604
605 if fails > 0 {
606 error!("Expected trailer on secondary slot to be erased");
607 }
608
609 fails > 0
610 }
611
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +0200612 pub fn run_oversized_bootstrap(&self) -> bool {
613 let mut flash = self.flash.clone();
614 let mut fails = 0;
615
616 if Caps::Bootstrap.present() {
617 info!("Try bootstraping image in the primary");
618
619 let boot_result = c::boot_go(&mut flash, &self.areadesc, None, None, false).interrupted();
620
621 if boot_result {
622 warn!("Failed first boot");
623 fails += 1;
624 }
625
626 if self.verify_images(&flash, 0, 1) {
627 warn!("Image in the first slot was not bootstrapped");
628 fails += 1;
629 }
630
631 if self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
632 BOOT_FLAG_SET, BOOT_FLAG_SET) {
633 warn!("Mismatched trailer for the primary slot");
634 fails += 1;
635 }
636 }
637
638 if fails > 0 {
639 error!("Expected trailer on secondary slot to be erased");
640 }
641
642 fails > 0
643 }
644
Fabio Utzigd0157342020-10-02 15:22:11 -0300645
David Brownc3898d62019-08-05 14:20:02 -0600646 /// Test a simple upgrade, with dependencies given, and verify that the
647 /// image does as is described in the test.
648 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600649 if !Caps::modifies_flash() {
650 return false;
651 }
652
David Brownc3898d62019-08-05 14:20:02 -0600653 let (flash, _) = self.try_upgrade(None, true);
654
655 self.verify_dep_images(&flash, deps)
656 }
657
Fabio Utzigf5480c72019-11-28 10:41:57 -0300658 fn is_swap_upgrade(&self) -> bool {
659 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
660 }
661
David Brown5c9e0f12019-01-09 16:34:33 -0700662 pub fn run_basic_revert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600663 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700664 return false;
665 }
David Brown5c9e0f12019-01-09 16:34:33 -0700666
David Brown5c9e0f12019-01-09 16:34:33 -0700667 let mut fails = 0;
668
669 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300670 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700671 for count in 2 .. 5 {
672 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700673 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700674 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700675 error!("Revert failure on count {}", count);
676 fails += 1;
677 }
678 }
679 }
680
681 fails > 0
682 }
683
684 pub fn run_perm_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600685 if !Caps::modifies_flash() {
686 return false;
687 }
688
David Brown5c9e0f12019-01-09 16:34:33 -0700689 let mut fails = 0;
690 let total_flash_ops = self.total_count.unwrap();
691
David Brown80704f82024-04-11 10:42:10 -0600692 if skip_slow_test() {
693 return false;
694 }
695
David Brown5c9e0f12019-01-09 16:34:33 -0700696 // Let's try an image halfway through.
697 for i in 1 .. total_flash_ops {
698 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300699 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700700 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700701 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700702 warn!("FAIL at step {} of {}", i, total_flash_ops);
703 fails += 1;
704 }
705
David Brown84b49f72019-03-01 10:58:22 -0700706 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
707 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100708 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700709 fails += 1;
710 }
711
David Brown84b49f72019-03-01 10:58:22 -0700712 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
713 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100714 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700715 fails += 1;
716 }
717
David Brownaec56b22021-03-10 05:22:07 -0700718 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
719 warn!("Secondary slot FAIL at step {} of {}",
720 i, total_flash_ops);
721 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700722 }
723 }
724
725 if fails > 0 {
726 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
727 fails as f32 * 100.0 / total_flash_ops as f32);
728 }
729
730 fails > 0
731 }
732
David Brown5c9e0f12019-01-09 16:34:33 -0700733 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600734 if !Caps::modifies_flash() {
735 return false;
736 }
737
David Brown5c9e0f12019-01-09 16:34:33 -0700738 let mut fails = 0;
739 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700740 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700741 info!("Random interruptions at reset points={:?}", total_counts);
742
David Brown84b49f72019-03-01 10:58:22 -0700743 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300744 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700745 // TODO: This result is ignored.
746 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700747 } else {
748 true
749 };
David Vincze2d736ad2019-02-18 11:50:22 +0100750 if !primary_slot_ok || !secondary_slot_ok {
751 error!("Image mismatch after random interrupts: primary slot={} \
752 secondary slot={}",
753 if primary_slot_ok { "ok" } else { "fail" },
754 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700755 fails += 1;
756 }
David Brown84b49f72019-03-01 10:58:22 -0700757 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
758 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100759 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700760 fails += 1;
761 }
David Brown84b49f72019-03-01 10:58:22 -0700762 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
763 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100764 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700765 fails += 1;
766 }
767
768 if fails > 0 {
769 error!("Error testing perm upgrade with {} fails", total_fails);
770 }
771
772 fails > 0
773 }
774
David Brown5c9e0f12019-01-09 16:34:33 -0700775 pub fn run_revert_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600776 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700777 return false;
778 }
David Brown5c9e0f12019-01-09 16:34:33 -0700779
David Brown5c9e0f12019-01-09 16:34:33 -0700780 let mut fails = 0;
781
David Brown80704f82024-04-11 10:42:10 -0600782 if skip_slow_test() {
783 return false;
784 }
785
Fabio Utzigf5480c72019-11-28 10:41:57 -0300786 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300787 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700788 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700789 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700790 error!("Revert failed at interruption {}", i);
791 fails += 1;
792 }
793 }
794 }
795
796 fails > 0
797 }
798
David Brown5c9e0f12019-01-09 16:34:33 -0700799 pub fn run_norevert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600800 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700801 return false;
802 }
David Brown5c9e0f12019-01-09 16:34:33 -0700803
David Brown76101572019-02-28 11:29:03 -0700804 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700805 let mut fails = 0;
806
807 info!("Try norevert");
808
809 // First do a normal upgrade...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100810 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700811 warn!("Failed first boot");
812 fails += 1;
813 }
814
815 //FIXME: copy_done is written by boot_go, is it ok if no copy
816 // was ever done?
817
David Brown84b49f72019-03-01 10:58:22 -0700818 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100819 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700820 fails += 1;
821 }
David Brown84b49f72019-03-01 10:58:22 -0700822 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
823 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100824 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700825 fails += 1;
826 }
David Brown84b49f72019-03-01 10:58:22 -0700827 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
828 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100829 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700830 fails += 1;
831 }
832
David Vincze2d736ad2019-02-18 11:50:22 +0100833 // Marks image in the primary slot as permanent,
834 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700835 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700836
David Brown84b49f72019-03-01 10:58:22 -0700837 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
838 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100839 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700840 fails += 1;
841 }
842
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100843 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700844 warn!("Failed second boot");
845 fails += 1;
846 }
847
David Brown84b49f72019-03-01 10:58:22 -0700848 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
849 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100850 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700851 fails += 1;
852 }
David Brown84b49f72019-03-01 10:58:22 -0700853 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700854 warn!("Failed image verification");
855 fails += 1;
856 }
857
858 if fails > 0 {
859 error!("Error running upgrade without revert");
860 }
861
862 fails > 0
863 }
864
Andrzej Puzdrowski9324d2b2022-08-11 15:16:56 +0200865 // Test taht too big upgrade image will be rejected
866 pub fn run_oversizefail_upgrade(&self) -> bool {
867 let mut flash = self.flash.clone();
868 let mut fails = 0;
869
870 info!("Try upgrade image with to big size");
871
872 // Only perform this test if an upgrade is expected to happen.
873 if !Caps::modifies_flash() {
874 info!("Skipping upgrade image with bad signature");
875 return false;
876 }
877
878 self.mark_upgrades(&mut flash, 0);
879 self.mark_permanent_upgrades(&mut flash, 0);
880 self.mark_upgrades(&mut flash, 1);
881
882 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
883 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
884 warn!("1. Mismatched trailer for the primary slot");
885 fails += 1;
886 }
887
888 // Run the bootloader...
889 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
890 warn!("Failed first boot");
891 fails += 1;
892 }
893
894 // State should not have changed
895 if !self.verify_images(&flash, 0, 0) {
896 warn!("Failed image verification");
897 fails += 1;
898 }
899 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
900 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
901 warn!("2. Mismatched trailer for the primary slot");
902 fails += 1;
903 }
904
905 if fails > 0 {
906 error!("Expected an upgrade failure when image has to big size");
907 }
908
909 fails > 0
910 }
911
David Brown2ee5f7f2020-01-13 14:04:01 -0700912 // Test that an upgrade is rejected. Assumes that the image was build
913 // such that the upgrade is instead a downgrade.
914 pub fn run_nodowngrade(&self) -> bool {
915 if !Caps::DowngradePrevention.present() {
916 return false;
917 }
918
919 let mut flash = self.flash.clone();
920 let mut fails = 0;
921
922 info!("Try no downgrade");
923
924 // First, do a normal upgrade.
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100925 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700926 warn!("Failed first boot");
927 fails += 1;
928 }
929
930 if !self.verify_images(&flash, 0, 0) {
931 warn!("Failed verification after downgrade rejection");
932 fails += 1;
933 }
934
935 if fails > 0 {
936 error!("Error testing downgrade rejection");
937 }
938
939 fails > 0
940 }
941
David Vincze2d736ad2019-02-18 11:50:22 +0100942 // Tests a new image written to the primary slot that already has magic and
943 // image_ok set while there is no image on the secondary slot, so no revert
944 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700945 pub fn run_norevert_newimage(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600946 if !Caps::modifies_flash() {
947 info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
948 return false;
949 }
950
David Brown76101572019-02-28 11:29:03 -0700951 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700952 let mut fails = 0;
953
954 info!("Try non-revert on imgtool generated image");
955
David Brown84b49f72019-03-01 10:58:22 -0700956 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700957
David Vincze2d736ad2019-02-18 11:50:22 +0100958 // This simulates writing an image created by imgtool to
959 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700960 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
961 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100962 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700963 fails += 1;
964 }
965
966 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100967 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700968 warn!("Failed first boot");
969 fails += 1;
970 }
971
972 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700973 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700974 warn!("Failed image verification");
975 fails += 1;
976 }
David Brown84b49f72019-03-01 10:58:22 -0700977 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
978 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100979 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700980 fails += 1;
981 }
David Brown84b49f72019-03-01 10:58:22 -0700982 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
983 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100984 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700985 fails += 1;
986 }
987
988 if fails > 0 {
989 error!("Expected a non revert with new image");
990 }
991
992 fails > 0
993 }
994
David Vincze2d736ad2019-02-18 11:50:22 +0100995 // Tests a new image written to the primary slot that already has magic and
996 // image_ok set while there is no image on the secondary slot, so no revert
997 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700998 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700999 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001000 let mut fails = 0;
1001
1002 info!("Try upgrade image with bad signature");
1003
David Brown6db44d72021-05-26 16:22:58 -06001004 // Only perform this test if an upgrade is expected to happen.
1005 if !Caps::modifies_flash() {
1006 info!("Skipping upgrade image with bad signature");
1007 return false;
1008 }
1009
David Brown84b49f72019-03-01 10:58:22 -07001010 self.mark_upgrades(&mut flash, 0);
1011 self.mark_permanent_upgrades(&mut flash, 0);
1012 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -07001013
David Brown84b49f72019-03-01 10:58:22 -07001014 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1015 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +01001016 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -07001017 fails += 1;
1018 }
1019
1020 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001021 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -07001022 warn!("Failed first boot");
1023 fails += 1;
1024 }
1025
1026 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -07001027 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -07001028 warn!("Failed image verification");
1029 fails += 1;
1030 }
David Brown84b49f72019-03-01 10:58:22 -07001031 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1032 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +01001033 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -07001034 fails += 1;
1035 }
1036
1037 if fails > 0 {
1038 error!("Expected an upgrade failure when image has bad signature");
1039 }
1040
1041 fails > 0
1042 }
1043
Fabio Utzig2c3be5c2020-07-09 19:54:45 -03001044 // Should detect there is a leftover trailer in an otherwise erased
1045 // secondary slot and erase its trailer.
1046 pub fn run_secondary_leftover_trailer(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -06001047 if !Caps::modifies_flash() {
1048 return false;
1049 }
1050
Fabio Utzig2c3be5c2020-07-09 19:54:45 -03001051 let mut flash = self.flash.clone();
1052 let mut fails = 0;
1053
1054 info!("Try with a leftover trailer in the secondary; must be erased");
1055
1056 // Add a trailer on the secondary slot
1057 self.mark_permanent_upgrades(&mut flash, 1);
1058 self.mark_upgrades(&mut flash, 1);
1059
1060 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001061 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -03001062 warn!("Failed first boot");
1063 fails += 1;
1064 }
1065
1066 // State should not have changed
1067 if !self.verify_images(&flash, 0, 0) {
1068 warn!("Failed image verification");
1069 fails += 1;
1070 }
1071 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1072 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
1073 warn!("Mismatched trailer for the secondary slot");
1074 fails += 1;
1075 }
1076
1077 if fails > 0 {
1078 error!("Expected trailer on secondary slot to be erased");
1079 }
1080
1081 fails > 0
1082 }
1083
David Brown5c9e0f12019-01-09 16:34:33 -07001084 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -03001085 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -07001086 }
1087
David Brown5c9e0f12019-01-09 16:34:33 -07001088 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -03001089 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -07001090 }
1091
1092 /// This test runs a simple upgrade with no fails in the images, but
1093 /// allowing for fails in the status area. This should run to the end
1094 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -07001095 pub fn run_with_status_fails_complete(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -06001096 if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -07001097 return false;
1098 }
1099
David Brown76101572019-02-28 11:29:03 -07001100 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001101 let mut fails = 0;
1102
1103 info!("Try swap with status fails");
1104
David Brown84b49f72019-03-01 10:58:22 -07001105 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001106 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -07001107
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001108 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brownc423ac42021-06-04 13:47:34 -06001109 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -07001110 warn!("Failed!");
1111 fails += 1;
1112 }
1113
1114 // Failed writes to the marked "bad" region don't assert anymore.
1115 // Any detected assert() is happening in another part of the code.
David Brownc423ac42021-06-04 13:47:34 -06001116 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001117 warn!("At least one assert() was called");
1118 fails += 1;
1119 }
1120
David Brown84b49f72019-03-01 10:58:22 -07001121 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1122 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +01001123 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -07001124 fails += 1;
1125 }
1126
David Brown84b49f72019-03-01 10:58:22 -07001127 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -07001128 warn!("Failed image verification");
1129 fails += 1;
1130 }
1131
David Vincze2d736ad2019-02-18 11:50:22 +01001132 info!("validate primary slot enabled; \
1133 re-run of boot_go should just work");
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001134 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -07001135 warn!("Failed!");
1136 fails += 1;
1137 }
1138
1139 if fails > 0 {
1140 error!("Error running upgrade with status write fails");
1141 }
1142
1143 fails > 0
1144 }
1145
1146 /// This test runs a simple upgrade with no fails in the images, but
1147 /// allowing for fails in the status area. This should run to the end
1148 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -07001149 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -06001150 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -07001151 false
David Vincze2d736ad2019-02-18 11:50:22 +01001152 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -07001153
David Brown76101572019-02-28 11:29:03 -07001154 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001155 let mut fails = 0;
1156 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -07001157
David Brown85904a82019-01-11 13:45:12 -07001158 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -07001159
David Brown85904a82019-01-11 13:45:12 -07001160 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -07001161
David Brown84b49f72019-03-01 10:58:22 -07001162 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001163 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -07001164
1165 // Should not fail, writing to bad regions does not assert
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001166 let asserts = c::boot_go(&mut flash, &self.areadesc,
1167 Some(&mut count), None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001168 if asserts != 0 {
1169 warn!("At least one assert() was called");
1170 fails += 1;
1171 }
1172
David Brown76101572019-02-28 11:29:03 -07001173 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -07001174
1175 info!("Resuming an interrupted swap operation");
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001176 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1177 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001178
1179 // This might throw no asserts, for large sector devices, where
1180 // a single failure writing is indistinguishable from no failure,
1181 // or throw a single assert for small sector devices that fail
1182 // multiple times...
1183 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +01001184 warn!("Expected single assert validating the primary slot, \
1185 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -07001186 fails += 1;
1187 }
1188
1189 if fails > 0 {
1190 error!("Error running upgrade with status write fails");
1191 }
1192
1193 fails > 0
1194 } else {
David Brown76101572019-02-28 11:29:03 -07001195 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001196 let mut fails = 0;
1197
1198 info!("Try interrupted swap with status fails");
1199
David Brown84b49f72019-03-01 10:58:22 -07001200 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001201 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -07001202
1203 // This is expected to fail while writing to bad regions...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001204 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1205 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001206 if asserts == 0 {
1207 warn!("No assert() detected");
1208 fails += 1;
1209 }
1210
1211 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -07001212 }
David Brown5c9e0f12019-01-09 16:34:33 -07001213 }
1214
David Brown0dfb8102021-06-03 15:29:11 -06001215 /// Test the direct XIP configuration. With this mode, flash images are never moved, and the
1216 /// bootloader merely selects which partition is the proper one to boot.
1217 pub fn run_direct_xip(&self) -> bool {
1218 if !Caps::DirectXip.present() {
1219 return false;
1220 }
1221
1222 // Clone the flash so we can tell if unchanged.
1223 let mut flash = self.flash.clone();
1224
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001225 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brown0dfb8102021-06-03 15:29:11 -06001226
1227 // Ensure the boot was successful.
1228 let resp = if let Some(resp) = result.resp() {
1229 resp
1230 } else {
1231 panic!("Boot didn't return a valid result");
1232 };
1233
1234 // This configuration should always try booting from the first upgrade slot.
1235 if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
1236 assert_eq!(offset, resp.image_off as usize);
1237 assert_eq!(dev_id, resp.flash_dev_id);
1238 } else {
1239 panic!("Unable to find upgrade image");
1240 }
1241 false
1242 }
1243
David Brown8a4e23b2021-06-11 10:29:01 -06001244 /// Test the ram-loading.
1245 pub fn run_ram_load(&self) -> bool {
1246 if !Caps::RamLoad.present() {
1247 return false;
1248 }
1249
1250 // Clone the flash so we can tell if unchanged.
1251 let mut flash = self.flash.clone();
1252
David Brownf17d3912021-06-23 16:10:51 -06001253 // Setup ram based on the ram configuration we determined earlier for the images.
1254 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
David Brown8a4e23b2021-06-11 10:29:01 -06001255
David Brownf17d3912021-06-23 16:10:51 -06001256 // println!("Ram: {:#?}", self.ram);
David Brown8a4e23b2021-06-11 10:29:01 -06001257
David Brownf17d3912021-06-23 16:10:51 -06001258 // Verify that the images area loaded into this.
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001259 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None,
1260 None, true));
David Brown8a4e23b2021-06-11 10:29:01 -06001261 if !result.success() {
David Brownf17d3912021-06-23 16:10:51 -06001262 error!("Failed to execute ram-load");
David Brown8a4e23b2021-06-11 10:29:01 -06001263 return true;
1264 }
1265
David Brownf17d3912021-06-23 16:10:51 -06001266 // Verify each image.
1267 for image in &self.images {
1268 let place = self.ram.lookup(&image.slots[0]);
1269 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1270 place.size as usize);
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001271 let src_sz = image.upgrades.size();
1272 if src_sz > ram_image.len() {
David Brownf17d3912021-06-23 16:10:51 -06001273 error!("Image ended up too large, nonsensical");
1274 return true;
1275 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001276 let src_image = &image.upgrades.plain[0..src_sz];
1277 let ram_image = &ram_image[0..src_sz];
David Brownf17d3912021-06-23 16:10:51 -06001278 if ram_image != src_image {
1279 error!("Image not loaded correctly");
1280 return true;
1281 }
1282
1283 }
1284
1285 return false;
David Brown8a4e23b2021-06-11 10:29:01 -06001286 }
1287
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001288 /// Test the split ram-loading.
1289 pub fn run_split_ram_load(&self) -> bool {
1290 if !Caps::RamLoad.present() {
1291 return false;
1292 }
1293
1294 // Clone the flash so we can tell if unchanged.
1295 let mut flash = self.flash.clone();
1296
1297 // Setup ram based on the ram configuration we determined earlier for the images.
1298 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1299
1300 for (idx, _image) in (&self.images).iter().enumerate() {
1301 // Verify that the images area loaded into this.
1302 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc,
1303 None, Some(idx as i32), true));
1304 if !result.success() {
1305 error!("Failed to execute ram-load");
1306 return true;
1307 }
1308 }
1309
1310 // Verify each image.
1311 for image in &self.images {
1312 let place = self.ram.lookup(&image.slots[0]);
1313 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1314 place.size as usize);
1315 let src_sz = image.upgrades.size();
1316 if src_sz > ram_image.len() {
1317 error!("Image ended up too large, nonsensical");
1318 return true;
1319 }
1320 let src_image = &image.upgrades.plain[0..src_sz];
1321 let ram_image = &ram_image[0..src_sz];
1322 if ram_image != src_image {
1323 error!("Image not loaded correctly");
1324 return true;
1325 }
1326
1327 }
1328
1329 return false;
1330 }
1331
Roland Mikheld6703522023-04-27 14:24:30 +02001332 pub fn run_hw_rollback_prot(&self) -> bool {
1333 if !Caps::HwRollbackProtection.present() {
1334 return false;
1335 }
1336
1337 let mut flash = self.flash.clone();
1338
1339 // set the "stored" security counter to a fixed value.
1340 c::set_security_counter(0, 30);
1341
1342 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
1343
1344 if result.success() {
1345 warn!("Successful boot when it did not suppose to happen!");
1346 return true;
1347 }
1348 let counter_val = c::get_security_counter(0);
1349 if counter_val != 30 {
1350 warn!("Counter was changed when it did not suppose to!");
1351 return true;
1352 }
1353
1354 false
1355 }
1356
Roland Mikhel6945bb62023-04-11 15:57:49 +02001357 pub fn run_ram_load_boot_with_result(&self, expected_result: bool) -> bool {
1358 if !Caps::RamLoad.present() {
1359 return false;
1360 }
1361 // Clone the flash so we can tell if unchanged.
1362 let mut flash = self.flash.clone();
1363
1364 // Create RAM config.
1365 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1366
1367 // Run the bootloader, and verify that it couldn't run to completion.
1368 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None,
1369 None, true));
1370
1371 if result.success() != expected_result {
1372 error!("RAM load boot result was not of the expected value! (was: {}, expected: {})", result.success(), expected_result);
1373 return true;
1374 }
1375
1376 false
1377 }
1378
David Brown5c9e0f12019-01-09 16:34:33 -07001379 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -07001380 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001381 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -07001382 if Caps::OverwriteUpgrade.present() {
1383 return;
1384 }
1385
David Brown84b49f72019-03-01 10:58:22 -07001386 // Set this for each image.
1387 for image in &self.images {
1388 let dev_id = &image.slots[slot].dev_id;
1389 let dev = flash.get_mut(&dev_id).unwrap();
1390 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001391 let off = &image.slots[slot].base_off;
1392 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -07001393 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -07001394
David Brown84b49f72019-03-01 10:58:22 -07001395 // Mark the status area as a bad area
1396 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1397 }
David Brown5c9e0f12019-01-09 16:34:33 -07001398 }
1399
David Brown76101572019-02-28 11:29:03 -07001400 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001401 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001402 return;
1403 }
1404
David Brown84b49f72019-03-01 10:58:22 -07001405 for image in &self.images {
1406 let dev_id = &image.slots[slot].dev_id;
1407 let dev = flash.get_mut(&dev_id).unwrap();
1408 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001409
David Brown84b49f72019-03-01 10:58:22 -07001410 // Disabling write verification the only assert triggered by
1411 // boot_go should be checking for integrity of status bytes.
1412 dev.set_verify_writes(false);
1413 }
David Brown5c9e0f12019-01-09 16:34:33 -07001414 }
1415
David Browndb505822019-03-01 10:04:20 -07001416 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1417 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001418 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001419 // Clone the flash to have a new copy.
1420 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001421
Fabio Utziged4a5362019-07-30 12:43:23 -03001422 if permanent {
1423 self.mark_permanent_upgrades(&mut flash, 1);
1424 }
David Brown5c9e0f12019-01-09 16:34:33 -07001425
David Browndb505822019-03-01 10:04:20 -07001426 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001427
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001428 let (first_interrupted, count) = match c::boot_go(&mut flash,
1429 &self.areadesc,
1430 Some(&mut counter),
1431 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001432 x if x.interrupted() => (true, stop.unwrap()),
1433 x if x.success() => (false, -counter),
1434 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001435 };
David Brown5c9e0f12019-01-09 16:34:33 -07001436
David Browndb505822019-03-01 10:04:20 -07001437 counter = 0;
1438 if first_interrupted {
1439 // fl.dump();
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001440 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1441 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001442 x if x.interrupted() => panic!("Shouldn't stop again"),
1443 x if x.success() => (),
1444 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001445 }
1446 }
David Brown5c9e0f12019-01-09 16:34:33 -07001447
David Browndb505822019-03-01 10:04:20 -07001448 (flash, count - counter)
1449 }
1450
1451 fn try_revert(&self, count: usize) -> SimMultiFlash {
1452 let mut flash = self.flash.clone();
1453
1454 // fl.write_file("image0.bin").unwrap();
1455 for i in 0 .. count {
1456 info!("Running boot pass {}", i + 1);
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001457 assert!(c::boot_go(&mut flash, &self.areadesc, None, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001458 }
1459 flash
1460 }
1461
1462 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1463 let mut flash = self.flash.clone();
1464 let mut fails = 0;
1465
1466 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001467 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1468 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001469 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001470 fails += 1;
1471 }
1472
Fabio Utzig8af7f792019-07-30 12:40:01 -03001473 // In a multi-image setup, copy done might be set if any number of
1474 // images was already successfully swapped.
1475 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1476 warn!("copy_done should be unset");
1477 fails += 1;
1478 }
1479
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001480 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001481 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001482 fails += 1;
1483 }
1484
David Brown84b49f72019-03-01 10:58:22 -07001485 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001486 warn!("Image in the primary slot before revert is invalid at stop={}",
1487 stop);
1488 fails += 1;
1489 }
David Brown84b49f72019-03-01 10:58:22 -07001490 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001491 warn!("Image in the secondary slot before revert is invalid at stop={}",
1492 stop);
1493 fails += 1;
1494 }
David Brown84b49f72019-03-01 10:58:22 -07001495 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1496 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001497 warn!("Mismatched trailer for the primary slot before revert");
1498 fails += 1;
1499 }
David Brown84b49f72019-03-01 10:58:22 -07001500 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1501 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001502 warn!("Mismatched trailer for the secondary slot before revert");
1503 fails += 1;
1504 }
1505
1506 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001507 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001508 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1509 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001510 warn!("Should have stopped revert at interruption point");
1511 fails += 1;
1512 }
1513
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001514 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001515 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001516 fails += 1;
1517 }
1518
David Brown84b49f72019-03-01 10:58:22 -07001519 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001520 warn!("Image in the primary slot after revert is invalid at stop={}",
1521 stop);
1522 fails += 1;
1523 }
David Brown84b49f72019-03-01 10:58:22 -07001524 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001525 warn!("Image in the secondary slot after revert is invalid at stop={}",
1526 stop);
1527 fails += 1;
1528 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001529
David Brown84b49f72019-03-01 10:58:22 -07001530 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1531 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001532 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001533 fails += 1;
1534 }
David Brown84b49f72019-03-01 10:58:22 -07001535 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1536 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001537 warn!("Mismatched trailer for the secondary slot after revert");
1538 fails += 1;
1539 }
1540
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001541 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001542 warn!("Should have finished 3rd boot");
1543 fails += 1;
1544 }
1545
1546 if !self.verify_images(&flash, 0, 0) {
1547 warn!("Image in the primary slot is invalid on 1st boot after revert");
1548 fails += 1;
1549 }
1550 if !self.verify_images(&flash, 1, 1) {
1551 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1552 fails += 1;
1553 }
1554
David Browndb505822019-03-01 10:04:20 -07001555 fails > 0
1556 }
1557
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001558
David Browndb505822019-03-01 10:04:20 -07001559 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1560 let mut flash = self.flash.clone();
1561
David Brown84b49f72019-03-01 10:58:22 -07001562 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001563
1564 let mut rng = rand::thread_rng();
1565 let mut resets = vec![0i32; count];
1566 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001567 for reset in &mut resets {
David Brown9c6322f2021-08-19 13:03:39 -06001568 let reset_counter = rng.gen_range(1 ..= remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001569 let mut counter = reset_counter;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001570 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1571 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001572 x if x.interrupted() => (),
1573 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001574 }
1575 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001576 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001577 }
1578
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001579 match c::boot_go(&mut flash, &self.areadesc, None, None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001580 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1581 x if x.success() => (),
1582 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001583 }
David Brown5c9e0f12019-01-09 16:34:33 -07001584
David Browndb505822019-03-01 10:04:20 -07001585 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001586 }
David Brown84b49f72019-03-01 10:58:22 -07001587
1588 /// Verify the image in the given flash device, the specified slot
1589 /// against the expected image.
1590 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001591 self.images.iter().all(|image| {
1592 verify_image(flash, &image.slots[slot],
1593 match against {
1594 0 => &image.primaries,
1595 1 => &image.upgrades,
1596 _ => panic!("Invalid 'against'")
1597 })
1598 })
David Brown84b49f72019-03-01 10:58:22 -07001599 }
1600
David Brownc3898d62019-08-05 14:20:02 -06001601 /// Verify the images, according to the dependency test.
1602 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1603 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1604 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1605 if !verify_image(flash, &image.slots[0],
1606 match upgrade {
1607 UpgradeInfo::Upgraded => &image.upgrades,
1608 UpgradeInfo::Held => &image.primaries,
1609 }) {
1610 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1611 return true;
1612 }
1613 }
1614
1615 false
1616 }
1617
Fabio Utzig8af7f792019-07-30 12:40:01 -03001618 /// Verify that at least one of the trailers of the images have the
1619 /// specified values.
1620 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1621 magic: Option<u8>, image_ok: Option<u8>,
1622 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001623 self.images.iter().any(|image| {
1624 verify_trailer(flash, &image.slots[slot],
1625 magic, image_ok, copy_done)
1626 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001627 }
1628
David Brown84b49f72019-03-01 10:58:22 -07001629 /// Verify that the trailers of the images have the specified
1630 /// values.
1631 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1632 magic: Option<u8>, image_ok: Option<u8>,
1633 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001634 self.images.iter().all(|image| {
1635 verify_trailer(flash, &image.slots[slot],
1636 magic, image_ok, copy_done)
1637 })
David Brown84b49f72019-03-01 10:58:22 -07001638 }
1639
1640 /// Mark each of the images for permanent upgrade.
1641 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1642 for image in &self.images {
1643 mark_permanent_upgrade(flash, &image.slots[slot]);
1644 }
1645 }
1646
1647 /// Mark each of the images for permanent upgrade.
1648 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1649 for image in &self.images {
1650 mark_upgrade(flash, &image.slots[slot]);
1651 }
1652 }
David Brown297029a2019-08-13 14:29:51 -06001653
1654 /// Dump out the flash image(s) to one or more files for debugging
1655 /// purposes. The names will be written as either "{prefix}.mcubin" or
1656 /// "{prefix}-001.mcubin" depending on how many images there are.
1657 pub fn debug_dump(&self, prefix: &str) {
1658 for (id, fdev) in &self.flash {
1659 let name = if self.flash.len() == 1 {
1660 format!("{}.mcubin", prefix)
1661 } else {
1662 format!("{}-{:>0}.mcubin", prefix, id)
1663 };
1664 fdev.write_file(&name).unwrap();
1665 }
1666 }
David Brown5c9e0f12019-01-09 16:34:33 -07001667}
1668
David Brownbf32c272021-06-16 17:11:37 -06001669impl RamData {
David Brownf17d3912021-06-23 16:10:51 -06001670 // TODO: This is not correct. The second slot of each image should be at the same address as
1671 // the primary.
David Brownbf32c272021-06-16 17:11:37 -06001672 fn new(slots: &[[SlotInfo; 2]]) -> RamData {
1673 let mut addr = RAM_LOAD_ADDR;
1674 let mut places = BTreeMap::new();
David Brownf17d3912021-06-23 16:10:51 -06001675 // println!("Setup:-------------");
David Brownbf32c272021-06-16 17:11:37 -06001676 for imgs in slots {
1677 for si in imgs {
David Brownf17d3912021-06-23 16:10:51 -06001678 // println!("Setup: si: {:?}", si);
David Brownbf32c272021-06-16 17:11:37 -06001679 let offset = addr;
1680 let size = si.len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001681 places.insert(SlotKey {
1682 dev_id: si.dev_id,
David Brownf17d3912021-06-23 16:10:51 -06001683 base_off: si.base_off,
David Brownbf32c272021-06-16 17:11:37 -06001684 }, SlotPlace { offset, size });
David Brownf17d3912021-06-23 16:10:51 -06001685 // println!(" load: offset: {}, size: {}", offset, size);
David Brownbf32c272021-06-16 17:11:37 -06001686 }
David Brownf17d3912021-06-23 16:10:51 -06001687 addr += imgs[0].len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001688 }
1689 RamData {
1690 places,
1691 total: addr,
1692 }
1693 }
David Brownf17d3912021-06-23 16:10:51 -06001694
1695 /// Lookup the ram data associated with a given flash partition. We just panic if not present,
1696 /// because all slots used should be in the map.
1697 fn lookup(&self, slot: &SlotInfo) -> &SlotPlace {
1698 self.places.get(&SlotKey{dev_id: slot.dev_id, base_off: slot.base_off})
1699 .expect("RamData should contain all slots")
1700 }
David Brownbf32c272021-06-16 17:11:37 -06001701}
1702
David Brown5c9e0f12019-01-09 16:34:33 -07001703/// Show the flash layout.
1704#[allow(dead_code)]
1705fn show_flash(flash: &dyn Flash) {
1706 println!("---- Flash configuration ----");
1707 for sector in flash.sector_iter() {
1708 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1709 sector.num, sector.base, sector.size);
1710 }
David Brown599b2db2021-03-10 05:23:26 -07001711 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001712}
1713
David Browna62c3eb2021-10-25 16:32:40 -06001714#[derive(Debug)]
1715enum ImageSize {
1716 /// Make the image the specified given size.
1717 Given(usize),
1718 /// Make the image as large as it can be for the partition/device.
1719 Largest,
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001720 /// Make the image quite larger than it can be for the partition/device/
1721 Oversized,
David Browna62c3eb2021-10-25 16:32:40 -06001722}
1723
Andrzej Puzdrowski5b90dc82022-08-08 12:49:24 +02001724#[cfg(not(feature = "max-align-32"))]
1725fn tralier_estimation(dev: &dyn Flash) -> usize {
Andrzej Puzdrowski5b90dc82022-08-08 12:49:24 +02001726 c::boot_trailer_sz(dev.align() as u32) as usize
1727}
1728
1729#[cfg(feature = "max-align-32")]
1730fn tralier_estimation(dev: &dyn Flash) -> usize {
1731
1732 let sector_size = dev.sector_iter().next().unwrap().size as u32;
1733
1734 align_up(c::boot_trailer_sz(dev.align() as u32), sector_size) as usize
1735}
1736
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001737fn image_largest_trailer(dev: &dyn Flash) -> usize {
1738 // Using the header size we know, the trailer size, and the slot size, we can compute
1739 // the largest image possible.
1740 let trailer = if Caps::OverwriteUpgrade.present() {
1741 // This computation is incorrect, and we need to figure out the correct size.
1742 // c::boot_status_sz(dev.align() as u32) as usize
1743 16 + 4 * dev.align()
1744 } else if Caps::SwapUsingMove.present() {
1745 let sector_size = dev.sector_iter().next().unwrap().size as u32;
1746 align_up(c::boot_trailer_sz(dev.align() as u32), sector_size) as usize
1747 } else if Caps::SwapUsingScratch.present() {
1748 tralier_estimation(dev)
1749 } else {
1750 panic!("The maximum image size can't be calculated.")
1751 };
1752
1753 trailer
1754}
1755
David Brown5c9e0f12019-01-09 16:34:33 -07001756/// Install a "program" into the given image. This fakes the image header, or at least all of the
1757/// fields used by the given code. Returns a copy of the image that was written.
David Browna62c3eb2021-10-25 16:32:40 -06001758fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: ImageSize,
David Brownf17d3912021-06-23 16:10:51 -06001759 ram: &RamData,
Roland Mikhel6945bb62023-04-11 15:57:49 +02001760 deps: &dyn Depender, img_manipulation: ImageManipulation, security_counter:Option<u32>) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001761 let offset = slot.base_off;
1762 let slot_len = slot.len;
1763 let dev_id = slot.dev_id;
David Brown07dd5f02021-10-26 16:43:15 -06001764 let dev = flash.get_mut(&dev_id).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001765
David Brown43643dd2019-01-11 15:43:28 -07001766 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
Roland Mikhel6945bb62023-04-11 15:57:49 +02001767 if img_manipulation == ImageManipulation::IgnoreRamLoadFlag {
1768 tlv.set_ignore_ram_load_flag();
1769 }
David Brown5c9e0f12019-01-09 16:34:33 -07001770
Roland Mikheld6703522023-04-27 14:24:30 +02001771 tlv.set_security_counter(security_counter);
1772
Roland Mikhel6945bb62023-04-11 15:57:49 +02001773
David Brownc3898d62019-08-05 14:20:02 -06001774 // Add the dependencies early to the tlv.
1775 for dep in deps.my_deps(offset, slot.index) {
1776 tlv.add_dependency(deps.other_id(), &dep);
1777 }
1778
David Brown5c9e0f12019-01-09 16:34:33 -07001779 const HDR_SIZE: usize = 32;
David Brownf17d3912021-06-23 16:10:51 -06001780 let place = ram.lookup(&slot);
1781 let load_addr = if Caps::RamLoad.present() {
Roland Mikhel6945bb62023-04-11 15:57:49 +02001782 match img_manipulation {
1783 ImageManipulation::WrongOffset => u32::MAX,
1784 ImageManipulation::OverlapImages(true) => RAM_LOAD_ADDR,
1785 ImageManipulation::OverlapImages(false) => place.offset - 1,
1786 _ => place.offset
1787 }
David Brownf17d3912021-06-23 16:10:51 -06001788 } else {
1789 0
1790 };
1791
David Browna62c3eb2021-10-25 16:32:40 -06001792 let len = match len {
1793 ImageSize::Given(size) => size,
David Brown07dd5f02021-10-26 16:43:15 -06001794 ImageSize::Largest => {
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001795 let trailer = image_largest_trailer(dev);
David Brown07dd5f02021-10-26 16:43:15 -06001796 let tlv_len = tlv.estimate_size();
1797 info!("slot: 0x{:x}, HDR: 0x{:x}, trailer: 0x{:x}",
1798 slot_len, HDR_SIZE, trailer);
1799 slot_len - HDR_SIZE - trailer - tlv_len
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001800 },
1801 ImageSize::Oversized => {
1802 let trailer = image_largest_trailer(dev);
1803 let tlv_len = tlv.estimate_size();
1804 info!("slot: 0x{:x}, HDR: 0x{:x}, trailer: 0x{:x}",
1805 slot_len, HDR_SIZE, trailer);
1806 // the overflow size is rougly estimated to work for all
1807 // configurations. It might be precise if tlv_len will be maked precise.
1808 slot_len - HDR_SIZE - trailer - tlv_len + dev.align()*4
David Brown07dd5f02021-10-26 16:43:15 -06001809 }
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001810
David Browna62c3eb2021-10-25 16:32:40 -06001811 };
1812
David Brown5c9e0f12019-01-09 16:34:33 -07001813 // Generate a boot header. Note that the size doesn't include the header.
1814 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001815 magic: tlv.get_magic(),
David Brownf17d3912021-06-23 16:10:51 -06001816 load_addr,
David Brown5c9e0f12019-01-09 16:34:33 -07001817 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001818 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001819 img_size: len as u32,
1820 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001821 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001822 _pad2: 0,
1823 };
1824
1825 let mut b_header = [0; HDR_SIZE];
1826 b_header[..32].clone_from_slice(header.as_raw());
1827 assert_eq!(b_header.len(), HDR_SIZE);
1828
1829 tlv.add_bytes(&b_header);
1830
1831 // The core of the image itself is just pseudorandom data.
1832 let mut b_img = vec![0; len];
1833 splat(&mut b_img, offset);
1834
David Browncb47dd72019-08-05 14:21:49 -06001835 // Add some information at the start of the payload to make it easier
1836 // to see what it is. This will fail if the image itself is too small.
1837 {
1838 let mut wr = Cursor::new(&mut b_img);
1839 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1840 offset, dev_id, slot).unwrap();
1841 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1842 }
1843
David Brown5c9e0f12019-01-09 16:34:33 -07001844 // TLV signatures work over plain image
1845 tlv.add_bytes(&b_img);
1846
1847 // Generate encrypted images
Salome Thirot6fdbf552021-05-14 16:46:14 +01001848 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1849 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001850 let mut b_encimg = vec![];
1851 if is_encrypted {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001852 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1853 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001854 tlv.generate_enc_key();
1855 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001856 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001857 b_encimg = b_img.clone();
Salome Thirot6fdbf552021-05-14 16:46:14 +01001858 if aes256 {
1859 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001860 let block = Aes256::new(&key);
1861 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001862 cipher.apply_keystream(&mut b_encimg);
1863 } else {
1864 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001865 let block = Aes128::new(&key);
1866 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001867 cipher.apply_keystream(&mut b_encimg);
1868 }
David Brown5c9e0f12019-01-09 16:34:33 -07001869 }
1870
1871 // Build the TLV itself.
Roland Mikhel6945bb62023-04-11 15:57:49 +02001872 if img_manipulation == ImageManipulation::BadSignature {
David Browne90b13f2019-12-06 15:04:00 -07001873 tlv.corrupt_sig();
1874 }
1875 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001876
David Brown5c9e0f12019-01-09 16:34:33 -07001877 let mut buf = vec![];
1878 buf.append(&mut b_header.to_vec());
1879 buf.append(&mut b_img);
1880 buf.append(&mut b_tlv.clone());
1881
David Brown95de4502019-11-15 12:01:34 -07001882 // Pad the buffer to a multiple of the flash alignment.
1883 let align = dev.align();
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001884 let image_sz = buf.len();
David Brown95de4502019-11-15 12:01:34 -07001885 while buf.len() % align != 0 {
1886 buf.push(dev.erased_val());
1887 }
1888
David Brown5c9e0f12019-01-09 16:34:33 -07001889 let mut encbuf = vec![];
1890 if is_encrypted {
1891 encbuf.append(&mut b_header.to_vec());
1892 encbuf.append(&mut b_encimg);
1893 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001894
1895 while encbuf.len() % align != 0 {
1896 encbuf.push(dev.erased_val());
1897 }
David Brown5c9e0f12019-01-09 16:34:33 -07001898 }
1899
David Vincze2d736ad2019-02-18 11:50:22 +01001900 // Since images are always non-encrypted in the primary slot, we first write
1901 // an encrypted image, re-read to use for verification, erase + flash
1902 // un-encrypted. In the secondary slot the image is written un-encrypted,
1903 // and if encryption is requested, it follows an erase + flash encrypted.
Roland Mikhel820e9cc2023-05-09 14:30:16 +02001904 //
1905 // In the case of ram-load when encryption is enabled both slots have to
1906 // be encrypted so in the event when the image is in the primary slot
1907 // the verification will fail as the image is not encrypted.
1908 if slot.index == 0 && !Caps::RamLoad.present() {
David Brown5c9e0f12019-01-09 16:34:33 -07001909 let enc_copy: Option<Vec<u8>>;
1910
1911 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001912 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001913
1914 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001915 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001916
1917 enc_copy = Some(enc);
1918
David Brown76101572019-02-28 11:29:03 -07001919 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001920 } else {
1921 enc_copy = None;
1922 }
1923
David Brown76101572019-02-28 11:29:03 -07001924 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001925
1926 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001927 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001928
David Brownca234692019-02-28 11:22:19 -07001929 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001930 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001931 plain: copy,
1932 cipher: enc_copy,
1933 }
David Brown5c9e0f12019-01-09 16:34:33 -07001934 } else {
1935
David Brown76101572019-02-28 11:29:03 -07001936 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001937
1938 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001939 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001940
1941 let enc_copy: Option<Vec<u8>>;
1942
1943 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001944 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001945
David Brown76101572019-02-28 11:29:03 -07001946 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001947
1948 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001949 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001950
1951 enc_copy = Some(enc);
1952 } else {
1953 enc_copy = None;
1954 }
1955
David Brownca234692019-02-28 11:22:19 -07001956 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001957 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001958 plain: copy,
1959 cipher: enc_copy,
1960 }
David Brown5c9e0f12019-01-09 16:34:33 -07001961 }
David Brown5c9e0f12019-01-09 16:34:33 -07001962}
1963
David Brown873be312019-09-03 12:22:32 -06001964/// Install no image. This is used when no upgrade happens.
1965fn install_no_image() -> ImageData {
1966 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001967 size: 0,
David Brown873be312019-09-03 12:22:32 -06001968 plain: vec![],
1969 cipher: None,
1970 }
1971}
1972
David Brown0bd8c6b2021-10-22 16:33:06 -06001973/// Construct a TLV generator based on how MCUboot is currently configured. The returned
1974/// ManifestGen will generate the appropriate entries based on this configuration.
David Brown5c9e0f12019-01-09 16:34:33 -07001975fn make_tlv() -> TlvGen {
David Brownac655bb2021-10-22 16:33:27 -06001976 let aes_key_size = if Caps::Aes256.present() { 256 } else { 128 };
David Brown5c9e0f12019-01-09 16:34:33 -07001977
David Brownb8882112019-01-11 14:04:11 -07001978 if Caps::EncKw.present() {
1979 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001980 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001981 } else if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001982 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001983 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001984 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001985 }
1986 } else if Caps::EncRsa.present() {
1987 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001988 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001989 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001990 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001991 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001992 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001993 if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001994 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001995 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001996 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001997 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001998 } else if Caps::EncX25519.present() {
1999 if Caps::Ed25519.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01002000 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03002001 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01002002 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03002003 }
David Brownb8882112019-01-11 14:04:11 -07002004 } else {
2005 // The non-encrypted configuration.
2006 if Caps::RSA2048.present() {
2007 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03002008 } else if Caps::RSA3072.present() {
2009 TlvGen::new_rsa3072_pss()
Roland Mikhel5899fac2023-03-14 13:59:55 +01002010 } else if Caps::EcdsaP256.present() || Caps::EcdsaP384.present() {
David Brownb8882112019-01-11 14:04:11 -07002011 TlvGen::new_ecdsa()
Roland Mikhel30978512023-02-08 14:06:58 +01002012 } else if Caps::Ed25519.present() {
Fabio Utzig97710282019-05-24 17:44:49 -03002013 TlvGen::new_ed25519()
Roland Mikheld6703522023-04-27 14:24:30 +02002014 } else if Caps::HwRollbackProtection.present() {
2015 TlvGen::new_sec_cnt()
David Brownb8882112019-01-11 14:04:11 -07002016 } else {
2017 TlvGen::new_hash_only()
2018 }
2019 }
David Brown5c9e0f12019-01-09 16:34:33 -07002020}
2021
David Brownca234692019-02-28 11:22:19 -07002022impl ImageData {
2023 /// Find the image contents for the given slot. This assumes that slot 0
2024 /// is unencrypted, and slot 1 is encrypted.
2025 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03002026 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03002027 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07002028 match (encrypted, slot) {
2029 (false, _) => &self.plain,
2030 (true, 0) => &self.plain,
2031 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
2032 _ => panic!("Invalid slot requested"),
2033 }
David Brown5c9e0f12019-01-09 16:34:33 -07002034 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03002035
2036 fn size(&self) -> usize {
2037 self.size
2038 }
David Brown5c9e0f12019-01-09 16:34:33 -07002039}
2040
David Brown5c9e0f12019-01-09 16:34:33 -07002041/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06002042fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
2043 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07002044 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06002045 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07002046
2047 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06002048 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07002049 let dev = flash.get(&dev_id).unwrap();
2050 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07002051
2052 if buf != &copy[..] {
2053 for i in 0 .. buf.len() {
2054 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06002055 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
2056 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07002057 break;
2058 }
2059 }
2060 false
2061 } else {
2062 true
2063 }
2064}
2065
David Brown3b090212019-07-30 15:59:28 -06002066fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07002067 magic: Option<u8>, image_ok: Option<u8>,
2068 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07002069 if Caps::OverwriteUpgrade.present() {
2070 return true;
2071 }
David Brown5c9e0f12019-01-09 16:34:33 -07002072
David Brown3b090212019-07-30 15:59:28 -06002073 let offset = slot.trailer_off + c::boot_max_align();
2074 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07002075 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07002076 let mut failed = false;
2077
David Brown76101572019-02-28 11:29:03 -07002078 let dev = flash.get(&dev_id).unwrap();
2079 let erased_val = dev.erased_val();
2080 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07002081
2082 failed |= match magic {
2083 Some(v) => {
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002084 let magic_off = (c::boot_max_align() * 3) + (c::boot_magic_sz() - MAGIC.len());
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002085 if v == 1 && &copy[magic_off..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07002086 warn!("\"magic\" mismatch at {:#x}", offset);
2087 true
2088 } else if v == 3 {
2089 let expected = [erased_val; 16];
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002090 if copy[magic_off..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07002091 warn!("\"magic\" mismatch at {:#x}", offset);
2092 true
2093 } else {
2094 false
2095 }
2096 } else {
2097 false
2098 }
2099 },
2100 None => false,
2101 };
2102
2103 failed |= match image_ok {
2104 Some(v) => {
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002105 let image_ok_off = c::boot_max_align() * 2;
2106 if (v == 1 && copy[image_ok_off] != v) || (v == 3 && copy[image_ok_off] != erased_val) {
2107 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[image_ok_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07002108 true
2109 } else {
2110 false
2111 }
2112 },
2113 None => false,
2114 };
2115
2116 failed |= match copy_done {
2117 Some(v) => {
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002118 let copy_done_off = c::boot_max_align();
2119 if (v == 1 && copy[copy_done_off] != v) || (v == 3 && copy[copy_done_off] != erased_val) {
2120 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[copy_done_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07002121 true
2122 } else {
2123 false
2124 }
2125 },
2126 None => false,
2127 };
2128
2129 !failed
2130}
2131
David Brown297029a2019-08-13 14:29:51 -06002132/// Install a partition table. This is a simplified partition table that
2133/// we write at the beginning of flash so make it easier for external tools
2134/// to analyze these images.
2135fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
2136 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
2137 for &id in &ids {
2138 // If there are any partitions in this device that start at 0, and
2139 // aren't marked as the BootLoader partition, avoid adding the
2140 // partition table. This makes it harder to view the image, but
2141 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07002142 let skip_ptable = areadesc
2143 .iter_areas()
2144 .any(|area| {
2145 area.device_id == id &&
2146 area.off == 0 &&
2147 area.flash_id != FlashId::BootLoader
2148 });
2149 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06002150 if log_enabled!(Info) {
2151 let special: Vec<FlashId> = areadesc.iter_areas()
2152 .filter(|area| area.device_id == id && area.off == 0)
2153 .map(|area| area.flash_id)
2154 .collect();
2155 info!("Skipping partition table: {:?}", special);
2156 }
2157 break;
2158 }
2159
2160 let mut buf: Vec<u8> = vec![];
2161 write!(&mut buf, "mcuboot\0").unwrap();
2162
2163 // Iterate through all of the partitions in that device, and encode
2164 // into the table.
2165 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
2166 buf.write_u32::<LittleEndian>(count as u32).unwrap();
2167
2168 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
2169 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
2170 buf.write_u32::<LittleEndian>(area.off).unwrap();
2171 buf.write_u32::<LittleEndian>(area.size).unwrap();
2172 buf.write_u32::<LittleEndian>(0).unwrap();
2173 }
2174
2175 let dev = flash.get_mut(&id).unwrap();
2176
2177 // Pad to alignment.
2178 while buf.len() % dev.align() != 0 {
2179 buf.push(0);
2180 }
2181
2182 dev.write(0, &buf).unwrap();
2183 }
2184}
2185
David Brown5c9e0f12019-01-09 16:34:33 -07002186/// The image header
2187#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07002188#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002189pub struct ImageHeader {
2190 magic: u32,
2191 load_addr: u32,
2192 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06002193 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07002194 img_size: u32,
2195 flags: u32,
2196 ver: ImageVersion,
2197 _pad2: u32,
2198}
2199
2200impl AsRaw for ImageHeader {}
2201
2202#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06002203#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002204pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06002205 pub major: u8,
2206 pub minor: u8,
2207 pub revision: u16,
2208 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07002209}
2210
David Brownc3898d62019-08-05 14:20:02 -06002211#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002212pub struct SlotInfo {
2213 pub base_off: usize,
2214 pub trailer_off: usize,
2215 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06002216 // Which slot within this device.
2217 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07002218 pub dev_id: u8,
2219}
2220
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002221#[cfg(not(feature = "max-align-32"))]
David Brown347dc572019-11-15 11:37:25 -07002222const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
2223 0x60, 0xd2, 0xef, 0x7f,
2224 0x35, 0x52, 0x50, 0x0f,
2225 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07002226
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002227#[cfg(feature = "max-align-32")]
2228const MAGIC: &[u8] = &[0x20, 0x00, 0x2d, 0xe1,
2229 0x5d, 0x29, 0x41, 0x0b,
2230 0x8d, 0x77, 0x67, 0x9c,
2231 0x11, 0x0f, 0x1f, 0x8a];
2232
David Brown5c9e0f12019-01-09 16:34:33 -07002233// Replicates defines found in bootutil.h
2234const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
2235const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
2236
2237const BOOT_FLAG_SET: Option<u8> = Some(1);
2238const BOOT_FLAG_UNSET: Option<u8> = Some(3);
2239
2240/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07002241pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
2242 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07002243 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07002244 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07002245 if offset % align != 0 || MAGIC.len() % align != 0 {
2246 // The write size is larger than the magic value. Fill a buffer
2247 // with the erased value, put the MAGIC in it, and write it in its
2248 // entirety.
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002249 let mut buf = vec![dev.erased_val(); c::boot_max_align()];
2250 let magic_off = (offset % align) + (c::boot_magic_sz() - MAGIC.len());
2251 buf[magic_off..].copy_from_slice(MAGIC);
David Brown95de4502019-11-15 12:01:34 -07002252 dev.write(offset - (offset % align), &buf).unwrap();
2253 } else {
2254 dev.write(offset, MAGIC).unwrap();
2255 }
David Brown5c9e0f12019-01-09 16:34:33 -07002256}
2257
2258/// Writes the image_ok flag which, guess what, tells the bootloader
2259/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07002260fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07002261 // Overwrite mode always is permanent, and only the magic is used in
2262 // the trailer. To avoid problems with large write sizes, don't try to
2263 // set anything in this case.
2264 if Caps::OverwriteUpgrade.present() {
2265 return;
2266 }
2267
David Brown76101572019-02-28 11:29:03 -07002268 let dev = flash.get_mut(&slot.dev_id).unwrap();
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002269 let align = dev.align();
2270 let mut ok = vec![dev.erased_val(); align];
David Brown5c9e0f12019-01-09 16:34:33 -07002271 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07002272 let off = slot.trailer_off + c::boot_max_align() * 3;
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002273 dev.write(off, &ok).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07002274}
2275
2276// Drop some pseudo-random gibberish onto the data.
2277fn splat(data: &mut [u8], seed: usize) {
David Brown9c6322f2021-08-19 13:03:39 -06002278 let mut seed_block = [0u8; 32];
David Browncd842842020-07-09 15:46:53 -06002279 let mut buf = Cursor::new(&mut seed_block[..]);
2280 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
2281 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
2282 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
2283 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
2284 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07002285 rng.fill_bytes(data);
2286}
2287
2288/// Return a read-only view into the raw bytes of this object
2289trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07002290 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07002291 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
2292 mem::size_of::<Self>()) }
2293 }
2294}
2295
David Brown07dd5f02021-10-26 16:43:15 -06002296/// Determine whether it makes sense to test this configuration with a maximally-sized image.
2297/// Returns an ImageSize representing the best size to test, possibly just with the given size.
2298fn maximal(size: usize) -> ImageSize {
2299 if Caps::OverwriteUpgrade.present() ||
2300 Caps::SwapUsingMove.present()
2301 {
2302 ImageSize::Given(size)
2303 } else {
2304 ImageSize::Largest
2305 }
2306}
2307
David Brown5c9e0f12019-01-09 16:34:33 -07002308pub fn show_sizes() {
2309 // This isn't panic safe.
2310 for min in &[1, 2, 4, 8] {
2311 let msize = c::boot_trailer_sz(*min);
2312 println!("{:2}: {} (0x{:x})", min, msize, msize);
2313 }
2314}
David Brown95de4502019-11-15 12:01:34 -07002315
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002316#[cfg(not(feature = "max-align-32"))]
David Brown95de4502019-11-15 12:01:34 -07002317fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07002318 &[1, 2, 4, 8]
2319}
2320
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002321#[cfg(feature = "max-align-32")]
David Brown95de4502019-11-15 12:01:34 -07002322fn test_alignments() -> &'static [usize] {
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002323 &[32]
David Brown95de4502019-11-15 12:01:34 -07002324}
David Brown80704f82024-04-11 10:42:10 -06002325
2326/// For testing, some of the tests are quite slow. This will query for an
2327/// environment variable `MCUBOOT_SKIP_SLOW_TESTS`, which can be set to avoid
2328/// running these tests.
2329fn skip_slow_test() -> bool {
2330 if let Ok(_) = std::env::var("MCUBOOT_SKIP_SLOW_TESTS") {
2331 true
2332 } else {
2333 false
2334 }
2335}