blob: cc9dd6ae21971f7db2b891a664ab61c71f9d0974 [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
David Brownc423ac42021-06-04 13:47:34 -0600480 if !c::boot_go(&mut flash, &self.areadesc, 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...
David Brownc423ac42021-06-04 13:47:34 -0600661 if !c::boot_go(&mut flash, &self.areadesc, 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
David Brownc423ac42021-06-04 13:47:34 -0600694 if !c::boot_go(&mut flash, &self.areadesc, 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.
David Brownc423ac42021-06-04 13:47:34 -0600729 if !c::boot_go(&mut flash, &self.areadesc, 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...
David Brownc423ac42021-06-04 13:47:34 -0600771 if !c::boot_go(&mut flash, &self.areadesc, 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...
David Brownc423ac42021-06-04 13:47:34 -0600825 if !c::boot_go(&mut flash, &self.areadesc, 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...
David Brownc423ac42021-06-04 13:47:34 -0600865 if !c::boot_go(&mut flash, &self.areadesc, 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
David Brownc423ac42021-06-04 13:47:34 -0600912 let result = c::boot_go(&mut flash, &self.areadesc, None, true);
913 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");
David Brownc423ac42021-06-04 13:47:34 -0600938 if !c::boot_go(&mut flash, &self.areadesc, 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
David Brownc423ac42021-06-04 13:47:34 -0600970 let asserts = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700971 if asserts != 0 {
972 warn!("At least one assert() was called");
973 fails += 1;
974 }
975
David Brown76101572019-02-28 11:29:03 -0700976 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700977
978 info!("Resuming an interrupted swap operation");
David Brownc423ac42021-06-04 13:47:34 -0600979 let asserts = c::boot_go(&mut flash, &self.areadesc, None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700980
981 // This might throw no asserts, for large sector devices, where
982 // a single failure writing is indistinguishable from no failure,
983 // or throw a single assert for small sector devices that fail
984 // multiple times...
985 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100986 warn!("Expected single assert validating the primary slot, \
987 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700988 fails += 1;
989 }
990
991 if fails > 0 {
992 error!("Error running upgrade with status write fails");
993 }
994
995 fails > 0
996 } else {
David Brown76101572019-02-28 11:29:03 -0700997 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700998 let mut fails = 0;
999
1000 info!("Try interrupted swap with status fails");
1001
David Brown84b49f72019-03-01 10:58:22 -07001002 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001003 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -07001004
1005 // This is expected to fail while writing to bad regions...
David Brownc423ac42021-06-04 13:47:34 -06001006 let asserts = c::boot_go(&mut flash, &self.areadesc, None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001007 if asserts == 0 {
1008 warn!("No assert() detected");
1009 fails += 1;
1010 }
1011
1012 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -07001013 }
David Brown5c9e0f12019-01-09 16:34:33 -07001014 }
1015
David Brown0dfb8102021-06-03 15:29:11 -06001016 /// Test the direct XIP configuration. With this mode, flash images are never moved, and the
1017 /// bootloader merely selects which partition is the proper one to boot.
1018 pub fn run_direct_xip(&self) -> bool {
1019 if !Caps::DirectXip.present() {
1020 return false;
1021 }
1022
1023 // Clone the flash so we can tell if unchanged.
1024 let mut flash = self.flash.clone();
1025
1026 let result = c::boot_go(&mut flash, &self.areadesc, None, true);
1027
1028 // Ensure the boot was successful.
1029 let resp = if let Some(resp) = result.resp() {
1030 resp
1031 } else {
1032 panic!("Boot didn't return a valid result");
1033 };
1034
1035 // This configuration should always try booting from the first upgrade slot.
1036 if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
1037 assert_eq!(offset, resp.image_off as usize);
1038 assert_eq!(dev_id, resp.flash_dev_id);
1039 } else {
1040 panic!("Unable to find upgrade image");
1041 }
1042 false
1043 }
1044
David Brown8a4e23b2021-06-11 10:29:01 -06001045 /// Test the ram-loading.
1046 pub fn run_ram_load(&self) -> bool {
1047 if !Caps::RamLoad.present() {
1048 return false;
1049 }
1050
1051 // Clone the flash so we can tell if unchanged.
1052 let mut flash = self.flash.clone();
1053
David Brownf17d3912021-06-23 16:10:51 -06001054 // Setup ram based on the ram configuration we determined earlier for the images.
1055 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
David Brown8a4e23b2021-06-11 10:29:01 -06001056
David Brownf17d3912021-06-23 16:10:51 -06001057 // println!("Ram: {:#?}", self.ram);
David Brown8a4e23b2021-06-11 10:29:01 -06001058
David Brownf17d3912021-06-23 16:10:51 -06001059 // Verify that the images area loaded into this.
David Brown8a4e23b2021-06-11 10:29:01 -06001060 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None, true));
1061 if !result.success() {
David Brownf17d3912021-06-23 16:10:51 -06001062 error!("Failed to execute ram-load");
David Brown8a4e23b2021-06-11 10:29:01 -06001063 return true;
1064 }
1065
David Brownf17d3912021-06-23 16:10:51 -06001066 // Verify each image.
1067 for image in &self.images {
1068 let place = self.ram.lookup(&image.slots[0]);
1069 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1070 place.size as usize);
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001071 let src_sz = image.upgrades.size();
1072 if src_sz > ram_image.len() {
David Brownf17d3912021-06-23 16:10:51 -06001073 error!("Image ended up too large, nonsensical");
1074 return true;
1075 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001076 let src_image = &image.upgrades.plain[0..src_sz];
1077 let ram_image = &ram_image[0..src_sz];
David Brownf17d3912021-06-23 16:10:51 -06001078 if ram_image != src_image {
1079 error!("Image not loaded correctly");
1080 return true;
1081 }
1082
1083 }
1084
1085 return false;
David Brown8a4e23b2021-06-11 10:29:01 -06001086 }
1087
David Brown5c9e0f12019-01-09 16:34:33 -07001088 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -07001089 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001090 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -07001091 if Caps::OverwriteUpgrade.present() {
1092 return;
1093 }
1094
David Brown84b49f72019-03-01 10:58:22 -07001095 // Set this for each image.
1096 for image in &self.images {
1097 let dev_id = &image.slots[slot].dev_id;
1098 let dev = flash.get_mut(&dev_id).unwrap();
1099 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001100 let off = &image.slots[slot].base_off;
1101 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -07001102 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -07001103
David Brown84b49f72019-03-01 10:58:22 -07001104 // Mark the status area as a bad area
1105 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1106 }
David Brown5c9e0f12019-01-09 16:34:33 -07001107 }
1108
David Brown76101572019-02-28 11:29:03 -07001109 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001110 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001111 return;
1112 }
1113
David Brown84b49f72019-03-01 10:58:22 -07001114 for image in &self.images {
1115 let dev_id = &image.slots[slot].dev_id;
1116 let dev = flash.get_mut(&dev_id).unwrap();
1117 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001118
David Brown84b49f72019-03-01 10:58:22 -07001119 // Disabling write verification the only assert triggered by
1120 // boot_go should be checking for integrity of status bytes.
1121 dev.set_verify_writes(false);
1122 }
David Brown5c9e0f12019-01-09 16:34:33 -07001123 }
1124
David Browndb505822019-03-01 10:04:20 -07001125 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1126 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001127 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001128 // Clone the flash to have a new copy.
1129 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001130
Fabio Utziged4a5362019-07-30 12:43:23 -03001131 if permanent {
1132 self.mark_permanent_upgrades(&mut flash, 1);
1133 }
David Brown5c9e0f12019-01-09 16:34:33 -07001134
David Browndb505822019-03-01 10:04:20 -07001135 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001136
David Browndb505822019-03-01 10:04:20 -07001137 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001138 x if x.interrupted() => (true, stop.unwrap()),
1139 x if x.success() => (false, -counter),
1140 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001141 };
David Brown5c9e0f12019-01-09 16:34:33 -07001142
David Browndb505822019-03-01 10:04:20 -07001143 counter = 0;
1144 if first_interrupted {
1145 // fl.dump();
1146 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001147 x if x.interrupted() => panic!("Shouldn't stop again"),
1148 x if x.success() => (),
1149 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001150 }
1151 }
David Brown5c9e0f12019-01-09 16:34:33 -07001152
David Browndb505822019-03-01 10:04:20 -07001153 (flash, count - counter)
1154 }
1155
1156 fn try_revert(&self, count: usize) -> SimMultiFlash {
1157 let mut flash = self.flash.clone();
1158
1159 // fl.write_file("image0.bin").unwrap();
1160 for i in 0 .. count {
1161 info!("Running boot pass {}", i + 1);
David Brownc423ac42021-06-04 13:47:34 -06001162 assert!(c::boot_go(&mut flash, &self.areadesc, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001163 }
1164 flash
1165 }
1166
1167 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1168 let mut flash = self.flash.clone();
1169 let mut fails = 0;
1170
1171 let mut counter = stop;
David Brownc423ac42021-06-04 13:47:34 -06001172 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001173 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001174 fails += 1;
1175 }
1176
Fabio Utzig8af7f792019-07-30 12:40:01 -03001177 // In a multi-image setup, copy done might be set if any number of
1178 // images was already successfully swapped.
1179 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1180 warn!("copy_done should be unset");
1181 fails += 1;
1182 }
1183
David Brownc423ac42021-06-04 13:47:34 -06001184 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001185 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001186 fails += 1;
1187 }
1188
David Brown84b49f72019-03-01 10:58:22 -07001189 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001190 warn!("Image in the primary slot before revert is invalid at stop={}",
1191 stop);
1192 fails += 1;
1193 }
David Brown84b49f72019-03-01 10:58:22 -07001194 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001195 warn!("Image in the secondary slot before revert is invalid at stop={}",
1196 stop);
1197 fails += 1;
1198 }
David Brown84b49f72019-03-01 10:58:22 -07001199 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1200 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001201 warn!("Mismatched trailer for the primary slot before revert");
1202 fails += 1;
1203 }
David Brown84b49f72019-03-01 10:58:22 -07001204 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1205 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001206 warn!("Mismatched trailer for the secondary slot before revert");
1207 fails += 1;
1208 }
1209
1210 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001211 let mut counter = stop;
David Brownc423ac42021-06-04 13:47:34 -06001212 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001213 warn!("Should have stopped revert at interruption point");
1214 fails += 1;
1215 }
1216
David Brownc423ac42021-06-04 13:47:34 -06001217 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001218 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001219 fails += 1;
1220 }
1221
David Brown84b49f72019-03-01 10:58:22 -07001222 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001223 warn!("Image in the primary slot after revert is invalid at stop={}",
1224 stop);
1225 fails += 1;
1226 }
David Brown84b49f72019-03-01 10:58:22 -07001227 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001228 warn!("Image in the secondary slot after revert is invalid at stop={}",
1229 stop);
1230 fails += 1;
1231 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001232
David Brown84b49f72019-03-01 10:58:22 -07001233 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1234 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001235 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001236 fails += 1;
1237 }
David Brown84b49f72019-03-01 10:58:22 -07001238 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1239 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001240 warn!("Mismatched trailer for the secondary slot after revert");
1241 fails += 1;
1242 }
1243
David Brownc423ac42021-06-04 13:47:34 -06001244 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001245 warn!("Should have finished 3rd boot");
1246 fails += 1;
1247 }
1248
1249 if !self.verify_images(&flash, 0, 0) {
1250 warn!("Image in the primary slot is invalid on 1st boot after revert");
1251 fails += 1;
1252 }
1253 if !self.verify_images(&flash, 1, 1) {
1254 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1255 fails += 1;
1256 }
1257
David Browndb505822019-03-01 10:04:20 -07001258 fails > 0
1259 }
1260
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001261
David Browndb505822019-03-01 10:04:20 -07001262 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1263 let mut flash = self.flash.clone();
1264
David Brown84b49f72019-03-01 10:58:22 -07001265 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001266
1267 let mut rng = rand::thread_rng();
1268 let mut resets = vec![0i32; count];
1269 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001270 for reset in &mut resets {
David Brown9c6322f2021-08-19 13:03:39 -06001271 let reset_counter = rng.gen_range(1 ..= remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001272 let mut counter = reset_counter;
1273 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001274 x if x.interrupted() => (),
1275 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001276 }
1277 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001278 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001279 }
1280
1281 match c::boot_go(&mut flash, &self.areadesc, None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001282 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1283 x if x.success() => (),
1284 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001285 }
David Brown5c9e0f12019-01-09 16:34:33 -07001286
David Browndb505822019-03-01 10:04:20 -07001287 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001288 }
David Brown84b49f72019-03-01 10:58:22 -07001289
1290 /// Verify the image in the given flash device, the specified slot
1291 /// against the expected image.
1292 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001293 self.images.iter().all(|image| {
1294 verify_image(flash, &image.slots[slot],
1295 match against {
1296 0 => &image.primaries,
1297 1 => &image.upgrades,
1298 _ => panic!("Invalid 'against'")
1299 })
1300 })
David Brown84b49f72019-03-01 10:58:22 -07001301 }
1302
David Brownc3898d62019-08-05 14:20:02 -06001303 /// Verify the images, according to the dependency test.
1304 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1305 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1306 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1307 if !verify_image(flash, &image.slots[0],
1308 match upgrade {
1309 UpgradeInfo::Upgraded => &image.upgrades,
1310 UpgradeInfo::Held => &image.primaries,
1311 }) {
1312 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1313 return true;
1314 }
1315 }
1316
1317 false
1318 }
1319
Fabio Utzig8af7f792019-07-30 12:40:01 -03001320 /// Verify that at least one of the trailers of the images have the
1321 /// specified values.
1322 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1323 magic: Option<u8>, image_ok: Option<u8>,
1324 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001325 self.images.iter().any(|image| {
1326 verify_trailer(flash, &image.slots[slot],
1327 magic, image_ok, copy_done)
1328 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001329 }
1330
David Brown84b49f72019-03-01 10:58:22 -07001331 /// Verify that the trailers of the images have the specified
1332 /// values.
1333 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1334 magic: Option<u8>, image_ok: Option<u8>,
1335 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001336 self.images.iter().all(|image| {
1337 verify_trailer(flash, &image.slots[slot],
1338 magic, image_ok, copy_done)
1339 })
David Brown84b49f72019-03-01 10:58:22 -07001340 }
1341
1342 /// Mark each of the images for permanent upgrade.
1343 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1344 for image in &self.images {
1345 mark_permanent_upgrade(flash, &image.slots[slot]);
1346 }
1347 }
1348
1349 /// Mark each of the images for permanent upgrade.
1350 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1351 for image in &self.images {
1352 mark_upgrade(flash, &image.slots[slot]);
1353 }
1354 }
David Brown297029a2019-08-13 14:29:51 -06001355
1356 /// Dump out the flash image(s) to one or more files for debugging
1357 /// purposes. The names will be written as either "{prefix}.mcubin" or
1358 /// "{prefix}-001.mcubin" depending on how many images there are.
1359 pub fn debug_dump(&self, prefix: &str) {
1360 for (id, fdev) in &self.flash {
1361 let name = if self.flash.len() == 1 {
1362 format!("{}.mcubin", prefix)
1363 } else {
1364 format!("{}-{:>0}.mcubin", prefix, id)
1365 };
1366 fdev.write_file(&name).unwrap();
1367 }
1368 }
David Brown5c9e0f12019-01-09 16:34:33 -07001369}
1370
David Brownbf32c272021-06-16 17:11:37 -06001371impl RamData {
David Brownf17d3912021-06-23 16:10:51 -06001372 // TODO: This is not correct. The second slot of each image should be at the same address as
1373 // the primary.
David Brownbf32c272021-06-16 17:11:37 -06001374 fn new(slots: &[[SlotInfo; 2]]) -> RamData {
1375 let mut addr = RAM_LOAD_ADDR;
1376 let mut places = BTreeMap::new();
David Brownf17d3912021-06-23 16:10:51 -06001377 // println!("Setup:-------------");
David Brownbf32c272021-06-16 17:11:37 -06001378 for imgs in slots {
1379 for si in imgs {
David Brownf17d3912021-06-23 16:10:51 -06001380 // println!("Setup: si: {:?}", si);
David Brownbf32c272021-06-16 17:11:37 -06001381 let offset = addr;
1382 let size = si.len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001383 places.insert(SlotKey {
1384 dev_id: si.dev_id,
David Brownf17d3912021-06-23 16:10:51 -06001385 base_off: si.base_off,
David Brownbf32c272021-06-16 17:11:37 -06001386 }, SlotPlace { offset, size });
David Brownf17d3912021-06-23 16:10:51 -06001387 // println!(" load: offset: {}, size: {}", offset, size);
David Brownbf32c272021-06-16 17:11:37 -06001388 }
David Brownf17d3912021-06-23 16:10:51 -06001389 addr += imgs[0].len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001390 }
1391 RamData {
1392 places,
1393 total: addr,
1394 }
1395 }
David Brownf17d3912021-06-23 16:10:51 -06001396
1397 /// Lookup the ram data associated with a given flash partition. We just panic if not present,
1398 /// because all slots used should be in the map.
1399 fn lookup(&self, slot: &SlotInfo) -> &SlotPlace {
1400 self.places.get(&SlotKey{dev_id: slot.dev_id, base_off: slot.base_off})
1401 .expect("RamData should contain all slots")
1402 }
David Brownbf32c272021-06-16 17:11:37 -06001403}
1404
David Brown5c9e0f12019-01-09 16:34:33 -07001405/// Show the flash layout.
1406#[allow(dead_code)]
1407fn show_flash(flash: &dyn Flash) {
1408 println!("---- Flash configuration ----");
1409 for sector in flash.sector_iter() {
1410 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1411 sector.num, sector.base, sector.size);
1412 }
David Brown599b2db2021-03-10 05:23:26 -07001413 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001414}
1415
1416/// Install a "program" into the given image. This fakes the image header, or at least all of the
1417/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001418fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownf17d3912021-06-23 16:10:51 -06001419 ram: &RamData,
David Brownc3898d62019-08-05 14:20:02 -06001420 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001421 let offset = slot.base_off;
1422 let slot_len = slot.len;
1423 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001424
David Brown43643dd2019-01-11 15:43:28 -07001425 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001426
David Brownc3898d62019-08-05 14:20:02 -06001427 // Add the dependencies early to the tlv.
1428 for dep in deps.my_deps(offset, slot.index) {
1429 tlv.add_dependency(deps.other_id(), &dep);
1430 }
1431
David Brown5c9e0f12019-01-09 16:34:33 -07001432 const HDR_SIZE: usize = 32;
1433
David Brownf17d3912021-06-23 16:10:51 -06001434 let place = ram.lookup(&slot);
1435 let load_addr = if Caps::RamLoad.present() {
1436 place.offset
1437 } else {
1438 0
1439 };
1440
David Brown5c9e0f12019-01-09 16:34:33 -07001441 // Generate a boot header. Note that the size doesn't include the header.
1442 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001443 magic: tlv.get_magic(),
David Brownf17d3912021-06-23 16:10:51 -06001444 load_addr,
David Brown5c9e0f12019-01-09 16:34:33 -07001445 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001446 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001447 img_size: len as u32,
1448 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001449 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001450 _pad2: 0,
1451 };
1452
1453 let mut b_header = [0; HDR_SIZE];
1454 b_header[..32].clone_from_slice(header.as_raw());
1455 assert_eq!(b_header.len(), HDR_SIZE);
1456
1457 tlv.add_bytes(&b_header);
1458
1459 // The core of the image itself is just pseudorandom data.
1460 let mut b_img = vec![0; len];
1461 splat(&mut b_img, offset);
1462
David Browncb47dd72019-08-05 14:21:49 -06001463 // Add some information at the start of the payload to make it easier
1464 // to see what it is. This will fail if the image itself is too small.
1465 {
1466 let mut wr = Cursor::new(&mut b_img);
1467 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1468 offset, dev_id, slot).unwrap();
1469 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1470 }
1471
David Brown5c9e0f12019-01-09 16:34:33 -07001472 // TLV signatures work over plain image
1473 tlv.add_bytes(&b_img);
1474
1475 // Generate encrypted images
Salome Thirot6fdbf552021-05-14 16:46:14 +01001476 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1477 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001478 let mut b_encimg = vec![];
1479 if is_encrypted {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001480 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1481 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001482 tlv.generate_enc_key();
1483 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001484 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001485 b_encimg = b_img.clone();
Salome Thirot6fdbf552021-05-14 16:46:14 +01001486 if aes256 {
1487 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001488 let block = Aes256::new(&key);
1489 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001490 cipher.apply_keystream(&mut b_encimg);
1491 } else {
1492 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001493 let block = Aes128::new(&key);
1494 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001495 cipher.apply_keystream(&mut b_encimg);
1496 }
David Brown5c9e0f12019-01-09 16:34:33 -07001497 }
1498
1499 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001500 if bad_sig {
1501 tlv.corrupt_sig();
1502 }
1503 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001504
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001505 let dev = flash.get_mut(&dev_id).unwrap();
1506
David Brown5c9e0f12019-01-09 16:34:33 -07001507 let mut buf = vec![];
1508 buf.append(&mut b_header.to_vec());
1509 buf.append(&mut b_img);
1510 buf.append(&mut b_tlv.clone());
1511
David Brown95de4502019-11-15 12:01:34 -07001512 // Pad the buffer to a multiple of the flash alignment.
1513 let align = dev.align();
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001514 let image_sz = buf.len();
David Brown95de4502019-11-15 12:01:34 -07001515 while buf.len() % align != 0 {
1516 buf.push(dev.erased_val());
1517 }
1518
David Brown5c9e0f12019-01-09 16:34:33 -07001519 let mut encbuf = vec![];
1520 if is_encrypted {
1521 encbuf.append(&mut b_header.to_vec());
1522 encbuf.append(&mut b_encimg);
1523 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001524
1525 while encbuf.len() % align != 0 {
1526 encbuf.push(dev.erased_val());
1527 }
David Brown5c9e0f12019-01-09 16:34:33 -07001528 }
1529
David Vincze2d736ad2019-02-18 11:50:22 +01001530 // Since images are always non-encrypted in the primary slot, we first write
1531 // an encrypted image, re-read to use for verification, erase + flash
1532 // un-encrypted. In the secondary slot the image is written un-encrypted,
1533 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001534
David Brown3b090212019-07-30 15:59:28 -06001535 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001536 let enc_copy: Option<Vec<u8>>;
1537
1538 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001539 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001540
1541 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001542 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001543
1544 enc_copy = Some(enc);
1545
David Brown76101572019-02-28 11:29:03 -07001546 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001547 } else {
1548 enc_copy = None;
1549 }
1550
David Brown76101572019-02-28 11:29:03 -07001551 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001552
1553 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001554 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001555
David Brownca234692019-02-28 11:22:19 -07001556 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001557 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001558 plain: copy,
1559 cipher: enc_copy,
1560 }
David Brown5c9e0f12019-01-09 16:34:33 -07001561 } else {
1562
David Brown76101572019-02-28 11:29:03 -07001563 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001564
1565 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001566 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001567
1568 let enc_copy: Option<Vec<u8>>;
1569
1570 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001571 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001572
David Brown76101572019-02-28 11:29:03 -07001573 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001574
1575 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001576 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001577
1578 enc_copy = Some(enc);
1579 } else {
1580 enc_copy = None;
1581 }
1582
David Brownca234692019-02-28 11:22:19 -07001583 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001584 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001585 plain: copy,
1586 cipher: enc_copy,
1587 }
David Brown5c9e0f12019-01-09 16:34:33 -07001588 }
David Brown5c9e0f12019-01-09 16:34:33 -07001589}
1590
David Brown873be312019-09-03 12:22:32 -06001591/// Install no image. This is used when no upgrade happens.
1592fn install_no_image() -> ImageData {
1593 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001594 size: 0,
David Brown873be312019-09-03 12:22:32 -06001595 plain: vec![],
1596 cipher: None,
1597 }
1598}
1599
David Brown5c9e0f12019-01-09 16:34:33 -07001600fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001601 if Caps::EcdsaP224.present() {
1602 panic!("Ecdsa P224 not supported in Simulator");
1603 }
Salome Thirot6fdbf552021-05-14 16:46:14 +01001604 let mut aes_key_size = 128;
1605 if Caps::Aes256.present() {
1606 aes_key_size = 256;
1607 }
David Brown5c9e0f12019-01-09 16:34:33 -07001608
David Brownb8882112019-01-11 14:04:11 -07001609 if Caps::EncKw.present() {
1610 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001611 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001612 } else if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001613 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001614 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001615 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001616 }
1617 } else if Caps::EncRsa.present() {
1618 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001619 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001620 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001621 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001622 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001623 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001624 if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001625 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001626 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001627 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001628 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001629 } else if Caps::EncX25519.present() {
1630 if Caps::Ed25519.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001631 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001632 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001633 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001634 }
David Brownb8882112019-01-11 14:04:11 -07001635 } else {
1636 // The non-encrypted configuration.
1637 if Caps::RSA2048.present() {
1638 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001639 } else if Caps::RSA3072.present() {
1640 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001641 } else if Caps::EcdsaP256.present() {
1642 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001643 } else if Caps::Ed25519.present() {
1644 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001645 } else {
1646 TlvGen::new_hash_only()
1647 }
1648 }
David Brown5c9e0f12019-01-09 16:34:33 -07001649}
1650
David Brownca234692019-02-28 11:22:19 -07001651impl ImageData {
1652 /// Find the image contents for the given slot. This assumes that slot 0
1653 /// is unencrypted, and slot 1 is encrypted.
1654 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001655 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001656 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001657 match (encrypted, slot) {
1658 (false, _) => &self.plain,
1659 (true, 0) => &self.plain,
1660 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1661 _ => panic!("Invalid slot requested"),
1662 }
David Brown5c9e0f12019-01-09 16:34:33 -07001663 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001664
1665 fn size(&self) -> usize {
1666 self.size
1667 }
David Brown5c9e0f12019-01-09 16:34:33 -07001668}
1669
David Brown5c9e0f12019-01-09 16:34:33 -07001670/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001671fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1672 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001673 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001674 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001675
1676 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001677 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001678 let dev = flash.get(&dev_id).unwrap();
1679 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001680
1681 if buf != &copy[..] {
1682 for i in 0 .. buf.len() {
1683 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001684 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1685 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001686 break;
1687 }
1688 }
1689 false
1690 } else {
1691 true
1692 }
1693}
1694
David Brown3b090212019-07-30 15:59:28 -06001695fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001696 magic: Option<u8>, image_ok: Option<u8>,
1697 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001698 if Caps::OverwriteUpgrade.present() {
1699 return true;
1700 }
David Brown5c9e0f12019-01-09 16:34:33 -07001701
David Brown3b090212019-07-30 15:59:28 -06001702 let offset = slot.trailer_off + c::boot_max_align();
1703 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001704 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001705 let mut failed = false;
1706
David Brown76101572019-02-28 11:29:03 -07001707 let dev = flash.get(&dev_id).unwrap();
1708 let erased_val = dev.erased_val();
1709 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001710
1711 failed |= match magic {
1712 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001713 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001714 warn!("\"magic\" mismatch at {:#x}", offset);
1715 true
1716 } else if v == 3 {
1717 let expected = [erased_val; 16];
David Brownd36f6b12021-03-10 05:23:56 -07001718 if copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001719 warn!("\"magic\" mismatch at {:#x}", offset);
1720 true
1721 } else {
1722 false
1723 }
1724 } else {
1725 false
1726 }
1727 },
1728 None => false,
1729 };
1730
1731 failed |= match image_ok {
1732 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001733 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001734 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1735 true
1736 } else {
1737 false
1738 }
1739 },
1740 None => false,
1741 };
1742
1743 failed |= match copy_done {
1744 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001745 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001746 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1747 true
1748 } else {
1749 false
1750 }
1751 },
1752 None => false,
1753 };
1754
1755 !failed
1756}
1757
David Brown297029a2019-08-13 14:29:51 -06001758/// Install a partition table. This is a simplified partition table that
1759/// we write at the beginning of flash so make it easier for external tools
1760/// to analyze these images.
1761fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1762 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1763 for &id in &ids {
1764 // If there are any partitions in this device that start at 0, and
1765 // aren't marked as the BootLoader partition, avoid adding the
1766 // partition table. This makes it harder to view the image, but
1767 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07001768 let skip_ptable = areadesc
1769 .iter_areas()
1770 .any(|area| {
1771 area.device_id == id &&
1772 area.off == 0 &&
1773 area.flash_id != FlashId::BootLoader
1774 });
1775 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06001776 if log_enabled!(Info) {
1777 let special: Vec<FlashId> = areadesc.iter_areas()
1778 .filter(|area| area.device_id == id && area.off == 0)
1779 .map(|area| area.flash_id)
1780 .collect();
1781 info!("Skipping partition table: {:?}", special);
1782 }
1783 break;
1784 }
1785
1786 let mut buf: Vec<u8> = vec![];
1787 write!(&mut buf, "mcuboot\0").unwrap();
1788
1789 // Iterate through all of the partitions in that device, and encode
1790 // into the table.
1791 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1792 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1793
1794 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1795 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1796 buf.write_u32::<LittleEndian>(area.off).unwrap();
1797 buf.write_u32::<LittleEndian>(area.size).unwrap();
1798 buf.write_u32::<LittleEndian>(0).unwrap();
1799 }
1800
1801 let dev = flash.get_mut(&id).unwrap();
1802
1803 // Pad to alignment.
1804 while buf.len() % dev.align() != 0 {
1805 buf.push(0);
1806 }
1807
1808 dev.write(0, &buf).unwrap();
1809 }
1810}
1811
David Brown5c9e0f12019-01-09 16:34:33 -07001812/// The image header
1813#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001814#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001815pub struct ImageHeader {
1816 magic: u32,
1817 load_addr: u32,
1818 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001819 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001820 img_size: u32,
1821 flags: u32,
1822 ver: ImageVersion,
1823 _pad2: u32,
1824}
1825
1826impl AsRaw for ImageHeader {}
1827
1828#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001829#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001830pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001831 pub major: u8,
1832 pub minor: u8,
1833 pub revision: u16,
1834 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001835}
1836
David Brownc3898d62019-08-05 14:20:02 -06001837#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001838pub struct SlotInfo {
1839 pub base_off: usize,
1840 pub trailer_off: usize,
1841 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001842 // Which slot within this device.
1843 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001844 pub dev_id: u8,
1845}
1846
David Brown347dc572019-11-15 11:37:25 -07001847const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1848 0x60, 0xd2, 0xef, 0x7f,
1849 0x35, 0x52, 0x50, 0x0f,
1850 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001851
1852// Replicates defines found in bootutil.h
1853const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1854const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1855
1856const BOOT_FLAG_SET: Option<u8> = Some(1);
1857const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1858
1859/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001860pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1861 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001862 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001863 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001864 if offset % align != 0 || MAGIC.len() % align != 0 {
1865 // The write size is larger than the magic value. Fill a buffer
1866 // with the erased value, put the MAGIC in it, and write it in its
1867 // entirety.
1868 let mut buf = vec![dev.erased_val(); align];
1869 buf[(offset % align)..].copy_from_slice(MAGIC);
1870 dev.write(offset - (offset % align), &buf).unwrap();
1871 } else {
1872 dev.write(offset, MAGIC).unwrap();
1873 }
David Brown5c9e0f12019-01-09 16:34:33 -07001874}
1875
1876/// Writes the image_ok flag which, guess what, tells the bootloader
1877/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001878fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001879 // Overwrite mode always is permanent, and only the magic is used in
1880 // the trailer. To avoid problems with large write sizes, don't try to
1881 // set anything in this case.
1882 if Caps::OverwriteUpgrade.present() {
1883 return;
1884 }
1885
David Brown76101572019-02-28 11:29:03 -07001886 let dev = flash.get_mut(&slot.dev_id).unwrap();
1887 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001888 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001889 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001890 let align = dev.align();
1891 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001892}
1893
1894// Drop some pseudo-random gibberish onto the data.
1895fn splat(data: &mut [u8], seed: usize) {
David Brown9c6322f2021-08-19 13:03:39 -06001896 let mut seed_block = [0u8; 32];
David Browncd842842020-07-09 15:46:53 -06001897 let mut buf = Cursor::new(&mut seed_block[..]);
1898 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
1899 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
1900 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
1901 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
1902 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07001903 rng.fill_bytes(data);
1904}
1905
1906/// Return a read-only view into the raw bytes of this object
1907trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07001908 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07001909 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1910 mem::size_of::<Self>()) }
1911 }
1912}
1913
1914pub fn show_sizes() {
1915 // This isn't panic safe.
1916 for min in &[1, 2, 4, 8] {
1917 let msize = c::boot_trailer_sz(*min);
1918 println!("{:2}: {} (0x{:x})", min, msize, msize);
1919 }
1920}
David Brown95de4502019-11-15 12:01:34 -07001921
1922#[cfg(not(feature = "large-write"))]
1923fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001924 &[1, 2, 4, 8]
1925}
1926
1927#[cfg(feature = "large-write")]
1928fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001929 &[1, 2, 4, 8, 128, 512]
1930}