blob: dbfb5feeb43459f527db7677e6e483be8468b5e7 [file] [log] [blame]
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001// Copyright (c) 2019-2021 Linaro LTD
David Browne2acfae2020-01-21 16:45:01 -07002// Copyright (c) 2019-2020 JUUL Labs
Roman Okhrimenko977b3752022-03-31 14:40:48 +03003// Copyright (c) 2019-2021 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::{
Roman Okhrimenko977b3752022-03-31 14:40:48 +030022 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};
Roman Okhrimenko977b3752022-03-31 14:40:48 +030027use aes::{
28 Aes128,
David Brown5c9e0f12019-01-09 16:34:33 -070029 Aes128Ctr,
Roman Okhrimenko977b3752022-03-31 14:40:48 +030030 Aes256,
31 Aes256Ctr,
32 NewBlockCipher,
David Brown5c9e0f12019-01-09 16:34:33 -070033};
Roman Okhrimenko977b3752022-03-31 14:40:48 +030034use 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};
Roman Okhrimenko977b3752022-03-31 14:40:48 +030041use 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};
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +030057use crate::utils::align_up;
Roman Okhrimenko977b3752022-03-31 14:40:48 +030058use typenum::{U32, U16};
59
60/// 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;
David Brown5c9e0f12019-01-09 16:34:33 -070063
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]>,
Roman Okhrimenko977b3752022-03-31 14:40:48 +030072 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>,
Roman Okhrimenko977b3752022-03-31 14:40:48 +030083 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 {
Roman Okhrimenko977b3752022-03-31 14:40: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
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300103/// 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,
117 base_off: usize,
118}
119
120#[derive(Clone, Debug)]
121struct SlotPlace {
122 offset: u32,
123 size: u32,
124}
125
David Browne5133242019-02-28 11:05:19 -0700126impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -0700127 /// Construct a new image builder for the given device. Returns
128 /// Some(builder) if is possible to test this configuration, or None if
129 /// not possible (for example, if there aren't enough image slots).
Fabio Utzig114a6472019-11-28 10:24:09 -0300130 pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
131 let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
132
133 for cap in unsupported_caps {
134 if cap.present() {
135 return Err(format!("unsupported {:?}", cap));
136 }
137 }
David Browne5133242019-02-28 11:05:19 -0700138
David Brown06ef06e2019-03-05 12:28:10 -0700139 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -0700140
David Brown06ef06e2019-03-05 12:28:10 -0700141 let mut slots = Vec::with_capacity(num_images);
142 for image in 0..num_images {
143 // This mapping must match that defined in
144 // `boot/zephyr/include/sysflash/sysflash.h`.
145 let id0 = match image {
146 0 => FlashId::Image0,
147 1 => FlashId::Image2,
148 _ => panic!("More than 2 images not supported"),
149 };
150 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
151 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300152 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700153 };
154 let id1 = match image {
155 0 => FlashId::Image1,
156 1 => FlashId::Image3,
157 _ => panic!("More than 2 images not supported"),
158 };
159 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
160 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300161 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700162 };
David Browne5133242019-02-28 11:05:19 -0700163
Christopher Collinsa1c12042019-05-23 14:00:28 -0700164 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700165
David Brown06ef06e2019-03-05 12:28:10 -0700166 // Construct a primary image.
167 let primary = SlotInfo {
168 base_off: primary_base as usize,
169 trailer_off: primary_base + primary_len - offset_from_end,
170 len: primary_len as usize,
171 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600172 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700173 };
174
175 // And an upgrade image.
176 let secondary = SlotInfo {
177 base_off: secondary_base as usize,
178 trailer_off: secondary_base + secondary_len - offset_from_end,
179 len: secondary_len as usize,
180 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600181 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700182 };
183
184 slots.push([primary, secondary]);
185 }
David Browne5133242019-02-28 11:05:19 -0700186
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300187 let ram = RamData::new(&slots);
188
Fabio Utzig114a6472019-11-28 10:24:09 -0300189 Ok(ImagesBuilder {
David Brown4dfb33c2021-03-10 05:15:45 -0700190 flash,
191 areadesc,
192 slots,
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300193 ram,
David Brown5bc62c62019-03-05 12:11:48 -0700194 })
David Browne5133242019-02-28 11:05:19 -0700195 }
196
197 pub fn each_device<F>(f: F)
198 where F: Fn(Self)
199 {
200 for &dev in ALL_DEVICES {
David Brown95de4502019-11-15 12:01:34 -0700201 for &align in test_alignments() {
David Browne5133242019-02-28 11:05:19 -0700202 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700203 match Self::new(dev, align, erased_val) {
Fabio Utzig114a6472019-11-28 10:24:09 -0300204 Ok(run) => f(run),
205 Err(msg) => warn!("Skipping {}: {}", dev, msg),
David Brown5bc62c62019-03-05 12:11:48 -0700206 }
David Browne5133242019-02-28 11:05:19 -0700207 }
208 }
209 }
210 }
211
212 /// Construct an `Images` that doesn't expect an upgrade to happen.
David Brownc3898d62019-08-05 14:20:02 -0600213 pub fn make_no_upgrade_image(self, deps: &DepTest) -> Images {
214 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700215 let mut flash = self.flash;
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300216 let ram = self.ram.clone(); // TODO: This is wasteful.
David Brownc3898d62019-08-05 14:20:02 -0600217 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
218 let dep: Box<dyn Depender> = if num_images > 1 {
219 Box::new(PairDep::new(num_images, image_num, deps))
220 } else {
David Brown2ee5f7f2020-01-13 14:04:01 -0700221 Box::new(BoringDep::new(image_num, deps))
David Brownc3898d62019-08-05 14:20:02 -0600222 };
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300223 let primaries = install_image(&mut flash, &slots[0],
224 42784, &ram, &*dep, false);
David Brown873be312019-09-03 12:22:32 -0600225 let upgrades = match deps.depends[image_num] {
226 DepType::NoUpgrade => install_no_image(),
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300227 _ => install_image(&mut flash, &slots[1],
228 46928, &ram, &*dep, false)
David Brown873be312019-09-03 12:22:32 -0600229 };
David Brown84b49f72019-03-01 10:58:22 -0700230 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700231 slots,
232 primaries,
233 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700234 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600235 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700236 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700237 flash,
David Browne5133242019-02-28 11:05:19 -0700238 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700239 images,
David Browne5133242019-02-28 11:05:19 -0700240 total_count: None,
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300241 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700242 }
243 }
244
David Brownc3898d62019-08-05 14:20:02 -0600245 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
246 let mut images = self.make_no_upgrade_image(deps);
David Brown84b49f72019-03-01 10:58:22 -0700247 for image in &images.images {
248 mark_upgrade(&mut images.flash, &image.slots[1]);
249 }
David Browne5133242019-02-28 11:05:19 -0700250
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300251 // The count is meaningless if no flash operations are performed.
252 if !Caps::modifies_flash() {
253 return images;
254 }
255
David Browne5133242019-02-28 11:05:19 -0700256 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300257 let total_count = match images.run_basic_upgrade(permanent) {
David Brown8973f552021-03-10 05:21:11 -0700258 Some(v) => v,
259 None =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600260 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
261 0
262 } else {
263 panic!("Unable to perform basic upgrade");
264 }
David Browne5133242019-02-28 11:05:19 -0700265 };
266
267 images.total_count = Some(total_count);
268 images
269 }
270
271 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700272 let mut bad_flash = self.flash;
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300273 let ram = self.ram.clone(); // TODO: Avoid this clone.
David Brownc3898d62019-08-05 14:20:02 -0600274 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
David Brown2ee5f7f2020-01-13 14:04:01 -0700275 let dep = BoringDep::new(image_num, &NO_DEPS);
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300276 let primaries = install_image(&mut bad_flash, &slots[0],
277 32784, &ram, &dep, false);
278 let upgrades = install_image(&mut bad_flash, &slots[1],
279 41928, &ram, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700280 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700281 slots,
282 primaries,
283 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700284 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700285 Images {
David Brown76101572019-02-28 11:29:03 -0700286 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700287 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700288 images,
David Browne5133242019-02-28 11:05:19 -0700289 total_count: None,
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300290 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700291 }
292 }
293
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300294 pub fn make_erased_secondary_image(self) -> Images {
295 let mut flash = self.flash;
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300296 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300297 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
298 let dep = BoringDep::new(image_num, &NO_DEPS);
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300299 let primaries = install_image(&mut flash, &slots[0],
300 32784, &ram, &dep, false);
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300301 let upgrades = install_no_image();
302 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700303 slots,
304 primaries,
305 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300306 }}).collect();
307 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700308 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300309 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700310 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300311 total_count: None,
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300312 ram: self.ram,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300313 }
314 }
315
Fabio Utzigd0157342020-10-02 15:22:11 -0300316 pub fn make_bootstrap_image(self) -> Images {
317 let mut flash = self.flash;
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300318 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzigd0157342020-10-02 15:22:11 -0300319 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
320 let dep = BoringDep::new(image_num, &NO_DEPS);
321 let primaries = install_no_image();
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300322 let upgrades = install_image(&mut flash, &slots[1],
323 32784, &ram, &dep, false);
Fabio Utzigd0157342020-10-02 15:22:11 -0300324 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700325 slots,
326 primaries,
327 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300328 }}).collect();
329 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700330 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300331 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700332 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300333 total_count: None,
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300334 ram: self.ram,
Fabio Utzigd0157342020-10-02 15:22:11 -0300335 }
336 }
337
David Browne5133242019-02-28 11:05:19 -0700338 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300339 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700340 match device {
341 DeviceName::Stm32f4 => {
342 // STM style flash. Large sectors, with a large scratch area.
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300343 // The flash layout as described is not present in any real STM32F4 device, but it
344 // serves to exercise support for sectors of varying sizes inside a single slot,
345 // as long as they are compatible in both slots and all fit in the scratch.
346 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024, 64 * 1024,
347 32 * 1024, 32 * 1024, 64 * 1024,
348 32 * 1024, 32 * 1024, 64 * 1024,
349 128 * 1024],
David Brown76101572019-02-28 11:29:03 -0700350 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700351 let dev_id = 0;
352 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700353 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700354 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
355 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
356 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
357
David Brown76101572019-02-28 11:29:03 -0700358 let mut flash = SimMultiFlash::new();
359 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200360 (flash, areadesc, &[Caps::SwapUsingMove, Caps::SwapUsingStatus])
David Browne5133242019-02-28 11:05:19 -0700361 }
362 DeviceName::K64f => {
363 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700364 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700365
366 let dev_id = 0;
367 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700368 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700369 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
370 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
371 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
372
David Brown76101572019-02-28 11:29:03 -0700373 let mut flash = SimMultiFlash::new();
374 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200375 (flash, areadesc, &[Caps::SwapUsingStatus])
David Browne5133242019-02-28 11:05:19 -0700376 }
377 DeviceName::K64fBig => {
378 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
379 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700380 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700381
382 let dev_id = 0;
383 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700384 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700385 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
386 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
387 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
388
David Brown76101572019-02-28 11:29:03 -0700389 let mut flash = SimMultiFlash::new();
390 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200391 (flash, areadesc, &[Caps::SwapUsingMove, Caps::SwapUsingStatus])
David Browne5133242019-02-28 11:05:19 -0700392 }
393 DeviceName::Nrf52840 => {
394 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
395 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700396 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700397
398 let dev_id = 0;
399 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700400 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700401 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
402 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
403 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
404
David Brown76101572019-02-28 11:29:03 -0700405 let mut flash = SimMultiFlash::new();
406 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200407 (flash, areadesc, &[Caps::SwapUsingStatus])
David Browne5133242019-02-28 11:05:19 -0700408 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300409 DeviceName::Nrf52840UnequalSlots => {
410 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
411
412 let dev_id = 0;
413 let mut areadesc = AreaDesc::new();
414 areadesc.add_flash_sectors(dev_id, &dev);
415 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
416 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
417
418 let mut flash = SimMultiFlash::new();
419 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200420 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade, Caps::SwapUsingStatus])
Fabio Utzigc659ec52020-07-13 21:18:48 -0300421 }
David Browne5133242019-02-28 11:05:19 -0700422 DeviceName::Nrf52840SpiFlash => {
423 // Simulate nrf52840 with external SPI flash. The external SPI flash
424 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700425 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
426 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700427
428 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700429 areadesc.add_flash_sectors(0, &dev0);
430 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700431
432 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
433 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
434 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
435
David Brown76101572019-02-28 11:29:03 -0700436 let mut flash = SimMultiFlash::new();
437 flash.insert(0, dev0);
438 flash.insert(1, dev1);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200439 (flash, areadesc, &[Caps::SwapUsingMove, Caps::SwapUsingStatus])
David Browne5133242019-02-28 11:05:19 -0700440 }
David Brown2bff6472019-03-05 13:58:35 -0700441 DeviceName::K64fMulti => {
442 // NXP style flash, but larger, to support multiple images.
443 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
444
445 let dev_id = 0;
446 let mut areadesc = AreaDesc::new();
447 areadesc.add_flash_sectors(dev_id, &dev);
448 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
449 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
450 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
451 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
452 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
453
454 let mut flash = SimMultiFlash::new();
455 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200456 (flash, areadesc, &[Caps::SwapUsingStatus])
457 }
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300458 DeviceName::PSoC6 => {
459 // PSoC style flash of 512K, single-image case
460 let dev = SimFlash::new(vec![512; 1024], align as usize, erased_val);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200461
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300462 let dev_id = 0;
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200463 let mut areadesc = AreaDesc::new();
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300464 areadesc.add_flash_sectors(dev_id, &dev);
465 areadesc.add_image(0x018000, 0x010000, FlashId::Image0, dev_id);
466 areadesc.add_image(0x028000, 0x010000, FlashId::Image1, dev_id);
467 areadesc.add_image(0x039800, 0x001000, FlashId::ImageScratch, dev_id);
468 areadesc.add_image(0x038000, 0x001800, FlashId::ImageSwapStatus, dev_id);
469
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200470 let mut flash = SimMultiFlash::new();
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300471 flash.insert(dev_id, dev);
472 (flash, areadesc, &[Caps::SwapUsingMove])
David Brown2bff6472019-03-05 13:58:35 -0700473 }
David Browne5133242019-02-28 11:05:19 -0700474 }
475 }
David Brownc3898d62019-08-05 14:20:02 -0600476
477 pub fn num_images(&self) -> usize {
478 self.slots.len()
479 }
David Browne5133242019-02-28 11:05:19 -0700480}
481
David Brown5c9e0f12019-01-09 16:34:33 -0700482impl Images {
483 /// A simple upgrade without forced failures.
484 ///
485 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700486 /// inject failures at chosen steps. Returns None if it was unable to
487 /// count the operations in a basic upgrade.
488 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300489 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700490 info!("Total flash operation count={}", total_count);
491
David Brown84b49f72019-03-01 10:58:22 -0700492 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700493 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700494 None
David Brown5c9e0f12019-01-09 16:34:33 -0700495 } else {
David Brown8973f552021-03-10 05:21:11 -0700496 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700497 }
498 }
499
Fabio Utzigd0157342020-10-02 15:22:11 -0300500 pub fn run_bootstrap(&self) -> bool {
501 let mut flash = self.flash.clone();
502 let mut fails = 0;
503
504 if Caps::Bootstrap.present() {
505 info!("Try bootstraping image in the primary");
506
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300507 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigd0157342020-10-02 15:22:11 -0300508 warn!("Failed first boot");
509 fails += 1;
510 }
511
512 if !self.verify_images(&flash, 0, 1) {
513 warn!("Image in the first slot was not bootstrapped");
514 fails += 1;
515 }
516
517 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
518 BOOT_FLAG_SET, BOOT_FLAG_SET) {
519 warn!("Mismatched trailer for the primary slot");
520 fails += 1;
521 }
522 }
523
524 if fails > 0 {
525 error!("Expected trailer on secondary slot to be erased");
526 }
527
528 fails > 0
529 }
530
531
David Brownc3898d62019-08-05 14:20:02 -0600532 /// Test a simple upgrade, with dependencies given, and verify that the
533 /// image does as is described in the test.
534 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300535 if !Caps::modifies_flash() {
536 return false;
537 }
538
David Brownc3898d62019-08-05 14:20:02 -0600539 let (flash, _) = self.try_upgrade(None, true);
540
541 self.verify_dep_images(&flash, deps)
542 }
543
Fabio Utzigf5480c72019-11-28 10:41:57 -0300544 fn is_swap_upgrade(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300545 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
Fabio Utzigf5480c72019-11-28 10:41:57 -0300546 }
547
David Brown5c9e0f12019-01-09 16:34:33 -0700548 pub fn run_basic_revert(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300549 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700550 return false;
551 }
David Brown5c9e0f12019-01-09 16:34:33 -0700552
David Brown5c9e0f12019-01-09 16:34:33 -0700553 let mut fails = 0;
554
555 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300556 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700557 for count in 2 .. 5 {
558 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700559 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700560 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700561 error!("Revert failure on count {}", count);
562 fails += 1;
563 }
564 }
565 }
566
567 fails > 0
568 }
569
570 pub fn run_perm_with_fails(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300571 if !Caps::modifies_flash() {
572 return false;
573 }
574
David Brown5c9e0f12019-01-09 16:34:33 -0700575 let mut fails = 0;
576 let total_flash_ops = self.total_count.unwrap();
577
578 // Let's try an image halfway through.
579 for i in 1 .. total_flash_ops {
580 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300581 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700582 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700583 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700584 warn!("FAIL at step {} of {}", i, total_flash_ops);
585 fails += 1;
586 }
587
David Brown84b49f72019-03-01 10:58:22 -0700588 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
589 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100590 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700591 fails += 1;
592 }
593
David Brown84b49f72019-03-01 10:58:22 -0700594 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
595 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100596 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700597 fails += 1;
598 }
599
David Brownaec56b22021-03-10 05:22:07 -0700600 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
601 warn!("Secondary slot FAIL at step {} of {}",
602 i, total_flash_ops);
603 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700604 }
605 }
606
607 if fails > 0 {
608 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
609 fails as f32 * 100.0 / total_flash_ops as f32);
610 }
611
612 fails > 0
613 }
614
David Brown5c9e0f12019-01-09 16:34:33 -0700615 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300616 if !Caps::modifies_flash() {
617 return false;
618 }
619
David Brown5c9e0f12019-01-09 16:34:33 -0700620 let mut fails = 0;
621 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700622 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700623 info!("Random interruptions at reset points={:?}", total_counts);
624
David Brown84b49f72019-03-01 10:58:22 -0700625 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300626 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700627 // TODO: This result is ignored.
628 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700629 } else {
630 true
631 };
David Vincze2d736ad2019-02-18 11:50:22 +0100632 if !primary_slot_ok || !secondary_slot_ok {
633 error!("Image mismatch after random interrupts: primary slot={} \
634 secondary slot={}",
635 if primary_slot_ok { "ok" } else { "fail" },
636 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700637 fails += 1;
638 }
David Brown84b49f72019-03-01 10:58:22 -0700639 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
640 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100641 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700642 fails += 1;
643 }
David Brown84b49f72019-03-01 10:58:22 -0700644 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
645 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100646 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700647 fails += 1;
648 }
649
650 if fails > 0 {
651 error!("Error testing perm upgrade with {} fails", total_fails);
652 }
653
654 fails > 0
655 }
656
David Brown5c9e0f12019-01-09 16:34:33 -0700657 pub fn run_revert_with_fails(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300658 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700659 return false;
660 }
David Brown5c9e0f12019-01-09 16:34:33 -0700661
David Brown5c9e0f12019-01-09 16:34:33 -0700662 let mut fails = 0;
663
Fabio Utzigf5480c72019-11-28 10:41:57 -0300664 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300665 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700666 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700667 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700668 error!("Revert failed at interruption {}", i);
669 fails += 1;
670 }
671 }
672 }
673
674 fails > 0
675 }
676
David Brown5c9e0f12019-01-09 16:34:33 -0700677 pub fn run_norevert(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300678 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700679 return false;
680 }
David Brown5c9e0f12019-01-09 16:34:33 -0700681
David Brown76101572019-02-28 11:29:03 -0700682 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700683 let mut fails = 0;
684
685 info!("Try norevert");
686
687 // First do a normal upgrade...
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300688 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700689 warn!("Failed first boot");
690 fails += 1;
691 }
692
693 //FIXME: copy_done is written by boot_go, is it ok if no copy
694 // was ever done?
695
David Brown84b49f72019-03-01 10:58:22 -0700696 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100697 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700698 fails += 1;
699 }
David Brown84b49f72019-03-01 10:58:22 -0700700 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
701 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100702 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700703 fails += 1;
704 }
David Brown84b49f72019-03-01 10:58:22 -0700705 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
706 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100707 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700708 fails += 1;
709 }
710
David Vincze2d736ad2019-02-18 11:50:22 +0100711 // Marks image in the primary slot as permanent,
712 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700713 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700714
David Brown84b49f72019-03-01 10:58:22 -0700715 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
716 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100717 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700718 fails += 1;
719 }
720
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300721 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700722 warn!("Failed second boot");
723 fails += 1;
724 }
725
David Brown84b49f72019-03-01 10:58:22 -0700726 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
727 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100728 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700729 fails += 1;
730 }
David Brown84b49f72019-03-01 10:58:22 -0700731 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700732 warn!("Failed image verification");
733 fails += 1;
734 }
735
736 if fails > 0 {
737 error!("Error running upgrade without revert");
738 }
739
740 fails > 0
741 }
742
David Brown2ee5f7f2020-01-13 14:04:01 -0700743 // Test that an upgrade is rejected. Assumes that the image was build
744 // such that the upgrade is instead a downgrade.
745 pub fn run_nodowngrade(&self) -> bool {
746 if !Caps::DowngradePrevention.present() {
747 return false;
748 }
749
750 let mut flash = self.flash.clone();
751 let mut fails = 0;
752
753 info!("Try no downgrade");
754
755 // First, do a normal upgrade.
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300756 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700757 warn!("Failed first boot");
758 fails += 1;
759 }
760
761 if !self.verify_images(&flash, 0, 0) {
762 warn!("Failed verification after downgrade rejection");
763 fails += 1;
764 }
765
766 if fails > 0 {
767 error!("Error testing downgrade rejection");
768 }
769
770 fails > 0
771 }
772
David Vincze2d736ad2019-02-18 11:50:22 +0100773 // Tests a new image written to the primary slot that already has magic and
774 // image_ok set while there is no image on the secondary slot, so no revert
775 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700776 pub fn run_norevert_newimage(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300777 if !Caps::modifies_flash() {
778 info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
779 return false;
780 }
781
David Brown76101572019-02-28 11:29:03 -0700782 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700783 let mut fails = 0;
784
785 info!("Try non-revert on imgtool generated image");
786
David Brown84b49f72019-03-01 10:58:22 -0700787 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700788
David Vincze2d736ad2019-02-18 11:50:22 +0100789 // This simulates writing an image created by imgtool to
790 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700791 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
792 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100793 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700794 fails += 1;
795 }
796
797 // Run the bootloader...
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300798 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700799 warn!("Failed first boot");
800 fails += 1;
801 }
802
803 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700804 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700805 warn!("Failed image verification");
806 fails += 1;
807 }
David Brown84b49f72019-03-01 10:58:22 -0700808 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
809 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100810 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700811 fails += 1;
812 }
David Brown84b49f72019-03-01 10:58:22 -0700813 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
814 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100815 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700816 fails += 1;
817 }
818
819 if fails > 0 {
820 error!("Expected a non revert with new image");
821 }
822
823 fails > 0
824 }
825
David Vincze2d736ad2019-02-18 11:50:22 +0100826 // Tests a new image written to the primary slot that already has magic and
827 // image_ok set while there is no image on the secondary slot, so no revert
828 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700829 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700830 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700831 let mut fails = 0;
832
833 info!("Try upgrade image with bad signature");
834
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300835 // Only perform this test if an upgrade is expected to happen.
836 if !Caps::modifies_flash() {
837 info!("Skipping upgrade image with bad signature");
838 return false;
839 }
840
David Brown84b49f72019-03-01 10:58:22 -0700841 self.mark_upgrades(&mut flash, 0);
842 self.mark_permanent_upgrades(&mut flash, 0);
843 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700844
David Brown84b49f72019-03-01 10:58:22 -0700845 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
846 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100847 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700848 fails += 1;
849 }
850
851 // Run the bootloader...
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300852 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700853 warn!("Failed first boot");
854 fails += 1;
855 }
856
857 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700858 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700859 warn!("Failed image verification");
860 fails += 1;
861 }
David Brown84b49f72019-03-01 10:58:22 -0700862 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
863 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100864 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700865 fails += 1;
866 }
867
868 if fails > 0 {
869 error!("Expected an upgrade failure when image has bad signature");
870 }
871
872 fails > 0
873 }
874
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300875 // Should detect there is a leftover trailer in an otherwise erased
876 // secondary slot and erase its trailer.
877 pub fn run_secondary_leftover_trailer(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300878 if !Caps::modifies_flash() {
879 return false;
880 }
881
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300882 let mut flash = self.flash.clone();
883 let mut fails = 0;
884
885 info!("Try with a leftover trailer in the secondary; must be erased");
886
887 // Add a trailer on the secondary slot
888 self.mark_permanent_upgrades(&mut flash, 1);
889 self.mark_upgrades(&mut flash, 1);
890
891 // Run the bootloader...
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300892 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300893 warn!("Failed first boot");
894 fails += 1;
895 }
896
897 // State should not have changed
898 if !self.verify_images(&flash, 0, 0) {
899 warn!("Failed image verification");
900 fails += 1;
901 }
902 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
903 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
904 warn!("Mismatched trailer for the secondary slot");
905 fails += 1;
906 }
907
908 if fails > 0 {
909 error!("Expected trailer on secondary slot to be erased");
910 }
911
912 fails > 0
913 }
914
David Brown5c9e0f12019-01-09 16:34:33 -0700915 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300916 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700917 }
918
David Brown5c9e0f12019-01-09 16:34:33 -0700919 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300920 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700921 }
922
923 /// This test runs a simple upgrade with no fails in the images, but
924 /// allowing for fails in the status area. This should run to the end
925 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700926 pub fn run_with_status_fails_complete(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300927 if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700928 return false;
929 }
930
David Brown76101572019-02-28 11:29:03 -0700931 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700932 let mut fails = 0;
933
934 info!("Try swap with status fails");
935
David Brown84b49f72019-03-01 10:58:22 -0700936 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700937 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700938
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300939 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300940 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700941 warn!("Failed!");
942 fails += 1;
943 }
944
945 // Failed writes to the marked "bad" region don't assert anymore.
946 // Any detected assert() is happening in another part of the code.
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300947 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -0700948 warn!("At least one assert() was called");
949 fails += 1;
950 }
951
David Brown84b49f72019-03-01 10:58:22 -0700952 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
953 BOOT_FLAG_SET, BOOT_FLAG_SET) {
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
David Brown84b49f72019-03-01 10:58:22 -0700958 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700959 warn!("Failed image verification");
960 fails += 1;
961 }
962
David Vincze2d736ad2019-02-18 11:50:22 +0100963 info!("validate primary slot enabled; \
964 re-run of boot_go should just work");
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300965 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700966 warn!("Failed!");
967 fails += 1;
968 }
969
970 if fails > 0 {
971 error!("Error running upgrade with status write fails");
972 }
973
974 fails > 0
975 }
976
977 /// This test runs a simple upgrade with no fails in the images, but
978 /// allowing for fails in the status area. This should run to the end
979 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700980 pub fn run_with_status_fails_with_reset(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300981 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700982 false
David Vincze2d736ad2019-02-18 11:50:22 +0100983 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700984
David Brown76101572019-02-28 11:29:03 -0700985 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700986 let mut fails = 0;
987 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700988
David Brown85904a82019-01-11 13:45:12 -0700989 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700990
David Brown85904a82019-01-11 13:45:12 -0700991 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700992
David Brown84b49f72019-03-01 10:58:22 -0700993 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700994 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700995
996 // Should not fail, writing to bad regions does not assert
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +0300997 let asserts = c::boot_go(&mut flash, &self.areadesc,
998 Some(&mut count), None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700999 if asserts != 0 {
1000 warn!("At least one assert() was called");
1001 fails += 1;
1002 }
1003
David Brown76101572019-02-28 11:29:03 -07001004 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -07001005
1006 info!("Resuming an interrupted swap operation");
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001007 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1008 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001009
1010 // This might throw no asserts, for large sector devices, where
1011 // a single failure writing is indistinguishable from no failure,
1012 // or throw a single assert for small sector devices that fail
1013 // multiple times...
1014 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +01001015 warn!("Expected single assert validating the primary slot, \
1016 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -07001017 fails += 1;
1018 }
1019
1020 if fails > 0 {
1021 error!("Error running upgrade with status write fails");
1022 }
1023
1024 fails > 0
1025 } else {
David Brown76101572019-02-28 11:29:03 -07001026 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001027 let mut fails = 0;
1028
1029 info!("Try interrupted swap with status fails");
1030
David Brown84b49f72019-03-01 10:58:22 -07001031 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001032 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -07001033
1034 // This is expected to fail while writing to bad regions...
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001035 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1036 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001037 if asserts == 0 {
1038 warn!("No assert() detected");
1039 fails += 1;
1040 }
1041
1042 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -07001043 }
David Brown5c9e0f12019-01-09 16:34:33 -07001044 }
1045
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001046 /// Test the direct XIP configuration. With this mode, flash images are never moved, and the
1047 /// bootloader merely selects which partition is the proper one to boot.
1048 pub fn run_direct_xip(&self) -> bool {
1049 if !Caps::DirectXip.present() {
1050 return false;
1051 }
1052
1053 // Clone the flash so we can tell if unchanged.
1054 let mut flash = self.flash.clone();
1055
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001056 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001057
1058 // Ensure the boot was successful.
1059 let resp = if let Some(resp) = result.resp() {
1060 resp
1061 } else {
1062 panic!("Boot didn't return a valid result");
1063 };
1064
1065 // This configuration should always try booting from the first upgrade slot.
1066 if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
1067 assert_eq!(offset, resp.image_off as usize);
1068 assert_eq!(dev_id, resp.flash_dev_id);
1069 } else {
1070 panic!("Unable to find upgrade image");
1071 }
1072 false
1073 }
1074
1075 /// Test the ram-loading.
1076 pub fn run_ram_load(&self) -> bool {
1077 if !Caps::RamLoad.present() {
1078 return false;
1079 }
1080
1081 // Clone the flash so we can tell if unchanged.
1082 let mut flash = self.flash.clone();
1083
1084 // Setup ram based on the ram configuration we determined earlier for the images.
1085 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1086
1087 // println!("Ram: {:#?}", self.ram);
1088
1089 // Verify that the images area loaded into this.
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001090 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None,
1091 None, true));
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001092 if !result.success() {
1093 error!("Failed to execute ram-load");
1094 return true;
1095 }
1096
1097 // Verify each image.
1098 for image in &self.images {
1099 let place = self.ram.lookup(&image.slots[0]);
1100 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1101 place.size as usize);
1102 let src_sz = image.upgrades.size();
1103 if src_sz > ram_image.len() {
1104 error!("Image ended up too large, nonsensical");
1105 return true;
1106 }
1107 let src_image = &image.upgrades.plain[0..src_sz];
1108 let ram_image = &ram_image[0..src_sz];
1109 if ram_image != src_image {
1110 error!("Image not loaded correctly");
1111 return true;
1112 }
1113
1114 }
1115
1116 return false;
1117 }
1118
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001119 /// Test the split ram-loading.
1120 pub fn run_split_ram_load(&self) -> bool {
1121 if !Caps::RamLoad.present() {
1122 return false;
1123 }
1124
1125 // Clone the flash so we can tell if unchanged.
1126 let mut flash = self.flash.clone();
1127
1128 // Setup ram based on the ram configuration we determined earlier for the images.
1129 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1130
1131 for (idx, _image) in (&self.images).iter().enumerate() {
1132 // Verify that the images area loaded into this.
1133 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc,
1134 None, Some(idx as i32), true));
1135 if !result.success() {
1136 error!("Failed to execute ram-load");
1137 return true;
1138 }
1139 }
1140
1141 // Verify each image.
1142 for image in &self.images {
1143 let place = self.ram.lookup(&image.slots[0]);
1144 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1145 place.size as usize);
1146 let src_sz = image.upgrades.size();
1147 if src_sz > ram_image.len() {
1148 error!("Image ended up too large, nonsensical");
1149 return true;
1150 }
1151 let src_image = &image.upgrades.plain[0..src_sz];
1152 let ram_image = &ram_image[0..src_sz];
1153 if ram_image != src_image {
1154 error!("Image not loaded correctly");
1155 return true;
1156 }
1157
1158 }
1159
1160 return false;
1161 }
1162
David Brown5c9e0f12019-01-09 16:34:33 -07001163 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -07001164 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001165 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -07001166 if Caps::OverwriteUpgrade.present() {
1167 return;
1168 }
1169
David Brown84b49f72019-03-01 10:58:22 -07001170 // Set this for each image.
1171 for image in &self.images {
1172 let dev_id = &image.slots[slot].dev_id;
1173 let dev = flash.get_mut(&dev_id).unwrap();
1174 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001175 let off = &image.slots[slot].base_off;
1176 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -07001177 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -07001178
David Brown84b49f72019-03-01 10:58:22 -07001179 // Mark the status area as a bad area
1180 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1181 }
David Brown5c9e0f12019-01-09 16:34:33 -07001182 }
1183
David Brown76101572019-02-28 11:29:03 -07001184 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001185 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001186 return;
1187 }
1188
David Brown84b49f72019-03-01 10:58:22 -07001189 for image in &self.images {
1190 let dev_id = &image.slots[slot].dev_id;
1191 let dev = flash.get_mut(&dev_id).unwrap();
1192 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001193
David Brown84b49f72019-03-01 10:58:22 -07001194 // Disabling write verification the only assert triggered by
1195 // boot_go should be checking for integrity of status bytes.
1196 dev.set_verify_writes(false);
1197 }
David Brown5c9e0f12019-01-09 16:34:33 -07001198 }
1199
David Browndb505822019-03-01 10:04:20 -07001200 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1201 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001202 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001203 // Clone the flash to have a new copy.
1204 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001205
Fabio Utziged4a5362019-07-30 12:43:23 -03001206 if permanent {
1207 self.mark_permanent_upgrades(&mut flash, 1);
1208 }
David Brown5c9e0f12019-01-09 16:34:33 -07001209
David Browndb505822019-03-01 10:04:20 -07001210 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001211
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001212 let (first_interrupted, count) = match c::boot_go(&mut flash,
1213 &self.areadesc,
1214 Some(&mut counter),
1215 None, false) {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001216 x if x.interrupted() => (true, stop.unwrap()),
1217 x if x.success() => (false, -counter),
1218 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001219 };
David Brown5c9e0f12019-01-09 16:34:33 -07001220
David Browndb505822019-03-01 10:04:20 -07001221 counter = 0;
1222 if first_interrupted {
1223 // fl.dump();
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001224 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1225 None, false) {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001226 x if x.interrupted() => panic!("Shouldn't stop again"),
1227 x if x.success() => (),
1228 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001229 }
1230 }
David Brown5c9e0f12019-01-09 16:34:33 -07001231
David Browndb505822019-03-01 10:04:20 -07001232 (flash, count - counter)
1233 }
1234
1235 fn try_revert(&self, count: usize) -> SimMultiFlash {
1236 let mut flash = self.flash.clone();
1237
1238 // fl.write_file("image0.bin").unwrap();
1239 for i in 0 .. count {
1240 info!("Running boot pass {}", i + 1);
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001241 assert!(c::boot_go(&mut flash, &self.areadesc, None, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001242 }
1243 flash
1244 }
1245
1246 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1247 let mut flash = self.flash.clone();
1248 let mut fails = 0;
1249
1250 let mut counter = stop;
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001251 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1252 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001253 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001254 fails += 1;
1255 }
1256
Fabio Utzig8af7f792019-07-30 12:40:01 -03001257 // In a multi-image setup, copy done might be set if any number of
1258 // images was already successfully swapped.
1259 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1260 warn!("copy_done should be unset");
1261 fails += 1;
1262 }
1263
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001264 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001265 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001266 fails += 1;
1267 }
1268
David Brown84b49f72019-03-01 10:58:22 -07001269 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001270 warn!("Image in the primary slot before revert is invalid at stop={}",
1271 stop);
1272 fails += 1;
1273 }
David Brown84b49f72019-03-01 10:58:22 -07001274 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001275 warn!("Image in the secondary slot before revert is invalid at stop={}",
1276 stop);
1277 fails += 1;
1278 }
David Brown84b49f72019-03-01 10:58:22 -07001279 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1280 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001281 warn!("Mismatched trailer for the primary slot before revert");
1282 fails += 1;
1283 }
David Brown84b49f72019-03-01 10:58:22 -07001284 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1285 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001286 warn!("Mismatched trailer for the secondary slot before revert");
1287 fails += 1;
1288 }
1289
1290 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001291 let mut counter = stop;
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001292 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1293 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001294 warn!("Should have stopped revert at interruption point");
1295 fails += 1;
1296 }
1297
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001298 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001299 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001300 fails += 1;
1301 }
1302
David Brown84b49f72019-03-01 10:58:22 -07001303 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001304 warn!("Image in the primary slot after revert is invalid at stop={}",
1305 stop);
1306 fails += 1;
1307 }
David Brown84b49f72019-03-01 10:58:22 -07001308 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001309 warn!("Image in the secondary slot after revert is invalid at stop={}",
1310 stop);
1311 fails += 1;
1312 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001313
David Brown84b49f72019-03-01 10:58:22 -07001314 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1315 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001316 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001317 fails += 1;
1318 }
David Brown84b49f72019-03-01 10:58:22 -07001319 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1320 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001321 warn!("Mismatched trailer for the secondary slot after revert");
1322 fails += 1;
1323 }
1324
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001325 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001326 warn!("Should have finished 3rd boot");
1327 fails += 1;
1328 }
1329
1330 if !self.verify_images(&flash, 0, 0) {
1331 warn!("Image in the primary slot is invalid on 1st boot after revert");
1332 fails += 1;
1333 }
1334 if !self.verify_images(&flash, 1, 1) {
1335 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1336 fails += 1;
1337 }
1338
David Browndb505822019-03-01 10:04:20 -07001339 fails > 0
1340 }
1341
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001342
David Browndb505822019-03-01 10:04:20 -07001343 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1344 let mut flash = self.flash.clone();
1345
David Brown84b49f72019-03-01 10:58:22 -07001346 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001347
1348 let mut rng = rand::thread_rng();
1349 let mut resets = vec![0i32; count];
1350 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001351 for reset in &mut resets {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001352 let reset_counter = rng.gen_range(1 ..= remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001353 let mut counter = reset_counter;
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001354 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1355 None, false) {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001356 x if x.interrupted() => (),
1357 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001358 }
1359 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001360 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001361 }
1362
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001363 match c::boot_go(&mut flash, &self.areadesc, None, None, false) {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001364 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1365 x if x.success() => (),
1366 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001367 }
David Brown5c9e0f12019-01-09 16:34:33 -07001368
David Browndb505822019-03-01 10:04:20 -07001369 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001370 }
David Brown84b49f72019-03-01 10:58:22 -07001371
1372 /// Verify the image in the given flash device, the specified slot
1373 /// against the expected image.
1374 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001375 self.images.iter().all(|image| {
1376 verify_image(flash, &image.slots[slot],
1377 match against {
1378 0 => &image.primaries,
1379 1 => &image.upgrades,
1380 _ => panic!("Invalid 'against'")
1381 })
1382 })
David Brown84b49f72019-03-01 10:58:22 -07001383 }
1384
David Brownc3898d62019-08-05 14:20:02 -06001385 /// Verify the images, according to the dependency test.
1386 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1387 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1388 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1389 if !verify_image(flash, &image.slots[0],
1390 match upgrade {
1391 UpgradeInfo::Upgraded => &image.upgrades,
1392 UpgradeInfo::Held => &image.primaries,
1393 }) {
1394 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1395 return true;
1396 }
1397 }
1398
1399 false
1400 }
1401
Fabio Utzig8af7f792019-07-30 12:40:01 -03001402 /// Verify that at least one of the trailers of the images have the
1403 /// specified values.
1404 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1405 magic: Option<u8>, image_ok: Option<u8>,
1406 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001407 self.images.iter().any(|image| {
1408 verify_trailer(flash, &image.slots[slot],
1409 magic, image_ok, copy_done)
1410 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001411 }
1412
David Brown84b49f72019-03-01 10:58:22 -07001413 /// Verify that the trailers of the images have the specified
1414 /// values.
1415 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1416 magic: Option<u8>, image_ok: Option<u8>,
1417 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001418 self.images.iter().all(|image| {
1419 verify_trailer(flash, &image.slots[slot],
1420 magic, image_ok, copy_done)
1421 })
David Brown84b49f72019-03-01 10:58:22 -07001422 }
1423
1424 /// Mark each of the images for permanent upgrade.
1425 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1426 for image in &self.images {
1427 mark_permanent_upgrade(flash, &image.slots[slot]);
1428 }
1429 }
1430
1431 /// Mark each of the images for permanent upgrade.
1432 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1433 for image in &self.images {
1434 mark_upgrade(flash, &image.slots[slot]);
1435 }
1436 }
David Brown297029a2019-08-13 14:29:51 -06001437
1438 /// Dump out the flash image(s) to one or more files for debugging
1439 /// purposes. The names will be written as either "{prefix}.mcubin" or
1440 /// "{prefix}-001.mcubin" depending on how many images there are.
1441 pub fn debug_dump(&self, prefix: &str) {
1442 for (id, fdev) in &self.flash {
1443 let name = if self.flash.len() == 1 {
1444 format!("{}.mcubin", prefix)
1445 } else {
1446 format!("{}-{:>0}.mcubin", prefix, id)
1447 };
1448 fdev.write_file(&name).unwrap();
1449 }
1450 }
David Brown5c9e0f12019-01-09 16:34:33 -07001451}
1452
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001453impl RamData {
1454 // TODO: This is not correct. The second slot of each image should be at the same address as
1455 // the primary.
1456 fn new(slots: &[[SlotInfo; 2]]) -> RamData {
1457 let mut addr = RAM_LOAD_ADDR;
1458 let mut places = BTreeMap::new();
1459 // println!("Setup:-------------");
1460 for imgs in slots {
1461 for si in imgs {
1462 // println!("Setup: si: {:?}", si);
1463 let offset = addr;
1464 let size = si.len as u32;
1465 places.insert(SlotKey {
1466 dev_id: si.dev_id,
1467 base_off: si.base_off,
1468 }, SlotPlace { offset, size });
1469 // println!(" load: offset: {}, size: {}", offset, size);
1470 }
1471 addr += imgs[0].len as u32;
1472 }
1473 RamData {
1474 places,
1475 total: addr,
1476 }
1477 }
1478
1479 /// Lookup the ram data associated with a given flash partition. We just panic if not present,
1480 /// because all slots used should be in the map.
1481 fn lookup(&self, slot: &SlotInfo) -> &SlotPlace {
1482 self.places.get(&SlotKey{dev_id: slot.dev_id, base_off: slot.base_off})
1483 .expect("RamData should contain all slots")
1484 }
1485}
1486
David Brown5c9e0f12019-01-09 16:34:33 -07001487/// Show the flash layout.
1488#[allow(dead_code)]
1489fn show_flash(flash: &dyn Flash) {
1490 println!("---- Flash configuration ----");
1491 for sector in flash.sector_iter() {
1492 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1493 sector.num, sector.base, sector.size);
1494 }
David Brown599b2db2021-03-10 05:23:26 -07001495 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001496}
1497
1498/// Install a "program" into the given image. This fakes the image header, or at least all of the
1499/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001500fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001501 ram: &RamData,
David Brownc3898d62019-08-05 14:20:02 -06001502 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001503 let offset = slot.base_off;
1504 let slot_len = slot.len;
1505 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001506
David Brown43643dd2019-01-11 15:43:28 -07001507 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001508
David Brownc3898d62019-08-05 14:20:02 -06001509 // Add the dependencies early to the tlv.
1510 for dep in deps.my_deps(offset, slot.index) {
1511 tlv.add_dependency(deps.other_id(), &dep);
1512 }
1513
David Brown5c9e0f12019-01-09 16:34:33 -07001514 const HDR_SIZE: usize = 32;
1515
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001516 let place = ram.lookup(&slot);
1517 let load_addr = if Caps::RamLoad.present() {
1518 place.offset
1519 } else {
1520 0
1521 };
1522
David Brown5c9e0f12019-01-09 16:34:33 -07001523 // Generate a boot header. Note that the size doesn't include the header.
1524 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001525 magic: tlv.get_magic(),
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001526 load_addr,
David Brown5c9e0f12019-01-09 16:34:33 -07001527 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001528 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001529 img_size: len as u32,
1530 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001531 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001532 _pad2: 0,
1533 };
1534
1535 let mut b_header = [0; HDR_SIZE];
1536 b_header[..32].clone_from_slice(header.as_raw());
1537 assert_eq!(b_header.len(), HDR_SIZE);
1538
1539 tlv.add_bytes(&b_header);
1540
1541 // The core of the image itself is just pseudorandom data.
1542 let mut b_img = vec![0; len];
1543 splat(&mut b_img, offset);
1544
David Browncb47dd72019-08-05 14:21:49 -06001545 // Add some information at the start of the payload to make it easier
1546 // to see what it is. This will fail if the image itself is too small.
1547 {
1548 let mut wr = Cursor::new(&mut b_img);
1549 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1550 offset, dev_id, slot).unwrap();
1551 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1552 }
1553
David Brown5c9e0f12019-01-09 16:34:33 -07001554 // TLV signatures work over plain image
1555 tlv.add_bytes(&b_img);
1556
1557 // Generate encrypted images
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001558 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1559 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001560 let mut b_encimg = vec![];
1561 if is_encrypted {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001562 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1563 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001564 tlv.generate_enc_key();
1565 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001566 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001567 b_encimg = b_img.clone();
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001568 if aes256 {
1569 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
1570 let block = Aes256::new(&key);
1571 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
1572 cipher.apply_keystream(&mut b_encimg);
1573 } else {
1574 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
1575 let block = Aes128::new(&key);
1576 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
1577 cipher.apply_keystream(&mut b_encimg);
1578 }
David Brown5c9e0f12019-01-09 16:34:33 -07001579 }
1580
1581 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001582 if bad_sig {
1583 tlv.corrupt_sig();
1584 }
1585 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001586
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001587 let dev = flash.get_mut(&dev_id).unwrap();
1588
David Brown5c9e0f12019-01-09 16:34:33 -07001589 let mut buf = vec![];
1590 buf.append(&mut b_header.to_vec());
1591 buf.append(&mut b_img);
1592 buf.append(&mut b_tlv.clone());
1593
David Brown95de4502019-11-15 12:01:34 -07001594 // Pad the buffer to a multiple of the flash alignment.
1595 let align = dev.align();
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001596 let image_sz = buf.len();
David Brown95de4502019-11-15 12:01:34 -07001597 while buf.len() % align != 0 {
1598 buf.push(dev.erased_val());
1599 }
1600
David Brown5c9e0f12019-01-09 16:34:33 -07001601 let mut encbuf = vec![];
1602 if is_encrypted {
1603 encbuf.append(&mut b_header.to_vec());
1604 encbuf.append(&mut b_encimg);
1605 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001606
1607 while encbuf.len() % align != 0 {
1608 encbuf.push(dev.erased_val());
1609 }
David Brown5c9e0f12019-01-09 16:34:33 -07001610 }
1611
David Vincze2d736ad2019-02-18 11:50:22 +01001612 // Since images are always non-encrypted in the primary slot, we first write
1613 // an encrypted image, re-read to use for verification, erase + flash
1614 // un-encrypted. In the secondary slot the image is written un-encrypted,
1615 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001616
David Brown3b090212019-07-30 15:59:28 -06001617 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001618 let enc_copy: Option<Vec<u8>>;
1619
1620 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001621 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001622
1623 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001624 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001625
1626 enc_copy = Some(enc);
1627
David Brown76101572019-02-28 11:29:03 -07001628 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001629 } else {
1630 enc_copy = None;
1631 }
1632
David Brown76101572019-02-28 11:29:03 -07001633 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001634
1635 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001636 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001637
David Brownca234692019-02-28 11:22:19 -07001638 ImageData {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001639 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001640 plain: copy,
1641 cipher: enc_copy,
1642 }
David Brown5c9e0f12019-01-09 16:34:33 -07001643 } else {
1644
David Brown76101572019-02-28 11:29:03 -07001645 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001646
1647 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001648 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001649
1650 let enc_copy: Option<Vec<u8>>;
1651
1652 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001653 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001654
David Brown76101572019-02-28 11:29:03 -07001655 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001656
1657 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001658 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001659
1660 enc_copy = Some(enc);
1661 } else {
1662 enc_copy = None;
1663 }
1664
David Brownca234692019-02-28 11:22:19 -07001665 ImageData {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001666 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001667 plain: copy,
1668 cipher: enc_copy,
1669 }
David Brown5c9e0f12019-01-09 16:34:33 -07001670 }
David Brown5c9e0f12019-01-09 16:34:33 -07001671}
1672
David Brown873be312019-09-03 12:22:32 -06001673/// Install no image. This is used when no upgrade happens.
1674fn install_no_image() -> ImageData {
1675 ImageData {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001676 size: 0,
David Brown873be312019-09-03 12:22:32 -06001677 plain: vec![],
1678 cipher: None,
1679 }
1680}
1681
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001682/// Construct a TLV generator based on how MCUboot is currently configured. The returned
1683/// ManifestGen will generate the appropriate entries based on this configuration.
David Brown5c9e0f12019-01-09 16:34:33 -07001684fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001685 if Caps::EcdsaP224.present() {
1686 panic!("Ecdsa P224 not supported in Simulator");
1687 }
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001688 let aes_key_size = if Caps::Aes256.present() { 256 } else { 128 };
David Brown5c9e0f12019-01-09 16:34:33 -07001689
David Brownb8882112019-01-11 14:04:11 -07001690 if Caps::EncKw.present() {
1691 if Caps::RSA2048.present() {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001692 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001693 } else if Caps::EcdsaP256.present() {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001694 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001695 } else {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001696 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001697 }
1698 } else if Caps::EncRsa.present() {
1699 if Caps::RSA2048.present() {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001700 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001701 } else {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001702 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001703 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001704 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001705 if Caps::EcdsaP256.present() {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001706 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001707 } else {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001708 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001709 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001710 } else if Caps::EncX25519.present() {
1711 if Caps::Ed25519.present() {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001712 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001713 } else {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001714 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001715 }
David Brownb8882112019-01-11 14:04:11 -07001716 } else {
1717 // The non-encrypted configuration.
1718 if Caps::RSA2048.present() {
1719 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001720 } else if Caps::RSA3072.present() {
1721 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001722 } else if Caps::EcdsaP256.present() {
1723 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001724 } else if Caps::Ed25519.present() {
1725 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001726 } else {
1727 TlvGen::new_hash_only()
1728 }
1729 }
David Brown5c9e0f12019-01-09 16:34:33 -07001730}
1731
David Brownca234692019-02-28 11:22:19 -07001732impl ImageData {
1733 /// Find the image contents for the given slot. This assumes that slot 0
1734 /// is unencrypted, and slot 1 is encrypted.
1735 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001736 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001737 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001738 match (encrypted, slot) {
1739 (false, _) => &self.plain,
1740 (true, 0) => &self.plain,
1741 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1742 _ => panic!("Invalid slot requested"),
1743 }
David Brown5c9e0f12019-01-09 16:34:33 -07001744 }
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001745
1746 fn size(&self) -> usize {
1747 self.size
1748 }
David Brown5c9e0f12019-01-09 16:34:33 -07001749}
1750
David Brown5c9e0f12019-01-09 16:34:33 -07001751/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001752fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1753 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001754 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001755 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001756
1757 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001758 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001759 let dev = flash.get(&dev_id).unwrap();
1760 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001761
1762 if buf != &copy[..] {
1763 for i in 0 .. buf.len() {
1764 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001765 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1766 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001767 break;
1768 }
1769 }
1770 false
1771 } else {
1772 true
1773 }
1774}
1775
David Brown3b090212019-07-30 15:59:28 -06001776fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001777 magic: Option<u8>, image_ok: Option<u8>,
1778 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001779 if Caps::OverwriteUpgrade.present() {
1780 return true;
1781 }
David Brown5c9e0f12019-01-09 16:34:33 -07001782
David Brown3b090212019-07-30 15:59:28 -06001783 let offset = slot.trailer_off + c::boot_max_align();
1784 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001785 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001786 let mut failed = false;
1787
David Brown76101572019-02-28 11:29:03 -07001788 let dev = flash.get(&dev_id).unwrap();
1789 let erased_val = dev.erased_val();
1790 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001791
1792 failed |= match magic {
1793 Some(v) => {
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001794 let magic_off = (c::boot_max_align() * 3) + (c::boot_magic_sz() - MAGIC.len());
1795 if v == 1 && &copy[magic_off..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001796 warn!("\"magic\" mismatch at {:#x}", offset);
1797 true
1798 } else if v == 3 {
1799 let expected = [erased_val; 16];
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001800 if copy[magic_off..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001801 warn!("\"magic\" mismatch at {:#x}", offset);
1802 true
1803 } else {
1804 false
1805 }
1806 } else {
1807 false
1808 }
1809 },
1810 None => false,
1811 };
1812
1813 failed |= match image_ok {
1814 Some(v) => {
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001815 let image_ok_off = c::boot_max_align() * 2;
1816 if (v == 1 && copy[image_ok_off] != v) || (v == 3 && copy[image_ok_off] != erased_val) {
1817 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[image_ok_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07001818 true
1819 } else {
1820 false
1821 }
1822 },
1823 None => false,
1824 };
1825
1826 failed |= match copy_done {
1827 Some(v) => {
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001828 let copy_done_off = c::boot_max_align();
1829 if (v == 1 && copy[copy_done_off] != v) || (v == 3 && copy[copy_done_off] != erased_val) {
1830 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[copy_done_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07001831 true
1832 } else {
1833 false
1834 }
1835 },
1836 None => false,
1837 };
1838
1839 !failed
1840}
1841
David Brown297029a2019-08-13 14:29:51 -06001842/// Install a partition table. This is a simplified partition table that
1843/// we write at the beginning of flash so make it easier for external tools
1844/// to analyze these images.
1845fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1846 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1847 for &id in &ids {
1848 // If there are any partitions in this device that start at 0, and
1849 // aren't marked as the BootLoader partition, avoid adding the
1850 // partition table. This makes it harder to view the image, but
1851 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07001852 let skip_ptable = areadesc
1853 .iter_areas()
1854 .any(|area| {
1855 area.device_id == id &&
1856 area.off == 0 &&
1857 area.flash_id != FlashId::BootLoader
1858 });
1859 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06001860 if log_enabled!(Info) {
1861 let special: Vec<FlashId> = areadesc.iter_areas()
1862 .filter(|area| area.device_id == id && area.off == 0)
1863 .map(|area| area.flash_id)
1864 .collect();
1865 info!("Skipping partition table: {:?}", special);
1866 }
1867 break;
1868 }
1869
1870 let mut buf: Vec<u8> = vec![];
1871 write!(&mut buf, "mcuboot\0").unwrap();
1872
1873 // Iterate through all of the partitions in that device, and encode
1874 // into the table.
1875 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1876 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1877
1878 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1879 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1880 buf.write_u32::<LittleEndian>(area.off).unwrap();
1881 buf.write_u32::<LittleEndian>(area.size).unwrap();
1882 buf.write_u32::<LittleEndian>(0).unwrap();
1883 }
1884
1885 let dev = flash.get_mut(&id).unwrap();
1886
1887 // Pad to alignment.
1888 while buf.len() % dev.align() != 0 {
1889 buf.push(0);
1890 }
1891
1892 dev.write(0, &buf).unwrap();
1893 }
1894}
1895
David Brown5c9e0f12019-01-09 16:34:33 -07001896/// The image header
1897#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001898#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001899pub struct ImageHeader {
1900 magic: u32,
1901 load_addr: u32,
1902 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001903 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001904 img_size: u32,
1905 flags: u32,
1906 ver: ImageVersion,
1907 _pad2: u32,
1908}
1909
1910impl AsRaw for ImageHeader {}
1911
1912#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001913#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001914pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001915 pub major: u8,
1916 pub minor: u8,
1917 pub revision: u16,
1918 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001919}
1920
David Brownc3898d62019-08-05 14:20:02 -06001921#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001922pub struct SlotInfo {
1923 pub base_off: usize,
1924 pub trailer_off: usize,
1925 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001926 // Which slot within this device.
1927 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001928 pub dev_id: u8,
1929}
1930
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001931#[cfg(not(feature = "max-align-32"))]
David Brown347dc572019-11-15 11:37:25 -07001932const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1933 0x60, 0xd2, 0xef, 0x7f,
1934 0x35, 0x52, 0x50, 0x0f,
1935 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001936
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001937#[cfg(feature = "max-align-32")]
1938const MAGIC: &[u8] = &[0x20, 0x00, 0x2d, 0xe1,
1939 0x5d, 0x29, 0x41, 0x0b,
1940 0x8d, 0x77, 0x67, 0x9c,
1941 0x11, 0x0f, 0x1f, 0x8a];
1942
David Brown5c9e0f12019-01-09 16:34:33 -07001943// Replicates defines found in bootutil.h
1944const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1945const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1946
1947const BOOT_FLAG_SET: Option<u8> = Some(1);
1948const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1949
1950/// Write out the magic so that the loader tries doing an upgrade.
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001951#[cfg(not(feature = "swap-status"))]
David Brown76101572019-02-28 11:29:03 -07001952pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1953 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001954 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001955 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001956 if offset % align != 0 || MAGIC.len() % align != 0 {
1957 // The write size is larger than the magic value. Fill a buffer
1958 // with the erased value, put the MAGIC in it, and write it in its
1959 // entirety.
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001960 let mut buf = vec![dev.erased_val(); c::boot_max_align()];
1961 let magic_off = (offset % align) + (c::boot_magic_sz() - MAGIC.len());
1962 buf[magic_off..].copy_from_slice(MAGIC);
David Brown95de4502019-11-15 12:01:34 -07001963 dev.write(offset - (offset % align), &buf).unwrap();
1964 } else {
1965 dev.write(offset, MAGIC).unwrap();
1966 }
David Brown5c9e0f12019-01-09 16:34:33 -07001967}
1968
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001969/// Write out the magic so that the loader tries doing an upgrade.
1970#[cfg(feature = "swap-status")]
1971pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1972 let dev = flash.get_mut(&slot.dev_id).unwrap();
1973 let align = dev.align();
1974 let offset = slot.trailer_off + c::boot_max_align() * 4;
1975 let mask = align - 1;
1976 let sector_off = offset & !mask;
1977 let mut buf = vec![dev.erased_val(); align];
1978 dev.read(sector_off, &mut buf).unwrap();
1979 buf[(offset & mask)..].copy_from_slice(MAGIC);
1980 dev.erase(sector_off, align).unwrap();
1981 dev.write(sector_off, &buf).unwrap();
1982}
1983
David Brown5c9e0f12019-01-09 16:34:33 -07001984/// Writes the image_ok flag which, guess what, tells the bootloader
1985/// the this image is ok (not a test, and no revert is to be performed).
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001986#[cfg(not(feature = "swap-status"))]
David Brown76101572019-02-28 11:29:03 -07001987fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001988 // Overwrite mode always is permanent, and only the magic is used in
1989 // the trailer. To avoid problems with large write sizes, don't try to
1990 // set anything in this case.
1991 if Caps::OverwriteUpgrade.present() {
1992 return;
1993 }
1994
David Brown76101572019-02-28 11:29:03 -07001995 let dev = flash.get_mut(&slot.dev_id).unwrap();
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03001996 let align = dev.align();
1997 let mut ok = vec![dev.erased_val(); align];
David Brown5c9e0f12019-01-09 16:34:33 -07001998 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001999 let off = slot.trailer_off + c::boot_max_align() * 3;
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03002000 dev.write(off, &ok).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07002001}
2002
Roman Okhrimenko977b3752022-03-31 14:40:48 +03002003/// Writes the image_ok flag which, guess what, tells the bootloader
2004/// the this image is ok (not a test, and no revert is to be performed).
2005#[cfg(feature = "swap-status")]
2006fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
2007 // Overwrite mode always is permanent, and only the magic is used in
2008 // the trailer. To avoid problems with large write sizes, don't try to
2009 // set anything in this case.
2010 if Caps::OverwriteUpgrade.present() {
2011 return;
2012 }
2013
2014 let dev = flash.get_mut(&slot.dev_id).unwrap();
2015 let align:usize = dev.align();
2016 let mask:usize = align - 1;
2017 let ok_off:usize = slot.trailer_off + c::boot_max_align() * 3;
2018 let sector_off:usize = ok_off & !mask;
2019 let mut buf = vec![dev.erased_val(); align];
2020 dev.read(sector_off, &mut buf).unwrap();
2021 buf[ok_off & mask] = 1u8;
2022 dev.erase(sector_off, align).unwrap();
2023 dev.write(sector_off, &buf[..align]).unwrap();
2024}
2025
David Brown5c9e0f12019-01-09 16:34:33 -07002026// Drop some pseudo-random gibberish onto the data.
2027fn splat(data: &mut [u8], seed: usize) {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03002028 let mut seed_block = [0u8; 32];
David Browncd842842020-07-09 15:46:53 -06002029 let mut buf = Cursor::new(&mut seed_block[..]);
2030 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
2031 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
2032 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
2033 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
2034 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07002035 rng.fill_bytes(data);
2036}
2037
2038/// Return a read-only view into the raw bytes of this object
2039trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07002040 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07002041 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
2042 mem::size_of::<Self>()) }
2043 }
2044}
2045
2046pub fn show_sizes() {
2047 // This isn't panic safe.
2048 for min in &[1, 2, 4, 8] {
2049 let msize = c::boot_trailer_sz(*min);
2050 println!("{:2}: {} (0x{:x})", min, msize, msize);
2051 }
2052}
David Brown95de4502019-11-15 12:01:34 -07002053
Roman Okhrimenko977b3752022-03-31 14:40:48 +03002054#[cfg(not(feature = "swap-status"))]
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03002055#[cfg(not(feature = "max-align-32"))]
David Brown95de4502019-11-15 12:01:34 -07002056fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07002057 &[1, 2, 4, 8]
2058}
2059
Roman Okhrimenko977b3752022-03-31 14:40:48 +03002060#[cfg(not(feature = "swap-status"))]
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03002061#[cfg(feature = "max-align-32")]
David Brown95de4502019-11-15 12:01:34 -07002062fn test_alignments() -> &'static [usize] {
Roman Okhrimenkodc0ca082023-06-21 20:49:51 +03002063 &[32]
David Brown95de4502019-11-15 12:01:34 -07002064}
Roman Okhrimenko977b3752022-03-31 14:40:48 +03002065
2066#[cfg(feature = "swap-status")]
2067fn test_alignments() -> &'static [usize] {
2068 &[512]
2069}