blob: c7b9846f322dbfb815476634634db746a6148ba1 [file] [log] [blame]
David Brownc8d62012021-10-27 15:03:48 -06001// Copyright (c) 2019-2021 Linaro LTD
David Browne2acfae2020-01-21 16:45:01 -07002// Copyright (c) 2019-2020 JUUL Labs
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],
David Brown07dd5f02021-10-26 16:43:15 -0600223 maximal(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],
David Brown07dd5f02021-10-26 16:43:15 -0600227 maximal(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],
David Brown07dd5f02021-10-26 16:43:15 -0600276 maximal(32784), &ram, &dep, false);
David Browna62c3eb2021-10-25 16:32:40 -0600277 let upgrades = install_image(&mut bad_flash, &slots[1],
David Brown07dd5f02021-10-26 16:43:15 -0600278 maximal(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],
David Brown07dd5f02021-10-26 16:43:15 -0600299 maximal(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],
David Brown07dd5f02021-10-26 16:43:15 -0600322 maximal(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.
Fabio Utzig5577cbd2021-12-10 17:34:28 -0300342 // The flash layout as described is not present in any real STM32F4 device, but it
343 // serves to exercise support for sectors of varying sizes inside a single slot,
344 // as long as they are compatible in both slots and all fit in the scratch.
345 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024, 64 * 1024,
346 32 * 1024, 32 * 1024, 64 * 1024,
347 32 * 1024, 32 * 1024, 64 * 1024,
348 128 * 1024],
David Brown76101572019-02-28 11:29:03 -0700349 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700350 let dev_id = 0;
351 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700352 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700353 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
354 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
355 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
356
David Brown76101572019-02-28 11:29:03 -0700357 let mut flash = SimMultiFlash::new();
358 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300359 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700360 }
361 DeviceName::K64f => {
362 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700363 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700364
365 let dev_id = 0;
366 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700367 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700368 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
369 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
370 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
371
David Brown76101572019-02-28 11:29:03 -0700372 let mut flash = SimMultiFlash::new();
373 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300374 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700375 }
376 DeviceName::K64fBig => {
377 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
378 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700379 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700380
381 let dev_id = 0;
382 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700383 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700384 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
385 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
386 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
387
David Brown76101572019-02-28 11:29:03 -0700388 let mut flash = SimMultiFlash::new();
389 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300390 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700391 }
392 DeviceName::Nrf52840 => {
393 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
394 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700395 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700396
397 let dev_id = 0;
398 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700399 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700400 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
401 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
402 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
403
David Brown76101572019-02-28 11:29:03 -0700404 let mut flash = SimMultiFlash::new();
405 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300406 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700407 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300408 DeviceName::Nrf52840UnequalSlots => {
409 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
410
411 let dev_id = 0;
412 let mut areadesc = AreaDesc::new();
413 areadesc.add_flash_sectors(dev_id, &dev);
414 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
415 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
416
417 let mut flash = SimMultiFlash::new();
418 flash.insert(dev_id, dev);
419 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
420 }
David Browne5133242019-02-28 11:05:19 -0700421 DeviceName::Nrf52840SpiFlash => {
422 // Simulate nrf52840 with external SPI flash. The external SPI flash
423 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700424 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
425 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700426
427 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700428 areadesc.add_flash_sectors(0, &dev0);
429 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700430
431 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
432 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
433 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
434
David Brown76101572019-02-28 11:29:03 -0700435 let mut flash = SimMultiFlash::new();
436 flash.insert(0, dev0);
437 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300438 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700439 }
David Brown2bff6472019-03-05 13:58:35 -0700440 DeviceName::K64fMulti => {
441 // NXP style flash, but larger, to support multiple images.
442 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
443
444 let dev_id = 0;
445 let mut areadesc = AreaDesc::new();
446 areadesc.add_flash_sectors(dev_id, &dev);
447 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
448 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
449 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
450 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
451 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
452
453 let mut flash = SimMultiFlash::new();
454 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300455 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700456 }
David Browne5133242019-02-28 11:05:19 -0700457 }
458 }
David Brownc3898d62019-08-05 14:20:02 -0600459
460 pub fn num_images(&self) -> usize {
461 self.slots.len()
462 }
David Browne5133242019-02-28 11:05:19 -0700463}
464
David Brown5c9e0f12019-01-09 16:34:33 -0700465impl Images {
466 /// A simple upgrade without forced failures.
467 ///
468 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700469 /// inject failures at chosen steps. Returns None if it was unable to
470 /// count the operations in a basic upgrade.
471 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300472 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700473 info!("Total flash operation count={}", total_count);
474
David Brown84b49f72019-03-01 10:58:22 -0700475 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700476 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700477 None
David Brown5c9e0f12019-01-09 16:34:33 -0700478 } else {
David Brown8973f552021-03-10 05:21:11 -0700479 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700480 }
481 }
482
Fabio Utzigd0157342020-10-02 15:22:11 -0300483 pub fn run_bootstrap(&self) -> bool {
484 let mut flash = self.flash.clone();
485 let mut fails = 0;
486
487 if Caps::Bootstrap.present() {
488 info!("Try bootstraping image in the primary");
489
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100490 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigd0157342020-10-02 15:22:11 -0300491 warn!("Failed first boot");
492 fails += 1;
493 }
494
495 if !self.verify_images(&flash, 0, 1) {
496 warn!("Image in the first slot was not bootstrapped");
497 fails += 1;
498 }
499
500 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
501 BOOT_FLAG_SET, BOOT_FLAG_SET) {
502 warn!("Mismatched trailer for the primary slot");
503 fails += 1;
504 }
505 }
506
507 if fails > 0 {
508 error!("Expected trailer on secondary slot to be erased");
509 }
510
511 fails > 0
512 }
513
514
David Brownc3898d62019-08-05 14:20:02 -0600515 /// Test a simple upgrade, with dependencies given, and verify that the
516 /// image does as is described in the test.
517 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600518 if !Caps::modifies_flash() {
519 return false;
520 }
521
David Brownc3898d62019-08-05 14:20:02 -0600522 let (flash, _) = self.try_upgrade(None, true);
523
524 self.verify_dep_images(&flash, deps)
525 }
526
Fabio Utzigf5480c72019-11-28 10:41:57 -0300527 fn is_swap_upgrade(&self) -> bool {
528 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
529 }
530
David Brown5c9e0f12019-01-09 16:34:33 -0700531 pub fn run_basic_revert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600532 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700533 return false;
534 }
David Brown5c9e0f12019-01-09 16:34:33 -0700535
David Brown5c9e0f12019-01-09 16:34:33 -0700536 let mut fails = 0;
537
538 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300539 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700540 for count in 2 .. 5 {
541 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700542 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700543 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700544 error!("Revert failure on count {}", count);
545 fails += 1;
546 }
547 }
548 }
549
550 fails > 0
551 }
552
553 pub fn run_perm_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600554 if !Caps::modifies_flash() {
555 return false;
556 }
557
David Brown5c9e0f12019-01-09 16:34:33 -0700558 let mut fails = 0;
559 let total_flash_ops = self.total_count.unwrap();
560
561 // Let's try an image halfway through.
562 for i in 1 .. total_flash_ops {
563 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300564 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700565 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700566 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700567 warn!("FAIL at step {} of {}", i, total_flash_ops);
568 fails += 1;
569 }
570
David Brown84b49f72019-03-01 10:58:22 -0700571 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
572 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100573 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700574 fails += 1;
575 }
576
David Brown84b49f72019-03-01 10:58:22 -0700577 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
578 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100579 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700580 fails += 1;
581 }
582
David Brownaec56b22021-03-10 05:22:07 -0700583 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
584 warn!("Secondary slot FAIL at step {} of {}",
585 i, total_flash_ops);
586 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700587 }
588 }
589
590 if fails > 0 {
591 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
592 fails as f32 * 100.0 / total_flash_ops as f32);
593 }
594
595 fails > 0
596 }
597
David Brown5c9e0f12019-01-09 16:34:33 -0700598 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600599 if !Caps::modifies_flash() {
600 return false;
601 }
602
David Brown5c9e0f12019-01-09 16:34:33 -0700603 let mut fails = 0;
604 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700605 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700606 info!("Random interruptions at reset points={:?}", total_counts);
607
David Brown84b49f72019-03-01 10:58:22 -0700608 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300609 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700610 // TODO: This result is ignored.
611 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700612 } else {
613 true
614 };
David Vincze2d736ad2019-02-18 11:50:22 +0100615 if !primary_slot_ok || !secondary_slot_ok {
616 error!("Image mismatch after random interrupts: primary slot={} \
617 secondary slot={}",
618 if primary_slot_ok { "ok" } else { "fail" },
619 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700620 fails += 1;
621 }
David Brown84b49f72019-03-01 10:58:22 -0700622 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
623 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100624 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700625 fails += 1;
626 }
David Brown84b49f72019-03-01 10:58:22 -0700627 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
628 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100629 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700630 fails += 1;
631 }
632
633 if fails > 0 {
634 error!("Error testing perm upgrade with {} fails", total_fails);
635 }
636
637 fails > 0
638 }
639
David Brown5c9e0f12019-01-09 16:34:33 -0700640 pub fn run_revert_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600641 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700642 return false;
643 }
David Brown5c9e0f12019-01-09 16:34:33 -0700644
David Brown5c9e0f12019-01-09 16:34:33 -0700645 let mut fails = 0;
646
Fabio Utzigf5480c72019-11-28 10:41:57 -0300647 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300648 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700649 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700650 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700651 error!("Revert failed at interruption {}", i);
652 fails += 1;
653 }
654 }
655 }
656
657 fails > 0
658 }
659
David Brown5c9e0f12019-01-09 16:34:33 -0700660 pub fn run_norevert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600661 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700662 return false;
663 }
David Brown5c9e0f12019-01-09 16:34:33 -0700664
David Brown76101572019-02-28 11:29:03 -0700665 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700666 let mut fails = 0;
667
668 info!("Try norevert");
669
670 // First do a normal upgrade...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100671 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700672 warn!("Failed first boot");
673 fails += 1;
674 }
675
676 //FIXME: copy_done is written by boot_go, is it ok if no copy
677 // was ever done?
678
David Brown84b49f72019-03-01 10:58:22 -0700679 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100680 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700681 fails += 1;
682 }
David Brown84b49f72019-03-01 10:58:22 -0700683 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
684 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100685 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700686 fails += 1;
687 }
David Brown84b49f72019-03-01 10:58:22 -0700688 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
689 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100690 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700691 fails += 1;
692 }
693
David Vincze2d736ad2019-02-18 11:50:22 +0100694 // Marks image in the primary slot as permanent,
695 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700696 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700697
David Brown84b49f72019-03-01 10:58:22 -0700698 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
699 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100700 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700701 fails += 1;
702 }
703
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100704 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700705 warn!("Failed second boot");
706 fails += 1;
707 }
708
David Brown84b49f72019-03-01 10:58:22 -0700709 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
710 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100711 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700712 fails += 1;
713 }
David Brown84b49f72019-03-01 10:58:22 -0700714 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700715 warn!("Failed image verification");
716 fails += 1;
717 }
718
719 if fails > 0 {
720 error!("Error running upgrade without revert");
721 }
722
723 fails > 0
724 }
725
David Brown2ee5f7f2020-01-13 14:04:01 -0700726 // Test that an upgrade is rejected. Assumes that the image was build
727 // such that the upgrade is instead a downgrade.
728 pub fn run_nodowngrade(&self) -> bool {
729 if !Caps::DowngradePrevention.present() {
730 return false;
731 }
732
733 let mut flash = self.flash.clone();
734 let mut fails = 0;
735
736 info!("Try no downgrade");
737
738 // First, do a normal upgrade.
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100739 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700740 warn!("Failed first boot");
741 fails += 1;
742 }
743
744 if !self.verify_images(&flash, 0, 0) {
745 warn!("Failed verification after downgrade rejection");
746 fails += 1;
747 }
748
749 if fails > 0 {
750 error!("Error testing downgrade rejection");
751 }
752
753 fails > 0
754 }
755
David Vincze2d736ad2019-02-18 11:50:22 +0100756 // Tests a new image written to the primary slot that already has magic and
757 // image_ok set while there is no image on the secondary slot, so no revert
758 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700759 pub fn run_norevert_newimage(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600760 if !Caps::modifies_flash() {
761 info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
762 return false;
763 }
764
David Brown76101572019-02-28 11:29:03 -0700765 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700766 let mut fails = 0;
767
768 info!("Try non-revert on imgtool generated image");
769
David Brown84b49f72019-03-01 10:58:22 -0700770 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700771
David Vincze2d736ad2019-02-18 11:50:22 +0100772 // This simulates writing an image created by imgtool to
773 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700774 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
775 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100776 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700777 fails += 1;
778 }
779
780 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100781 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700782 warn!("Failed first boot");
783 fails += 1;
784 }
785
786 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700787 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700788 warn!("Failed image verification");
789 fails += 1;
790 }
David Brown84b49f72019-03-01 10:58:22 -0700791 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
792 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100793 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700794 fails += 1;
795 }
David Brown84b49f72019-03-01 10:58:22 -0700796 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
797 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100798 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700799 fails += 1;
800 }
801
802 if fails > 0 {
803 error!("Expected a non revert with new image");
804 }
805
806 fails > 0
807 }
808
David Vincze2d736ad2019-02-18 11:50:22 +0100809 // Tests a new image written to the primary slot that already has magic and
810 // image_ok set while there is no image on the secondary slot, so no revert
811 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700812 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700813 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700814 let mut fails = 0;
815
816 info!("Try upgrade image with bad signature");
817
David Brown6db44d72021-05-26 16:22:58 -0600818 // Only perform this test if an upgrade is expected to happen.
819 if !Caps::modifies_flash() {
820 info!("Skipping upgrade image with bad signature");
821 return false;
822 }
823
David Brown84b49f72019-03-01 10:58:22 -0700824 self.mark_upgrades(&mut flash, 0);
825 self.mark_permanent_upgrades(&mut flash, 0);
826 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700827
David Brown84b49f72019-03-01 10:58:22 -0700828 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
829 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100830 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700831 fails += 1;
832 }
833
834 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100835 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700836 warn!("Failed first boot");
837 fails += 1;
838 }
839
840 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700841 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700842 warn!("Failed image verification");
843 fails += 1;
844 }
David Brown84b49f72019-03-01 10:58:22 -0700845 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
846 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100847 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700848 fails += 1;
849 }
850
851 if fails > 0 {
852 error!("Expected an upgrade failure when image has bad signature");
853 }
854
855 fails > 0
856 }
857
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300858 // Should detect there is a leftover trailer in an otherwise erased
859 // secondary slot and erase its trailer.
860 pub fn run_secondary_leftover_trailer(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600861 if !Caps::modifies_flash() {
862 return false;
863 }
864
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300865 let mut flash = self.flash.clone();
866 let mut fails = 0;
867
868 info!("Try with a leftover trailer in the secondary; must be erased");
869
870 // Add a trailer on the secondary slot
871 self.mark_permanent_upgrades(&mut flash, 1);
872 self.mark_upgrades(&mut flash, 1);
873
874 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100875 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300876 warn!("Failed first boot");
877 fails += 1;
878 }
879
880 // State should not have changed
881 if !self.verify_images(&flash, 0, 0) {
882 warn!("Failed image verification");
883 fails += 1;
884 }
885 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
886 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
887 warn!("Mismatched trailer for the secondary slot");
888 fails += 1;
889 }
890
891 if fails > 0 {
892 error!("Expected trailer on secondary slot to be erased");
893 }
894
895 fails > 0
896 }
897
David Brown5c9e0f12019-01-09 16:34:33 -0700898 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300899 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700900 }
901
David Brown5c9e0f12019-01-09 16:34:33 -0700902 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300903 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700904 }
905
906 /// This test runs a simple upgrade with no fails in the images, but
907 /// allowing for fails in the status area. This should run to the end
908 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700909 pub fn run_with_status_fails_complete(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600910 if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700911 return false;
912 }
913
David Brown76101572019-02-28 11:29:03 -0700914 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700915 let mut fails = 0;
916
917 info!("Try swap with status fails");
918
David Brown84b49f72019-03-01 10:58:22 -0700919 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700920 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700921
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100922 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brownc423ac42021-06-04 13:47:34 -0600923 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700924 warn!("Failed!");
925 fails += 1;
926 }
927
928 // Failed writes to the marked "bad" region don't assert anymore.
929 // Any detected assert() is happening in another part of the code.
David Brownc423ac42021-06-04 13:47:34 -0600930 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -0700931 warn!("At least one assert() was called");
932 fails += 1;
933 }
934
David Brown84b49f72019-03-01 10:58:22 -0700935 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
936 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100937 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700938 fails += 1;
939 }
940
David Brown84b49f72019-03-01 10:58:22 -0700941 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700942 warn!("Failed image verification");
943 fails += 1;
944 }
945
David Vincze2d736ad2019-02-18 11:50:22 +0100946 info!("validate primary slot enabled; \
947 re-run of boot_go should just work");
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100948 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700949 warn!("Failed!");
950 fails += 1;
951 }
952
953 if fails > 0 {
954 error!("Error running upgrade with status write fails");
955 }
956
957 fails > 0
958 }
959
960 /// This test runs a simple upgrade with no fails in the images, but
961 /// allowing for fails in the status area. This should run to the end
962 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700963 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600964 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700965 false
David Vincze2d736ad2019-02-18 11:50:22 +0100966 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700967
David Brown76101572019-02-28 11:29:03 -0700968 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700969 let mut fails = 0;
970 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700971
David Brown85904a82019-01-11 13:45:12 -0700972 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700973
David Brown85904a82019-01-11 13:45:12 -0700974 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700975
David Brown84b49f72019-03-01 10:58:22 -0700976 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700977 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700978
979 // Should not fail, writing to bad regions does not assert
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100980 let asserts = c::boot_go(&mut flash, &self.areadesc,
981 Some(&mut count), None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700982 if asserts != 0 {
983 warn!("At least one assert() was called");
984 fails += 1;
985 }
986
David Brown76101572019-02-28 11:29:03 -0700987 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700988
989 info!("Resuming an interrupted swap operation");
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100990 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
991 true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700992
993 // This might throw no asserts, for large sector devices, where
994 // a single failure writing is indistinguishable from no failure,
995 // or throw a single assert for small sector devices that fail
996 // multiple times...
997 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100998 warn!("Expected single assert validating the primary slot, \
999 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -07001000 fails += 1;
1001 }
1002
1003 if fails > 0 {
1004 error!("Error running upgrade with status write fails");
1005 }
1006
1007 fails > 0
1008 } else {
David Brown76101572019-02-28 11:29:03 -07001009 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001010 let mut fails = 0;
1011
1012 info!("Try interrupted swap with status fails");
1013
David Brown84b49f72019-03-01 10:58:22 -07001014 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001015 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -07001016
1017 // This is expected to fail while writing to bad regions...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001018 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1019 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001020 if asserts == 0 {
1021 warn!("No assert() detected");
1022 fails += 1;
1023 }
1024
1025 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -07001026 }
David Brown5c9e0f12019-01-09 16:34:33 -07001027 }
1028
David Brown0dfb8102021-06-03 15:29:11 -06001029 /// Test the direct XIP configuration. With this mode, flash images are never moved, and the
1030 /// bootloader merely selects which partition is the proper one to boot.
1031 pub fn run_direct_xip(&self) -> bool {
1032 if !Caps::DirectXip.present() {
1033 return false;
1034 }
1035
1036 // Clone the flash so we can tell if unchanged.
1037 let mut flash = self.flash.clone();
1038
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001039 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brown0dfb8102021-06-03 15:29:11 -06001040
1041 // Ensure the boot was successful.
1042 let resp = if let Some(resp) = result.resp() {
1043 resp
1044 } else {
1045 panic!("Boot didn't return a valid result");
1046 };
1047
1048 // This configuration should always try booting from the first upgrade slot.
1049 if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
1050 assert_eq!(offset, resp.image_off as usize);
1051 assert_eq!(dev_id, resp.flash_dev_id);
1052 } else {
1053 panic!("Unable to find upgrade image");
1054 }
1055 false
1056 }
1057
David Brown8a4e23b2021-06-11 10:29:01 -06001058 /// Test the ram-loading.
1059 pub fn run_ram_load(&self) -> bool {
1060 if !Caps::RamLoad.present() {
1061 return false;
1062 }
1063
1064 // Clone the flash so we can tell if unchanged.
1065 let mut flash = self.flash.clone();
1066
David Brownf17d3912021-06-23 16:10:51 -06001067 // Setup ram based on the ram configuration we determined earlier for the images.
1068 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
David Brown8a4e23b2021-06-11 10:29:01 -06001069
David Brownf17d3912021-06-23 16:10:51 -06001070 // println!("Ram: {:#?}", self.ram);
David Brown8a4e23b2021-06-11 10:29:01 -06001071
David Brownf17d3912021-06-23 16:10:51 -06001072 // Verify that the images area loaded into this.
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001073 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None,
1074 None, true));
David Brown8a4e23b2021-06-11 10:29:01 -06001075 if !result.success() {
David Brownf17d3912021-06-23 16:10:51 -06001076 error!("Failed to execute ram-load");
David Brown8a4e23b2021-06-11 10:29:01 -06001077 return true;
1078 }
1079
David Brownf17d3912021-06-23 16:10:51 -06001080 // Verify each image.
1081 for image in &self.images {
1082 let place = self.ram.lookup(&image.slots[0]);
1083 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1084 place.size as usize);
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001085 let src_sz = image.upgrades.size();
1086 if src_sz > ram_image.len() {
David Brownf17d3912021-06-23 16:10:51 -06001087 error!("Image ended up too large, nonsensical");
1088 return true;
1089 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001090 let src_image = &image.upgrades.plain[0..src_sz];
1091 let ram_image = &ram_image[0..src_sz];
David Brownf17d3912021-06-23 16:10:51 -06001092 if ram_image != src_image {
1093 error!("Image not loaded correctly");
1094 return true;
1095 }
1096
1097 }
1098
1099 return false;
David Brown8a4e23b2021-06-11 10:29:01 -06001100 }
1101
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001102 /// Test the split ram-loading.
1103 pub fn run_split_ram_load(&self) -> bool {
1104 if !Caps::RamLoad.present() {
1105 return false;
1106 }
1107
1108 // Clone the flash so we can tell if unchanged.
1109 let mut flash = self.flash.clone();
1110
1111 // Setup ram based on the ram configuration we determined earlier for the images.
1112 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1113
1114 for (idx, _image) in (&self.images).iter().enumerate() {
1115 // Verify that the images area loaded into this.
1116 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc,
1117 None, Some(idx as i32), true));
1118 if !result.success() {
1119 error!("Failed to execute ram-load");
1120 return true;
1121 }
1122 }
1123
1124 // Verify each image.
1125 for image in &self.images {
1126 let place = self.ram.lookup(&image.slots[0]);
1127 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1128 place.size as usize);
1129 let src_sz = image.upgrades.size();
1130 if src_sz > ram_image.len() {
1131 error!("Image ended up too large, nonsensical");
1132 return true;
1133 }
1134 let src_image = &image.upgrades.plain[0..src_sz];
1135 let ram_image = &ram_image[0..src_sz];
1136 if ram_image != src_image {
1137 error!("Image not loaded correctly");
1138 return true;
1139 }
1140
1141 }
1142
1143 return false;
1144 }
1145
David Brown5c9e0f12019-01-09 16:34:33 -07001146 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -07001147 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001148 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -07001149 if Caps::OverwriteUpgrade.present() {
1150 return;
1151 }
1152
David Brown84b49f72019-03-01 10:58:22 -07001153 // Set this for each image.
1154 for image in &self.images {
1155 let dev_id = &image.slots[slot].dev_id;
1156 let dev = flash.get_mut(&dev_id).unwrap();
1157 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001158 let off = &image.slots[slot].base_off;
1159 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -07001160 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -07001161
David Brown84b49f72019-03-01 10:58:22 -07001162 // Mark the status area as a bad area
1163 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1164 }
David Brown5c9e0f12019-01-09 16:34:33 -07001165 }
1166
David Brown76101572019-02-28 11:29:03 -07001167 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001168 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001169 return;
1170 }
1171
David Brown84b49f72019-03-01 10:58:22 -07001172 for image in &self.images {
1173 let dev_id = &image.slots[slot].dev_id;
1174 let dev = flash.get_mut(&dev_id).unwrap();
1175 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001176
David Brown84b49f72019-03-01 10:58:22 -07001177 // Disabling write verification the only assert triggered by
1178 // boot_go should be checking for integrity of status bytes.
1179 dev.set_verify_writes(false);
1180 }
David Brown5c9e0f12019-01-09 16:34:33 -07001181 }
1182
David Browndb505822019-03-01 10:04:20 -07001183 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1184 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001185 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001186 // Clone the flash to have a new copy.
1187 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001188
Fabio Utziged4a5362019-07-30 12:43:23 -03001189 if permanent {
1190 self.mark_permanent_upgrades(&mut flash, 1);
1191 }
David Brown5c9e0f12019-01-09 16:34:33 -07001192
David Browndb505822019-03-01 10:04:20 -07001193 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001194
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001195 let (first_interrupted, count) = match c::boot_go(&mut flash,
1196 &self.areadesc,
1197 Some(&mut counter),
1198 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001199 x if x.interrupted() => (true, stop.unwrap()),
1200 x if x.success() => (false, -counter),
1201 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001202 };
David Brown5c9e0f12019-01-09 16:34:33 -07001203
David Browndb505822019-03-01 10:04:20 -07001204 counter = 0;
1205 if first_interrupted {
1206 // fl.dump();
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001207 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1208 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001209 x if x.interrupted() => panic!("Shouldn't stop again"),
1210 x if x.success() => (),
1211 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001212 }
1213 }
David Brown5c9e0f12019-01-09 16:34:33 -07001214
David Browndb505822019-03-01 10:04:20 -07001215 (flash, count - counter)
1216 }
1217
1218 fn try_revert(&self, count: usize) -> SimMultiFlash {
1219 let mut flash = self.flash.clone();
1220
1221 // fl.write_file("image0.bin").unwrap();
1222 for i in 0 .. count {
1223 info!("Running boot pass {}", i + 1);
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001224 assert!(c::boot_go(&mut flash, &self.areadesc, None, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001225 }
1226 flash
1227 }
1228
1229 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1230 let mut flash = self.flash.clone();
1231 let mut fails = 0;
1232
1233 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001234 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1235 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001236 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001237 fails += 1;
1238 }
1239
Fabio Utzig8af7f792019-07-30 12:40:01 -03001240 // In a multi-image setup, copy done might be set if any number of
1241 // images was already successfully swapped.
1242 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1243 warn!("copy_done should be unset");
1244 fails += 1;
1245 }
1246
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001247 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001248 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001249 fails += 1;
1250 }
1251
David Brown84b49f72019-03-01 10:58:22 -07001252 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001253 warn!("Image in the primary slot before revert is invalid at stop={}",
1254 stop);
1255 fails += 1;
1256 }
David Brown84b49f72019-03-01 10:58:22 -07001257 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001258 warn!("Image in the secondary slot before revert is invalid at stop={}",
1259 stop);
1260 fails += 1;
1261 }
David Brown84b49f72019-03-01 10:58:22 -07001262 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1263 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001264 warn!("Mismatched trailer for the primary slot before revert");
1265 fails += 1;
1266 }
David Brown84b49f72019-03-01 10:58:22 -07001267 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1268 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001269 warn!("Mismatched trailer for the secondary slot before revert");
1270 fails += 1;
1271 }
1272
1273 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001274 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001275 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1276 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001277 warn!("Should have stopped revert at interruption point");
1278 fails += 1;
1279 }
1280
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001281 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001282 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001283 fails += 1;
1284 }
1285
David Brown84b49f72019-03-01 10:58:22 -07001286 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001287 warn!("Image in the primary slot after revert is invalid at stop={}",
1288 stop);
1289 fails += 1;
1290 }
David Brown84b49f72019-03-01 10:58:22 -07001291 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001292 warn!("Image in the secondary slot after revert is invalid at stop={}",
1293 stop);
1294 fails += 1;
1295 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001296
David Brown84b49f72019-03-01 10:58:22 -07001297 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1298 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001299 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001300 fails += 1;
1301 }
David Brown84b49f72019-03-01 10:58:22 -07001302 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1303 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001304 warn!("Mismatched trailer for the secondary slot after revert");
1305 fails += 1;
1306 }
1307
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001308 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001309 warn!("Should have finished 3rd boot");
1310 fails += 1;
1311 }
1312
1313 if !self.verify_images(&flash, 0, 0) {
1314 warn!("Image in the primary slot is invalid on 1st boot after revert");
1315 fails += 1;
1316 }
1317 if !self.verify_images(&flash, 1, 1) {
1318 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1319 fails += 1;
1320 }
1321
David Browndb505822019-03-01 10:04:20 -07001322 fails > 0
1323 }
1324
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001325
David Browndb505822019-03-01 10:04:20 -07001326 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1327 let mut flash = self.flash.clone();
1328
David Brown84b49f72019-03-01 10:58:22 -07001329 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001330
1331 let mut rng = rand::thread_rng();
1332 let mut resets = vec![0i32; count];
1333 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001334 for reset in &mut resets {
David Brown9c6322f2021-08-19 13:03:39 -06001335 let reset_counter = rng.gen_range(1 ..= remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001336 let mut counter = reset_counter;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001337 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1338 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001339 x if x.interrupted() => (),
1340 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001341 }
1342 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001343 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001344 }
1345
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001346 match c::boot_go(&mut flash, &self.areadesc, None, None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001347 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1348 x if x.success() => (),
1349 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001350 }
David Brown5c9e0f12019-01-09 16:34:33 -07001351
David Browndb505822019-03-01 10:04:20 -07001352 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001353 }
David Brown84b49f72019-03-01 10:58:22 -07001354
1355 /// Verify the image in the given flash device, the specified slot
1356 /// against the expected image.
1357 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001358 self.images.iter().all(|image| {
1359 verify_image(flash, &image.slots[slot],
1360 match against {
1361 0 => &image.primaries,
1362 1 => &image.upgrades,
1363 _ => panic!("Invalid 'against'")
1364 })
1365 })
David Brown84b49f72019-03-01 10:58:22 -07001366 }
1367
David Brownc3898d62019-08-05 14:20:02 -06001368 /// Verify the images, according to the dependency test.
1369 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1370 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1371 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1372 if !verify_image(flash, &image.slots[0],
1373 match upgrade {
1374 UpgradeInfo::Upgraded => &image.upgrades,
1375 UpgradeInfo::Held => &image.primaries,
1376 }) {
1377 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1378 return true;
1379 }
1380 }
1381
1382 false
1383 }
1384
Fabio Utzig8af7f792019-07-30 12:40:01 -03001385 /// Verify that at least one of the trailers of the images have the
1386 /// specified values.
1387 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1388 magic: Option<u8>, image_ok: Option<u8>,
1389 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001390 self.images.iter().any(|image| {
1391 verify_trailer(flash, &image.slots[slot],
1392 magic, image_ok, copy_done)
1393 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001394 }
1395
David Brown84b49f72019-03-01 10:58:22 -07001396 /// Verify that the trailers of the images have the specified
1397 /// values.
1398 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1399 magic: Option<u8>, image_ok: Option<u8>,
1400 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001401 self.images.iter().all(|image| {
1402 verify_trailer(flash, &image.slots[slot],
1403 magic, image_ok, copy_done)
1404 })
David Brown84b49f72019-03-01 10:58:22 -07001405 }
1406
1407 /// Mark each of the images for permanent upgrade.
1408 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1409 for image in &self.images {
1410 mark_permanent_upgrade(flash, &image.slots[slot]);
1411 }
1412 }
1413
1414 /// Mark each of the images for permanent upgrade.
1415 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1416 for image in &self.images {
1417 mark_upgrade(flash, &image.slots[slot]);
1418 }
1419 }
David Brown297029a2019-08-13 14:29:51 -06001420
1421 /// Dump out the flash image(s) to one or more files for debugging
1422 /// purposes. The names will be written as either "{prefix}.mcubin" or
1423 /// "{prefix}-001.mcubin" depending on how many images there are.
1424 pub fn debug_dump(&self, prefix: &str) {
1425 for (id, fdev) in &self.flash {
1426 let name = if self.flash.len() == 1 {
1427 format!("{}.mcubin", prefix)
1428 } else {
1429 format!("{}-{:>0}.mcubin", prefix, id)
1430 };
1431 fdev.write_file(&name).unwrap();
1432 }
1433 }
David Brown5c9e0f12019-01-09 16:34:33 -07001434}
1435
David Brownbf32c272021-06-16 17:11:37 -06001436impl RamData {
David Brownf17d3912021-06-23 16:10:51 -06001437 // TODO: This is not correct. The second slot of each image should be at the same address as
1438 // the primary.
David Brownbf32c272021-06-16 17:11:37 -06001439 fn new(slots: &[[SlotInfo; 2]]) -> RamData {
1440 let mut addr = RAM_LOAD_ADDR;
1441 let mut places = BTreeMap::new();
David Brownf17d3912021-06-23 16:10:51 -06001442 // println!("Setup:-------------");
David Brownbf32c272021-06-16 17:11:37 -06001443 for imgs in slots {
1444 for si in imgs {
David Brownf17d3912021-06-23 16:10:51 -06001445 // println!("Setup: si: {:?}", si);
David Brownbf32c272021-06-16 17:11:37 -06001446 let offset = addr;
1447 let size = si.len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001448 places.insert(SlotKey {
1449 dev_id: si.dev_id,
David Brownf17d3912021-06-23 16:10:51 -06001450 base_off: si.base_off,
David Brownbf32c272021-06-16 17:11:37 -06001451 }, SlotPlace { offset, size });
David Brownf17d3912021-06-23 16:10:51 -06001452 // println!(" load: offset: {}, size: {}", offset, size);
David Brownbf32c272021-06-16 17:11:37 -06001453 }
David Brownf17d3912021-06-23 16:10:51 -06001454 addr += imgs[0].len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001455 }
1456 RamData {
1457 places,
1458 total: addr,
1459 }
1460 }
David Brownf17d3912021-06-23 16:10:51 -06001461
1462 /// Lookup the ram data associated with a given flash partition. We just panic if not present,
1463 /// because all slots used should be in the map.
1464 fn lookup(&self, slot: &SlotInfo) -> &SlotPlace {
1465 self.places.get(&SlotKey{dev_id: slot.dev_id, base_off: slot.base_off})
1466 .expect("RamData should contain all slots")
1467 }
David Brownbf32c272021-06-16 17:11:37 -06001468}
1469
David Brown5c9e0f12019-01-09 16:34:33 -07001470/// Show the flash layout.
1471#[allow(dead_code)]
1472fn show_flash(flash: &dyn Flash) {
1473 println!("---- Flash configuration ----");
1474 for sector in flash.sector_iter() {
1475 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1476 sector.num, sector.base, sector.size);
1477 }
David Brown599b2db2021-03-10 05:23:26 -07001478 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001479}
1480
David Browna62c3eb2021-10-25 16:32:40 -06001481#[derive(Debug)]
1482enum ImageSize {
1483 /// Make the image the specified given size.
1484 Given(usize),
1485 /// Make the image as large as it can be for the partition/device.
1486 Largest,
1487}
1488
David Brown5c9e0f12019-01-09 16:34:33 -07001489/// Install a "program" into the given image. This fakes the image header, or at least all of the
1490/// fields used by the given code. Returns a copy of the image that was written.
David Browna62c3eb2021-10-25 16:32:40 -06001491fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: ImageSize,
David Brownf17d3912021-06-23 16:10:51 -06001492 ram: &RamData,
David Brownc3898d62019-08-05 14:20:02 -06001493 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001494 let offset = slot.base_off;
1495 let slot_len = slot.len;
1496 let dev_id = slot.dev_id;
David Brown07dd5f02021-10-26 16:43:15 -06001497 let dev = flash.get_mut(&dev_id).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001498
David Brown43643dd2019-01-11 15:43:28 -07001499 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001500
David Brownc3898d62019-08-05 14:20:02 -06001501 // Add the dependencies early to the tlv.
1502 for dep in deps.my_deps(offset, slot.index) {
1503 tlv.add_dependency(deps.other_id(), &dep);
1504 }
1505
David Brown5c9e0f12019-01-09 16:34:33 -07001506 const HDR_SIZE: usize = 32;
1507
David Brownf17d3912021-06-23 16:10:51 -06001508 let place = ram.lookup(&slot);
1509 let load_addr = if Caps::RamLoad.present() {
1510 place.offset
1511 } else {
1512 0
1513 };
1514
David Browna62c3eb2021-10-25 16:32:40 -06001515 let len = match len {
1516 ImageSize::Given(size) => size,
David Brown07dd5f02021-10-26 16:43:15 -06001517 ImageSize::Largest => {
1518 // Using the header size we know, the trailer size, and the slot size, we can compute
1519 // the largest image possible.
1520 let trailer = if Caps::OverwriteUpgrade.present() {
1521 // This computation is incorrect, and we need to figure out the correct size.
1522 // c::boot_status_sz(dev.align() as u32) as usize
1523 16 + 4 * dev.align()
1524 } else {
1525 c::boot_trailer_sz(dev.align() as u32) as usize
1526 };
1527 let tlv_len = tlv.estimate_size();
1528 info!("slot: 0x{:x}, HDR: 0x{:x}, trailer: 0x{:x}",
1529 slot_len, HDR_SIZE, trailer);
1530 slot_len - HDR_SIZE - trailer - tlv_len
1531 }
David Browna62c3eb2021-10-25 16:32:40 -06001532 };
1533
David Brown5c9e0f12019-01-09 16:34:33 -07001534 // Generate a boot header. Note that the size doesn't include the header.
1535 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001536 magic: tlv.get_magic(),
David Brownf17d3912021-06-23 16:10:51 -06001537 load_addr,
David Brown5c9e0f12019-01-09 16:34:33 -07001538 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001539 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001540 img_size: len as u32,
1541 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001542 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001543 _pad2: 0,
1544 };
1545
1546 let mut b_header = [0; HDR_SIZE];
1547 b_header[..32].clone_from_slice(header.as_raw());
1548 assert_eq!(b_header.len(), HDR_SIZE);
1549
1550 tlv.add_bytes(&b_header);
1551
1552 // The core of the image itself is just pseudorandom data.
1553 let mut b_img = vec![0; len];
1554 splat(&mut b_img, offset);
1555
David Browncb47dd72019-08-05 14:21:49 -06001556 // Add some information at the start of the payload to make it easier
1557 // to see what it is. This will fail if the image itself is too small.
1558 {
1559 let mut wr = Cursor::new(&mut b_img);
1560 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1561 offset, dev_id, slot).unwrap();
1562 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1563 }
1564
David Brown5c9e0f12019-01-09 16:34:33 -07001565 // TLV signatures work over plain image
1566 tlv.add_bytes(&b_img);
1567
1568 // Generate encrypted images
Salome Thirot6fdbf552021-05-14 16:46:14 +01001569 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1570 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001571 let mut b_encimg = vec![];
1572 if is_encrypted {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001573 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1574 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001575 tlv.generate_enc_key();
1576 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001577 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001578 b_encimg = b_img.clone();
Salome Thirot6fdbf552021-05-14 16:46:14 +01001579 if aes256 {
1580 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001581 let block = Aes256::new(&key);
1582 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001583 cipher.apply_keystream(&mut b_encimg);
1584 } else {
1585 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001586 let block = Aes128::new(&key);
1587 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001588 cipher.apply_keystream(&mut b_encimg);
1589 }
David Brown5c9e0f12019-01-09 16:34:33 -07001590 }
1591
1592 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001593 if bad_sig {
1594 tlv.corrupt_sig();
1595 }
1596 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001597
David Brown5c9e0f12019-01-09 16:34:33 -07001598 let mut buf = vec![];
1599 buf.append(&mut b_header.to_vec());
1600 buf.append(&mut b_img);
1601 buf.append(&mut b_tlv.clone());
1602
David Brown95de4502019-11-15 12:01:34 -07001603 // Pad the buffer to a multiple of the flash alignment.
1604 let align = dev.align();
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001605 let image_sz = buf.len();
David Brown95de4502019-11-15 12:01:34 -07001606 while buf.len() % align != 0 {
1607 buf.push(dev.erased_val());
1608 }
1609
David Brown5c9e0f12019-01-09 16:34:33 -07001610 let mut encbuf = vec![];
1611 if is_encrypted {
1612 encbuf.append(&mut b_header.to_vec());
1613 encbuf.append(&mut b_encimg);
1614 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001615
1616 while encbuf.len() % align != 0 {
1617 encbuf.push(dev.erased_val());
1618 }
David Brown5c9e0f12019-01-09 16:34:33 -07001619 }
1620
David Vincze2d736ad2019-02-18 11:50:22 +01001621 // Since images are always non-encrypted in the primary slot, we first write
1622 // an encrypted image, re-read to use for verification, erase + flash
1623 // un-encrypted. In the secondary slot the image is written un-encrypted,
1624 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001625
David Brown3b090212019-07-30 15:59:28 -06001626 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001627 let enc_copy: Option<Vec<u8>>;
1628
1629 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001630 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001631
1632 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001633 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001634
1635 enc_copy = Some(enc);
1636
David Brown76101572019-02-28 11:29:03 -07001637 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001638 } else {
1639 enc_copy = None;
1640 }
1641
David Brown76101572019-02-28 11:29:03 -07001642 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001643
1644 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001645 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001646
David Brownca234692019-02-28 11:22:19 -07001647 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001648 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001649 plain: copy,
1650 cipher: enc_copy,
1651 }
David Brown5c9e0f12019-01-09 16:34:33 -07001652 } else {
1653
David Brown76101572019-02-28 11:29:03 -07001654 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001655
1656 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001657 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001658
1659 let enc_copy: Option<Vec<u8>>;
1660
1661 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001662 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001663
David Brown76101572019-02-28 11:29:03 -07001664 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001665
1666 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001667 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001668
1669 enc_copy = Some(enc);
1670 } else {
1671 enc_copy = None;
1672 }
1673
David Brownca234692019-02-28 11:22:19 -07001674 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001675 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001676 plain: copy,
1677 cipher: enc_copy,
1678 }
David Brown5c9e0f12019-01-09 16:34:33 -07001679 }
David Brown5c9e0f12019-01-09 16:34:33 -07001680}
1681
David Brown873be312019-09-03 12:22:32 -06001682/// Install no image. This is used when no upgrade happens.
1683fn install_no_image() -> ImageData {
1684 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001685 size: 0,
David Brown873be312019-09-03 12:22:32 -06001686 plain: vec![],
1687 cipher: None,
1688 }
1689}
1690
David Brown0bd8c6b2021-10-22 16:33:06 -06001691/// Construct a TLV generator based on how MCUboot is currently configured. The returned
1692/// ManifestGen will generate the appropriate entries based on this configuration.
David Brown5c9e0f12019-01-09 16:34:33 -07001693fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001694 if Caps::EcdsaP224.present() {
1695 panic!("Ecdsa P224 not supported in Simulator");
1696 }
David Brownac655bb2021-10-22 16:33:27 -06001697 let aes_key_size = if Caps::Aes256.present() { 256 } else { 128 };
David Brown5c9e0f12019-01-09 16:34:33 -07001698
David Brownb8882112019-01-11 14:04:11 -07001699 if Caps::EncKw.present() {
1700 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001701 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001702 } else if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001703 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001704 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001705 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001706 }
1707 } else if Caps::EncRsa.present() {
1708 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001709 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001710 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001711 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001712 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001713 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001714 if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001715 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001716 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001717 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001718 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001719 } else if Caps::EncX25519.present() {
1720 if Caps::Ed25519.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001721 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001722 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001723 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001724 }
David Brownb8882112019-01-11 14:04:11 -07001725 } else {
1726 // The non-encrypted configuration.
1727 if Caps::RSA2048.present() {
1728 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001729 } else if Caps::RSA3072.present() {
1730 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001731 } else if Caps::EcdsaP256.present() {
1732 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001733 } else if Caps::Ed25519.present() {
1734 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001735 } else {
1736 TlvGen::new_hash_only()
1737 }
1738 }
David Brown5c9e0f12019-01-09 16:34:33 -07001739}
1740
David Brownca234692019-02-28 11:22:19 -07001741impl ImageData {
1742 /// Find the image contents for the given slot. This assumes that slot 0
1743 /// is unencrypted, and slot 1 is encrypted.
1744 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001745 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001746 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001747 match (encrypted, slot) {
1748 (false, _) => &self.plain,
1749 (true, 0) => &self.plain,
1750 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1751 _ => panic!("Invalid slot requested"),
1752 }
David Brown5c9e0f12019-01-09 16:34:33 -07001753 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001754
1755 fn size(&self) -> usize {
1756 self.size
1757 }
David Brown5c9e0f12019-01-09 16:34:33 -07001758}
1759
David Brown5c9e0f12019-01-09 16:34:33 -07001760/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001761fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1762 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001763 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001764 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001765
1766 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001767 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001768 let dev = flash.get(&dev_id).unwrap();
1769 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001770
1771 if buf != &copy[..] {
1772 for i in 0 .. buf.len() {
1773 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001774 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1775 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001776 break;
1777 }
1778 }
1779 false
1780 } else {
1781 true
1782 }
1783}
1784
David Brown3b090212019-07-30 15:59:28 -06001785fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001786 magic: Option<u8>, image_ok: Option<u8>,
1787 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001788 if Caps::OverwriteUpgrade.present() {
1789 return true;
1790 }
David Brown5c9e0f12019-01-09 16:34:33 -07001791
David Brown3b090212019-07-30 15:59:28 -06001792 let offset = slot.trailer_off + c::boot_max_align();
1793 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001794 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001795 let mut failed = false;
1796
David Brown76101572019-02-28 11:29:03 -07001797 let dev = flash.get(&dev_id).unwrap();
1798 let erased_val = dev.erased_val();
1799 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001800
1801 failed |= match magic {
1802 Some(v) => {
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001803 let magic_off = c::boot_max_align() * 3;
1804 if v == 1 && &copy[magic_off..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001805 warn!("\"magic\" mismatch at {:#x}", offset);
1806 true
1807 } else if v == 3 {
1808 let expected = [erased_val; 16];
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001809 if copy[magic_off..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001810 warn!("\"magic\" mismatch at {:#x}", offset);
1811 true
1812 } else {
1813 false
1814 }
1815 } else {
1816 false
1817 }
1818 },
1819 None => false,
1820 };
1821
1822 failed |= match image_ok {
1823 Some(v) => {
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001824 let image_ok_off = c::boot_max_align() * 2;
1825 if (v == 1 && copy[image_ok_off] != v) || (v == 3 && copy[image_ok_off] != erased_val) {
1826 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[image_ok_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07001827 true
1828 } else {
1829 false
1830 }
1831 },
1832 None => false,
1833 };
1834
1835 failed |= match copy_done {
1836 Some(v) => {
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001837 let copy_done_off = c::boot_max_align();
1838 if (v == 1 && copy[copy_done_off] != v) || (v == 3 && copy[copy_done_off] != erased_val) {
1839 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[copy_done_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07001840 true
1841 } else {
1842 false
1843 }
1844 },
1845 None => false,
1846 };
1847
1848 !failed
1849}
1850
David Brown297029a2019-08-13 14:29:51 -06001851/// Install a partition table. This is a simplified partition table that
1852/// we write at the beginning of flash so make it easier for external tools
1853/// to analyze these images.
1854fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1855 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1856 for &id in &ids {
1857 // If there are any partitions in this device that start at 0, and
1858 // aren't marked as the BootLoader partition, avoid adding the
1859 // partition table. This makes it harder to view the image, but
1860 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07001861 let skip_ptable = areadesc
1862 .iter_areas()
1863 .any(|area| {
1864 area.device_id == id &&
1865 area.off == 0 &&
1866 area.flash_id != FlashId::BootLoader
1867 });
1868 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06001869 if log_enabled!(Info) {
1870 let special: Vec<FlashId> = areadesc.iter_areas()
1871 .filter(|area| area.device_id == id && area.off == 0)
1872 .map(|area| area.flash_id)
1873 .collect();
1874 info!("Skipping partition table: {:?}", special);
1875 }
1876 break;
1877 }
1878
1879 let mut buf: Vec<u8> = vec![];
1880 write!(&mut buf, "mcuboot\0").unwrap();
1881
1882 // Iterate through all of the partitions in that device, and encode
1883 // into the table.
1884 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1885 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1886
1887 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1888 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1889 buf.write_u32::<LittleEndian>(area.off).unwrap();
1890 buf.write_u32::<LittleEndian>(area.size).unwrap();
1891 buf.write_u32::<LittleEndian>(0).unwrap();
1892 }
1893
1894 let dev = flash.get_mut(&id).unwrap();
1895
1896 // Pad to alignment.
1897 while buf.len() % dev.align() != 0 {
1898 buf.push(0);
1899 }
1900
1901 dev.write(0, &buf).unwrap();
1902 }
1903}
1904
David Brown5c9e0f12019-01-09 16:34:33 -07001905/// The image header
1906#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001907#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001908pub struct ImageHeader {
1909 magic: u32,
1910 load_addr: u32,
1911 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001912 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001913 img_size: u32,
1914 flags: u32,
1915 ver: ImageVersion,
1916 _pad2: u32,
1917}
1918
1919impl AsRaw for ImageHeader {}
1920
1921#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001922#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001923pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001924 pub major: u8,
1925 pub minor: u8,
1926 pub revision: u16,
1927 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001928}
1929
David Brownc3898d62019-08-05 14:20:02 -06001930#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001931pub struct SlotInfo {
1932 pub base_off: usize,
1933 pub trailer_off: usize,
1934 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001935 // Which slot within this device.
1936 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001937 pub dev_id: u8,
1938}
1939
David Brown347dc572019-11-15 11:37:25 -07001940const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1941 0x60, 0xd2, 0xef, 0x7f,
1942 0x35, 0x52, 0x50, 0x0f,
1943 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001944
1945// Replicates defines found in bootutil.h
1946const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1947const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1948
1949const BOOT_FLAG_SET: Option<u8> = Some(1);
1950const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1951
1952/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001953pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1954 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001955 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001956 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001957 if offset % align != 0 || MAGIC.len() % align != 0 {
1958 // The write size is larger than the magic value. Fill a buffer
1959 // with the erased value, put the MAGIC in it, and write it in its
1960 // entirety.
1961 let mut buf = vec![dev.erased_val(); align];
1962 buf[(offset % align)..].copy_from_slice(MAGIC);
1963 dev.write(offset - (offset % align), &buf).unwrap();
1964 } else {
1965 dev.write(offset, MAGIC).unwrap();
1966 }
David Brown5c9e0f12019-01-09 16:34:33 -07001967}
1968
1969/// Writes the image_ok flag which, guess what, tells the bootloader
1970/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001971fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001972 // Overwrite mode always is permanent, and only the magic is used in
1973 // the trailer. To avoid problems with large write sizes, don't try to
1974 // set anything in this case.
1975 if Caps::OverwriteUpgrade.present() {
1976 return;
1977 }
1978
David Brown76101572019-02-28 11:29:03 -07001979 let dev = flash.get_mut(&slot.dev_id).unwrap();
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001980 let align = dev.align();
1981 let mut ok = vec![dev.erased_val(); align];
David Brown5c9e0f12019-01-09 16:34:33 -07001982 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001983 let off = slot.trailer_off + c::boot_max_align() * 3;
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001984 dev.write(off, &ok).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001985}
1986
1987// Drop some pseudo-random gibberish onto the data.
1988fn splat(data: &mut [u8], seed: usize) {
David Brown9c6322f2021-08-19 13:03:39 -06001989 let mut seed_block = [0u8; 32];
David Browncd842842020-07-09 15:46:53 -06001990 let mut buf = Cursor::new(&mut seed_block[..]);
1991 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
1992 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
1993 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
1994 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
1995 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07001996 rng.fill_bytes(data);
1997}
1998
1999/// Return a read-only view into the raw bytes of this object
2000trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07002001 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07002002 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
2003 mem::size_of::<Self>()) }
2004 }
2005}
2006
David Brown07dd5f02021-10-26 16:43:15 -06002007/// Determine whether it makes sense to test this configuration with a maximally-sized image.
2008/// Returns an ImageSize representing the best size to test, possibly just with the given size.
2009fn maximal(size: usize) -> ImageSize {
2010 if Caps::OverwriteUpgrade.present() ||
2011 Caps::SwapUsingMove.present()
2012 {
2013 ImageSize::Given(size)
2014 } else {
2015 ImageSize::Largest
2016 }
2017}
2018
David Brown5c9e0f12019-01-09 16:34:33 -07002019pub fn show_sizes() {
2020 // This isn't panic safe.
2021 for min in &[1, 2, 4, 8] {
2022 let msize = c::boot_trailer_sz(*min);
2023 println!("{:2}: {} (0x{:x})", min, msize, msize);
2024 }
2025}
David Brown95de4502019-11-15 12:01:34 -07002026
2027#[cfg(not(feature = "large-write"))]
2028fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07002029 &[1, 2, 4, 8]
2030}
2031
2032#[cfg(feature = "large-write")]
2033fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07002034 &[1, 2, 4, 8, 128, 512]
2035}