blob: 54e4f31b0631f5c2d87e479b6300b5598ae20cca [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
692 // Let's try an image halfway through.
693 for i in 1 .. total_flash_ops {
694 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300695 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700696 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700697 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700698 warn!("FAIL at step {} of {}", i, total_flash_ops);
699 fails += 1;
700 }
701
David Brown84b49f72019-03-01 10:58:22 -0700702 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
703 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100704 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700705 fails += 1;
706 }
707
David Brown84b49f72019-03-01 10:58:22 -0700708 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
709 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100710 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700711 fails += 1;
712 }
713
David Brownaec56b22021-03-10 05:22:07 -0700714 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
715 warn!("Secondary slot FAIL at step {} of {}",
716 i, total_flash_ops);
717 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700718 }
719 }
720
721 if fails > 0 {
722 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
723 fails as f32 * 100.0 / total_flash_ops as f32);
724 }
725
726 fails > 0
727 }
728
David Brown5c9e0f12019-01-09 16:34:33 -0700729 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600730 if !Caps::modifies_flash() {
731 return false;
732 }
733
David Brown5c9e0f12019-01-09 16:34:33 -0700734 let mut fails = 0;
735 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700736 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700737 info!("Random interruptions at reset points={:?}", total_counts);
738
David Brown84b49f72019-03-01 10:58:22 -0700739 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300740 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700741 // TODO: This result is ignored.
742 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700743 } else {
744 true
745 };
David Vincze2d736ad2019-02-18 11:50:22 +0100746 if !primary_slot_ok || !secondary_slot_ok {
747 error!("Image mismatch after random interrupts: primary slot={} \
748 secondary slot={}",
749 if primary_slot_ok { "ok" } else { "fail" },
750 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700751 fails += 1;
752 }
David Brown84b49f72019-03-01 10:58:22 -0700753 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
754 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100755 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700756 fails += 1;
757 }
David Brown84b49f72019-03-01 10:58:22 -0700758 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
759 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100760 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700761 fails += 1;
762 }
763
764 if fails > 0 {
765 error!("Error testing perm upgrade with {} fails", total_fails);
766 }
767
768 fails > 0
769 }
770
David Brown5c9e0f12019-01-09 16:34:33 -0700771 pub fn run_revert_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600772 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700773 return false;
774 }
David Brown5c9e0f12019-01-09 16:34:33 -0700775
David Brown5c9e0f12019-01-09 16:34:33 -0700776 let mut fails = 0;
777
Fabio Utzigf5480c72019-11-28 10:41:57 -0300778 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300779 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700780 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700781 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700782 error!("Revert failed at interruption {}", i);
783 fails += 1;
784 }
785 }
786 }
787
788 fails > 0
789 }
790
David Brown5c9e0f12019-01-09 16:34:33 -0700791 pub fn run_norevert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600792 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700793 return false;
794 }
David Brown5c9e0f12019-01-09 16:34:33 -0700795
David Brown76101572019-02-28 11:29:03 -0700796 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700797 let mut fails = 0;
798
799 info!("Try norevert");
800
801 // First do a normal upgrade...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100802 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700803 warn!("Failed first boot");
804 fails += 1;
805 }
806
807 //FIXME: copy_done is written by boot_go, is it ok if no copy
808 // was ever done?
809
David Brown84b49f72019-03-01 10:58:22 -0700810 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100811 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700812 fails += 1;
813 }
David Brown84b49f72019-03-01 10:58:22 -0700814 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
815 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100816 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700817 fails += 1;
818 }
David Brown84b49f72019-03-01 10:58:22 -0700819 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
820 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100821 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700822 fails += 1;
823 }
824
David Vincze2d736ad2019-02-18 11:50:22 +0100825 // Marks image in the primary slot as permanent,
826 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700827 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700828
David Brown84b49f72019-03-01 10:58:22 -0700829 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
830 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100831 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700832 fails += 1;
833 }
834
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100835 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700836 warn!("Failed second boot");
837 fails += 1;
838 }
839
David Brown84b49f72019-03-01 10:58:22 -0700840 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
841 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100842 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700843 fails += 1;
844 }
David Brown84b49f72019-03-01 10:58:22 -0700845 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700846 warn!("Failed image verification");
847 fails += 1;
848 }
849
850 if fails > 0 {
851 error!("Error running upgrade without revert");
852 }
853
854 fails > 0
855 }
856
Andrzej Puzdrowski9324d2b2022-08-11 15:16:56 +0200857 // Test taht too big upgrade image will be rejected
858 pub fn run_oversizefail_upgrade(&self) -> bool {
859 let mut flash = self.flash.clone();
860 let mut fails = 0;
861
862 info!("Try upgrade image with to big size");
863
864 // Only perform this test if an upgrade is expected to happen.
865 if !Caps::modifies_flash() {
866 info!("Skipping upgrade image with bad signature");
867 return false;
868 }
869
870 self.mark_upgrades(&mut flash, 0);
871 self.mark_permanent_upgrades(&mut flash, 0);
872 self.mark_upgrades(&mut flash, 1);
873
874 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
875 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
876 warn!("1. Mismatched trailer for the primary slot");
877 fails += 1;
878 }
879
880 // Run the bootloader...
881 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
882 warn!("Failed first boot");
883 fails += 1;
884 }
885
886 // State should not have changed
887 if !self.verify_images(&flash, 0, 0) {
888 warn!("Failed image verification");
889 fails += 1;
890 }
891 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
892 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
893 warn!("2. Mismatched trailer for the primary slot");
894 fails += 1;
895 }
896
897 if fails > 0 {
898 error!("Expected an upgrade failure when image has to big size");
899 }
900
901 fails > 0
902 }
903
David Brown2ee5f7f2020-01-13 14:04:01 -0700904 // Test that an upgrade is rejected. Assumes that the image was build
905 // such that the upgrade is instead a downgrade.
906 pub fn run_nodowngrade(&self) -> bool {
907 if !Caps::DowngradePrevention.present() {
908 return false;
909 }
910
911 let mut flash = self.flash.clone();
912 let mut fails = 0;
913
914 info!("Try no downgrade");
915
916 // First, do a normal upgrade.
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100917 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700918 warn!("Failed first boot");
919 fails += 1;
920 }
921
922 if !self.verify_images(&flash, 0, 0) {
923 warn!("Failed verification after downgrade rejection");
924 fails += 1;
925 }
926
927 if fails > 0 {
928 error!("Error testing downgrade rejection");
929 }
930
931 fails > 0
932 }
933
David Vincze2d736ad2019-02-18 11:50:22 +0100934 // Tests a new image written to the primary slot that already has magic and
935 // image_ok set while there is no image on the secondary slot, so no revert
936 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700937 pub fn run_norevert_newimage(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600938 if !Caps::modifies_flash() {
939 info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
940 return false;
941 }
942
David Brown76101572019-02-28 11:29:03 -0700943 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700944 let mut fails = 0;
945
946 info!("Try non-revert on imgtool generated image");
947
David Brown84b49f72019-03-01 10:58:22 -0700948 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700949
David Vincze2d736ad2019-02-18 11:50:22 +0100950 // This simulates writing an image created by imgtool to
951 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700952 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
953 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100954 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700955 fails += 1;
956 }
957
958 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100959 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700960 warn!("Failed first boot");
961 fails += 1;
962 }
963
964 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700965 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700966 warn!("Failed image verification");
967 fails += 1;
968 }
David Brown84b49f72019-03-01 10:58:22 -0700969 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
970 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100971 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700972 fails += 1;
973 }
David Brown84b49f72019-03-01 10:58:22 -0700974 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
975 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100976 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700977 fails += 1;
978 }
979
980 if fails > 0 {
981 error!("Expected a non revert with new image");
982 }
983
984 fails > 0
985 }
986
David Vincze2d736ad2019-02-18 11:50:22 +0100987 // Tests a new image written to the primary slot that already has magic and
988 // image_ok set while there is no image on the secondary slot, so no revert
989 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700990 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700991 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700992 let mut fails = 0;
993
994 info!("Try upgrade image with bad signature");
995
David Brown6db44d72021-05-26 16:22:58 -0600996 // Only perform this test if an upgrade is expected to happen.
997 if !Caps::modifies_flash() {
998 info!("Skipping upgrade image with bad signature");
999 return false;
1000 }
1001
David Brown84b49f72019-03-01 10:58:22 -07001002 self.mark_upgrades(&mut flash, 0);
1003 self.mark_permanent_upgrades(&mut flash, 0);
1004 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -07001005
David Brown84b49f72019-03-01 10:58:22 -07001006 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1007 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +01001008 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -07001009 fails += 1;
1010 }
1011
1012 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001013 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -07001014 warn!("Failed first boot");
1015 fails += 1;
1016 }
1017
1018 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -07001019 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -07001020 warn!("Failed image verification");
1021 fails += 1;
1022 }
David Brown84b49f72019-03-01 10:58:22 -07001023 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1024 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +01001025 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -07001026 fails += 1;
1027 }
1028
1029 if fails > 0 {
1030 error!("Expected an upgrade failure when image has bad signature");
1031 }
1032
1033 fails > 0
1034 }
1035
Fabio Utzig2c3be5c2020-07-09 19:54:45 -03001036 // Should detect there is a leftover trailer in an otherwise erased
1037 // secondary slot and erase its trailer.
1038 pub fn run_secondary_leftover_trailer(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -06001039 if !Caps::modifies_flash() {
1040 return false;
1041 }
1042
Fabio Utzig2c3be5c2020-07-09 19:54:45 -03001043 let mut flash = self.flash.clone();
1044 let mut fails = 0;
1045
1046 info!("Try with a leftover trailer in the secondary; must be erased");
1047
1048 // Add a trailer on the secondary slot
1049 self.mark_permanent_upgrades(&mut flash, 1);
1050 self.mark_upgrades(&mut flash, 1);
1051
1052 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001053 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -03001054 warn!("Failed first boot");
1055 fails += 1;
1056 }
1057
1058 // State should not have changed
1059 if !self.verify_images(&flash, 0, 0) {
1060 warn!("Failed image verification");
1061 fails += 1;
1062 }
1063 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1064 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
1065 warn!("Mismatched trailer for the secondary slot");
1066 fails += 1;
1067 }
1068
1069 if fails > 0 {
1070 error!("Expected trailer on secondary slot to be erased");
1071 }
1072
1073 fails > 0
1074 }
1075
David Brown5c9e0f12019-01-09 16:34:33 -07001076 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -03001077 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -07001078 }
1079
David Brown5c9e0f12019-01-09 16:34:33 -07001080 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -03001081 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -07001082 }
1083
1084 /// This test runs a simple upgrade with no fails in the images, but
1085 /// allowing for fails in the status area. This should run to the end
1086 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -07001087 pub fn run_with_status_fails_complete(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -06001088 if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -07001089 return false;
1090 }
1091
David Brown76101572019-02-28 11:29:03 -07001092 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001093 let mut fails = 0;
1094
1095 info!("Try swap with status fails");
1096
David Brown84b49f72019-03-01 10:58:22 -07001097 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001098 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -07001099
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001100 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brownc423ac42021-06-04 13:47:34 -06001101 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -07001102 warn!("Failed!");
1103 fails += 1;
1104 }
1105
1106 // Failed writes to the marked "bad" region don't assert anymore.
1107 // Any detected assert() is happening in another part of the code.
David Brownc423ac42021-06-04 13:47:34 -06001108 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001109 warn!("At least one assert() was called");
1110 fails += 1;
1111 }
1112
David Brown84b49f72019-03-01 10:58:22 -07001113 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1114 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +01001115 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -07001116 fails += 1;
1117 }
1118
David Brown84b49f72019-03-01 10:58:22 -07001119 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -07001120 warn!("Failed image verification");
1121 fails += 1;
1122 }
1123
David Vincze2d736ad2019-02-18 11:50:22 +01001124 info!("validate primary slot enabled; \
1125 re-run of boot_go should just work");
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001126 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -07001127 warn!("Failed!");
1128 fails += 1;
1129 }
1130
1131 if fails > 0 {
1132 error!("Error running upgrade with status write fails");
1133 }
1134
1135 fails > 0
1136 }
1137
1138 /// This test runs a simple upgrade with no fails in the images, but
1139 /// allowing for fails in the status area. This should run to the end
1140 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -07001141 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -06001142 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -07001143 false
David Vincze2d736ad2019-02-18 11:50:22 +01001144 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -07001145
David Brown76101572019-02-28 11:29:03 -07001146 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001147 let mut fails = 0;
1148 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -07001149
David Brown85904a82019-01-11 13:45:12 -07001150 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -07001151
David Brown85904a82019-01-11 13:45:12 -07001152 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -07001153
David Brown84b49f72019-03-01 10:58:22 -07001154 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001155 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -07001156
1157 // Should not fail, writing to bad regions does not assert
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001158 let asserts = c::boot_go(&mut flash, &self.areadesc,
1159 Some(&mut count), None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001160 if asserts != 0 {
1161 warn!("At least one assert() was called");
1162 fails += 1;
1163 }
1164
David Brown76101572019-02-28 11:29:03 -07001165 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -07001166
1167 info!("Resuming an interrupted swap operation");
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001168 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1169 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001170
1171 // This might throw no asserts, for large sector devices, where
1172 // a single failure writing is indistinguishable from no failure,
1173 // or throw a single assert for small sector devices that fail
1174 // multiple times...
1175 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +01001176 warn!("Expected single assert validating the primary slot, \
1177 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -07001178 fails += 1;
1179 }
1180
1181 if fails > 0 {
1182 error!("Error running upgrade with status write fails");
1183 }
1184
1185 fails > 0
1186 } else {
David Brown76101572019-02-28 11:29:03 -07001187 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001188 let mut fails = 0;
1189
1190 info!("Try interrupted swap with status fails");
1191
David Brown84b49f72019-03-01 10:58:22 -07001192 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001193 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -07001194
1195 // This is expected to fail while writing to bad regions...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001196 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1197 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001198 if asserts == 0 {
1199 warn!("No assert() detected");
1200 fails += 1;
1201 }
1202
1203 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -07001204 }
David Brown5c9e0f12019-01-09 16:34:33 -07001205 }
1206
David Brown0dfb8102021-06-03 15:29:11 -06001207 /// Test the direct XIP configuration. With this mode, flash images are never moved, and the
1208 /// bootloader merely selects which partition is the proper one to boot.
1209 pub fn run_direct_xip(&self) -> bool {
1210 if !Caps::DirectXip.present() {
1211 return false;
1212 }
1213
1214 // Clone the flash so we can tell if unchanged.
1215 let mut flash = self.flash.clone();
1216
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001217 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brown0dfb8102021-06-03 15:29:11 -06001218
1219 // Ensure the boot was successful.
1220 let resp = if let Some(resp) = result.resp() {
1221 resp
1222 } else {
1223 panic!("Boot didn't return a valid result");
1224 };
1225
1226 // This configuration should always try booting from the first upgrade slot.
1227 if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
1228 assert_eq!(offset, resp.image_off as usize);
1229 assert_eq!(dev_id, resp.flash_dev_id);
1230 } else {
1231 panic!("Unable to find upgrade image");
1232 }
1233 false
1234 }
1235
David Brown8a4e23b2021-06-11 10:29:01 -06001236 /// Test the ram-loading.
1237 pub fn run_ram_load(&self) -> bool {
1238 if !Caps::RamLoad.present() {
1239 return false;
1240 }
1241
1242 // Clone the flash so we can tell if unchanged.
1243 let mut flash = self.flash.clone();
1244
David Brownf17d3912021-06-23 16:10:51 -06001245 // Setup ram based on the ram configuration we determined earlier for the images.
1246 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
David Brown8a4e23b2021-06-11 10:29:01 -06001247
David Brownf17d3912021-06-23 16:10:51 -06001248 // println!("Ram: {:#?}", self.ram);
David Brown8a4e23b2021-06-11 10:29:01 -06001249
David Brownf17d3912021-06-23 16:10:51 -06001250 // Verify that the images area loaded into this.
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001251 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None,
1252 None, true));
David Brown8a4e23b2021-06-11 10:29:01 -06001253 if !result.success() {
David Brownf17d3912021-06-23 16:10:51 -06001254 error!("Failed to execute ram-load");
David Brown8a4e23b2021-06-11 10:29:01 -06001255 return true;
1256 }
1257
David Brownf17d3912021-06-23 16:10:51 -06001258 // Verify each image.
1259 for image in &self.images {
1260 let place = self.ram.lookup(&image.slots[0]);
1261 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1262 place.size as usize);
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001263 let src_sz = image.upgrades.size();
1264 if src_sz > ram_image.len() {
David Brownf17d3912021-06-23 16:10:51 -06001265 error!("Image ended up too large, nonsensical");
1266 return true;
1267 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001268 let src_image = &image.upgrades.plain[0..src_sz];
1269 let ram_image = &ram_image[0..src_sz];
David Brownf17d3912021-06-23 16:10:51 -06001270 if ram_image != src_image {
1271 error!("Image not loaded correctly");
1272 return true;
1273 }
1274
1275 }
1276
1277 return false;
David Brown8a4e23b2021-06-11 10:29:01 -06001278 }
1279
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001280 /// Test the split ram-loading.
1281 pub fn run_split_ram_load(&self) -> bool {
1282 if !Caps::RamLoad.present() {
1283 return false;
1284 }
1285
1286 // Clone the flash so we can tell if unchanged.
1287 let mut flash = self.flash.clone();
1288
1289 // Setup ram based on the ram configuration we determined earlier for the images.
1290 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1291
1292 for (idx, _image) in (&self.images).iter().enumerate() {
1293 // Verify that the images area loaded into this.
1294 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc,
1295 None, Some(idx as i32), true));
1296 if !result.success() {
1297 error!("Failed to execute ram-load");
1298 return true;
1299 }
1300 }
1301
1302 // Verify each image.
1303 for image in &self.images {
1304 let place = self.ram.lookup(&image.slots[0]);
1305 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1306 place.size as usize);
1307 let src_sz = image.upgrades.size();
1308 if src_sz > ram_image.len() {
1309 error!("Image ended up too large, nonsensical");
1310 return true;
1311 }
1312 let src_image = &image.upgrades.plain[0..src_sz];
1313 let ram_image = &ram_image[0..src_sz];
1314 if ram_image != src_image {
1315 error!("Image not loaded correctly");
1316 return true;
1317 }
1318
1319 }
1320
1321 return false;
1322 }
1323
Roland Mikheld6703522023-04-27 14:24:30 +02001324 pub fn run_hw_rollback_prot(&self) -> bool {
1325 if !Caps::HwRollbackProtection.present() {
1326 return false;
1327 }
1328
1329 let mut flash = self.flash.clone();
1330
1331 // set the "stored" security counter to a fixed value.
1332 c::set_security_counter(0, 30);
1333
1334 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
1335
1336 if result.success() {
1337 warn!("Successful boot when it did not suppose to happen!");
1338 return true;
1339 }
1340 let counter_val = c::get_security_counter(0);
1341 if counter_val != 30 {
1342 warn!("Counter was changed when it did not suppose to!");
1343 return true;
1344 }
1345
1346 false
1347 }
1348
Roland Mikhel6945bb62023-04-11 15:57:49 +02001349 pub fn run_ram_load_boot_with_result(&self, expected_result: bool) -> bool {
1350 if !Caps::RamLoad.present() {
1351 return false;
1352 }
1353 // Clone the flash so we can tell if unchanged.
1354 let mut flash = self.flash.clone();
1355
1356 // Create RAM config.
1357 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1358
1359 // Run the bootloader, and verify that it couldn't run to completion.
1360 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None,
1361 None, true));
1362
1363 if result.success() != expected_result {
1364 error!("RAM load boot result was not of the expected value! (was: {}, expected: {})", result.success(), expected_result);
1365 return true;
1366 }
1367
1368 false
1369 }
1370
David Brown5c9e0f12019-01-09 16:34:33 -07001371 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -07001372 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001373 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -07001374 if Caps::OverwriteUpgrade.present() {
1375 return;
1376 }
1377
David Brown84b49f72019-03-01 10:58:22 -07001378 // Set this for each image.
1379 for image in &self.images {
1380 let dev_id = &image.slots[slot].dev_id;
1381 let dev = flash.get_mut(&dev_id).unwrap();
1382 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001383 let off = &image.slots[slot].base_off;
1384 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -07001385 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -07001386
David Brown84b49f72019-03-01 10:58:22 -07001387 // Mark the status area as a bad area
1388 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1389 }
David Brown5c9e0f12019-01-09 16:34:33 -07001390 }
1391
David Brown76101572019-02-28 11:29:03 -07001392 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001393 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001394 return;
1395 }
1396
David Brown84b49f72019-03-01 10:58:22 -07001397 for image in &self.images {
1398 let dev_id = &image.slots[slot].dev_id;
1399 let dev = flash.get_mut(&dev_id).unwrap();
1400 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001401
David Brown84b49f72019-03-01 10:58:22 -07001402 // Disabling write verification the only assert triggered by
1403 // boot_go should be checking for integrity of status bytes.
1404 dev.set_verify_writes(false);
1405 }
David Brown5c9e0f12019-01-09 16:34:33 -07001406 }
1407
David Browndb505822019-03-01 10:04:20 -07001408 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1409 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001410 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001411 // Clone the flash to have a new copy.
1412 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001413
Fabio Utziged4a5362019-07-30 12:43:23 -03001414 if permanent {
1415 self.mark_permanent_upgrades(&mut flash, 1);
1416 }
David Brown5c9e0f12019-01-09 16:34:33 -07001417
David Browndb505822019-03-01 10:04:20 -07001418 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001419
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001420 let (first_interrupted, count) = match c::boot_go(&mut flash,
1421 &self.areadesc,
1422 Some(&mut counter),
1423 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001424 x if x.interrupted() => (true, stop.unwrap()),
1425 x if x.success() => (false, -counter),
1426 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001427 };
David Brown5c9e0f12019-01-09 16:34:33 -07001428
David Browndb505822019-03-01 10:04:20 -07001429 counter = 0;
1430 if first_interrupted {
1431 // fl.dump();
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001432 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1433 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001434 x if x.interrupted() => panic!("Shouldn't stop again"),
1435 x if x.success() => (),
1436 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001437 }
1438 }
David Brown5c9e0f12019-01-09 16:34:33 -07001439
David Browndb505822019-03-01 10:04:20 -07001440 (flash, count - counter)
1441 }
1442
1443 fn try_revert(&self, count: usize) -> SimMultiFlash {
1444 let mut flash = self.flash.clone();
1445
1446 // fl.write_file("image0.bin").unwrap();
1447 for i in 0 .. count {
1448 info!("Running boot pass {}", i + 1);
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001449 assert!(c::boot_go(&mut flash, &self.areadesc, None, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001450 }
1451 flash
1452 }
1453
1454 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1455 let mut flash = self.flash.clone();
1456 let mut fails = 0;
1457
1458 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001459 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1460 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001461 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001462 fails += 1;
1463 }
1464
Fabio Utzig8af7f792019-07-30 12:40:01 -03001465 // In a multi-image setup, copy done might be set if any number of
1466 // images was already successfully swapped.
1467 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1468 warn!("copy_done should be unset");
1469 fails += 1;
1470 }
1471
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001472 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001473 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001474 fails += 1;
1475 }
1476
David Brown84b49f72019-03-01 10:58:22 -07001477 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001478 warn!("Image in the primary slot before revert is invalid at stop={}",
1479 stop);
1480 fails += 1;
1481 }
David Brown84b49f72019-03-01 10:58:22 -07001482 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001483 warn!("Image in the secondary slot before revert is invalid at stop={}",
1484 stop);
1485 fails += 1;
1486 }
David Brown84b49f72019-03-01 10:58:22 -07001487 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1488 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001489 warn!("Mismatched trailer for the primary slot before revert");
1490 fails += 1;
1491 }
David Brown84b49f72019-03-01 10:58:22 -07001492 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1493 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001494 warn!("Mismatched trailer for the secondary slot before revert");
1495 fails += 1;
1496 }
1497
1498 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001499 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001500 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1501 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001502 warn!("Should have stopped revert at interruption point");
1503 fails += 1;
1504 }
1505
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001506 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001507 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001508 fails += 1;
1509 }
1510
David Brown84b49f72019-03-01 10:58:22 -07001511 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001512 warn!("Image in the primary slot after revert is invalid at stop={}",
1513 stop);
1514 fails += 1;
1515 }
David Brown84b49f72019-03-01 10:58:22 -07001516 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001517 warn!("Image in the secondary slot after revert is invalid at stop={}",
1518 stop);
1519 fails += 1;
1520 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001521
David Brown84b49f72019-03-01 10:58:22 -07001522 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1523 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001524 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001525 fails += 1;
1526 }
David Brown84b49f72019-03-01 10:58:22 -07001527 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1528 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001529 warn!("Mismatched trailer for the secondary slot after revert");
1530 fails += 1;
1531 }
1532
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001533 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001534 warn!("Should have finished 3rd boot");
1535 fails += 1;
1536 }
1537
1538 if !self.verify_images(&flash, 0, 0) {
1539 warn!("Image in the primary slot is invalid on 1st boot after revert");
1540 fails += 1;
1541 }
1542 if !self.verify_images(&flash, 1, 1) {
1543 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1544 fails += 1;
1545 }
1546
David Browndb505822019-03-01 10:04:20 -07001547 fails > 0
1548 }
1549
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001550
David Browndb505822019-03-01 10:04:20 -07001551 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1552 let mut flash = self.flash.clone();
1553
David Brown84b49f72019-03-01 10:58:22 -07001554 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001555
1556 let mut rng = rand::thread_rng();
1557 let mut resets = vec![0i32; count];
1558 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001559 for reset in &mut resets {
David Brown9c6322f2021-08-19 13:03:39 -06001560 let reset_counter = rng.gen_range(1 ..= remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001561 let mut counter = reset_counter;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001562 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1563 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001564 x if x.interrupted() => (),
1565 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001566 }
1567 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001568 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001569 }
1570
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001571 match c::boot_go(&mut flash, &self.areadesc, None, None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001572 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1573 x if x.success() => (),
1574 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001575 }
David Brown5c9e0f12019-01-09 16:34:33 -07001576
David Browndb505822019-03-01 10:04:20 -07001577 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001578 }
David Brown84b49f72019-03-01 10:58:22 -07001579
1580 /// Verify the image in the given flash device, the specified slot
1581 /// against the expected image.
1582 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001583 self.images.iter().all(|image| {
1584 verify_image(flash, &image.slots[slot],
1585 match against {
1586 0 => &image.primaries,
1587 1 => &image.upgrades,
1588 _ => panic!("Invalid 'against'")
1589 })
1590 })
David Brown84b49f72019-03-01 10:58:22 -07001591 }
1592
David Brownc3898d62019-08-05 14:20:02 -06001593 /// Verify the images, according to the dependency test.
1594 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1595 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1596 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1597 if !verify_image(flash, &image.slots[0],
1598 match upgrade {
1599 UpgradeInfo::Upgraded => &image.upgrades,
1600 UpgradeInfo::Held => &image.primaries,
1601 }) {
1602 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1603 return true;
1604 }
1605 }
1606
1607 false
1608 }
1609
Fabio Utzig8af7f792019-07-30 12:40:01 -03001610 /// Verify that at least one of the trailers of the images have the
1611 /// specified values.
1612 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1613 magic: Option<u8>, image_ok: Option<u8>,
1614 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001615 self.images.iter().any(|image| {
1616 verify_trailer(flash, &image.slots[slot],
1617 magic, image_ok, copy_done)
1618 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001619 }
1620
David Brown84b49f72019-03-01 10:58:22 -07001621 /// Verify that the trailers of the images have the specified
1622 /// values.
1623 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1624 magic: Option<u8>, image_ok: Option<u8>,
1625 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001626 self.images.iter().all(|image| {
1627 verify_trailer(flash, &image.slots[slot],
1628 magic, image_ok, copy_done)
1629 })
David Brown84b49f72019-03-01 10:58:22 -07001630 }
1631
1632 /// Mark each of the images for permanent upgrade.
1633 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1634 for image in &self.images {
1635 mark_permanent_upgrade(flash, &image.slots[slot]);
1636 }
1637 }
1638
1639 /// Mark each of the images for permanent upgrade.
1640 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1641 for image in &self.images {
1642 mark_upgrade(flash, &image.slots[slot]);
1643 }
1644 }
David Brown297029a2019-08-13 14:29:51 -06001645
1646 /// Dump out the flash image(s) to one or more files for debugging
1647 /// purposes. The names will be written as either "{prefix}.mcubin" or
1648 /// "{prefix}-001.mcubin" depending on how many images there are.
1649 pub fn debug_dump(&self, prefix: &str) {
1650 for (id, fdev) in &self.flash {
1651 let name = if self.flash.len() == 1 {
1652 format!("{}.mcubin", prefix)
1653 } else {
1654 format!("{}-{:>0}.mcubin", prefix, id)
1655 };
1656 fdev.write_file(&name).unwrap();
1657 }
1658 }
David Brown5c9e0f12019-01-09 16:34:33 -07001659}
1660
David Brownbf32c272021-06-16 17:11:37 -06001661impl RamData {
David Brownf17d3912021-06-23 16:10:51 -06001662 // TODO: This is not correct. The second slot of each image should be at the same address as
1663 // the primary.
David Brownbf32c272021-06-16 17:11:37 -06001664 fn new(slots: &[[SlotInfo; 2]]) -> RamData {
1665 let mut addr = RAM_LOAD_ADDR;
1666 let mut places = BTreeMap::new();
David Brownf17d3912021-06-23 16:10:51 -06001667 // println!("Setup:-------------");
David Brownbf32c272021-06-16 17:11:37 -06001668 for imgs in slots {
1669 for si in imgs {
David Brownf17d3912021-06-23 16:10:51 -06001670 // println!("Setup: si: {:?}", si);
David Brownbf32c272021-06-16 17:11:37 -06001671 let offset = addr;
1672 let size = si.len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001673 places.insert(SlotKey {
1674 dev_id: si.dev_id,
David Brownf17d3912021-06-23 16:10:51 -06001675 base_off: si.base_off,
David Brownbf32c272021-06-16 17:11:37 -06001676 }, SlotPlace { offset, size });
David Brownf17d3912021-06-23 16:10:51 -06001677 // println!(" load: offset: {}, size: {}", offset, size);
David Brownbf32c272021-06-16 17:11:37 -06001678 }
David Brownf17d3912021-06-23 16:10:51 -06001679 addr += imgs[0].len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001680 }
1681 RamData {
1682 places,
1683 total: addr,
1684 }
1685 }
David Brownf17d3912021-06-23 16:10:51 -06001686
1687 /// Lookup the ram data associated with a given flash partition. We just panic if not present,
1688 /// because all slots used should be in the map.
1689 fn lookup(&self, slot: &SlotInfo) -> &SlotPlace {
1690 self.places.get(&SlotKey{dev_id: slot.dev_id, base_off: slot.base_off})
1691 .expect("RamData should contain all slots")
1692 }
David Brownbf32c272021-06-16 17:11:37 -06001693}
1694
David Brown5c9e0f12019-01-09 16:34:33 -07001695/// Show the flash layout.
1696#[allow(dead_code)]
1697fn show_flash(flash: &dyn Flash) {
1698 println!("---- Flash configuration ----");
1699 for sector in flash.sector_iter() {
1700 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1701 sector.num, sector.base, sector.size);
1702 }
David Brown599b2db2021-03-10 05:23:26 -07001703 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001704}
1705
David Browna62c3eb2021-10-25 16:32:40 -06001706#[derive(Debug)]
1707enum ImageSize {
1708 /// Make the image the specified given size.
1709 Given(usize),
1710 /// Make the image as large as it can be for the partition/device.
1711 Largest,
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001712 /// Make the image quite larger than it can be for the partition/device/
1713 Oversized,
David Browna62c3eb2021-10-25 16:32:40 -06001714}
1715
Andrzej Puzdrowski5b90dc82022-08-08 12:49:24 +02001716#[cfg(not(feature = "max-align-32"))]
1717fn tralier_estimation(dev: &dyn Flash) -> usize {
Andrzej Puzdrowski5b90dc82022-08-08 12:49:24 +02001718 c::boot_trailer_sz(dev.align() as u32) as usize
1719}
1720
1721#[cfg(feature = "max-align-32")]
1722fn tralier_estimation(dev: &dyn Flash) -> usize {
1723
1724 let sector_size = dev.sector_iter().next().unwrap().size as u32;
1725
1726 align_up(c::boot_trailer_sz(dev.align() as u32), sector_size) as usize
1727}
1728
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001729fn image_largest_trailer(dev: &dyn Flash) -> usize {
1730 // Using the header size we know, the trailer size, and the slot size, we can compute
1731 // the largest image possible.
1732 let trailer = if Caps::OverwriteUpgrade.present() {
1733 // This computation is incorrect, and we need to figure out the correct size.
1734 // c::boot_status_sz(dev.align() as u32) as usize
1735 16 + 4 * dev.align()
1736 } else if Caps::SwapUsingMove.present() {
1737 let sector_size = dev.sector_iter().next().unwrap().size as u32;
1738 align_up(c::boot_trailer_sz(dev.align() as u32), sector_size) as usize
1739 } else if Caps::SwapUsingScratch.present() {
1740 tralier_estimation(dev)
1741 } else {
1742 panic!("The maximum image size can't be calculated.")
1743 };
1744
1745 trailer
1746}
1747
David Brown5c9e0f12019-01-09 16:34:33 -07001748/// Install a "program" into the given image. This fakes the image header, or at least all of the
1749/// fields used by the given code. Returns a copy of the image that was written.
David Browna62c3eb2021-10-25 16:32:40 -06001750fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: ImageSize,
David Brownf17d3912021-06-23 16:10:51 -06001751 ram: &RamData,
Roland Mikhel6945bb62023-04-11 15:57:49 +02001752 deps: &dyn Depender, img_manipulation: ImageManipulation, security_counter:Option<u32>) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001753 let offset = slot.base_off;
1754 let slot_len = slot.len;
1755 let dev_id = slot.dev_id;
David Brown07dd5f02021-10-26 16:43:15 -06001756 let dev = flash.get_mut(&dev_id).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001757
David Brown43643dd2019-01-11 15:43:28 -07001758 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
Roland Mikhel6945bb62023-04-11 15:57:49 +02001759 if img_manipulation == ImageManipulation::IgnoreRamLoadFlag {
1760 tlv.set_ignore_ram_load_flag();
1761 }
David Brown5c9e0f12019-01-09 16:34:33 -07001762
Roland Mikheld6703522023-04-27 14:24:30 +02001763 tlv.set_security_counter(security_counter);
1764
Roland Mikhel6945bb62023-04-11 15:57:49 +02001765
David Brownc3898d62019-08-05 14:20:02 -06001766 // Add the dependencies early to the tlv.
1767 for dep in deps.my_deps(offset, slot.index) {
1768 tlv.add_dependency(deps.other_id(), &dep);
1769 }
1770
David Brown5c9e0f12019-01-09 16:34:33 -07001771 const HDR_SIZE: usize = 32;
David Brownf17d3912021-06-23 16:10:51 -06001772 let place = ram.lookup(&slot);
1773 let load_addr = if Caps::RamLoad.present() {
Roland Mikhel6945bb62023-04-11 15:57:49 +02001774 match img_manipulation {
1775 ImageManipulation::WrongOffset => u32::MAX,
1776 ImageManipulation::OverlapImages(true) => RAM_LOAD_ADDR,
1777 ImageManipulation::OverlapImages(false) => place.offset - 1,
1778 _ => place.offset
1779 }
David Brownf17d3912021-06-23 16:10:51 -06001780 } else {
1781 0
1782 };
1783
David Browna62c3eb2021-10-25 16:32:40 -06001784 let len = match len {
1785 ImageSize::Given(size) => size,
David Brown07dd5f02021-10-26 16:43:15 -06001786 ImageSize::Largest => {
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001787 let trailer = image_largest_trailer(dev);
David Brown07dd5f02021-10-26 16:43:15 -06001788 let tlv_len = tlv.estimate_size();
1789 info!("slot: 0x{:x}, HDR: 0x{:x}, trailer: 0x{:x}",
1790 slot_len, HDR_SIZE, trailer);
1791 slot_len - HDR_SIZE - trailer - tlv_len
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001792 },
1793 ImageSize::Oversized => {
1794 let trailer = image_largest_trailer(dev);
1795 let tlv_len = tlv.estimate_size();
1796 info!("slot: 0x{:x}, HDR: 0x{:x}, trailer: 0x{:x}",
1797 slot_len, HDR_SIZE, trailer);
1798 // the overflow size is rougly estimated to work for all
1799 // configurations. It might be precise if tlv_len will be maked precise.
1800 slot_len - HDR_SIZE - trailer - tlv_len + dev.align()*4
David Brown07dd5f02021-10-26 16:43:15 -06001801 }
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001802
David Browna62c3eb2021-10-25 16:32:40 -06001803 };
1804
David Brown5c9e0f12019-01-09 16:34:33 -07001805 // Generate a boot header. Note that the size doesn't include the header.
1806 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001807 magic: tlv.get_magic(),
David Brownf17d3912021-06-23 16:10:51 -06001808 load_addr,
David Brown5c9e0f12019-01-09 16:34:33 -07001809 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001810 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001811 img_size: len as u32,
1812 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001813 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001814 _pad2: 0,
1815 };
1816
1817 let mut b_header = [0; HDR_SIZE];
1818 b_header[..32].clone_from_slice(header.as_raw());
1819 assert_eq!(b_header.len(), HDR_SIZE);
1820
1821 tlv.add_bytes(&b_header);
1822
1823 // The core of the image itself is just pseudorandom data.
1824 let mut b_img = vec![0; len];
1825 splat(&mut b_img, offset);
1826
David Browncb47dd72019-08-05 14:21:49 -06001827 // Add some information at the start of the payload to make it easier
1828 // to see what it is. This will fail if the image itself is too small.
1829 {
1830 let mut wr = Cursor::new(&mut b_img);
1831 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1832 offset, dev_id, slot).unwrap();
1833 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1834 }
1835
David Brown5c9e0f12019-01-09 16:34:33 -07001836 // TLV signatures work over plain image
1837 tlv.add_bytes(&b_img);
1838
1839 // Generate encrypted images
Salome Thirot6fdbf552021-05-14 16:46:14 +01001840 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1841 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001842 let mut b_encimg = vec![];
1843 if is_encrypted {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001844 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1845 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001846 tlv.generate_enc_key();
1847 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001848 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001849 b_encimg = b_img.clone();
Salome Thirot6fdbf552021-05-14 16:46:14 +01001850 if aes256 {
1851 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001852 let block = Aes256::new(&key);
1853 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001854 cipher.apply_keystream(&mut b_encimg);
1855 } else {
1856 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001857 let block = Aes128::new(&key);
1858 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001859 cipher.apply_keystream(&mut b_encimg);
1860 }
David Brown5c9e0f12019-01-09 16:34:33 -07001861 }
1862
1863 // Build the TLV itself.
Roland Mikhel6945bb62023-04-11 15:57:49 +02001864 if img_manipulation == ImageManipulation::BadSignature {
David Browne90b13f2019-12-06 15:04:00 -07001865 tlv.corrupt_sig();
1866 }
1867 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001868
David Brown5c9e0f12019-01-09 16:34:33 -07001869 let mut buf = vec![];
1870 buf.append(&mut b_header.to_vec());
1871 buf.append(&mut b_img);
1872 buf.append(&mut b_tlv.clone());
1873
David Brown95de4502019-11-15 12:01:34 -07001874 // Pad the buffer to a multiple of the flash alignment.
1875 let align = dev.align();
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001876 let image_sz = buf.len();
David Brown95de4502019-11-15 12:01:34 -07001877 while buf.len() % align != 0 {
1878 buf.push(dev.erased_val());
1879 }
1880
David Brown5c9e0f12019-01-09 16:34:33 -07001881 let mut encbuf = vec![];
1882 if is_encrypted {
1883 encbuf.append(&mut b_header.to_vec());
1884 encbuf.append(&mut b_encimg);
1885 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001886
1887 while encbuf.len() % align != 0 {
1888 encbuf.push(dev.erased_val());
1889 }
David Brown5c9e0f12019-01-09 16:34:33 -07001890 }
1891
David Vincze2d736ad2019-02-18 11:50:22 +01001892 // Since images are always non-encrypted in the primary slot, we first write
1893 // an encrypted image, re-read to use for verification, erase + flash
1894 // un-encrypted. In the secondary slot the image is written un-encrypted,
1895 // and if encryption is requested, it follows an erase + flash encrypted.
Roland Mikhel820e9cc2023-05-09 14:30:16 +02001896 //
1897 // In the case of ram-load when encryption is enabled both slots have to
1898 // be encrypted so in the event when the image is in the primary slot
1899 // the verification will fail as the image is not encrypted.
1900 if slot.index == 0 && !Caps::RamLoad.present() {
David Brown5c9e0f12019-01-09 16:34:33 -07001901 let enc_copy: Option<Vec<u8>>;
1902
1903 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001904 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001905
1906 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001907 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001908
1909 enc_copy = Some(enc);
1910
David Brown76101572019-02-28 11:29:03 -07001911 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001912 } else {
1913 enc_copy = None;
1914 }
1915
David Brown76101572019-02-28 11:29:03 -07001916 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001917
1918 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001919 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001920
David Brownca234692019-02-28 11:22:19 -07001921 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001922 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001923 plain: copy,
1924 cipher: enc_copy,
1925 }
David Brown5c9e0f12019-01-09 16:34:33 -07001926 } else {
1927
David Brown76101572019-02-28 11:29:03 -07001928 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001929
1930 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001931 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001932
1933 let enc_copy: Option<Vec<u8>>;
1934
1935 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001936 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001937
David Brown76101572019-02-28 11:29:03 -07001938 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001939
1940 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001941 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001942
1943 enc_copy = Some(enc);
1944 } else {
1945 enc_copy = None;
1946 }
1947
David Brownca234692019-02-28 11:22:19 -07001948 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001949 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001950 plain: copy,
1951 cipher: enc_copy,
1952 }
David Brown5c9e0f12019-01-09 16:34:33 -07001953 }
David Brown5c9e0f12019-01-09 16:34:33 -07001954}
1955
David Brown873be312019-09-03 12:22:32 -06001956/// Install no image. This is used when no upgrade happens.
1957fn install_no_image() -> ImageData {
1958 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001959 size: 0,
David Brown873be312019-09-03 12:22:32 -06001960 plain: vec![],
1961 cipher: None,
1962 }
1963}
1964
David Brown0bd8c6b2021-10-22 16:33:06 -06001965/// Construct a TLV generator based on how MCUboot is currently configured. The returned
1966/// ManifestGen will generate the appropriate entries based on this configuration.
David Brown5c9e0f12019-01-09 16:34:33 -07001967fn make_tlv() -> TlvGen {
David Brownac655bb2021-10-22 16:33:27 -06001968 let aes_key_size = if Caps::Aes256.present() { 256 } else { 128 };
David Brown5c9e0f12019-01-09 16:34:33 -07001969
David Brownb8882112019-01-11 14:04:11 -07001970 if Caps::EncKw.present() {
1971 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001972 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001973 } else if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001974 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001975 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001976 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001977 }
1978 } else if Caps::EncRsa.present() {
1979 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001980 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001981 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001982 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001983 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001984 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001985 if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001986 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001987 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001988 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001989 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001990 } else if Caps::EncX25519.present() {
1991 if Caps::Ed25519.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001992 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001993 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001994 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001995 }
David Brownb8882112019-01-11 14:04:11 -07001996 } else {
1997 // The non-encrypted configuration.
1998 if Caps::RSA2048.present() {
1999 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03002000 } else if Caps::RSA3072.present() {
2001 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07002002 } else if Caps::EcdsaP256.present() {
2003 TlvGen::new_ecdsa()
Roland Mikhel30978512023-02-08 14:06:58 +01002004 } else if Caps::Ed25519.present() {
Fabio Utzig97710282019-05-24 17:44:49 -03002005 TlvGen::new_ed25519()
Roland Mikheld6703522023-04-27 14:24:30 +02002006 } else if Caps::HwRollbackProtection.present() {
2007 TlvGen::new_sec_cnt()
David Brownb8882112019-01-11 14:04:11 -07002008 } else {
2009 TlvGen::new_hash_only()
2010 }
2011 }
David Brown5c9e0f12019-01-09 16:34:33 -07002012}
2013
David Brownca234692019-02-28 11:22:19 -07002014impl ImageData {
2015 /// Find the image contents for the given slot. This assumes that slot 0
2016 /// is unencrypted, and slot 1 is encrypted.
2017 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03002018 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03002019 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07002020 match (encrypted, slot) {
2021 (false, _) => &self.plain,
2022 (true, 0) => &self.plain,
2023 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
2024 _ => panic!("Invalid slot requested"),
2025 }
David Brown5c9e0f12019-01-09 16:34:33 -07002026 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03002027
2028 fn size(&self) -> usize {
2029 self.size
2030 }
David Brown5c9e0f12019-01-09 16:34:33 -07002031}
2032
David Brown5c9e0f12019-01-09 16:34:33 -07002033/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06002034fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
2035 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07002036 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06002037 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07002038
2039 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06002040 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07002041 let dev = flash.get(&dev_id).unwrap();
2042 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07002043
2044 if buf != &copy[..] {
2045 for i in 0 .. buf.len() {
2046 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06002047 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
2048 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07002049 break;
2050 }
2051 }
2052 false
2053 } else {
2054 true
2055 }
2056}
2057
David Brown3b090212019-07-30 15:59:28 -06002058fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07002059 magic: Option<u8>, image_ok: Option<u8>,
2060 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07002061 if Caps::OverwriteUpgrade.present() {
2062 return true;
2063 }
David Brown5c9e0f12019-01-09 16:34:33 -07002064
David Brown3b090212019-07-30 15:59:28 -06002065 let offset = slot.trailer_off + c::boot_max_align();
2066 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07002067 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07002068 let mut failed = false;
2069
David Brown76101572019-02-28 11:29:03 -07002070 let dev = flash.get(&dev_id).unwrap();
2071 let erased_val = dev.erased_val();
2072 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07002073
2074 failed |= match magic {
2075 Some(v) => {
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002076 let magic_off = (c::boot_max_align() * 3) + (c::boot_magic_sz() - MAGIC.len());
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002077 if v == 1 && &copy[magic_off..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07002078 warn!("\"magic\" mismatch at {:#x}", offset);
2079 true
2080 } else if v == 3 {
2081 let expected = [erased_val; 16];
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002082 if copy[magic_off..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07002083 warn!("\"magic\" mismatch at {:#x}", offset);
2084 true
2085 } else {
2086 false
2087 }
2088 } else {
2089 false
2090 }
2091 },
2092 None => false,
2093 };
2094
2095 failed |= match image_ok {
2096 Some(v) => {
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002097 let image_ok_off = c::boot_max_align() * 2;
2098 if (v == 1 && copy[image_ok_off] != v) || (v == 3 && copy[image_ok_off] != erased_val) {
2099 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[image_ok_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07002100 true
2101 } else {
2102 false
2103 }
2104 },
2105 None => false,
2106 };
2107
2108 failed |= match copy_done {
2109 Some(v) => {
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002110 let copy_done_off = c::boot_max_align();
2111 if (v == 1 && copy[copy_done_off] != v) || (v == 3 && copy[copy_done_off] != erased_val) {
2112 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[copy_done_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07002113 true
2114 } else {
2115 false
2116 }
2117 },
2118 None => false,
2119 };
2120
2121 !failed
2122}
2123
David Brown297029a2019-08-13 14:29:51 -06002124/// Install a partition table. This is a simplified partition table that
2125/// we write at the beginning of flash so make it easier for external tools
2126/// to analyze these images.
2127fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
2128 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
2129 for &id in &ids {
2130 // If there are any partitions in this device that start at 0, and
2131 // aren't marked as the BootLoader partition, avoid adding the
2132 // partition table. This makes it harder to view the image, but
2133 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07002134 let skip_ptable = areadesc
2135 .iter_areas()
2136 .any(|area| {
2137 area.device_id == id &&
2138 area.off == 0 &&
2139 area.flash_id != FlashId::BootLoader
2140 });
2141 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06002142 if log_enabled!(Info) {
2143 let special: Vec<FlashId> = areadesc.iter_areas()
2144 .filter(|area| area.device_id == id && area.off == 0)
2145 .map(|area| area.flash_id)
2146 .collect();
2147 info!("Skipping partition table: {:?}", special);
2148 }
2149 break;
2150 }
2151
2152 let mut buf: Vec<u8> = vec![];
2153 write!(&mut buf, "mcuboot\0").unwrap();
2154
2155 // Iterate through all of the partitions in that device, and encode
2156 // into the table.
2157 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
2158 buf.write_u32::<LittleEndian>(count as u32).unwrap();
2159
2160 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
2161 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
2162 buf.write_u32::<LittleEndian>(area.off).unwrap();
2163 buf.write_u32::<LittleEndian>(area.size).unwrap();
2164 buf.write_u32::<LittleEndian>(0).unwrap();
2165 }
2166
2167 let dev = flash.get_mut(&id).unwrap();
2168
2169 // Pad to alignment.
2170 while buf.len() % dev.align() != 0 {
2171 buf.push(0);
2172 }
2173
2174 dev.write(0, &buf).unwrap();
2175 }
2176}
2177
David Brown5c9e0f12019-01-09 16:34:33 -07002178/// The image header
2179#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07002180#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002181pub struct ImageHeader {
2182 magic: u32,
2183 load_addr: u32,
2184 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06002185 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07002186 img_size: u32,
2187 flags: u32,
2188 ver: ImageVersion,
2189 _pad2: u32,
2190}
2191
2192impl AsRaw for ImageHeader {}
2193
2194#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06002195#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002196pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06002197 pub major: u8,
2198 pub minor: u8,
2199 pub revision: u16,
2200 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07002201}
2202
David Brownc3898d62019-08-05 14:20:02 -06002203#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002204pub struct SlotInfo {
2205 pub base_off: usize,
2206 pub trailer_off: usize,
2207 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06002208 // Which slot within this device.
2209 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07002210 pub dev_id: u8,
2211}
2212
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002213#[cfg(not(feature = "max-align-32"))]
David Brown347dc572019-11-15 11:37:25 -07002214const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
2215 0x60, 0xd2, 0xef, 0x7f,
2216 0x35, 0x52, 0x50, 0x0f,
2217 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07002218
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002219#[cfg(feature = "max-align-32")]
2220const MAGIC: &[u8] = &[0x20, 0x00, 0x2d, 0xe1,
2221 0x5d, 0x29, 0x41, 0x0b,
2222 0x8d, 0x77, 0x67, 0x9c,
2223 0x11, 0x0f, 0x1f, 0x8a];
2224
David Brown5c9e0f12019-01-09 16:34:33 -07002225// Replicates defines found in bootutil.h
2226const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
2227const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
2228
2229const BOOT_FLAG_SET: Option<u8> = Some(1);
2230const BOOT_FLAG_UNSET: Option<u8> = Some(3);
2231
2232/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07002233pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
2234 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07002235 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07002236 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07002237 if offset % align != 0 || MAGIC.len() % align != 0 {
2238 // The write size is larger than the magic value. Fill a buffer
2239 // with the erased value, put the MAGIC in it, and write it in its
2240 // entirety.
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002241 let mut buf = vec![dev.erased_val(); c::boot_max_align()];
2242 let magic_off = (offset % align) + (c::boot_magic_sz() - MAGIC.len());
2243 buf[magic_off..].copy_from_slice(MAGIC);
David Brown95de4502019-11-15 12:01:34 -07002244 dev.write(offset - (offset % align), &buf).unwrap();
2245 } else {
2246 dev.write(offset, MAGIC).unwrap();
2247 }
David Brown5c9e0f12019-01-09 16:34:33 -07002248}
2249
2250/// Writes the image_ok flag which, guess what, tells the bootloader
2251/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07002252fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07002253 // Overwrite mode always is permanent, and only the magic is used in
2254 // the trailer. To avoid problems with large write sizes, don't try to
2255 // set anything in this case.
2256 if Caps::OverwriteUpgrade.present() {
2257 return;
2258 }
2259
David Brown76101572019-02-28 11:29:03 -07002260 let dev = flash.get_mut(&slot.dev_id).unwrap();
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002261 let align = dev.align();
2262 let mut ok = vec![dev.erased_val(); align];
David Brown5c9e0f12019-01-09 16:34:33 -07002263 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07002264 let off = slot.trailer_off + c::boot_max_align() * 3;
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002265 dev.write(off, &ok).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07002266}
2267
2268// Drop some pseudo-random gibberish onto the data.
2269fn splat(data: &mut [u8], seed: usize) {
David Brown9c6322f2021-08-19 13:03:39 -06002270 let mut seed_block = [0u8; 32];
David Browncd842842020-07-09 15:46:53 -06002271 let mut buf = Cursor::new(&mut seed_block[..]);
2272 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
2273 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
2274 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
2275 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
2276 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07002277 rng.fill_bytes(data);
2278}
2279
2280/// Return a read-only view into the raw bytes of this object
2281trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07002282 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07002283 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
2284 mem::size_of::<Self>()) }
2285 }
2286}
2287
David Brown07dd5f02021-10-26 16:43:15 -06002288/// Determine whether it makes sense to test this configuration with a maximally-sized image.
2289/// Returns an ImageSize representing the best size to test, possibly just with the given size.
2290fn maximal(size: usize) -> ImageSize {
2291 if Caps::OverwriteUpgrade.present() ||
2292 Caps::SwapUsingMove.present()
2293 {
2294 ImageSize::Given(size)
2295 } else {
2296 ImageSize::Largest
2297 }
2298}
2299
David Brown5c9e0f12019-01-09 16:34:33 -07002300pub fn show_sizes() {
2301 // This isn't panic safe.
2302 for min in &[1, 2, 4, 8] {
2303 let msize = c::boot_trailer_sz(*min);
2304 println!("{:2}: {} (0x{:x})", min, msize, msize);
2305 }
2306}
David Brown95de4502019-11-15 12:01:34 -07002307
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002308#[cfg(not(feature = "max-align-32"))]
David Brown95de4502019-11-15 12:01:34 -07002309fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07002310 &[1, 2, 4, 8]
2311}
2312
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002313#[cfg(feature = "max-align-32")]
David Brown95de4502019-11-15 12:01:34 -07002314fn test_alignments() -> &'static [usize] {
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002315 &[32]
David Brown95de4502019-11-15 12:01:34 -07002316}