blob: 5ef0e57e739a46322f54eb765f157361c323cb3e [file] [log] [blame]
David Browne2acfae2020-01-21 16:45:01 -07001// Copyright (c) 2019 Linaro LTD
2// Copyright (c) 2019-2020 JUUL Labs
Salome Thirot6fdbf552021-05-14 16:46:14 +01003// 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::{
David Brownbf32c272021-06-16 17:11:37 -060022 collections::{BTreeMap, HashSet},
David Browncb47dd72019-08-05 14:21:49 -060023 io::{Cursor, Write},
David Brown5c9e0f12019-01-09 16:34:33 -070024 mem,
25 slice,
26};
David Brown9c6322f2021-08-19 13:03:39 -060027use aes::{
28 Aes128,
David Brown5c9e0f12019-01-09 16:34:33 -070029 Aes128Ctr,
David Brown9c6322f2021-08-19 13:03:39 -060030 Aes256,
Salome Thirot6fdbf552021-05-14 16:46:14 +010031 Aes256Ctr,
David Brown9c6322f2021-08-19 13:03:39 -060032 NewBlockCipher,
David Brown5c9e0f12019-01-09 16:34:33 -070033};
David Brown9c6322f2021-08-19 13:03:39 -060034use cipher::{
35 FromBlockCipher,
36 generic_array::GenericArray,
37 StreamCipher,
38 };
David Brown5c9e0f12019-01-09 16:34:33 -070039
David Brown76101572019-02-28 11:29:03 -070040use simflash::{Flash, SimFlash, SimMultiFlash};
David Brown8a4e23b2021-06-11 10:29:01 -060041use mcuboot_sys::{c, AreaDesc, FlashId, RamBlock};
David Browne5133242019-02-28 11:05:19 -070042use crate::{
43 ALL_DEVICES,
44 DeviceName,
45};
David Brown5c9e0f12019-01-09 16:34:33 -070046use crate::caps::Caps;
David Brownc3898d62019-08-05 14:20:02 -060047use crate::depends::{
48 BoringDep,
49 Depender,
50 DepTest,
David Brown873be312019-09-03 12:22:32 -060051 DepType,
David Brown2ee5f7f2020-01-13 14:04:01 -070052 NO_DEPS,
David Brownc3898d62019-08-05 14:20:02 -060053 PairDep,
54 UpgradeInfo,
55};
Fabio Utzig90f449e2019-10-24 07:43:53 -030056use crate::tlv::{ManifestGen, TlvGen, TlvFlags};
Salome Thirot6fdbf552021-05-14 16:46:14 +010057use typenum::{U32, U16};
David Brown5c9e0f12019-01-09 16:34:33 -070058
David Brown8a4e23b2021-06-11 10:29:01 -060059/// For testing, use a non-zero offset for the ram-load, to make sure the offset is getting used
60/// properly, but the value is not really that important.
61const RAM_LOAD_ADDR: u32 = 1024;
62
David Browne5133242019-02-28 11:05:19 -070063/// A builder for Images. This describes a single run of the simulator,
64/// capturing the configuration of a particular set of devices, including
65/// the flash simulator(s) and the information about the slots.
66#[derive(Clone)]
67pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070068 flash: SimMultiFlash,
David Browne5133242019-02-28 11:05:19 -070069 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070070 slots: Vec<[SlotInfo; 2]>,
David Brownbf32c272021-06-16 17:11:37 -060071 ram: RamData,
David Browne5133242019-02-28 11:05:19 -070072}
73
David Brown998aa8d2019-02-28 10:54:50 -070074/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070075/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070076/// and upgrades hold the expected contents of these images.
77pub struct Images {
David Brown76101572019-02-28 11:29:03 -070078 flash: SimMultiFlash,
David Brownca234692019-02-28 11:22:19 -070079 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070080 images: Vec<OneImage>,
81 total_count: Option<i32>,
David Brownbf32c272021-06-16 17:11:37 -060082 ram: RamData,
David Brown84b49f72019-03-01 10:58:22 -070083}
84
85/// When doing multi-image, there is an instance of this information for
86/// each of the images. Single image there will be one of these.
87struct OneImage {
David Brownca234692019-02-28 11:22:19 -070088 slots: [SlotInfo; 2],
89 primaries: ImageData,
90 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070091}
92
93/// The Rust-side representation of an image. For unencrypted images, this
94/// is just the unencrypted payload. For encrypted images, we store both
95/// the encrypted and the plaintext.
96struct ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -030097 size: usize,
David Brownca234692019-02-28 11:22:19 -070098 plain: Vec<u8>,
99 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -0700100}
101
David Brownbf32c272021-06-16 17:11:37 -0600102/// For the RamLoad test cases, we need a contiguous area of RAM to load these images into. For
103/// multi-image builds, these may not correspond with the offsets. This has to be computed early,
104/// before images are built, because each image contains the offset where the image is to be loaded
105/// in the header, which is contained within the signature.
106#[derive(Clone, Debug)]
107struct RamData {
108 places: BTreeMap<SlotKey, SlotPlace>,
109 total: u32,
110}
111
112/// Every slot is indexed by this key.
113#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
114struct SlotKey {
115 dev_id: u8,
David Brownf17d3912021-06-23 16:10:51 -0600116 base_off: usize,
David Brownbf32c272021-06-16 17:11:37 -0600117}
118
119#[derive(Clone, Debug)]
120struct SlotPlace {
121 offset: u32,
122 size: u32,
123}
124
David Browne5133242019-02-28 11:05:19 -0700125impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -0700126 /// Construct a new image builder for the given device. Returns
127 /// Some(builder) if is possible to test this configuration, or None if
128 /// not possible (for example, if there aren't enough image slots).
Fabio Utzig114a6472019-11-28 10:24:09 -0300129 pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
130 let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
131
132 for cap in unsupported_caps {
133 if cap.present() {
134 return Err(format!("unsupported {:?}", cap));
135 }
136 }
David Browne5133242019-02-28 11:05:19 -0700137
David Brown06ef06e2019-03-05 12:28:10 -0700138 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -0700139
David Brown06ef06e2019-03-05 12:28:10 -0700140 let mut slots = Vec::with_capacity(num_images);
141 for image in 0..num_images {
142 // This mapping must match that defined in
143 // `boot/zephyr/include/sysflash/sysflash.h`.
144 let id0 = match image {
145 0 => FlashId::Image0,
146 1 => FlashId::Image2,
147 _ => panic!("More than 2 images not supported"),
148 };
149 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
150 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300151 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700152 };
153 let id1 = match image {
154 0 => FlashId::Image1,
155 1 => FlashId::Image3,
156 _ => panic!("More than 2 images not supported"),
157 };
158 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
159 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300160 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700161 };
David Browne5133242019-02-28 11:05:19 -0700162
Christopher Collinsa1c12042019-05-23 14:00:28 -0700163 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700164
David Brown06ef06e2019-03-05 12:28:10 -0700165 // Construct a primary image.
166 let primary = SlotInfo {
167 base_off: primary_base as usize,
168 trailer_off: primary_base + primary_len - offset_from_end,
169 len: primary_len as usize,
170 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600171 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700172 };
173
174 // And an upgrade image.
175 let secondary = SlotInfo {
176 base_off: secondary_base as usize,
177 trailer_off: secondary_base + secondary_len - offset_from_end,
178 len: secondary_len as usize,
179 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600180 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700181 };
182
183 slots.push([primary, secondary]);
184 }
David Browne5133242019-02-28 11:05:19 -0700185
David Brownbf32c272021-06-16 17:11:37 -0600186 let ram = RamData::new(&slots);
187
Fabio Utzig114a6472019-11-28 10:24:09 -0300188 Ok(ImagesBuilder {
David Brown4dfb33c2021-03-10 05:15:45 -0700189 flash,
190 areadesc,
191 slots,
David Brownbf32c272021-06-16 17:11:37 -0600192 ram,
David Brown5bc62c62019-03-05 12:11:48 -0700193 })
David Browne5133242019-02-28 11:05:19 -0700194 }
195
196 pub fn each_device<F>(f: F)
197 where F: Fn(Self)
198 {
199 for &dev in ALL_DEVICES {
David Brown95de4502019-11-15 12:01:34 -0700200 for &align in test_alignments() {
David Browne5133242019-02-28 11:05:19 -0700201 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700202 match Self::new(dev, align, erased_val) {
Fabio Utzig114a6472019-11-28 10:24:09 -0300203 Ok(run) => f(run),
204 Err(msg) => warn!("Skipping {}: {}", dev, msg),
David Brown5bc62c62019-03-05 12:11:48 -0700205 }
David Browne5133242019-02-28 11:05:19 -0700206 }
207 }
208 }
209 }
210
211 /// Construct an `Images` that doesn't expect an upgrade to happen.
David Brownc3898d62019-08-05 14:20:02 -0600212 pub fn make_no_upgrade_image(self, deps: &DepTest) -> Images {
213 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700214 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600215 let ram = self.ram.clone(); // TODO: This is wasteful.
David Brownc3898d62019-08-05 14:20:02 -0600216 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
217 let dep: Box<dyn Depender> = if num_images > 1 {
218 Box::new(PairDep::new(num_images, image_num, deps))
219 } else {
David Brown2ee5f7f2020-01-13 14:04:01 -0700220 Box::new(BoringDep::new(image_num, deps))
David Brownc3898d62019-08-05 14:20:02 -0600221 };
David Brownbf32c272021-06-16 17:11:37 -0600222 let primaries = install_image(&mut flash, &slots[0], 42784, &ram, &*dep, false);
David Brown873be312019-09-03 12:22:32 -0600223 let upgrades = match deps.depends[image_num] {
224 DepType::NoUpgrade => install_no_image(),
David Brownbf32c272021-06-16 17:11:37 -0600225 _ => install_image(&mut flash, &slots[1], 46928, &ram, &*dep, false)
David Brown873be312019-09-03 12:22:32 -0600226 };
David Brown84b49f72019-03-01 10:58:22 -0700227 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700228 slots,
229 primaries,
230 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700231 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600232 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700233 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700234 flash,
David Browne5133242019-02-28 11:05:19 -0700235 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700236 images,
David Browne5133242019-02-28 11:05:19 -0700237 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600238 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700239 }
240 }
241
David Brownc3898d62019-08-05 14:20:02 -0600242 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
243 let mut images = self.make_no_upgrade_image(deps);
David Brown84b49f72019-03-01 10:58:22 -0700244 for image in &images.images {
245 mark_upgrade(&mut images.flash, &image.slots[1]);
246 }
David Browne5133242019-02-28 11:05:19 -0700247
David Brown6db44d72021-05-26 16:22:58 -0600248 // The count is meaningless if no flash operations are performed.
249 if !Caps::modifies_flash() {
250 return images;
251 }
252
David Browne5133242019-02-28 11:05:19 -0700253 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300254 let total_count = match images.run_basic_upgrade(permanent) {
David Brown8973f552021-03-10 05:21:11 -0700255 Some(v) => v,
256 None =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600257 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
258 0
259 } else {
260 panic!("Unable to perform basic upgrade");
261 }
David Browne5133242019-02-28 11:05:19 -0700262 };
263
264 images.total_count = Some(total_count);
265 images
266 }
267
268 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700269 let mut bad_flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600270 let ram = self.ram.clone(); // TODO: Avoid this clone.
David Brownc3898d62019-08-05 14:20:02 -0600271 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
David Brown2ee5f7f2020-01-13 14:04:01 -0700272 let dep = BoringDep::new(image_num, &NO_DEPS);
David Brownbf32c272021-06-16 17:11:37 -0600273 let primaries = install_image(&mut bad_flash, &slots[0], 32784, &ram, &dep, false);
274 let upgrades = install_image(&mut bad_flash, &slots[1], 41928, &ram, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700275 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700276 slots,
277 primaries,
278 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700279 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700280 Images {
David Brown76101572019-02-28 11:29:03 -0700281 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700282 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700283 images,
David Browne5133242019-02-28 11:05:19 -0700284 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600285 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700286 }
287 }
288
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300289 pub fn make_erased_secondary_image(self) -> Images {
290 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600291 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300292 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
293 let dep = BoringDep::new(image_num, &NO_DEPS);
David Brownbf32c272021-06-16 17:11:37 -0600294 let primaries = install_image(&mut flash, &slots[0], 32784, &ram, &dep, false);
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300295 let upgrades = install_no_image();
296 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700297 slots,
298 primaries,
299 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300300 }}).collect();
301 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700302 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300303 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700304 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300305 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600306 ram: self.ram,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300307 }
308 }
309
Fabio Utzigd0157342020-10-02 15:22:11 -0300310 pub fn make_bootstrap_image(self) -> Images {
311 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600312 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzigd0157342020-10-02 15:22:11 -0300313 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
314 let dep = BoringDep::new(image_num, &NO_DEPS);
315 let primaries = install_no_image();
David Brownbf32c272021-06-16 17:11:37 -0600316 let upgrades = install_image(&mut flash, &slots[1], 32784, &ram, &dep, false);
Fabio Utzigd0157342020-10-02 15:22:11 -0300317 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700318 slots,
319 primaries,
320 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300321 }}).collect();
322 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700323 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300324 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700325 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300326 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600327 ram: self.ram,
Fabio Utzigd0157342020-10-02 15:22:11 -0300328 }
329 }
330
David Browne5133242019-02-28 11:05:19 -0700331 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300332 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700333 match device {
334 DeviceName::Stm32f4 => {
335 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700336 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
337 64 * 1024,
338 128 * 1024, 128 * 1024, 128 * 1024],
339 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700340 let dev_id = 0;
341 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700342 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700343 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
344 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
345 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
346
David Brown76101572019-02-28 11:29:03 -0700347 let mut flash = SimMultiFlash::new();
348 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300349 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700350 }
351 DeviceName::K64f => {
352 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700353 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700354
355 let dev_id = 0;
356 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700357 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700358 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
359 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
360 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
361
David Brown76101572019-02-28 11:29:03 -0700362 let mut flash = SimMultiFlash::new();
363 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300364 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700365 }
366 DeviceName::K64fBig => {
367 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
368 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700369 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700370
371 let dev_id = 0;
372 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700373 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700374 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
375 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
376 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
377
David Brown76101572019-02-28 11:29:03 -0700378 let mut flash = SimMultiFlash::new();
379 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300380 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700381 }
382 DeviceName::Nrf52840 => {
383 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
384 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700385 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700386
387 let dev_id = 0;
388 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700389 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700390 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
391 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
392 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
393
David Brown76101572019-02-28 11:29:03 -0700394 let mut flash = SimMultiFlash::new();
395 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300396 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700397 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300398 DeviceName::Nrf52840UnequalSlots => {
399 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
400
401 let dev_id = 0;
402 let mut areadesc = AreaDesc::new();
403 areadesc.add_flash_sectors(dev_id, &dev);
404 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
405 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
406
407 let mut flash = SimMultiFlash::new();
408 flash.insert(dev_id, dev);
409 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
410 }
David Browne5133242019-02-28 11:05:19 -0700411 DeviceName::Nrf52840SpiFlash => {
412 // Simulate nrf52840 with external SPI flash. The external SPI flash
413 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700414 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
415 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700416
417 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700418 areadesc.add_flash_sectors(0, &dev0);
419 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700420
421 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
422 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
423 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
424
David Brown76101572019-02-28 11:29:03 -0700425 let mut flash = SimMultiFlash::new();
426 flash.insert(0, dev0);
427 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300428 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700429 }
David Brown2bff6472019-03-05 13:58:35 -0700430 DeviceName::K64fMulti => {
431 // NXP style flash, but larger, to support multiple images.
432 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
433
434 let dev_id = 0;
435 let mut areadesc = AreaDesc::new();
436 areadesc.add_flash_sectors(dev_id, &dev);
437 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
438 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
439 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
440 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
441 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
442
443 let mut flash = SimMultiFlash::new();
444 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300445 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700446 }
David Browne5133242019-02-28 11:05:19 -0700447 }
448 }
David Brownc3898d62019-08-05 14:20:02 -0600449
450 pub fn num_images(&self) -> usize {
451 self.slots.len()
452 }
David Browne5133242019-02-28 11:05:19 -0700453}
454
David Brown5c9e0f12019-01-09 16:34:33 -0700455impl Images {
456 /// A simple upgrade without forced failures.
457 ///
458 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700459 /// inject failures at chosen steps. Returns None if it was unable to
460 /// count the operations in a basic upgrade.
461 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300462 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700463 info!("Total flash operation count={}", total_count);
464
David Brown84b49f72019-03-01 10:58:22 -0700465 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700466 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700467 None
David Brown5c9e0f12019-01-09 16:34:33 -0700468 } else {
David Brown8973f552021-03-10 05:21:11 -0700469 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700470 }
471 }
472
Fabio Utzigd0157342020-10-02 15:22:11 -0300473 pub fn run_bootstrap(&self) -> bool {
474 let mut flash = self.flash.clone();
475 let mut fails = 0;
476
477 if Caps::Bootstrap.present() {
478 info!("Try bootstraping image in the primary");
479
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100480 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigd0157342020-10-02 15:22:11 -0300481 warn!("Failed first boot");
482 fails += 1;
483 }
484
485 if !self.verify_images(&flash, 0, 1) {
486 warn!("Image in the first slot was not bootstrapped");
487 fails += 1;
488 }
489
490 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
491 BOOT_FLAG_SET, BOOT_FLAG_SET) {
492 warn!("Mismatched trailer for the primary slot");
493 fails += 1;
494 }
495 }
496
497 if fails > 0 {
498 error!("Expected trailer on secondary slot to be erased");
499 }
500
501 fails > 0
502 }
503
504
David Brownc3898d62019-08-05 14:20:02 -0600505 /// Test a simple upgrade, with dependencies given, and verify that the
506 /// image does as is described in the test.
507 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600508 if !Caps::modifies_flash() {
509 return false;
510 }
511
David Brownc3898d62019-08-05 14:20:02 -0600512 let (flash, _) = self.try_upgrade(None, true);
513
514 self.verify_dep_images(&flash, deps)
515 }
516
Fabio Utzigf5480c72019-11-28 10:41:57 -0300517 fn is_swap_upgrade(&self) -> bool {
518 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
519 }
520
David Brown5c9e0f12019-01-09 16:34:33 -0700521 pub fn run_basic_revert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600522 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700523 return false;
524 }
David Brown5c9e0f12019-01-09 16:34:33 -0700525
David Brown5c9e0f12019-01-09 16:34:33 -0700526 let mut fails = 0;
527
528 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300529 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700530 for count in 2 .. 5 {
531 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700532 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700533 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700534 error!("Revert failure on count {}", count);
535 fails += 1;
536 }
537 }
538 }
539
540 fails > 0
541 }
542
543 pub fn run_perm_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600544 if !Caps::modifies_flash() {
545 return false;
546 }
547
David Brown5c9e0f12019-01-09 16:34:33 -0700548 let mut fails = 0;
549 let total_flash_ops = self.total_count.unwrap();
550
551 // Let's try an image halfway through.
552 for i in 1 .. total_flash_ops {
553 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300554 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700555 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700556 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700557 warn!("FAIL at step {} of {}", i, total_flash_ops);
558 fails += 1;
559 }
560
David Brown84b49f72019-03-01 10:58:22 -0700561 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
562 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100563 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700564 fails += 1;
565 }
566
David Brown84b49f72019-03-01 10:58:22 -0700567 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
568 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100569 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700570 fails += 1;
571 }
572
David Brownaec56b22021-03-10 05:22:07 -0700573 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
574 warn!("Secondary slot FAIL at step {} of {}",
575 i, total_flash_ops);
576 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700577 }
578 }
579
580 if fails > 0 {
581 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
582 fails as f32 * 100.0 / total_flash_ops as f32);
583 }
584
585 fails > 0
586 }
587
David Brown5c9e0f12019-01-09 16:34:33 -0700588 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600589 if !Caps::modifies_flash() {
590 return false;
591 }
592
David Brown5c9e0f12019-01-09 16:34:33 -0700593 let mut fails = 0;
594 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700595 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700596 info!("Random interruptions at reset points={:?}", total_counts);
597
David Brown84b49f72019-03-01 10:58:22 -0700598 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300599 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700600 // TODO: This result is ignored.
601 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700602 } else {
603 true
604 };
David Vincze2d736ad2019-02-18 11:50:22 +0100605 if !primary_slot_ok || !secondary_slot_ok {
606 error!("Image mismatch after random interrupts: primary slot={} \
607 secondary slot={}",
608 if primary_slot_ok { "ok" } else { "fail" },
609 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700610 fails += 1;
611 }
David Brown84b49f72019-03-01 10:58:22 -0700612 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
613 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100614 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700615 fails += 1;
616 }
David Brown84b49f72019-03-01 10:58:22 -0700617 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
618 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100619 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700620 fails += 1;
621 }
622
623 if fails > 0 {
624 error!("Error testing perm upgrade with {} fails", total_fails);
625 }
626
627 fails > 0
628 }
629
David Brown5c9e0f12019-01-09 16:34:33 -0700630 pub fn run_revert_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600631 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700632 return false;
633 }
David Brown5c9e0f12019-01-09 16:34:33 -0700634
David Brown5c9e0f12019-01-09 16:34:33 -0700635 let mut fails = 0;
636
Fabio Utzigf5480c72019-11-28 10:41:57 -0300637 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300638 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700639 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700640 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700641 error!("Revert failed at interruption {}", i);
642 fails += 1;
643 }
644 }
645 }
646
647 fails > 0
648 }
649
David Brown5c9e0f12019-01-09 16:34:33 -0700650 pub fn run_norevert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600651 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700652 return false;
653 }
David Brown5c9e0f12019-01-09 16:34:33 -0700654
David Brown76101572019-02-28 11:29:03 -0700655 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700656 let mut fails = 0;
657
658 info!("Try norevert");
659
660 // First do a normal upgrade...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100661 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700662 warn!("Failed first boot");
663 fails += 1;
664 }
665
666 //FIXME: copy_done is written by boot_go, is it ok if no copy
667 // was ever done?
668
David Brown84b49f72019-03-01 10:58:22 -0700669 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100670 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700671 fails += 1;
672 }
David Brown84b49f72019-03-01 10:58:22 -0700673 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
674 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100675 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700676 fails += 1;
677 }
David Brown84b49f72019-03-01 10:58:22 -0700678 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
679 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100680 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700681 fails += 1;
682 }
683
David Vincze2d736ad2019-02-18 11:50:22 +0100684 // Marks image in the primary slot as permanent,
685 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700686 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700687
David Brown84b49f72019-03-01 10:58:22 -0700688 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
689 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100690 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700691 fails += 1;
692 }
693
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100694 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700695 warn!("Failed second boot");
696 fails += 1;
697 }
698
David Brown84b49f72019-03-01 10:58:22 -0700699 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
700 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100701 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700702 fails += 1;
703 }
David Brown84b49f72019-03-01 10:58:22 -0700704 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700705 warn!("Failed image verification");
706 fails += 1;
707 }
708
709 if fails > 0 {
710 error!("Error running upgrade without revert");
711 }
712
713 fails > 0
714 }
715
David Brown2ee5f7f2020-01-13 14:04:01 -0700716 // Test that an upgrade is rejected. Assumes that the image was build
717 // such that the upgrade is instead a downgrade.
718 pub fn run_nodowngrade(&self) -> bool {
719 if !Caps::DowngradePrevention.present() {
720 return false;
721 }
722
723 let mut flash = self.flash.clone();
724 let mut fails = 0;
725
726 info!("Try no downgrade");
727
728 // First, do a normal upgrade.
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100729 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700730 warn!("Failed first boot");
731 fails += 1;
732 }
733
734 if !self.verify_images(&flash, 0, 0) {
735 warn!("Failed verification after downgrade rejection");
736 fails += 1;
737 }
738
739 if fails > 0 {
740 error!("Error testing downgrade rejection");
741 }
742
743 fails > 0
744 }
745
David Vincze2d736ad2019-02-18 11:50:22 +0100746 // Tests a new image written to the primary slot that already has magic and
747 // image_ok set while there is no image on the secondary slot, so no revert
748 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700749 pub fn run_norevert_newimage(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600750 if !Caps::modifies_flash() {
751 info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
752 return false;
753 }
754
David Brown76101572019-02-28 11:29:03 -0700755 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700756 let mut fails = 0;
757
758 info!("Try non-revert on imgtool generated image");
759
David Brown84b49f72019-03-01 10:58:22 -0700760 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700761
David Vincze2d736ad2019-02-18 11:50:22 +0100762 // This simulates writing an image created by imgtool to
763 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700764 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
765 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100766 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700767 fails += 1;
768 }
769
770 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100771 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700772 warn!("Failed first boot");
773 fails += 1;
774 }
775
776 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700777 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700778 warn!("Failed image verification");
779 fails += 1;
780 }
David Brown84b49f72019-03-01 10:58:22 -0700781 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
782 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100783 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700784 fails += 1;
785 }
David Brown84b49f72019-03-01 10:58:22 -0700786 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
787 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100788 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700789 fails += 1;
790 }
791
792 if fails > 0 {
793 error!("Expected a non revert with new image");
794 }
795
796 fails > 0
797 }
798
David Vincze2d736ad2019-02-18 11:50:22 +0100799 // Tests a new image written to the primary slot that already has magic and
800 // image_ok set while there is no image on the secondary slot, so no revert
801 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700802 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700803 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700804 let mut fails = 0;
805
806 info!("Try upgrade image with bad signature");
807
David Brown6db44d72021-05-26 16:22:58 -0600808 // Only perform this test if an upgrade is expected to happen.
809 if !Caps::modifies_flash() {
810 info!("Skipping upgrade image with bad signature");
811 return false;
812 }
813
David Brown84b49f72019-03-01 10:58:22 -0700814 self.mark_upgrades(&mut flash, 0);
815 self.mark_permanent_upgrades(&mut flash, 0);
816 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700817
David Brown84b49f72019-03-01 10:58:22 -0700818 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
819 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100820 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700821 fails += 1;
822 }
823
824 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100825 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700826 warn!("Failed first boot");
827 fails += 1;
828 }
829
830 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700831 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700832 warn!("Failed image verification");
833 fails += 1;
834 }
David Brown84b49f72019-03-01 10:58:22 -0700835 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
836 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100837 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700838 fails += 1;
839 }
840
841 if fails > 0 {
842 error!("Expected an upgrade failure when image has bad signature");
843 }
844
845 fails > 0
846 }
847
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300848 // Should detect there is a leftover trailer in an otherwise erased
849 // secondary slot and erase its trailer.
850 pub fn run_secondary_leftover_trailer(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600851 if !Caps::modifies_flash() {
852 return false;
853 }
854
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300855 let mut flash = self.flash.clone();
856 let mut fails = 0;
857
858 info!("Try with a leftover trailer in the secondary; must be erased");
859
860 // Add a trailer on the secondary slot
861 self.mark_permanent_upgrades(&mut flash, 1);
862 self.mark_upgrades(&mut flash, 1);
863
864 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100865 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300866 warn!("Failed first boot");
867 fails += 1;
868 }
869
870 // State should not have changed
871 if !self.verify_images(&flash, 0, 0) {
872 warn!("Failed image verification");
873 fails += 1;
874 }
875 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
876 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
877 warn!("Mismatched trailer for the secondary slot");
878 fails += 1;
879 }
880
881 if fails > 0 {
882 error!("Expected trailer on secondary slot to be erased");
883 }
884
885 fails > 0
886 }
887
David Brown5c9e0f12019-01-09 16:34:33 -0700888 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300889 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700890 }
891
David Brown5c9e0f12019-01-09 16:34:33 -0700892 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300893 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700894 }
895
896 /// This test runs a simple upgrade with no fails in the images, but
897 /// allowing for fails in the status area. This should run to the end
898 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700899 pub fn run_with_status_fails_complete(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600900 if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700901 return false;
902 }
903
David Brown76101572019-02-28 11:29:03 -0700904 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700905 let mut fails = 0;
906
907 info!("Try swap with status fails");
908
David Brown84b49f72019-03-01 10:58:22 -0700909 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700910 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700911
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100912 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brownc423ac42021-06-04 13:47:34 -0600913 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700914 warn!("Failed!");
915 fails += 1;
916 }
917
918 // Failed writes to the marked "bad" region don't assert anymore.
919 // Any detected assert() is happening in another part of the code.
David Brownc423ac42021-06-04 13:47:34 -0600920 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -0700921 warn!("At least one assert() was called");
922 fails += 1;
923 }
924
David Brown84b49f72019-03-01 10:58:22 -0700925 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
926 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100927 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700928 fails += 1;
929 }
930
David Brown84b49f72019-03-01 10:58:22 -0700931 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700932 warn!("Failed image verification");
933 fails += 1;
934 }
935
David Vincze2d736ad2019-02-18 11:50:22 +0100936 info!("validate primary slot enabled; \
937 re-run of boot_go should just work");
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100938 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700939 warn!("Failed!");
940 fails += 1;
941 }
942
943 if fails > 0 {
944 error!("Error running upgrade with status write fails");
945 }
946
947 fails > 0
948 }
949
950 /// This test runs a simple upgrade with no fails in the images, but
951 /// allowing for fails in the status area. This should run to the end
952 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700953 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600954 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700955 false
David Vincze2d736ad2019-02-18 11:50:22 +0100956 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700957
David Brown76101572019-02-28 11:29:03 -0700958 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700959 let mut fails = 0;
960 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700961
David Brown85904a82019-01-11 13:45:12 -0700962 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700963
David Brown85904a82019-01-11 13:45:12 -0700964 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700965
David Brown84b49f72019-03-01 10:58:22 -0700966 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700967 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700968
969 // Should not fail, writing to bad regions does not assert
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100970 let asserts = c::boot_go(&mut flash, &self.areadesc,
971 Some(&mut count), None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700972 if asserts != 0 {
973 warn!("At least one assert() was called");
974 fails += 1;
975 }
976
David Brown76101572019-02-28 11:29:03 -0700977 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700978
979 info!("Resuming an interrupted swap operation");
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100980 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
981 true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700982
983 // This might throw no asserts, for large sector devices, where
984 // a single failure writing is indistinguishable from no failure,
985 // or throw a single assert for small sector devices that fail
986 // multiple times...
987 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100988 warn!("Expected single assert validating the primary slot, \
989 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700990 fails += 1;
991 }
992
993 if fails > 0 {
994 error!("Error running upgrade with status write fails");
995 }
996
997 fails > 0
998 } else {
David Brown76101572019-02-28 11:29:03 -0700999 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001000 let mut fails = 0;
1001
1002 info!("Try interrupted swap with status fails");
1003
David Brown84b49f72019-03-01 10:58:22 -07001004 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001005 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -07001006
1007 // This is expected to fail while writing to bad regions...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001008 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1009 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001010 if asserts == 0 {
1011 warn!("No assert() detected");
1012 fails += 1;
1013 }
1014
1015 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -07001016 }
David Brown5c9e0f12019-01-09 16:34:33 -07001017 }
1018
David Brown0dfb8102021-06-03 15:29:11 -06001019 /// Test the direct XIP configuration. With this mode, flash images are never moved, and the
1020 /// bootloader merely selects which partition is the proper one to boot.
1021 pub fn run_direct_xip(&self) -> bool {
1022 if !Caps::DirectXip.present() {
1023 return false;
1024 }
1025
1026 // Clone the flash so we can tell if unchanged.
1027 let mut flash = self.flash.clone();
1028
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001029 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brown0dfb8102021-06-03 15:29:11 -06001030
1031 // Ensure the boot was successful.
1032 let resp = if let Some(resp) = result.resp() {
1033 resp
1034 } else {
1035 panic!("Boot didn't return a valid result");
1036 };
1037
1038 // This configuration should always try booting from the first upgrade slot.
1039 if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
1040 assert_eq!(offset, resp.image_off as usize);
1041 assert_eq!(dev_id, resp.flash_dev_id);
1042 } else {
1043 panic!("Unable to find upgrade image");
1044 }
1045 false
1046 }
1047
David Brown8a4e23b2021-06-11 10:29:01 -06001048 /// Test the ram-loading.
1049 pub fn run_ram_load(&self) -> bool {
1050 if !Caps::RamLoad.present() {
1051 return false;
1052 }
1053
1054 // Clone the flash so we can tell if unchanged.
1055 let mut flash = self.flash.clone();
1056
David Brownf17d3912021-06-23 16:10:51 -06001057 // Setup ram based on the ram configuration we determined earlier for the images.
1058 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
David Brown8a4e23b2021-06-11 10:29:01 -06001059
David Brownf17d3912021-06-23 16:10:51 -06001060 // println!("Ram: {:#?}", self.ram);
David Brown8a4e23b2021-06-11 10:29:01 -06001061
David Brownf17d3912021-06-23 16:10:51 -06001062 // Verify that the images area loaded into this.
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001063 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None,
1064 None, true));
David Brown8a4e23b2021-06-11 10:29:01 -06001065 if !result.success() {
David Brownf17d3912021-06-23 16:10:51 -06001066 error!("Failed to execute ram-load");
David Brown8a4e23b2021-06-11 10:29:01 -06001067 return true;
1068 }
1069
David Brownf17d3912021-06-23 16:10:51 -06001070 // Verify each image.
1071 for image in &self.images {
1072 let place = self.ram.lookup(&image.slots[0]);
1073 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1074 place.size as usize);
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001075 let src_sz = image.upgrades.size();
1076 if src_sz > ram_image.len() {
David Brownf17d3912021-06-23 16:10:51 -06001077 error!("Image ended up too large, nonsensical");
1078 return true;
1079 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001080 let src_image = &image.upgrades.plain[0..src_sz];
1081 let ram_image = &ram_image[0..src_sz];
David Brownf17d3912021-06-23 16:10:51 -06001082 if ram_image != src_image {
1083 error!("Image not loaded correctly");
1084 return true;
1085 }
1086
1087 }
1088
1089 return false;
David Brown8a4e23b2021-06-11 10:29:01 -06001090 }
1091
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001092 /// Test the split ram-loading.
1093 pub fn run_split_ram_load(&self) -> bool {
1094 if !Caps::RamLoad.present() {
1095 return false;
1096 }
1097
1098 // Clone the flash so we can tell if unchanged.
1099 let mut flash = self.flash.clone();
1100
1101 // Setup ram based on the ram configuration we determined earlier for the images.
1102 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1103
1104 for (idx, _image) in (&self.images).iter().enumerate() {
1105 // Verify that the images area loaded into this.
1106 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc,
1107 None, Some(idx as i32), true));
1108 if !result.success() {
1109 error!("Failed to execute ram-load");
1110 return true;
1111 }
1112 }
1113
1114 // Verify each image.
1115 for image in &self.images {
1116 let place = self.ram.lookup(&image.slots[0]);
1117 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1118 place.size as usize);
1119 let src_sz = image.upgrades.size();
1120 if src_sz > ram_image.len() {
1121 error!("Image ended up too large, nonsensical");
1122 return true;
1123 }
1124 let src_image = &image.upgrades.plain[0..src_sz];
1125 let ram_image = &ram_image[0..src_sz];
1126 if ram_image != src_image {
1127 error!("Image not loaded correctly");
1128 return true;
1129 }
1130
1131 }
1132
1133 return false;
1134 }
1135
David Brown5c9e0f12019-01-09 16:34:33 -07001136 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -07001137 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001138 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -07001139 if Caps::OverwriteUpgrade.present() {
1140 return;
1141 }
1142
David Brown84b49f72019-03-01 10:58:22 -07001143 // Set this for each image.
1144 for image in &self.images {
1145 let dev_id = &image.slots[slot].dev_id;
1146 let dev = flash.get_mut(&dev_id).unwrap();
1147 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001148 let off = &image.slots[slot].base_off;
1149 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -07001150 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -07001151
David Brown84b49f72019-03-01 10:58:22 -07001152 // Mark the status area as a bad area
1153 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1154 }
David Brown5c9e0f12019-01-09 16:34:33 -07001155 }
1156
David Brown76101572019-02-28 11:29:03 -07001157 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001158 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001159 return;
1160 }
1161
David Brown84b49f72019-03-01 10:58:22 -07001162 for image in &self.images {
1163 let dev_id = &image.slots[slot].dev_id;
1164 let dev = flash.get_mut(&dev_id).unwrap();
1165 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001166
David Brown84b49f72019-03-01 10:58:22 -07001167 // Disabling write verification the only assert triggered by
1168 // boot_go should be checking for integrity of status bytes.
1169 dev.set_verify_writes(false);
1170 }
David Brown5c9e0f12019-01-09 16:34:33 -07001171 }
1172
David Browndb505822019-03-01 10:04:20 -07001173 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1174 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001175 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001176 // Clone the flash to have a new copy.
1177 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001178
Fabio Utziged4a5362019-07-30 12:43:23 -03001179 if permanent {
1180 self.mark_permanent_upgrades(&mut flash, 1);
1181 }
David Brown5c9e0f12019-01-09 16:34:33 -07001182
David Browndb505822019-03-01 10:04:20 -07001183 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001184
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001185 let (first_interrupted, count) = match c::boot_go(&mut flash,
1186 &self.areadesc,
1187 Some(&mut counter),
1188 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001189 x if x.interrupted() => (true, stop.unwrap()),
1190 x if x.success() => (false, -counter),
1191 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001192 };
David Brown5c9e0f12019-01-09 16:34:33 -07001193
David Browndb505822019-03-01 10:04:20 -07001194 counter = 0;
1195 if first_interrupted {
1196 // fl.dump();
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001197 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1198 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001199 x if x.interrupted() => panic!("Shouldn't stop again"),
1200 x if x.success() => (),
1201 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001202 }
1203 }
David Brown5c9e0f12019-01-09 16:34:33 -07001204
David Browndb505822019-03-01 10:04:20 -07001205 (flash, count - counter)
1206 }
1207
1208 fn try_revert(&self, count: usize) -> SimMultiFlash {
1209 let mut flash = self.flash.clone();
1210
1211 // fl.write_file("image0.bin").unwrap();
1212 for i in 0 .. count {
1213 info!("Running boot pass {}", i + 1);
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001214 assert!(c::boot_go(&mut flash, &self.areadesc, None, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001215 }
1216 flash
1217 }
1218
1219 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1220 let mut flash = self.flash.clone();
1221 let mut fails = 0;
1222
1223 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001224 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1225 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001226 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001227 fails += 1;
1228 }
1229
Fabio Utzig8af7f792019-07-30 12:40:01 -03001230 // In a multi-image setup, copy done might be set if any number of
1231 // images was already successfully swapped.
1232 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1233 warn!("copy_done should be unset");
1234 fails += 1;
1235 }
1236
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001237 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001238 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001239 fails += 1;
1240 }
1241
David Brown84b49f72019-03-01 10:58:22 -07001242 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001243 warn!("Image in the primary slot before revert is invalid at stop={}",
1244 stop);
1245 fails += 1;
1246 }
David Brown84b49f72019-03-01 10:58:22 -07001247 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001248 warn!("Image in the secondary slot before revert is invalid at stop={}",
1249 stop);
1250 fails += 1;
1251 }
David Brown84b49f72019-03-01 10:58:22 -07001252 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1253 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001254 warn!("Mismatched trailer for the primary slot before revert");
1255 fails += 1;
1256 }
David Brown84b49f72019-03-01 10:58:22 -07001257 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1258 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001259 warn!("Mismatched trailer for the secondary slot before revert");
1260 fails += 1;
1261 }
1262
1263 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001264 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001265 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1266 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001267 warn!("Should have stopped revert at interruption point");
1268 fails += 1;
1269 }
1270
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001271 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001272 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001273 fails += 1;
1274 }
1275
David Brown84b49f72019-03-01 10:58:22 -07001276 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001277 warn!("Image in the primary slot after revert is invalid at stop={}",
1278 stop);
1279 fails += 1;
1280 }
David Brown84b49f72019-03-01 10:58:22 -07001281 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001282 warn!("Image in the secondary slot after revert is invalid at stop={}",
1283 stop);
1284 fails += 1;
1285 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001286
David Brown84b49f72019-03-01 10:58:22 -07001287 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1288 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001289 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001290 fails += 1;
1291 }
David Brown84b49f72019-03-01 10:58:22 -07001292 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1293 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001294 warn!("Mismatched trailer for the secondary slot after revert");
1295 fails += 1;
1296 }
1297
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001298 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001299 warn!("Should have finished 3rd boot");
1300 fails += 1;
1301 }
1302
1303 if !self.verify_images(&flash, 0, 0) {
1304 warn!("Image in the primary slot is invalid on 1st boot after revert");
1305 fails += 1;
1306 }
1307 if !self.verify_images(&flash, 1, 1) {
1308 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1309 fails += 1;
1310 }
1311
David Browndb505822019-03-01 10:04:20 -07001312 fails > 0
1313 }
1314
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001315
David Browndb505822019-03-01 10:04:20 -07001316 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1317 let mut flash = self.flash.clone();
1318
David Brown84b49f72019-03-01 10:58:22 -07001319 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001320
1321 let mut rng = rand::thread_rng();
1322 let mut resets = vec![0i32; count];
1323 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001324 for reset in &mut resets {
David Brown9c6322f2021-08-19 13:03:39 -06001325 let reset_counter = rng.gen_range(1 ..= remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001326 let mut counter = reset_counter;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001327 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1328 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001329 x if x.interrupted() => (),
1330 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001331 }
1332 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001333 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001334 }
1335
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001336 match c::boot_go(&mut flash, &self.areadesc, None, None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001337 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1338 x if x.success() => (),
1339 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001340 }
David Brown5c9e0f12019-01-09 16:34:33 -07001341
David Browndb505822019-03-01 10:04:20 -07001342 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001343 }
David Brown84b49f72019-03-01 10:58:22 -07001344
1345 /// Verify the image in the given flash device, the specified slot
1346 /// against the expected image.
1347 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001348 self.images.iter().all(|image| {
1349 verify_image(flash, &image.slots[slot],
1350 match against {
1351 0 => &image.primaries,
1352 1 => &image.upgrades,
1353 _ => panic!("Invalid 'against'")
1354 })
1355 })
David Brown84b49f72019-03-01 10:58:22 -07001356 }
1357
David Brownc3898d62019-08-05 14:20:02 -06001358 /// Verify the images, according to the dependency test.
1359 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1360 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1361 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1362 if !verify_image(flash, &image.slots[0],
1363 match upgrade {
1364 UpgradeInfo::Upgraded => &image.upgrades,
1365 UpgradeInfo::Held => &image.primaries,
1366 }) {
1367 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1368 return true;
1369 }
1370 }
1371
1372 false
1373 }
1374
Fabio Utzig8af7f792019-07-30 12:40:01 -03001375 /// Verify that at least one of the trailers of the images have the
1376 /// specified values.
1377 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1378 magic: Option<u8>, image_ok: Option<u8>,
1379 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001380 self.images.iter().any(|image| {
1381 verify_trailer(flash, &image.slots[slot],
1382 magic, image_ok, copy_done)
1383 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001384 }
1385
David Brown84b49f72019-03-01 10:58:22 -07001386 /// Verify that the trailers of the images have the specified
1387 /// values.
1388 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1389 magic: Option<u8>, image_ok: Option<u8>,
1390 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001391 self.images.iter().all(|image| {
1392 verify_trailer(flash, &image.slots[slot],
1393 magic, image_ok, copy_done)
1394 })
David Brown84b49f72019-03-01 10:58:22 -07001395 }
1396
1397 /// Mark each of the images for permanent upgrade.
1398 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1399 for image in &self.images {
1400 mark_permanent_upgrade(flash, &image.slots[slot]);
1401 }
1402 }
1403
1404 /// Mark each of the images for permanent upgrade.
1405 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1406 for image in &self.images {
1407 mark_upgrade(flash, &image.slots[slot]);
1408 }
1409 }
David Brown297029a2019-08-13 14:29:51 -06001410
1411 /// Dump out the flash image(s) to one or more files for debugging
1412 /// purposes. The names will be written as either "{prefix}.mcubin" or
1413 /// "{prefix}-001.mcubin" depending on how many images there are.
1414 pub fn debug_dump(&self, prefix: &str) {
1415 for (id, fdev) in &self.flash {
1416 let name = if self.flash.len() == 1 {
1417 format!("{}.mcubin", prefix)
1418 } else {
1419 format!("{}-{:>0}.mcubin", prefix, id)
1420 };
1421 fdev.write_file(&name).unwrap();
1422 }
1423 }
David Brown5c9e0f12019-01-09 16:34:33 -07001424}
1425
David Brownbf32c272021-06-16 17:11:37 -06001426impl RamData {
David Brownf17d3912021-06-23 16:10:51 -06001427 // TODO: This is not correct. The second slot of each image should be at the same address as
1428 // the primary.
David Brownbf32c272021-06-16 17:11:37 -06001429 fn new(slots: &[[SlotInfo; 2]]) -> RamData {
1430 let mut addr = RAM_LOAD_ADDR;
1431 let mut places = BTreeMap::new();
David Brownf17d3912021-06-23 16:10:51 -06001432 // println!("Setup:-------------");
David Brownbf32c272021-06-16 17:11:37 -06001433 for imgs in slots {
1434 for si in imgs {
David Brownf17d3912021-06-23 16:10:51 -06001435 // println!("Setup: si: {:?}", si);
David Brownbf32c272021-06-16 17:11:37 -06001436 let offset = addr;
1437 let size = si.len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001438 places.insert(SlotKey {
1439 dev_id: si.dev_id,
David Brownf17d3912021-06-23 16:10:51 -06001440 base_off: si.base_off,
David Brownbf32c272021-06-16 17:11:37 -06001441 }, SlotPlace { offset, size });
David Brownf17d3912021-06-23 16:10:51 -06001442 // println!(" load: offset: {}, size: {}", offset, size);
David Brownbf32c272021-06-16 17:11:37 -06001443 }
David Brownf17d3912021-06-23 16:10:51 -06001444 addr += imgs[0].len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001445 }
1446 RamData {
1447 places,
1448 total: addr,
1449 }
1450 }
David Brownf17d3912021-06-23 16:10:51 -06001451
1452 /// Lookup the ram data associated with a given flash partition. We just panic if not present,
1453 /// because all slots used should be in the map.
1454 fn lookup(&self, slot: &SlotInfo) -> &SlotPlace {
1455 self.places.get(&SlotKey{dev_id: slot.dev_id, base_off: slot.base_off})
1456 .expect("RamData should contain all slots")
1457 }
David Brownbf32c272021-06-16 17:11:37 -06001458}
1459
David Brown5c9e0f12019-01-09 16:34:33 -07001460/// Show the flash layout.
1461#[allow(dead_code)]
1462fn show_flash(flash: &dyn Flash) {
1463 println!("---- Flash configuration ----");
1464 for sector in flash.sector_iter() {
1465 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1466 sector.num, sector.base, sector.size);
1467 }
David Brown599b2db2021-03-10 05:23:26 -07001468 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001469}
1470
1471/// Install a "program" into the given image. This fakes the image header, or at least all of the
1472/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001473fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownf17d3912021-06-23 16:10:51 -06001474 ram: &RamData,
David Brownc3898d62019-08-05 14:20:02 -06001475 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001476 let offset = slot.base_off;
1477 let slot_len = slot.len;
1478 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001479
David Brown43643dd2019-01-11 15:43:28 -07001480 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001481
David Brownc3898d62019-08-05 14:20:02 -06001482 // Add the dependencies early to the tlv.
1483 for dep in deps.my_deps(offset, slot.index) {
1484 tlv.add_dependency(deps.other_id(), &dep);
1485 }
1486
David Brown5c9e0f12019-01-09 16:34:33 -07001487 const HDR_SIZE: usize = 32;
1488
David Brownf17d3912021-06-23 16:10:51 -06001489 let place = ram.lookup(&slot);
1490 let load_addr = if Caps::RamLoad.present() {
1491 place.offset
1492 } else {
1493 0
1494 };
1495
David Brown5c9e0f12019-01-09 16:34:33 -07001496 // Generate a boot header. Note that the size doesn't include the header.
1497 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001498 magic: tlv.get_magic(),
David Brownf17d3912021-06-23 16:10:51 -06001499 load_addr,
David Brown5c9e0f12019-01-09 16:34:33 -07001500 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001501 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001502 img_size: len as u32,
1503 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001504 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001505 _pad2: 0,
1506 };
1507
1508 let mut b_header = [0; HDR_SIZE];
1509 b_header[..32].clone_from_slice(header.as_raw());
1510 assert_eq!(b_header.len(), HDR_SIZE);
1511
1512 tlv.add_bytes(&b_header);
1513
1514 // The core of the image itself is just pseudorandom data.
1515 let mut b_img = vec![0; len];
1516 splat(&mut b_img, offset);
1517
David Browncb47dd72019-08-05 14:21:49 -06001518 // Add some information at the start of the payload to make it easier
1519 // to see what it is. This will fail if the image itself is too small.
1520 {
1521 let mut wr = Cursor::new(&mut b_img);
1522 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1523 offset, dev_id, slot).unwrap();
1524 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1525 }
1526
David Brown5c9e0f12019-01-09 16:34:33 -07001527 // TLV signatures work over plain image
1528 tlv.add_bytes(&b_img);
1529
1530 // Generate encrypted images
Salome Thirot6fdbf552021-05-14 16:46:14 +01001531 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1532 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001533 let mut b_encimg = vec![];
1534 if is_encrypted {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001535 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1536 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001537 tlv.generate_enc_key();
1538 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001539 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001540 b_encimg = b_img.clone();
Salome Thirot6fdbf552021-05-14 16:46:14 +01001541 if aes256 {
1542 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001543 let block = Aes256::new(&key);
1544 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001545 cipher.apply_keystream(&mut b_encimg);
1546 } else {
1547 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001548 let block = Aes128::new(&key);
1549 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001550 cipher.apply_keystream(&mut b_encimg);
1551 }
David Brown5c9e0f12019-01-09 16:34:33 -07001552 }
1553
1554 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001555 if bad_sig {
1556 tlv.corrupt_sig();
1557 }
1558 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001559
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001560 let dev = flash.get_mut(&dev_id).unwrap();
1561
David Brown5c9e0f12019-01-09 16:34:33 -07001562 let mut buf = vec![];
1563 buf.append(&mut b_header.to_vec());
1564 buf.append(&mut b_img);
1565 buf.append(&mut b_tlv.clone());
1566
David Brown95de4502019-11-15 12:01:34 -07001567 // Pad the buffer to a multiple of the flash alignment.
1568 let align = dev.align();
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001569 let image_sz = buf.len();
David Brown95de4502019-11-15 12:01:34 -07001570 while buf.len() % align != 0 {
1571 buf.push(dev.erased_val());
1572 }
1573
David Brown5c9e0f12019-01-09 16:34:33 -07001574 let mut encbuf = vec![];
1575 if is_encrypted {
1576 encbuf.append(&mut b_header.to_vec());
1577 encbuf.append(&mut b_encimg);
1578 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001579
1580 while encbuf.len() % align != 0 {
1581 encbuf.push(dev.erased_val());
1582 }
David Brown5c9e0f12019-01-09 16:34:33 -07001583 }
1584
David Vincze2d736ad2019-02-18 11:50:22 +01001585 // Since images are always non-encrypted in the primary slot, we first write
1586 // an encrypted image, re-read to use for verification, erase + flash
1587 // un-encrypted. In the secondary slot the image is written un-encrypted,
1588 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001589
David Brown3b090212019-07-30 15:59:28 -06001590 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001591 let enc_copy: Option<Vec<u8>>;
1592
1593 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001594 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001595
1596 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001597 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001598
1599 enc_copy = Some(enc);
1600
David Brown76101572019-02-28 11:29:03 -07001601 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001602 } else {
1603 enc_copy = None;
1604 }
1605
David Brown76101572019-02-28 11:29:03 -07001606 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001607
1608 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001609 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001610
David Brownca234692019-02-28 11:22:19 -07001611 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001612 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001613 plain: copy,
1614 cipher: enc_copy,
1615 }
David Brown5c9e0f12019-01-09 16:34:33 -07001616 } else {
1617
David Brown76101572019-02-28 11:29:03 -07001618 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001619
1620 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001621 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001622
1623 let enc_copy: Option<Vec<u8>>;
1624
1625 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001626 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001627
David Brown76101572019-02-28 11:29:03 -07001628 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001629
1630 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001631 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001632
1633 enc_copy = Some(enc);
1634 } else {
1635 enc_copy = None;
1636 }
1637
David Brownca234692019-02-28 11:22:19 -07001638 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44: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 }
David Brown5c9e0f12019-01-09 16:34:33 -07001644}
1645
David Brown873be312019-09-03 12:22:32 -06001646/// Install no image. This is used when no upgrade happens.
1647fn install_no_image() -> ImageData {
1648 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001649 size: 0,
David Brown873be312019-09-03 12:22:32 -06001650 plain: vec![],
1651 cipher: None,
1652 }
1653}
1654
David Brown0bd8c6b2021-10-22 16:33:06 -06001655/// Construct a TLV generator based on how MCUboot is currently configured. The returned
1656/// ManifestGen will generate the appropriate entries based on this configuration.
David Brown5c9e0f12019-01-09 16:34:33 -07001657fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001658 if Caps::EcdsaP224.present() {
1659 panic!("Ecdsa P224 not supported in Simulator");
1660 }
Salome Thirot6fdbf552021-05-14 16:46:14 +01001661 let mut aes_key_size = 128;
1662 if Caps::Aes256.present() {
1663 aes_key_size = 256;
1664 }
David Brown5c9e0f12019-01-09 16:34:33 -07001665
David Brownb8882112019-01-11 14:04:11 -07001666 if Caps::EncKw.present() {
1667 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001668 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001669 } else if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001670 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001671 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001672 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001673 }
1674 } else if Caps::EncRsa.present() {
1675 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001676 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001677 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001678 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001679 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001680 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001681 if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001682 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001683 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001684 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001685 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001686 } else if Caps::EncX25519.present() {
1687 if Caps::Ed25519.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001688 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001689 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001690 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001691 }
David Brownb8882112019-01-11 14:04:11 -07001692 } else {
1693 // The non-encrypted configuration.
1694 if Caps::RSA2048.present() {
1695 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001696 } else if Caps::RSA3072.present() {
1697 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001698 } else if Caps::EcdsaP256.present() {
1699 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001700 } else if Caps::Ed25519.present() {
1701 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001702 } else {
1703 TlvGen::new_hash_only()
1704 }
1705 }
David Brown5c9e0f12019-01-09 16:34:33 -07001706}
1707
David Brownca234692019-02-28 11:22:19 -07001708impl ImageData {
1709 /// Find the image contents for the given slot. This assumes that slot 0
1710 /// is unencrypted, and slot 1 is encrypted.
1711 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001712 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001713 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001714 match (encrypted, slot) {
1715 (false, _) => &self.plain,
1716 (true, 0) => &self.plain,
1717 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1718 _ => panic!("Invalid slot requested"),
1719 }
David Brown5c9e0f12019-01-09 16:34:33 -07001720 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001721
1722 fn size(&self) -> usize {
1723 self.size
1724 }
David Brown5c9e0f12019-01-09 16:34:33 -07001725}
1726
David Brown5c9e0f12019-01-09 16:34:33 -07001727/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001728fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1729 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001730 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001731 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001732
1733 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001734 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001735 let dev = flash.get(&dev_id).unwrap();
1736 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001737
1738 if buf != &copy[..] {
1739 for i in 0 .. buf.len() {
1740 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001741 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1742 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001743 break;
1744 }
1745 }
1746 false
1747 } else {
1748 true
1749 }
1750}
1751
David Brown3b090212019-07-30 15:59:28 -06001752fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001753 magic: Option<u8>, image_ok: Option<u8>,
1754 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001755 if Caps::OverwriteUpgrade.present() {
1756 return true;
1757 }
David Brown5c9e0f12019-01-09 16:34:33 -07001758
David Brown3b090212019-07-30 15:59:28 -06001759 let offset = slot.trailer_off + c::boot_max_align();
1760 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001761 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001762 let mut failed = false;
1763
David Brown76101572019-02-28 11:29:03 -07001764 let dev = flash.get(&dev_id).unwrap();
1765 let erased_val = dev.erased_val();
1766 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001767
1768 failed |= match magic {
1769 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001770 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001771 warn!("\"magic\" mismatch at {:#x}", offset);
1772 true
1773 } else if v == 3 {
1774 let expected = [erased_val; 16];
David Brownd36f6b12021-03-10 05:23:56 -07001775 if copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001776 warn!("\"magic\" mismatch at {:#x}", offset);
1777 true
1778 } else {
1779 false
1780 }
1781 } else {
1782 false
1783 }
1784 },
1785 None => false,
1786 };
1787
1788 failed |= match image_ok {
1789 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001790 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001791 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1792 true
1793 } else {
1794 false
1795 }
1796 },
1797 None => false,
1798 };
1799
1800 failed |= match copy_done {
1801 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001802 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001803 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1804 true
1805 } else {
1806 false
1807 }
1808 },
1809 None => false,
1810 };
1811
1812 !failed
1813}
1814
David Brown297029a2019-08-13 14:29:51 -06001815/// Install a partition table. This is a simplified partition table that
1816/// we write at the beginning of flash so make it easier for external tools
1817/// to analyze these images.
1818fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1819 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1820 for &id in &ids {
1821 // If there are any partitions in this device that start at 0, and
1822 // aren't marked as the BootLoader partition, avoid adding the
1823 // partition table. This makes it harder to view the image, but
1824 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07001825 let skip_ptable = areadesc
1826 .iter_areas()
1827 .any(|area| {
1828 area.device_id == id &&
1829 area.off == 0 &&
1830 area.flash_id != FlashId::BootLoader
1831 });
1832 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06001833 if log_enabled!(Info) {
1834 let special: Vec<FlashId> = areadesc.iter_areas()
1835 .filter(|area| area.device_id == id && area.off == 0)
1836 .map(|area| area.flash_id)
1837 .collect();
1838 info!("Skipping partition table: {:?}", special);
1839 }
1840 break;
1841 }
1842
1843 let mut buf: Vec<u8> = vec![];
1844 write!(&mut buf, "mcuboot\0").unwrap();
1845
1846 // Iterate through all of the partitions in that device, and encode
1847 // into the table.
1848 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1849 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1850
1851 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1852 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1853 buf.write_u32::<LittleEndian>(area.off).unwrap();
1854 buf.write_u32::<LittleEndian>(area.size).unwrap();
1855 buf.write_u32::<LittleEndian>(0).unwrap();
1856 }
1857
1858 let dev = flash.get_mut(&id).unwrap();
1859
1860 // Pad to alignment.
1861 while buf.len() % dev.align() != 0 {
1862 buf.push(0);
1863 }
1864
1865 dev.write(0, &buf).unwrap();
1866 }
1867}
1868
David Brown5c9e0f12019-01-09 16:34:33 -07001869/// The image header
1870#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001871#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001872pub struct ImageHeader {
1873 magic: u32,
1874 load_addr: u32,
1875 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001876 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001877 img_size: u32,
1878 flags: u32,
1879 ver: ImageVersion,
1880 _pad2: u32,
1881}
1882
1883impl AsRaw for ImageHeader {}
1884
1885#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001886#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001887pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001888 pub major: u8,
1889 pub minor: u8,
1890 pub revision: u16,
1891 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001892}
1893
David Brownc3898d62019-08-05 14:20:02 -06001894#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001895pub struct SlotInfo {
1896 pub base_off: usize,
1897 pub trailer_off: usize,
1898 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001899 // Which slot within this device.
1900 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001901 pub dev_id: u8,
1902}
1903
David Brown347dc572019-11-15 11:37:25 -07001904const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1905 0x60, 0xd2, 0xef, 0x7f,
1906 0x35, 0x52, 0x50, 0x0f,
1907 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001908
1909// Replicates defines found in bootutil.h
1910const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1911const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1912
1913const BOOT_FLAG_SET: Option<u8> = Some(1);
1914const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1915
1916/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001917pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1918 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001919 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001920 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001921 if offset % align != 0 || MAGIC.len() % align != 0 {
1922 // The write size is larger than the magic value. Fill a buffer
1923 // with the erased value, put the MAGIC in it, and write it in its
1924 // entirety.
1925 let mut buf = vec![dev.erased_val(); align];
1926 buf[(offset % align)..].copy_from_slice(MAGIC);
1927 dev.write(offset - (offset % align), &buf).unwrap();
1928 } else {
1929 dev.write(offset, MAGIC).unwrap();
1930 }
David Brown5c9e0f12019-01-09 16:34:33 -07001931}
1932
1933/// Writes the image_ok flag which, guess what, tells the bootloader
1934/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001935fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001936 // Overwrite mode always is permanent, and only the magic is used in
1937 // the trailer. To avoid problems with large write sizes, don't try to
1938 // set anything in this case.
1939 if Caps::OverwriteUpgrade.present() {
1940 return;
1941 }
1942
David Brown76101572019-02-28 11:29:03 -07001943 let dev = flash.get_mut(&slot.dev_id).unwrap();
1944 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001945 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001946 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001947 let align = dev.align();
1948 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001949}
1950
1951// Drop some pseudo-random gibberish onto the data.
1952fn splat(data: &mut [u8], seed: usize) {
David Brown9c6322f2021-08-19 13:03:39 -06001953 let mut seed_block = [0u8; 32];
David Browncd842842020-07-09 15:46:53 -06001954 let mut buf = Cursor::new(&mut seed_block[..]);
1955 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
1956 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
1957 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
1958 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
1959 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07001960 rng.fill_bytes(data);
1961}
1962
1963/// Return a read-only view into the raw bytes of this object
1964trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07001965 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07001966 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1967 mem::size_of::<Self>()) }
1968 }
1969}
1970
1971pub fn show_sizes() {
1972 // This isn't panic safe.
1973 for min in &[1, 2, 4, 8] {
1974 let msize = c::boot_trailer_sz(*min);
1975 println!("{:2}: {} (0x{:x})", min, msize, msize);
1976 }
1977}
David Brown95de4502019-11-15 12:01:34 -07001978
1979#[cfg(not(feature = "large-write"))]
1980fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001981 &[1, 2, 4, 8]
1982}
1983
1984#[cfg(feature = "large-write")]
1985fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001986 &[1, 2, 4, 8, 128, 512]
1987}