blob: 2897bb2c5fe3d3c405472b1426bf06ef27d247bf [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 Browna62c3eb2021-10-25 16:32:40 -0600222 let primaries = install_image(&mut flash, &slots[0],
223 ImageSize::Given(42784), &ram, &*dep, false);
David Brown873be312019-09-03 12:22:32 -0600224 let upgrades = match deps.depends[image_num] {
225 DepType::NoUpgrade => install_no_image(),
David Browna62c3eb2021-10-25 16:32:40 -0600226 _ => install_image(&mut flash, &slots[1],
227 ImageSize::Given(46928), &ram, &*dep, false)
David Brown873be312019-09-03 12:22:32 -0600228 };
David Brown84b49f72019-03-01 10:58:22 -0700229 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700230 slots,
231 primaries,
232 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700233 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600234 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700235 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700236 flash,
David Browne5133242019-02-28 11:05:19 -0700237 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700238 images,
David Browne5133242019-02-28 11:05:19 -0700239 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600240 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700241 }
242 }
243
David Brownc3898d62019-08-05 14:20:02 -0600244 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
245 let mut images = self.make_no_upgrade_image(deps);
David Brown84b49f72019-03-01 10:58:22 -0700246 for image in &images.images {
247 mark_upgrade(&mut images.flash, &image.slots[1]);
248 }
David Browne5133242019-02-28 11:05:19 -0700249
David Brown6db44d72021-05-26 16:22:58 -0600250 // The count is meaningless if no flash operations are performed.
251 if !Caps::modifies_flash() {
252 return images;
253 }
254
David Browne5133242019-02-28 11:05:19 -0700255 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300256 let total_count = match images.run_basic_upgrade(permanent) {
David Brown8973f552021-03-10 05:21:11 -0700257 Some(v) => v,
258 None =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600259 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
260 0
261 } else {
262 panic!("Unable to perform basic upgrade");
263 }
David Browne5133242019-02-28 11:05:19 -0700264 };
265
266 images.total_count = Some(total_count);
267 images
268 }
269
270 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700271 let mut bad_flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600272 let ram = self.ram.clone(); // TODO: Avoid this clone.
David Brownc3898d62019-08-05 14:20:02 -0600273 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
David Brown2ee5f7f2020-01-13 14:04:01 -0700274 let dep = BoringDep::new(image_num, &NO_DEPS);
David Browna62c3eb2021-10-25 16:32:40 -0600275 let primaries = install_image(&mut bad_flash, &slots[0],
276 ImageSize::Given(32784), &ram, &dep, false);
277 let upgrades = install_image(&mut bad_flash, &slots[1],
278 ImageSize::Given(41928), &ram, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700279 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700280 slots,
281 primaries,
282 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700283 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700284 Images {
David Brown76101572019-02-28 11:29:03 -0700285 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700286 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700287 images,
David Browne5133242019-02-28 11:05:19 -0700288 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600289 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700290 }
291 }
292
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300293 pub fn make_erased_secondary_image(self) -> Images {
294 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600295 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300296 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
297 let dep = BoringDep::new(image_num, &NO_DEPS);
David Browna62c3eb2021-10-25 16:32:40 -0600298 let primaries = install_image(&mut flash, &slots[0],
299 ImageSize::Given(32784), &ram, &dep, false);
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300300 let upgrades = install_no_image();
301 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700302 slots,
303 primaries,
304 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300305 }}).collect();
306 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700307 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300308 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700309 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300310 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600311 ram: self.ram,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300312 }
313 }
314
Fabio Utzigd0157342020-10-02 15:22:11 -0300315 pub fn make_bootstrap_image(self) -> Images {
316 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600317 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzigd0157342020-10-02 15:22:11 -0300318 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
319 let dep = BoringDep::new(image_num, &NO_DEPS);
320 let primaries = install_no_image();
David Browna62c3eb2021-10-25 16:32:40 -0600321 let upgrades = install_image(&mut flash, &slots[1],
322 ImageSize::Given(32784), &ram, &dep, false);
Fabio Utzigd0157342020-10-02 15:22:11 -0300323 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700324 slots,
325 primaries,
326 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300327 }}).collect();
328 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700329 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300330 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700331 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300332 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600333 ram: self.ram,
Fabio Utzigd0157342020-10-02 15:22:11 -0300334 }
335 }
336
David Browne5133242019-02-28 11:05:19 -0700337 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300338 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700339 match device {
340 DeviceName::Stm32f4 => {
341 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700342 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
343 64 * 1024,
344 128 * 1024, 128 * 1024, 128 * 1024],
345 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700346 let dev_id = 0;
347 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700348 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700349 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
350 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
351 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
352
David Brown76101572019-02-28 11:29:03 -0700353 let mut flash = SimMultiFlash::new();
354 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300355 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700356 }
357 DeviceName::K64f => {
358 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700359 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700360
361 let dev_id = 0;
362 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700363 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700364 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
365 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
366 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
367
David Brown76101572019-02-28 11:29:03 -0700368 let mut flash = SimMultiFlash::new();
369 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300370 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700371 }
372 DeviceName::K64fBig => {
373 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
374 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700375 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700376
377 let dev_id = 0;
378 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700379 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700380 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
381 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
382 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
383
David Brown76101572019-02-28 11:29:03 -0700384 let mut flash = SimMultiFlash::new();
385 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300386 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700387 }
388 DeviceName::Nrf52840 => {
389 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
390 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700391 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700392
393 let dev_id = 0;
394 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700395 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700396 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
397 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
398 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
399
David Brown76101572019-02-28 11:29:03 -0700400 let mut flash = SimMultiFlash::new();
401 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300402 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700403 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300404 DeviceName::Nrf52840UnequalSlots => {
405 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
406
407 let dev_id = 0;
408 let mut areadesc = AreaDesc::new();
409 areadesc.add_flash_sectors(dev_id, &dev);
410 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
411 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
412
413 let mut flash = SimMultiFlash::new();
414 flash.insert(dev_id, dev);
415 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
416 }
David Browne5133242019-02-28 11:05:19 -0700417 DeviceName::Nrf52840SpiFlash => {
418 // Simulate nrf52840 with external SPI flash. The external SPI flash
419 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700420 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
421 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700422
423 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700424 areadesc.add_flash_sectors(0, &dev0);
425 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700426
427 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
428 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
429 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
430
David Brown76101572019-02-28 11:29:03 -0700431 let mut flash = SimMultiFlash::new();
432 flash.insert(0, dev0);
433 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300434 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700435 }
David Brown2bff6472019-03-05 13:58:35 -0700436 DeviceName::K64fMulti => {
437 // NXP style flash, but larger, to support multiple images.
438 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
439
440 let dev_id = 0;
441 let mut areadesc = AreaDesc::new();
442 areadesc.add_flash_sectors(dev_id, &dev);
443 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
444 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
445 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
446 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
447 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
448
449 let mut flash = SimMultiFlash::new();
450 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300451 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700452 }
David Browne5133242019-02-28 11:05:19 -0700453 }
454 }
David Brownc3898d62019-08-05 14:20:02 -0600455
456 pub fn num_images(&self) -> usize {
457 self.slots.len()
458 }
David Browne5133242019-02-28 11:05:19 -0700459}
460
David Brown5c9e0f12019-01-09 16:34:33 -0700461impl Images {
462 /// A simple upgrade without forced failures.
463 ///
464 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700465 /// inject failures at chosen steps. Returns None if it was unable to
466 /// count the operations in a basic upgrade.
467 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300468 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700469 info!("Total flash operation count={}", total_count);
470
David Brown84b49f72019-03-01 10:58:22 -0700471 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700472 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700473 None
David Brown5c9e0f12019-01-09 16:34:33 -0700474 } else {
David Brown8973f552021-03-10 05:21:11 -0700475 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700476 }
477 }
478
Fabio Utzigd0157342020-10-02 15:22:11 -0300479 pub fn run_bootstrap(&self) -> bool {
480 let mut flash = self.flash.clone();
481 let mut fails = 0;
482
483 if Caps::Bootstrap.present() {
484 info!("Try bootstraping image in the primary");
485
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100486 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigd0157342020-10-02 15:22:11 -0300487 warn!("Failed first boot");
488 fails += 1;
489 }
490
491 if !self.verify_images(&flash, 0, 1) {
492 warn!("Image in the first slot was not bootstrapped");
493 fails += 1;
494 }
495
496 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
497 BOOT_FLAG_SET, BOOT_FLAG_SET) {
498 warn!("Mismatched trailer for the primary slot");
499 fails += 1;
500 }
501 }
502
503 if fails > 0 {
504 error!("Expected trailer on secondary slot to be erased");
505 }
506
507 fails > 0
508 }
509
510
David Brownc3898d62019-08-05 14:20:02 -0600511 /// Test a simple upgrade, with dependencies given, and verify that the
512 /// image does as is described in the test.
513 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600514 if !Caps::modifies_flash() {
515 return false;
516 }
517
David Brownc3898d62019-08-05 14:20:02 -0600518 let (flash, _) = self.try_upgrade(None, true);
519
520 self.verify_dep_images(&flash, deps)
521 }
522
Fabio Utzigf5480c72019-11-28 10:41:57 -0300523 fn is_swap_upgrade(&self) -> bool {
524 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
525 }
526
David Brown5c9e0f12019-01-09 16:34:33 -0700527 pub fn run_basic_revert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600528 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700529 return false;
530 }
David Brown5c9e0f12019-01-09 16:34:33 -0700531
David Brown5c9e0f12019-01-09 16:34:33 -0700532 let mut fails = 0;
533
534 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300535 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700536 for count in 2 .. 5 {
537 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700538 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700539 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700540 error!("Revert failure on count {}", count);
541 fails += 1;
542 }
543 }
544 }
545
546 fails > 0
547 }
548
549 pub fn run_perm_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600550 if !Caps::modifies_flash() {
551 return false;
552 }
553
David Brown5c9e0f12019-01-09 16:34:33 -0700554 let mut fails = 0;
555 let total_flash_ops = self.total_count.unwrap();
556
557 // Let's try an image halfway through.
558 for i in 1 .. total_flash_ops {
559 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300560 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700561 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700562 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700563 warn!("FAIL at step {} of {}", i, total_flash_ops);
564 fails += 1;
565 }
566
David Brown84b49f72019-03-01 10:58:22 -0700567 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
568 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100569 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700570 fails += 1;
571 }
572
David Brown84b49f72019-03-01 10:58:22 -0700573 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
574 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100575 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700576 fails += 1;
577 }
578
David Brownaec56b22021-03-10 05:22:07 -0700579 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
580 warn!("Secondary slot FAIL at step {} of {}",
581 i, total_flash_ops);
582 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700583 }
584 }
585
586 if fails > 0 {
587 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
588 fails as f32 * 100.0 / total_flash_ops as f32);
589 }
590
591 fails > 0
592 }
593
David Brown5c9e0f12019-01-09 16:34:33 -0700594 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600595 if !Caps::modifies_flash() {
596 return false;
597 }
598
David Brown5c9e0f12019-01-09 16:34:33 -0700599 let mut fails = 0;
600 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700601 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700602 info!("Random interruptions at reset points={:?}", total_counts);
603
David Brown84b49f72019-03-01 10:58:22 -0700604 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300605 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700606 // TODO: This result is ignored.
607 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700608 } else {
609 true
610 };
David Vincze2d736ad2019-02-18 11:50:22 +0100611 if !primary_slot_ok || !secondary_slot_ok {
612 error!("Image mismatch after random interrupts: primary slot={} \
613 secondary slot={}",
614 if primary_slot_ok { "ok" } else { "fail" },
615 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700616 fails += 1;
617 }
David Brown84b49f72019-03-01 10:58:22 -0700618 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
619 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100620 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700621 fails += 1;
622 }
David Brown84b49f72019-03-01 10:58:22 -0700623 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
624 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100625 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700626 fails += 1;
627 }
628
629 if fails > 0 {
630 error!("Error testing perm upgrade with {} fails", total_fails);
631 }
632
633 fails > 0
634 }
635
David Brown5c9e0f12019-01-09 16:34:33 -0700636 pub fn run_revert_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600637 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700638 return false;
639 }
David Brown5c9e0f12019-01-09 16:34:33 -0700640
David Brown5c9e0f12019-01-09 16:34:33 -0700641 let mut fails = 0;
642
Fabio Utzigf5480c72019-11-28 10:41:57 -0300643 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300644 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700645 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700646 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700647 error!("Revert failed at interruption {}", i);
648 fails += 1;
649 }
650 }
651 }
652
653 fails > 0
654 }
655
David Brown5c9e0f12019-01-09 16:34:33 -0700656 pub fn run_norevert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600657 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700658 return false;
659 }
David Brown5c9e0f12019-01-09 16:34:33 -0700660
David Brown76101572019-02-28 11:29:03 -0700661 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700662 let mut fails = 0;
663
664 info!("Try norevert");
665
666 // First do a normal upgrade...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100667 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700668 warn!("Failed first boot");
669 fails += 1;
670 }
671
672 //FIXME: copy_done is written by boot_go, is it ok if no copy
673 // was ever done?
674
David Brown84b49f72019-03-01 10:58:22 -0700675 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100676 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700677 fails += 1;
678 }
David Brown84b49f72019-03-01 10:58:22 -0700679 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
680 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100681 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700682 fails += 1;
683 }
David Brown84b49f72019-03-01 10:58:22 -0700684 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
685 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100686 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700687 fails += 1;
688 }
689
David Vincze2d736ad2019-02-18 11:50:22 +0100690 // Marks image in the primary slot as permanent,
691 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700692 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700693
David Brown84b49f72019-03-01 10:58:22 -0700694 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
695 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100696 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700697 fails += 1;
698 }
699
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100700 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700701 warn!("Failed second boot");
702 fails += 1;
703 }
704
David Brown84b49f72019-03-01 10:58:22 -0700705 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
706 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100707 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700708 fails += 1;
709 }
David Brown84b49f72019-03-01 10:58:22 -0700710 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700711 warn!("Failed image verification");
712 fails += 1;
713 }
714
715 if fails > 0 {
716 error!("Error running upgrade without revert");
717 }
718
719 fails > 0
720 }
721
David Brown2ee5f7f2020-01-13 14:04:01 -0700722 // Test that an upgrade is rejected. Assumes that the image was build
723 // such that the upgrade is instead a downgrade.
724 pub fn run_nodowngrade(&self) -> bool {
725 if !Caps::DowngradePrevention.present() {
726 return false;
727 }
728
729 let mut flash = self.flash.clone();
730 let mut fails = 0;
731
732 info!("Try no downgrade");
733
734 // First, do a normal upgrade.
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100735 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700736 warn!("Failed first boot");
737 fails += 1;
738 }
739
740 if !self.verify_images(&flash, 0, 0) {
741 warn!("Failed verification after downgrade rejection");
742 fails += 1;
743 }
744
745 if fails > 0 {
746 error!("Error testing downgrade rejection");
747 }
748
749 fails > 0
750 }
751
David Vincze2d736ad2019-02-18 11:50:22 +0100752 // Tests a new image written to the primary slot that already has magic and
753 // image_ok set while there is no image on the secondary slot, so no revert
754 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700755 pub fn run_norevert_newimage(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600756 if !Caps::modifies_flash() {
757 info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
758 return false;
759 }
760
David Brown76101572019-02-28 11:29:03 -0700761 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700762 let mut fails = 0;
763
764 info!("Try non-revert on imgtool generated image");
765
David Brown84b49f72019-03-01 10:58:22 -0700766 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700767
David Vincze2d736ad2019-02-18 11:50:22 +0100768 // This simulates writing an image created by imgtool to
769 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700770 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
771 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100772 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700773 fails += 1;
774 }
775
776 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100777 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700778 warn!("Failed first boot");
779 fails += 1;
780 }
781
782 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700783 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700784 warn!("Failed image verification");
785 fails += 1;
786 }
David Brown84b49f72019-03-01 10:58:22 -0700787 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
788 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100789 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700790 fails += 1;
791 }
David Brown84b49f72019-03-01 10:58:22 -0700792 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
793 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100794 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700795 fails += 1;
796 }
797
798 if fails > 0 {
799 error!("Expected a non revert with new image");
800 }
801
802 fails > 0
803 }
804
David Vincze2d736ad2019-02-18 11:50:22 +0100805 // Tests a new image written to the primary slot that already has magic and
806 // image_ok set while there is no image on the secondary slot, so no revert
807 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700808 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700809 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700810 let mut fails = 0;
811
812 info!("Try upgrade image with bad signature");
813
David Brown6db44d72021-05-26 16:22:58 -0600814 // Only perform this test if an upgrade is expected to happen.
815 if !Caps::modifies_flash() {
816 info!("Skipping upgrade image with bad signature");
817 return false;
818 }
819
David Brown84b49f72019-03-01 10:58:22 -0700820 self.mark_upgrades(&mut flash, 0);
821 self.mark_permanent_upgrades(&mut flash, 0);
822 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700823
David Brown84b49f72019-03-01 10:58:22 -0700824 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
825 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100826 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700827 fails += 1;
828 }
829
830 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100831 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700832 warn!("Failed first boot");
833 fails += 1;
834 }
835
836 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700837 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700838 warn!("Failed image verification");
839 fails += 1;
840 }
David Brown84b49f72019-03-01 10:58:22 -0700841 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
842 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100843 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700844 fails += 1;
845 }
846
847 if fails > 0 {
848 error!("Expected an upgrade failure when image has bad signature");
849 }
850
851 fails > 0
852 }
853
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300854 // Should detect there is a leftover trailer in an otherwise erased
855 // secondary slot and erase its trailer.
856 pub fn run_secondary_leftover_trailer(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600857 if !Caps::modifies_flash() {
858 return false;
859 }
860
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300861 let mut flash = self.flash.clone();
862 let mut fails = 0;
863
864 info!("Try with a leftover trailer in the secondary; must be erased");
865
866 // Add a trailer on the secondary slot
867 self.mark_permanent_upgrades(&mut flash, 1);
868 self.mark_upgrades(&mut flash, 1);
869
870 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100871 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300872 warn!("Failed first boot");
873 fails += 1;
874 }
875
876 // State should not have changed
877 if !self.verify_images(&flash, 0, 0) {
878 warn!("Failed image verification");
879 fails += 1;
880 }
881 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
882 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
883 warn!("Mismatched trailer for the secondary slot");
884 fails += 1;
885 }
886
887 if fails > 0 {
888 error!("Expected trailer on secondary slot to be erased");
889 }
890
891 fails > 0
892 }
893
David Brown5c9e0f12019-01-09 16:34:33 -0700894 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300895 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700896 }
897
David Brown5c9e0f12019-01-09 16:34:33 -0700898 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300899 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700900 }
901
902 /// This test runs a simple upgrade with no fails in the images, but
903 /// allowing for fails in the status area. This should run to the end
904 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700905 pub fn run_with_status_fails_complete(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600906 if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700907 return false;
908 }
909
David Brown76101572019-02-28 11:29:03 -0700910 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700911 let mut fails = 0;
912
913 info!("Try swap with status fails");
914
David Brown84b49f72019-03-01 10:58:22 -0700915 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700916 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700917
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100918 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brownc423ac42021-06-04 13:47:34 -0600919 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700920 warn!("Failed!");
921 fails += 1;
922 }
923
924 // Failed writes to the marked "bad" region don't assert anymore.
925 // Any detected assert() is happening in another part of the code.
David Brownc423ac42021-06-04 13:47:34 -0600926 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -0700927 warn!("At least one assert() was called");
928 fails += 1;
929 }
930
David Brown84b49f72019-03-01 10:58:22 -0700931 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
932 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100933 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700934 fails += 1;
935 }
936
David Brown84b49f72019-03-01 10:58:22 -0700937 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700938 warn!("Failed image verification");
939 fails += 1;
940 }
941
David Vincze2d736ad2019-02-18 11:50:22 +0100942 info!("validate primary slot enabled; \
943 re-run of boot_go should just work");
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100944 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700945 warn!("Failed!");
946 fails += 1;
947 }
948
949 if fails > 0 {
950 error!("Error running upgrade with status write fails");
951 }
952
953 fails > 0
954 }
955
956 /// This test runs a simple upgrade with no fails in the images, but
957 /// allowing for fails in the status area. This should run to the end
958 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700959 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600960 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700961 false
David Vincze2d736ad2019-02-18 11:50:22 +0100962 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700963
David Brown76101572019-02-28 11:29:03 -0700964 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700965 let mut fails = 0;
966 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700967
David Brown85904a82019-01-11 13:45:12 -0700968 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700969
David Brown85904a82019-01-11 13:45:12 -0700970 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700971
David Brown84b49f72019-03-01 10:58:22 -0700972 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700973 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700974
975 // Should not fail, writing to bad regions does not assert
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100976 let asserts = c::boot_go(&mut flash, &self.areadesc,
977 Some(&mut count), None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700978 if asserts != 0 {
979 warn!("At least one assert() was called");
980 fails += 1;
981 }
982
David Brown76101572019-02-28 11:29:03 -0700983 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700984
985 info!("Resuming an interrupted swap operation");
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100986 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
987 true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700988
989 // This might throw no asserts, for large sector devices, where
990 // a single failure writing is indistinguishable from no failure,
991 // or throw a single assert for small sector devices that fail
992 // multiple times...
993 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100994 warn!("Expected single assert validating the primary slot, \
995 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700996 fails += 1;
997 }
998
999 if fails > 0 {
1000 error!("Error running upgrade with status write fails");
1001 }
1002
1003 fails > 0
1004 } else {
David Brown76101572019-02-28 11:29:03 -07001005 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001006 let mut fails = 0;
1007
1008 info!("Try interrupted swap with status fails");
1009
David Brown84b49f72019-03-01 10:58:22 -07001010 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001011 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -07001012
1013 // This is expected to fail while writing to bad regions...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001014 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1015 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001016 if asserts == 0 {
1017 warn!("No assert() detected");
1018 fails += 1;
1019 }
1020
1021 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -07001022 }
David Brown5c9e0f12019-01-09 16:34:33 -07001023 }
1024
David Brown0dfb8102021-06-03 15:29:11 -06001025 /// Test the direct XIP configuration. With this mode, flash images are never moved, and the
1026 /// bootloader merely selects which partition is the proper one to boot.
1027 pub fn run_direct_xip(&self) -> bool {
1028 if !Caps::DirectXip.present() {
1029 return false;
1030 }
1031
1032 // Clone the flash so we can tell if unchanged.
1033 let mut flash = self.flash.clone();
1034
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001035 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brown0dfb8102021-06-03 15:29:11 -06001036
1037 // Ensure the boot was successful.
1038 let resp = if let Some(resp) = result.resp() {
1039 resp
1040 } else {
1041 panic!("Boot didn't return a valid result");
1042 };
1043
1044 // This configuration should always try booting from the first upgrade slot.
1045 if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
1046 assert_eq!(offset, resp.image_off as usize);
1047 assert_eq!(dev_id, resp.flash_dev_id);
1048 } else {
1049 panic!("Unable to find upgrade image");
1050 }
1051 false
1052 }
1053
David Brown8a4e23b2021-06-11 10:29:01 -06001054 /// Test the ram-loading.
1055 pub fn run_ram_load(&self) -> bool {
1056 if !Caps::RamLoad.present() {
1057 return false;
1058 }
1059
1060 // Clone the flash so we can tell if unchanged.
1061 let mut flash = self.flash.clone();
1062
David Brownf17d3912021-06-23 16:10:51 -06001063 // Setup ram based on the ram configuration we determined earlier for the images.
1064 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
David Brown8a4e23b2021-06-11 10:29:01 -06001065
David Brownf17d3912021-06-23 16:10:51 -06001066 // println!("Ram: {:#?}", self.ram);
David Brown8a4e23b2021-06-11 10:29:01 -06001067
David Brownf17d3912021-06-23 16:10:51 -06001068 // Verify that the images area loaded into this.
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001069 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None,
1070 None, true));
David Brown8a4e23b2021-06-11 10:29:01 -06001071 if !result.success() {
David Brownf17d3912021-06-23 16:10:51 -06001072 error!("Failed to execute ram-load");
David Brown8a4e23b2021-06-11 10:29:01 -06001073 return true;
1074 }
1075
David Brownf17d3912021-06-23 16:10:51 -06001076 // Verify each image.
1077 for image in &self.images {
1078 let place = self.ram.lookup(&image.slots[0]);
1079 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1080 place.size as usize);
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001081 let src_sz = image.upgrades.size();
1082 if src_sz > ram_image.len() {
David Brownf17d3912021-06-23 16:10:51 -06001083 error!("Image ended up too large, nonsensical");
1084 return true;
1085 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001086 let src_image = &image.upgrades.plain[0..src_sz];
1087 let ram_image = &ram_image[0..src_sz];
David Brownf17d3912021-06-23 16:10:51 -06001088 if ram_image != src_image {
1089 error!("Image not loaded correctly");
1090 return true;
1091 }
1092
1093 }
1094
1095 return false;
David Brown8a4e23b2021-06-11 10:29:01 -06001096 }
1097
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001098 /// Test the split ram-loading.
1099 pub fn run_split_ram_load(&self) -> bool {
1100 if !Caps::RamLoad.present() {
1101 return false;
1102 }
1103
1104 // Clone the flash so we can tell if unchanged.
1105 let mut flash = self.flash.clone();
1106
1107 // Setup ram based on the ram configuration we determined earlier for the images.
1108 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1109
1110 for (idx, _image) in (&self.images).iter().enumerate() {
1111 // Verify that the images area loaded into this.
1112 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc,
1113 None, Some(idx as i32), true));
1114 if !result.success() {
1115 error!("Failed to execute ram-load");
1116 return true;
1117 }
1118 }
1119
1120 // Verify each image.
1121 for image in &self.images {
1122 let place = self.ram.lookup(&image.slots[0]);
1123 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1124 place.size as usize);
1125 let src_sz = image.upgrades.size();
1126 if src_sz > ram_image.len() {
1127 error!("Image ended up too large, nonsensical");
1128 return true;
1129 }
1130 let src_image = &image.upgrades.plain[0..src_sz];
1131 let ram_image = &ram_image[0..src_sz];
1132 if ram_image != src_image {
1133 error!("Image not loaded correctly");
1134 return true;
1135 }
1136
1137 }
1138
1139 return false;
1140 }
1141
David Brown5c9e0f12019-01-09 16:34:33 -07001142 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -07001143 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001144 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -07001145 if Caps::OverwriteUpgrade.present() {
1146 return;
1147 }
1148
David Brown84b49f72019-03-01 10:58:22 -07001149 // Set this for each image.
1150 for image in &self.images {
1151 let dev_id = &image.slots[slot].dev_id;
1152 let dev = flash.get_mut(&dev_id).unwrap();
1153 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001154 let off = &image.slots[slot].base_off;
1155 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -07001156 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -07001157
David Brown84b49f72019-03-01 10:58:22 -07001158 // Mark the status area as a bad area
1159 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1160 }
David Brown5c9e0f12019-01-09 16:34:33 -07001161 }
1162
David Brown76101572019-02-28 11:29:03 -07001163 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001164 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001165 return;
1166 }
1167
David Brown84b49f72019-03-01 10:58:22 -07001168 for image in &self.images {
1169 let dev_id = &image.slots[slot].dev_id;
1170 let dev = flash.get_mut(&dev_id).unwrap();
1171 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001172
David Brown84b49f72019-03-01 10:58:22 -07001173 // Disabling write verification the only assert triggered by
1174 // boot_go should be checking for integrity of status bytes.
1175 dev.set_verify_writes(false);
1176 }
David Brown5c9e0f12019-01-09 16:34:33 -07001177 }
1178
David Browndb505822019-03-01 10:04:20 -07001179 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1180 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001181 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001182 // Clone the flash to have a new copy.
1183 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001184
Fabio Utziged4a5362019-07-30 12:43:23 -03001185 if permanent {
1186 self.mark_permanent_upgrades(&mut flash, 1);
1187 }
David Brown5c9e0f12019-01-09 16:34:33 -07001188
David Browndb505822019-03-01 10:04:20 -07001189 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001190
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001191 let (first_interrupted, count) = match c::boot_go(&mut flash,
1192 &self.areadesc,
1193 Some(&mut counter),
1194 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001195 x if x.interrupted() => (true, stop.unwrap()),
1196 x if x.success() => (false, -counter),
1197 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001198 };
David Brown5c9e0f12019-01-09 16:34:33 -07001199
David Browndb505822019-03-01 10:04:20 -07001200 counter = 0;
1201 if first_interrupted {
1202 // fl.dump();
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001203 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1204 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001205 x if x.interrupted() => panic!("Shouldn't stop again"),
1206 x if x.success() => (),
1207 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001208 }
1209 }
David Brown5c9e0f12019-01-09 16:34:33 -07001210
David Browndb505822019-03-01 10:04:20 -07001211 (flash, count - counter)
1212 }
1213
1214 fn try_revert(&self, count: usize) -> SimMultiFlash {
1215 let mut flash = self.flash.clone();
1216
1217 // fl.write_file("image0.bin").unwrap();
1218 for i in 0 .. count {
1219 info!("Running boot pass {}", i + 1);
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001220 assert!(c::boot_go(&mut flash, &self.areadesc, None, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001221 }
1222 flash
1223 }
1224
1225 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1226 let mut flash = self.flash.clone();
1227 let mut fails = 0;
1228
1229 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001230 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1231 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001232 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001233 fails += 1;
1234 }
1235
Fabio Utzig8af7f792019-07-30 12:40:01 -03001236 // In a multi-image setup, copy done might be set if any number of
1237 // images was already successfully swapped.
1238 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1239 warn!("copy_done should be unset");
1240 fails += 1;
1241 }
1242
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001243 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001244 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001245 fails += 1;
1246 }
1247
David Brown84b49f72019-03-01 10:58:22 -07001248 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001249 warn!("Image in the primary slot before revert is invalid at stop={}",
1250 stop);
1251 fails += 1;
1252 }
David Brown84b49f72019-03-01 10:58:22 -07001253 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001254 warn!("Image in the secondary slot before revert is invalid at stop={}",
1255 stop);
1256 fails += 1;
1257 }
David Brown84b49f72019-03-01 10:58:22 -07001258 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1259 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001260 warn!("Mismatched trailer for the primary slot before revert");
1261 fails += 1;
1262 }
David Brown84b49f72019-03-01 10:58:22 -07001263 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1264 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001265 warn!("Mismatched trailer for the secondary slot before revert");
1266 fails += 1;
1267 }
1268
1269 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001270 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001271 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1272 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001273 warn!("Should have stopped revert at interruption point");
1274 fails += 1;
1275 }
1276
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001277 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001278 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001279 fails += 1;
1280 }
1281
David Brown84b49f72019-03-01 10:58:22 -07001282 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001283 warn!("Image in the primary slot after revert is invalid at stop={}",
1284 stop);
1285 fails += 1;
1286 }
David Brown84b49f72019-03-01 10:58:22 -07001287 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001288 warn!("Image in the secondary slot after revert is invalid at stop={}",
1289 stop);
1290 fails += 1;
1291 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001292
David Brown84b49f72019-03-01 10:58:22 -07001293 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1294 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001295 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001296 fails += 1;
1297 }
David Brown84b49f72019-03-01 10:58:22 -07001298 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1299 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001300 warn!("Mismatched trailer for the secondary slot after revert");
1301 fails += 1;
1302 }
1303
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001304 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001305 warn!("Should have finished 3rd boot");
1306 fails += 1;
1307 }
1308
1309 if !self.verify_images(&flash, 0, 0) {
1310 warn!("Image in the primary slot is invalid on 1st boot after revert");
1311 fails += 1;
1312 }
1313 if !self.verify_images(&flash, 1, 1) {
1314 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1315 fails += 1;
1316 }
1317
David Browndb505822019-03-01 10:04:20 -07001318 fails > 0
1319 }
1320
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001321
David Browndb505822019-03-01 10:04:20 -07001322 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1323 let mut flash = self.flash.clone();
1324
David Brown84b49f72019-03-01 10:58:22 -07001325 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001326
1327 let mut rng = rand::thread_rng();
1328 let mut resets = vec![0i32; count];
1329 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001330 for reset in &mut resets {
David Brown9c6322f2021-08-19 13:03:39 -06001331 let reset_counter = rng.gen_range(1 ..= remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001332 let mut counter = reset_counter;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001333 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1334 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001335 x if x.interrupted() => (),
1336 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001337 }
1338 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001339 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001340 }
1341
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001342 match c::boot_go(&mut flash, &self.areadesc, None, None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001343 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1344 x if x.success() => (),
1345 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001346 }
David Brown5c9e0f12019-01-09 16:34:33 -07001347
David Browndb505822019-03-01 10:04:20 -07001348 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001349 }
David Brown84b49f72019-03-01 10:58:22 -07001350
1351 /// Verify the image in the given flash device, the specified slot
1352 /// against the expected image.
1353 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001354 self.images.iter().all(|image| {
1355 verify_image(flash, &image.slots[slot],
1356 match against {
1357 0 => &image.primaries,
1358 1 => &image.upgrades,
1359 _ => panic!("Invalid 'against'")
1360 })
1361 })
David Brown84b49f72019-03-01 10:58:22 -07001362 }
1363
David Brownc3898d62019-08-05 14:20:02 -06001364 /// Verify the images, according to the dependency test.
1365 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1366 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1367 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1368 if !verify_image(flash, &image.slots[0],
1369 match upgrade {
1370 UpgradeInfo::Upgraded => &image.upgrades,
1371 UpgradeInfo::Held => &image.primaries,
1372 }) {
1373 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1374 return true;
1375 }
1376 }
1377
1378 false
1379 }
1380
Fabio Utzig8af7f792019-07-30 12:40:01 -03001381 /// Verify that at least one of the trailers of the images have the
1382 /// specified values.
1383 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1384 magic: Option<u8>, image_ok: Option<u8>,
1385 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001386 self.images.iter().any(|image| {
1387 verify_trailer(flash, &image.slots[slot],
1388 magic, image_ok, copy_done)
1389 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001390 }
1391
David Brown84b49f72019-03-01 10:58:22 -07001392 /// Verify that the trailers of the images have the specified
1393 /// values.
1394 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1395 magic: Option<u8>, image_ok: Option<u8>,
1396 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001397 self.images.iter().all(|image| {
1398 verify_trailer(flash, &image.slots[slot],
1399 magic, image_ok, copy_done)
1400 })
David Brown84b49f72019-03-01 10:58:22 -07001401 }
1402
1403 /// Mark each of the images for permanent upgrade.
1404 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1405 for image in &self.images {
1406 mark_permanent_upgrade(flash, &image.slots[slot]);
1407 }
1408 }
1409
1410 /// Mark each of the images for permanent upgrade.
1411 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1412 for image in &self.images {
1413 mark_upgrade(flash, &image.slots[slot]);
1414 }
1415 }
David Brown297029a2019-08-13 14:29:51 -06001416
1417 /// Dump out the flash image(s) to one or more files for debugging
1418 /// purposes. The names will be written as either "{prefix}.mcubin" or
1419 /// "{prefix}-001.mcubin" depending on how many images there are.
1420 pub fn debug_dump(&self, prefix: &str) {
1421 for (id, fdev) in &self.flash {
1422 let name = if self.flash.len() == 1 {
1423 format!("{}.mcubin", prefix)
1424 } else {
1425 format!("{}-{:>0}.mcubin", prefix, id)
1426 };
1427 fdev.write_file(&name).unwrap();
1428 }
1429 }
David Brown5c9e0f12019-01-09 16:34:33 -07001430}
1431
David Brownbf32c272021-06-16 17:11:37 -06001432impl RamData {
David Brownf17d3912021-06-23 16:10:51 -06001433 // TODO: This is not correct. The second slot of each image should be at the same address as
1434 // the primary.
David Brownbf32c272021-06-16 17:11:37 -06001435 fn new(slots: &[[SlotInfo; 2]]) -> RamData {
1436 let mut addr = RAM_LOAD_ADDR;
1437 let mut places = BTreeMap::new();
David Brownf17d3912021-06-23 16:10:51 -06001438 // println!("Setup:-------------");
David Brownbf32c272021-06-16 17:11:37 -06001439 for imgs in slots {
1440 for si in imgs {
David Brownf17d3912021-06-23 16:10:51 -06001441 // println!("Setup: si: {:?}", si);
David Brownbf32c272021-06-16 17:11:37 -06001442 let offset = addr;
1443 let size = si.len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001444 places.insert(SlotKey {
1445 dev_id: si.dev_id,
David Brownf17d3912021-06-23 16:10:51 -06001446 base_off: si.base_off,
David Brownbf32c272021-06-16 17:11:37 -06001447 }, SlotPlace { offset, size });
David Brownf17d3912021-06-23 16:10:51 -06001448 // println!(" load: offset: {}, size: {}", offset, size);
David Brownbf32c272021-06-16 17:11:37 -06001449 }
David Brownf17d3912021-06-23 16:10:51 -06001450 addr += imgs[0].len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001451 }
1452 RamData {
1453 places,
1454 total: addr,
1455 }
1456 }
David Brownf17d3912021-06-23 16:10:51 -06001457
1458 /// Lookup the ram data associated with a given flash partition. We just panic if not present,
1459 /// because all slots used should be in the map.
1460 fn lookup(&self, slot: &SlotInfo) -> &SlotPlace {
1461 self.places.get(&SlotKey{dev_id: slot.dev_id, base_off: slot.base_off})
1462 .expect("RamData should contain all slots")
1463 }
David Brownbf32c272021-06-16 17:11:37 -06001464}
1465
David Brown5c9e0f12019-01-09 16:34:33 -07001466/// Show the flash layout.
1467#[allow(dead_code)]
1468fn show_flash(flash: &dyn Flash) {
1469 println!("---- Flash configuration ----");
1470 for sector in flash.sector_iter() {
1471 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1472 sector.num, sector.base, sector.size);
1473 }
David Brown599b2db2021-03-10 05:23:26 -07001474 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001475}
1476
David Browna62c3eb2021-10-25 16:32:40 -06001477#[derive(Debug)]
1478enum ImageSize {
1479 /// Make the image the specified given size.
1480 Given(usize),
1481 /// Make the image as large as it can be for the partition/device.
1482 Largest,
1483}
1484
David Brown5c9e0f12019-01-09 16:34:33 -07001485/// Install a "program" into the given image. This fakes the image header, or at least all of the
1486/// fields used by the given code. Returns a copy of the image that was written.
David Browna62c3eb2021-10-25 16:32:40 -06001487fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: ImageSize,
David Brownf17d3912021-06-23 16:10:51 -06001488 ram: &RamData,
David Brownc3898d62019-08-05 14:20:02 -06001489 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001490 let offset = slot.base_off;
1491 let slot_len = slot.len;
1492 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001493
David Brown43643dd2019-01-11 15:43:28 -07001494 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001495
David Brownc3898d62019-08-05 14:20:02 -06001496 // Add the dependencies early to the tlv.
1497 for dep in deps.my_deps(offset, slot.index) {
1498 tlv.add_dependency(deps.other_id(), &dep);
1499 }
1500
David Brown5c9e0f12019-01-09 16:34:33 -07001501 const HDR_SIZE: usize = 32;
1502
David Brownf17d3912021-06-23 16:10:51 -06001503 let place = ram.lookup(&slot);
1504 let load_addr = if Caps::RamLoad.present() {
1505 place.offset
1506 } else {
1507 0
1508 };
1509
David Browna62c3eb2021-10-25 16:32:40 -06001510 let len = match len {
1511 ImageSize::Given(size) => size,
1512 ImageSize::Largest => unimplemented!(),
1513 };
1514
David Brown5c9e0f12019-01-09 16:34:33 -07001515 // Generate a boot header. Note that the size doesn't include the header.
1516 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001517 magic: tlv.get_magic(),
David Brownf17d3912021-06-23 16:10:51 -06001518 load_addr,
David Brown5c9e0f12019-01-09 16:34:33 -07001519 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001520 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001521 img_size: len as u32,
1522 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001523 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001524 _pad2: 0,
1525 };
1526
1527 let mut b_header = [0; HDR_SIZE];
1528 b_header[..32].clone_from_slice(header.as_raw());
1529 assert_eq!(b_header.len(), HDR_SIZE);
1530
1531 tlv.add_bytes(&b_header);
1532
1533 // The core of the image itself is just pseudorandom data.
1534 let mut b_img = vec![0; len];
1535 splat(&mut b_img, offset);
1536
David Browncb47dd72019-08-05 14:21:49 -06001537 // Add some information at the start of the payload to make it easier
1538 // to see what it is. This will fail if the image itself is too small.
1539 {
1540 let mut wr = Cursor::new(&mut b_img);
1541 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1542 offset, dev_id, slot).unwrap();
1543 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1544 }
1545
David Brown5c9e0f12019-01-09 16:34:33 -07001546 // TLV signatures work over plain image
1547 tlv.add_bytes(&b_img);
1548
1549 // Generate encrypted images
Salome Thirot6fdbf552021-05-14 16:46:14 +01001550 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1551 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001552 let mut b_encimg = vec![];
1553 if is_encrypted {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001554 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1555 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001556 tlv.generate_enc_key();
1557 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001558 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001559 b_encimg = b_img.clone();
Salome Thirot6fdbf552021-05-14 16:46:14 +01001560 if aes256 {
1561 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001562 let block = Aes256::new(&key);
1563 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001564 cipher.apply_keystream(&mut b_encimg);
1565 } else {
1566 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001567 let block = Aes128::new(&key);
1568 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001569 cipher.apply_keystream(&mut b_encimg);
1570 }
David Brown5c9e0f12019-01-09 16:34:33 -07001571 }
1572
1573 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001574 if bad_sig {
1575 tlv.corrupt_sig();
1576 }
1577 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001578
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001579 let dev = flash.get_mut(&dev_id).unwrap();
1580
David Brown5c9e0f12019-01-09 16:34:33 -07001581 let mut buf = vec![];
1582 buf.append(&mut b_header.to_vec());
1583 buf.append(&mut b_img);
1584 buf.append(&mut b_tlv.clone());
1585
David Brown95de4502019-11-15 12:01:34 -07001586 // Pad the buffer to a multiple of the flash alignment.
1587 let align = dev.align();
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001588 let image_sz = buf.len();
David Brown95de4502019-11-15 12:01:34 -07001589 while buf.len() % align != 0 {
1590 buf.push(dev.erased_val());
1591 }
1592
David Brown5c9e0f12019-01-09 16:34:33 -07001593 let mut encbuf = vec![];
1594 if is_encrypted {
1595 encbuf.append(&mut b_header.to_vec());
1596 encbuf.append(&mut b_encimg);
1597 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001598
1599 while encbuf.len() % align != 0 {
1600 encbuf.push(dev.erased_val());
1601 }
David Brown5c9e0f12019-01-09 16:34:33 -07001602 }
1603
David Vincze2d736ad2019-02-18 11:50:22 +01001604 // Since images are always non-encrypted in the primary slot, we first write
1605 // an encrypted image, re-read to use for verification, erase + flash
1606 // un-encrypted. In the secondary slot the image is written un-encrypted,
1607 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001608
David Brown3b090212019-07-30 15:59:28 -06001609 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001610 let enc_copy: Option<Vec<u8>>;
1611
1612 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001613 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001614
1615 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001616 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001617
1618 enc_copy = Some(enc);
1619
David Brown76101572019-02-28 11:29:03 -07001620 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001621 } else {
1622 enc_copy = None;
1623 }
1624
David Brown76101572019-02-28 11:29:03 -07001625 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001626
1627 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001628 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001629
David Brownca234692019-02-28 11:22:19 -07001630 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001631 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001632 plain: copy,
1633 cipher: enc_copy,
1634 }
David Brown5c9e0f12019-01-09 16:34:33 -07001635 } else {
1636
David Brown76101572019-02-28 11:29:03 -07001637 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001638
1639 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001640 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001641
1642 let enc_copy: Option<Vec<u8>>;
1643
1644 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001645 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001646
David Brown76101572019-02-28 11:29:03 -07001647 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001648
1649 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001650 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001651
1652 enc_copy = Some(enc);
1653 } else {
1654 enc_copy = None;
1655 }
1656
David Brownca234692019-02-28 11:22:19 -07001657 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001658 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001659 plain: copy,
1660 cipher: enc_copy,
1661 }
David Brown5c9e0f12019-01-09 16:34:33 -07001662 }
David Brown5c9e0f12019-01-09 16:34:33 -07001663}
1664
David Brown873be312019-09-03 12:22:32 -06001665/// Install no image. This is used when no upgrade happens.
1666fn install_no_image() -> ImageData {
1667 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001668 size: 0,
David Brown873be312019-09-03 12:22:32 -06001669 plain: vec![],
1670 cipher: None,
1671 }
1672}
1673
David Brown0bd8c6b2021-10-22 16:33:06 -06001674/// Construct a TLV generator based on how MCUboot is currently configured. The returned
1675/// ManifestGen will generate the appropriate entries based on this configuration.
David Brown5c9e0f12019-01-09 16:34:33 -07001676fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001677 if Caps::EcdsaP224.present() {
1678 panic!("Ecdsa P224 not supported in Simulator");
1679 }
David Brownac655bb2021-10-22 16:33:27 -06001680 let aes_key_size = if Caps::Aes256.present() { 256 } else { 128 };
David Brown5c9e0f12019-01-09 16:34:33 -07001681
David Brownb8882112019-01-11 14:04:11 -07001682 if Caps::EncKw.present() {
1683 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001684 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001685 } else if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001686 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001687 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001688 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001689 }
1690 } else if Caps::EncRsa.present() {
1691 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001692 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001693 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001694 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001695 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001696 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001697 if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001698 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001699 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001700 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001701 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001702 } else if Caps::EncX25519.present() {
1703 if Caps::Ed25519.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001704 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001705 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001706 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001707 }
David Brownb8882112019-01-11 14:04:11 -07001708 } else {
1709 // The non-encrypted configuration.
1710 if Caps::RSA2048.present() {
1711 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001712 } else if Caps::RSA3072.present() {
1713 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001714 } else if Caps::EcdsaP256.present() {
1715 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001716 } else if Caps::Ed25519.present() {
1717 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001718 } else {
1719 TlvGen::new_hash_only()
1720 }
1721 }
David Brown5c9e0f12019-01-09 16:34:33 -07001722}
1723
David Brownca234692019-02-28 11:22:19 -07001724impl ImageData {
1725 /// Find the image contents for the given slot. This assumes that slot 0
1726 /// is unencrypted, and slot 1 is encrypted.
1727 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001728 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001729 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001730 match (encrypted, slot) {
1731 (false, _) => &self.plain,
1732 (true, 0) => &self.plain,
1733 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1734 _ => panic!("Invalid slot requested"),
1735 }
David Brown5c9e0f12019-01-09 16:34:33 -07001736 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001737
1738 fn size(&self) -> usize {
1739 self.size
1740 }
David Brown5c9e0f12019-01-09 16:34:33 -07001741}
1742
David Brown5c9e0f12019-01-09 16:34:33 -07001743/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001744fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1745 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001746 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001747 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001748
1749 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001750 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001751 let dev = flash.get(&dev_id).unwrap();
1752 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001753
1754 if buf != &copy[..] {
1755 for i in 0 .. buf.len() {
1756 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001757 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1758 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001759 break;
1760 }
1761 }
1762 false
1763 } else {
1764 true
1765 }
1766}
1767
David Brown3b090212019-07-30 15:59:28 -06001768fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001769 magic: Option<u8>, image_ok: Option<u8>,
1770 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001771 if Caps::OverwriteUpgrade.present() {
1772 return true;
1773 }
David Brown5c9e0f12019-01-09 16:34:33 -07001774
David Brown3b090212019-07-30 15:59:28 -06001775 let offset = slot.trailer_off + c::boot_max_align();
1776 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001777 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001778 let mut failed = false;
1779
David Brown76101572019-02-28 11:29:03 -07001780 let dev = flash.get(&dev_id).unwrap();
1781 let erased_val = dev.erased_val();
1782 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001783
1784 failed |= match magic {
1785 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001786 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001787 warn!("\"magic\" mismatch at {:#x}", offset);
1788 true
1789 } else if v == 3 {
1790 let expected = [erased_val; 16];
David Brownd36f6b12021-03-10 05:23:56 -07001791 if copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001792 warn!("\"magic\" mismatch at {:#x}", offset);
1793 true
1794 } else {
1795 false
1796 }
1797 } else {
1798 false
1799 }
1800 },
1801 None => false,
1802 };
1803
1804 failed |= match image_ok {
1805 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001806 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001807 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1808 true
1809 } else {
1810 false
1811 }
1812 },
1813 None => false,
1814 };
1815
1816 failed |= match copy_done {
1817 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001818 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001819 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1820 true
1821 } else {
1822 false
1823 }
1824 },
1825 None => false,
1826 };
1827
1828 !failed
1829}
1830
David Brown297029a2019-08-13 14:29:51 -06001831/// Install a partition table. This is a simplified partition table that
1832/// we write at the beginning of flash so make it easier for external tools
1833/// to analyze these images.
1834fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1835 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1836 for &id in &ids {
1837 // If there are any partitions in this device that start at 0, and
1838 // aren't marked as the BootLoader partition, avoid adding the
1839 // partition table. This makes it harder to view the image, but
1840 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07001841 let skip_ptable = areadesc
1842 .iter_areas()
1843 .any(|area| {
1844 area.device_id == id &&
1845 area.off == 0 &&
1846 area.flash_id != FlashId::BootLoader
1847 });
1848 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06001849 if log_enabled!(Info) {
1850 let special: Vec<FlashId> = areadesc.iter_areas()
1851 .filter(|area| area.device_id == id && area.off == 0)
1852 .map(|area| area.flash_id)
1853 .collect();
1854 info!("Skipping partition table: {:?}", special);
1855 }
1856 break;
1857 }
1858
1859 let mut buf: Vec<u8> = vec![];
1860 write!(&mut buf, "mcuboot\0").unwrap();
1861
1862 // Iterate through all of the partitions in that device, and encode
1863 // into the table.
1864 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1865 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1866
1867 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1868 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1869 buf.write_u32::<LittleEndian>(area.off).unwrap();
1870 buf.write_u32::<LittleEndian>(area.size).unwrap();
1871 buf.write_u32::<LittleEndian>(0).unwrap();
1872 }
1873
1874 let dev = flash.get_mut(&id).unwrap();
1875
1876 // Pad to alignment.
1877 while buf.len() % dev.align() != 0 {
1878 buf.push(0);
1879 }
1880
1881 dev.write(0, &buf).unwrap();
1882 }
1883}
1884
David Brown5c9e0f12019-01-09 16:34:33 -07001885/// The image header
1886#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001887#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001888pub struct ImageHeader {
1889 magic: u32,
1890 load_addr: u32,
1891 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001892 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001893 img_size: u32,
1894 flags: u32,
1895 ver: ImageVersion,
1896 _pad2: u32,
1897}
1898
1899impl AsRaw for ImageHeader {}
1900
1901#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001902#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001903pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001904 pub major: u8,
1905 pub minor: u8,
1906 pub revision: u16,
1907 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001908}
1909
David Brownc3898d62019-08-05 14:20:02 -06001910#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001911pub struct SlotInfo {
1912 pub base_off: usize,
1913 pub trailer_off: usize,
1914 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001915 // Which slot within this device.
1916 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001917 pub dev_id: u8,
1918}
1919
David Brown347dc572019-11-15 11:37:25 -07001920const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1921 0x60, 0xd2, 0xef, 0x7f,
1922 0x35, 0x52, 0x50, 0x0f,
1923 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001924
1925// Replicates defines found in bootutil.h
1926const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1927const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1928
1929const BOOT_FLAG_SET: Option<u8> = Some(1);
1930const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1931
1932/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001933pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1934 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001935 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001936 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001937 if offset % align != 0 || MAGIC.len() % align != 0 {
1938 // The write size is larger than the magic value. Fill a buffer
1939 // with the erased value, put the MAGIC in it, and write it in its
1940 // entirety.
1941 let mut buf = vec![dev.erased_val(); align];
1942 buf[(offset % align)..].copy_from_slice(MAGIC);
1943 dev.write(offset - (offset % align), &buf).unwrap();
1944 } else {
1945 dev.write(offset, MAGIC).unwrap();
1946 }
David Brown5c9e0f12019-01-09 16:34:33 -07001947}
1948
1949/// Writes the image_ok flag which, guess what, tells the bootloader
1950/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001951fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001952 // Overwrite mode always is permanent, and only the magic is used in
1953 // the trailer. To avoid problems with large write sizes, don't try to
1954 // set anything in this case.
1955 if Caps::OverwriteUpgrade.present() {
1956 return;
1957 }
1958
David Brown76101572019-02-28 11:29:03 -07001959 let dev = flash.get_mut(&slot.dev_id).unwrap();
1960 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001961 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001962 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001963 let align = dev.align();
1964 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001965}
1966
1967// Drop some pseudo-random gibberish onto the data.
1968fn splat(data: &mut [u8], seed: usize) {
David Brown9c6322f2021-08-19 13:03:39 -06001969 let mut seed_block = [0u8; 32];
David Browncd842842020-07-09 15:46:53 -06001970 let mut buf = Cursor::new(&mut seed_block[..]);
1971 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
1972 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
1973 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
1974 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
1975 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07001976 rng.fill_bytes(data);
1977}
1978
1979/// Return a read-only view into the raw bytes of this object
1980trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07001981 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07001982 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1983 mem::size_of::<Self>()) }
1984 }
1985}
1986
1987pub fn show_sizes() {
1988 // This isn't panic safe.
1989 for min in &[1, 2, 4, 8] {
1990 let msize = c::boot_trailer_sz(*min);
1991 println!("{:2}: {} (0x{:x})", min, msize, msize);
1992 }
1993}
David Brown95de4502019-11-15 12:01:34 -07001994
1995#[cfg(not(feature = "large-write"))]
1996fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001997 &[1, 2, 4, 8]
1998}
1999
2000#[cfg(feature = "large-write")]
2001fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07002002 &[1, 2, 4, 8, 128, 512]
2003}