blob: e8aacc14c2b04f8c7101d664a55c59f2bc61d585 [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};
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -030057use crate::utils::align_up;
Salome Thirot6fdbf552021-05-14 16:46:14 +010058use typenum::{U32, U16};
David Brown5c9e0f12019-01-09 16:34:33 -070059
David Brown8a4e23b2021-06-11 10:29:01 -060060/// For testing, use a non-zero offset for the ram-load, to make sure the offset is getting used
61/// properly, but the value is not really that important.
62const RAM_LOAD_ADDR: u32 = 1024;
63
David Browne5133242019-02-28 11:05:19 -070064/// A builder for Images. This describes a single run of the simulator,
65/// capturing the configuration of a particular set of devices, including
66/// the flash simulator(s) and the information about the slots.
67#[derive(Clone)]
68pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070069 flash: SimMultiFlash,
David Browne5133242019-02-28 11:05:19 -070070 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070071 slots: Vec<[SlotInfo; 2]>,
David Brownbf32c272021-06-16 17:11:37 -060072 ram: RamData,
David Browne5133242019-02-28 11:05:19 -070073}
74
David Brown998aa8d2019-02-28 10:54:50 -070075/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070076/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070077/// and upgrades hold the expected contents of these images.
78pub struct Images {
David Brown76101572019-02-28 11:29:03 -070079 flash: SimMultiFlash,
David Brownca234692019-02-28 11:22:19 -070080 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070081 images: Vec<OneImage>,
82 total_count: Option<i32>,
David Brownbf32c272021-06-16 17:11:37 -060083 ram: RamData,
David Brown84b49f72019-03-01 10:58:22 -070084}
85
86/// When doing multi-image, there is an instance of this information for
87/// each of the images. Single image there will be one of these.
88struct OneImage {
David Brownca234692019-02-28 11:22:19 -070089 slots: [SlotInfo; 2],
90 primaries: ImageData,
91 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070092}
93
94/// The Rust-side representation of an image. For unencrypted images, this
95/// is just the unencrypted payload. For encrypted images, we store both
96/// the encrypted and the plaintext.
97struct ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -030098 size: usize,
David Brownca234692019-02-28 11:22:19 -070099 plain: Vec<u8>,
100 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -0700101}
102
David Brownbf32c272021-06-16 17:11:37 -0600103/// For the RamLoad test cases, we need a contiguous area of RAM to load these images into. For
104/// multi-image builds, these may not correspond with the offsets. This has to be computed early,
105/// before images are built, because each image contains the offset where the image is to be loaded
106/// in the header, which is contained within the signature.
107#[derive(Clone, Debug)]
108struct RamData {
109 places: BTreeMap<SlotKey, SlotPlace>,
110 total: u32,
111}
112
113/// Every slot is indexed by this key.
114#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
115struct SlotKey {
116 dev_id: u8,
David Brownf17d3912021-06-23 16:10:51 -0600117 base_off: usize,
David Brownbf32c272021-06-16 17:11:37 -0600118}
119
120#[derive(Clone, Debug)]
121struct SlotPlace {
122 offset: u32,
123 size: u32,
124}
125
David Browne5133242019-02-28 11:05:19 -0700126impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -0700127 /// Construct a new image builder for the given device. Returns
128 /// Some(builder) if is possible to test this configuration, or None if
129 /// not possible (for example, if there aren't enough image slots).
Fabio Utzig114a6472019-11-28 10:24:09 -0300130 pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
131 let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
132
133 for cap in unsupported_caps {
134 if cap.present() {
135 return Err(format!("unsupported {:?}", cap));
136 }
137 }
David Browne5133242019-02-28 11:05:19 -0700138
David Brown06ef06e2019-03-05 12:28:10 -0700139 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -0700140
David Brown06ef06e2019-03-05 12:28:10 -0700141 let mut slots = Vec::with_capacity(num_images);
142 for image in 0..num_images {
143 // This mapping must match that defined in
144 // `boot/zephyr/include/sysflash/sysflash.h`.
145 let id0 = match image {
146 0 => FlashId::Image0,
147 1 => FlashId::Image2,
148 _ => panic!("More than 2 images not supported"),
149 };
150 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
151 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300152 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700153 };
154 let id1 = match image {
155 0 => FlashId::Image1,
156 1 => FlashId::Image3,
157 _ => panic!("More than 2 images not supported"),
158 };
159 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
160 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300161 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700162 };
David Browne5133242019-02-28 11:05:19 -0700163
Christopher Collinsa1c12042019-05-23 14:00:28 -0700164 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700165
David Brown06ef06e2019-03-05 12:28:10 -0700166 // Construct a primary image.
167 let primary = SlotInfo {
168 base_off: primary_base as usize,
169 trailer_off: primary_base + primary_len - offset_from_end,
170 len: primary_len as usize,
171 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600172 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700173 };
174
175 // And an upgrade image.
176 let secondary = SlotInfo {
177 base_off: secondary_base as usize,
178 trailer_off: secondary_base + secondary_len - offset_from_end,
179 len: secondary_len as usize,
180 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600181 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700182 };
183
184 slots.push([primary, secondary]);
185 }
David Browne5133242019-02-28 11:05:19 -0700186
David Brownbf32c272021-06-16 17:11:37 -0600187 let ram = RamData::new(&slots);
188
Fabio Utzig114a6472019-11-28 10:24:09 -0300189 Ok(ImagesBuilder {
David Brown4dfb33c2021-03-10 05:15:45 -0700190 flash,
191 areadesc,
192 slots,
David Brownbf32c272021-06-16 17:11:37 -0600193 ram,
David Brown5bc62c62019-03-05 12:11:48 -0700194 })
David Browne5133242019-02-28 11:05:19 -0700195 }
196
197 pub fn each_device<F>(f: F)
198 where F: Fn(Self)
199 {
200 for &dev in ALL_DEVICES {
David Brown95de4502019-11-15 12:01:34 -0700201 for &align in test_alignments() {
David Browne5133242019-02-28 11:05:19 -0700202 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700203 match Self::new(dev, align, erased_val) {
Fabio Utzig114a6472019-11-28 10:24:09 -0300204 Ok(run) => f(run),
205 Err(msg) => warn!("Skipping {}: {}", dev, msg),
David Brown5bc62c62019-03-05 12:11:48 -0700206 }
David Browne5133242019-02-28 11:05:19 -0700207 }
208 }
209 }
210 }
211
212 /// Construct an `Images` that doesn't expect an upgrade to happen.
David Brownc3898d62019-08-05 14:20:02 -0600213 pub fn make_no_upgrade_image(self, deps: &DepTest) -> Images {
214 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700215 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600216 let ram = self.ram.clone(); // TODO: This is wasteful.
David Brownc3898d62019-08-05 14:20:02 -0600217 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
218 let dep: Box<dyn Depender> = if num_images > 1 {
219 Box::new(PairDep::new(num_images, image_num, deps))
220 } else {
David Brown2ee5f7f2020-01-13 14:04:01 -0700221 Box::new(BoringDep::new(image_num, deps))
David Brownc3898d62019-08-05 14:20:02 -0600222 };
David Browna62c3eb2021-10-25 16:32:40 -0600223 let primaries = install_image(&mut flash, &slots[0],
David Brown07dd5f02021-10-26 16:43:15 -0600224 maximal(42784), &ram, &*dep, false);
David Brown873be312019-09-03 12:22:32 -0600225 let upgrades = match deps.depends[image_num] {
226 DepType::NoUpgrade => install_no_image(),
David Browna62c3eb2021-10-25 16:32:40 -0600227 _ => install_image(&mut flash, &slots[1],
David Brown07dd5f02021-10-26 16:43:15 -0600228 maximal(46928), &ram, &*dep, false)
David Brown873be312019-09-03 12:22:32 -0600229 };
David Brown84b49f72019-03-01 10:58:22 -0700230 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700231 slots,
232 primaries,
233 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700234 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600235 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700236 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700237 flash,
David Browne5133242019-02-28 11:05:19 -0700238 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700239 images,
David Browne5133242019-02-28 11:05:19 -0700240 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600241 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700242 }
243 }
244
David Brownc3898d62019-08-05 14:20:02 -0600245 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
246 let mut images = self.make_no_upgrade_image(deps);
David Brown84b49f72019-03-01 10:58:22 -0700247 for image in &images.images {
248 mark_upgrade(&mut images.flash, &image.slots[1]);
249 }
David Browne5133242019-02-28 11:05:19 -0700250
David Brown6db44d72021-05-26 16:22:58 -0600251 // The count is meaningless if no flash operations are performed.
252 if !Caps::modifies_flash() {
253 return images;
254 }
255
David Browne5133242019-02-28 11:05:19 -0700256 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300257 let total_count = match images.run_basic_upgrade(permanent) {
David Brown8973f552021-03-10 05:21:11 -0700258 Some(v) => v,
259 None =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600260 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
261 0
262 } else {
263 panic!("Unable to perform basic upgrade");
264 }
David Browne5133242019-02-28 11:05:19 -0700265 };
266
267 images.total_count = Some(total_count);
268 images
269 }
270
271 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700272 let mut bad_flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600273 let ram = self.ram.clone(); // TODO: Avoid this clone.
David Brownc3898d62019-08-05 14:20:02 -0600274 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
David Brown2ee5f7f2020-01-13 14:04:01 -0700275 let dep = BoringDep::new(image_num, &NO_DEPS);
David Browna62c3eb2021-10-25 16:32:40 -0600276 let primaries = install_image(&mut bad_flash, &slots[0],
David Brown07dd5f02021-10-26 16:43:15 -0600277 maximal(32784), &ram, &dep, false);
David Browna62c3eb2021-10-25 16:32:40 -0600278 let upgrades = install_image(&mut bad_flash, &slots[1],
David Brown07dd5f02021-10-26 16:43:15 -0600279 maximal(41928), &ram, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700280 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700281 slots,
282 primaries,
283 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700284 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700285 Images {
David Brown76101572019-02-28 11:29:03 -0700286 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700287 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700288 images,
David Browne5133242019-02-28 11:05:19 -0700289 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600290 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700291 }
292 }
293
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300294 pub fn make_erased_secondary_image(self) -> Images {
295 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600296 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300297 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
298 let dep = BoringDep::new(image_num, &NO_DEPS);
David Browna62c3eb2021-10-25 16:32:40 -0600299 let primaries = install_image(&mut flash, &slots[0],
David Brown07dd5f02021-10-26 16:43:15 -0600300 maximal(32784), &ram, &dep, false);
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300301 let upgrades = install_no_image();
302 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700303 slots,
304 primaries,
305 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300306 }}).collect();
307 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700308 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300309 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700310 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300311 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600312 ram: self.ram,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300313 }
314 }
315
Fabio Utzigd0157342020-10-02 15:22:11 -0300316 pub fn make_bootstrap_image(self) -> Images {
317 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600318 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzigd0157342020-10-02 15:22:11 -0300319 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
320 let dep = BoringDep::new(image_num, &NO_DEPS);
321 let primaries = install_no_image();
David Browna62c3eb2021-10-25 16:32:40 -0600322 let upgrades = install_image(&mut flash, &slots[1],
David Brown07dd5f02021-10-26 16:43:15 -0600323 maximal(32784), &ram, &dep, false);
Fabio Utzigd0157342020-10-02 15:22:11 -0300324 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700325 slots,
326 primaries,
327 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300328 }}).collect();
329 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700330 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300331 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700332 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300333 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600334 ram: self.ram,
Fabio Utzigd0157342020-10-02 15:22:11 -0300335 }
336 }
337
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +0200338 pub fn make_oversized_bootstrap_image(self) -> Images {
339 let mut flash = self.flash;
340 let ram = self.ram.clone(); // TODO: Avoid this clone.
341 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
342 let dep = BoringDep::new(image_num, &NO_DEPS);
343 let primaries = install_no_image();
344 let upgrades = install_image(&mut flash, &slots[1],
345 ImageSize::Oversized, &ram, &dep, false);
346 OneImage {
347 slots,
348 primaries,
349 upgrades,
350 }}).collect();
351 Images {
352 flash,
353 areadesc: self.areadesc,
354 images,
355 total_count: None,
356 ram: self.ram,
357 }
358 }
359
David Browne5133242019-02-28 11:05:19 -0700360 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300361 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700362 match device {
363 DeviceName::Stm32f4 => {
364 // STM style flash. Large sectors, with a large scratch area.
Fabio Utzig5577cbd2021-12-10 17:34:28 -0300365 // The flash layout as described is not present in any real STM32F4 device, but it
366 // serves to exercise support for sectors of varying sizes inside a single slot,
367 // as long as they are compatible in both slots and all fit in the scratch.
368 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024, 64 * 1024,
369 32 * 1024, 32 * 1024, 64 * 1024,
370 32 * 1024, 32 * 1024, 64 * 1024,
371 128 * 1024],
David Brown76101572019-02-28 11:29:03 -0700372 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700373 let dev_id = 0;
374 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700375 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700376 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
377 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
378 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
379
David Brown76101572019-02-28 11:29:03 -0700380 let mut flash = SimMultiFlash::new();
381 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300382 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700383 }
384 DeviceName::K64f => {
385 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700386 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700387
388 let dev_id = 0;
389 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700390 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700391 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
392 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
393 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
394
David Brown76101572019-02-28 11:29:03 -0700395 let mut flash = SimMultiFlash::new();
396 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300397 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700398 }
399 DeviceName::K64fBig => {
400 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
401 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700402 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700403
404 let dev_id = 0;
405 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700406 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700407 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
408 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
409 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
410
David Brown76101572019-02-28 11:29:03 -0700411 let mut flash = SimMultiFlash::new();
412 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300413 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700414 }
415 DeviceName::Nrf52840 => {
416 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
417 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700418 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700419
420 let dev_id = 0;
421 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700422 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700423 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
424 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
425 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
426
David Brown76101572019-02-28 11:29:03 -0700427 let mut flash = SimMultiFlash::new();
428 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300429 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700430 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300431 DeviceName::Nrf52840UnequalSlots => {
432 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
433
434 let dev_id = 0;
435 let mut areadesc = AreaDesc::new();
436 areadesc.add_flash_sectors(dev_id, &dev);
437 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
438 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
439
440 let mut flash = SimMultiFlash::new();
441 flash.insert(dev_id, dev);
442 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
443 }
David Browne5133242019-02-28 11:05:19 -0700444 DeviceName::Nrf52840SpiFlash => {
445 // Simulate nrf52840 with external SPI flash. The external SPI flash
446 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700447 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
448 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700449
450 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700451 areadesc.add_flash_sectors(0, &dev0);
452 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700453
454 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
455 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
456 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
457
David Brown76101572019-02-28 11:29:03 -0700458 let mut flash = SimMultiFlash::new();
459 flash.insert(0, dev0);
460 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300461 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700462 }
David Brown2bff6472019-03-05 13:58:35 -0700463 DeviceName::K64fMulti => {
464 // NXP style flash, but larger, to support multiple images.
465 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
466
467 let dev_id = 0;
468 let mut areadesc = AreaDesc::new();
469 areadesc.add_flash_sectors(dev_id, &dev);
470 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
471 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
472 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
473 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
474 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
475
476 let mut flash = SimMultiFlash::new();
477 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300478 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700479 }
David Browne5133242019-02-28 11:05:19 -0700480 }
481 }
David Brownc3898d62019-08-05 14:20:02 -0600482
483 pub fn num_images(&self) -> usize {
484 self.slots.len()
485 }
David Browne5133242019-02-28 11:05:19 -0700486}
487
David Brown5c9e0f12019-01-09 16:34:33 -0700488impl Images {
489 /// A simple upgrade without forced failures.
490 ///
491 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700492 /// inject failures at chosen steps. Returns None if it was unable to
493 /// count the operations in a basic upgrade.
494 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300495 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700496 info!("Total flash operation count={}", total_count);
497
David Brown84b49f72019-03-01 10:58:22 -0700498 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700499 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700500 None
David Brown5c9e0f12019-01-09 16:34:33 -0700501 } else {
David Brown8973f552021-03-10 05:21:11 -0700502 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700503 }
504 }
505
Fabio Utzigd0157342020-10-02 15:22:11 -0300506 pub fn run_bootstrap(&self) -> bool {
507 let mut flash = self.flash.clone();
508 let mut fails = 0;
509
510 if Caps::Bootstrap.present() {
511 info!("Try bootstraping image in the primary");
512
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100513 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigd0157342020-10-02 15:22:11 -0300514 warn!("Failed first boot");
515 fails += 1;
516 }
517
518 if !self.verify_images(&flash, 0, 1) {
519 warn!("Image in the first slot was not bootstrapped");
520 fails += 1;
521 }
522
523 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
524 BOOT_FLAG_SET, BOOT_FLAG_SET) {
525 warn!("Mismatched trailer for the primary slot");
526 fails += 1;
527 }
528 }
529
530 if fails > 0 {
531 error!("Expected trailer on secondary slot to be erased");
532 }
533
534 fails > 0
535 }
536
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +0200537 pub fn run_oversized_bootstrap(&self) -> bool {
538 let mut flash = self.flash.clone();
539 let mut fails = 0;
540
541 if Caps::Bootstrap.present() {
542 info!("Try bootstraping image in the primary");
543
544 let boot_result = c::boot_go(&mut flash, &self.areadesc, None, None, false).interrupted();
545
546 if boot_result {
547 warn!("Failed first boot");
548 fails += 1;
549 }
550
551 if self.verify_images(&flash, 0, 1) {
552 warn!("Image in the first slot was not bootstrapped");
553 fails += 1;
554 }
555
556 if self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
557 BOOT_FLAG_SET, BOOT_FLAG_SET) {
558 warn!("Mismatched trailer for the primary slot");
559 fails += 1;
560 }
561 }
562
563 if fails > 0 {
564 error!("Expected trailer on secondary slot to be erased");
565 }
566
567 fails > 0
568 }
569
Fabio Utzigd0157342020-10-02 15:22:11 -0300570
David Brownc3898d62019-08-05 14:20:02 -0600571 /// Test a simple upgrade, with dependencies given, and verify that the
572 /// image does as is described in the test.
573 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600574 if !Caps::modifies_flash() {
575 return false;
576 }
577
David Brownc3898d62019-08-05 14:20:02 -0600578 let (flash, _) = self.try_upgrade(None, true);
579
580 self.verify_dep_images(&flash, deps)
581 }
582
Fabio Utzigf5480c72019-11-28 10:41:57 -0300583 fn is_swap_upgrade(&self) -> bool {
584 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
585 }
586
David Brown5c9e0f12019-01-09 16:34:33 -0700587 pub fn run_basic_revert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600588 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700589 return false;
590 }
David Brown5c9e0f12019-01-09 16:34:33 -0700591
David Brown5c9e0f12019-01-09 16:34:33 -0700592 let mut fails = 0;
593
594 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300595 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700596 for count in 2 .. 5 {
597 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700598 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700599 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700600 error!("Revert failure on count {}", count);
601 fails += 1;
602 }
603 }
604 }
605
606 fails > 0
607 }
608
609 pub fn run_perm_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600610 if !Caps::modifies_flash() {
611 return false;
612 }
613
David Brown5c9e0f12019-01-09 16:34:33 -0700614 let mut fails = 0;
615 let total_flash_ops = self.total_count.unwrap();
616
617 // Let's try an image halfway through.
618 for i in 1 .. total_flash_ops {
619 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300620 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700621 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700622 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700623 warn!("FAIL at step {} of {}", i, total_flash_ops);
624 fails += 1;
625 }
626
David Brown84b49f72019-03-01 10:58:22 -0700627 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
628 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100629 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700630 fails += 1;
631 }
632
David Brown84b49f72019-03-01 10:58:22 -0700633 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
634 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100635 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700636 fails += 1;
637 }
638
David Brownaec56b22021-03-10 05:22:07 -0700639 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
640 warn!("Secondary slot FAIL at step {} of {}",
641 i, total_flash_ops);
642 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700643 }
644 }
645
646 if fails > 0 {
647 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
648 fails as f32 * 100.0 / total_flash_ops as f32);
649 }
650
651 fails > 0
652 }
653
David Brown5c9e0f12019-01-09 16:34:33 -0700654 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600655 if !Caps::modifies_flash() {
656 return false;
657 }
658
David Brown5c9e0f12019-01-09 16:34:33 -0700659 let mut fails = 0;
660 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700661 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700662 info!("Random interruptions at reset points={:?}", total_counts);
663
David Brown84b49f72019-03-01 10:58:22 -0700664 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300665 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700666 // TODO: This result is ignored.
667 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700668 } else {
669 true
670 };
David Vincze2d736ad2019-02-18 11:50:22 +0100671 if !primary_slot_ok || !secondary_slot_ok {
672 error!("Image mismatch after random interrupts: primary slot={} \
673 secondary slot={}",
674 if primary_slot_ok { "ok" } else { "fail" },
675 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700676 fails += 1;
677 }
David Brown84b49f72019-03-01 10:58:22 -0700678 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
679 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100680 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700681 fails += 1;
682 }
David Brown84b49f72019-03-01 10:58:22 -0700683 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
684 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100685 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700686 fails += 1;
687 }
688
689 if fails > 0 {
690 error!("Error testing perm upgrade with {} fails", total_fails);
691 }
692
693 fails > 0
694 }
695
David Brown5c9e0f12019-01-09 16:34:33 -0700696 pub fn run_revert_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600697 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700698 return false;
699 }
David Brown5c9e0f12019-01-09 16:34:33 -0700700
David Brown5c9e0f12019-01-09 16:34:33 -0700701 let mut fails = 0;
702
Fabio Utzigf5480c72019-11-28 10:41:57 -0300703 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300704 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700705 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700706 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700707 error!("Revert failed at interruption {}", i);
708 fails += 1;
709 }
710 }
711 }
712
713 fails > 0
714 }
715
David Brown5c9e0f12019-01-09 16:34:33 -0700716 pub fn run_norevert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600717 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700718 return false;
719 }
David Brown5c9e0f12019-01-09 16:34:33 -0700720
David Brown76101572019-02-28 11:29:03 -0700721 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700722 let mut fails = 0;
723
724 info!("Try norevert");
725
726 // First do a normal upgrade...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100727 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700728 warn!("Failed first boot");
729 fails += 1;
730 }
731
732 //FIXME: copy_done is written by boot_go, is it ok if no copy
733 // was ever done?
734
David Brown84b49f72019-03-01 10:58:22 -0700735 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100736 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700737 fails += 1;
738 }
David Brown84b49f72019-03-01 10:58:22 -0700739 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
740 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100741 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700742 fails += 1;
743 }
David Brown84b49f72019-03-01 10:58:22 -0700744 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
745 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100746 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700747 fails += 1;
748 }
749
David Vincze2d736ad2019-02-18 11:50:22 +0100750 // Marks image in the primary slot as permanent,
751 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700752 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700753
David Brown84b49f72019-03-01 10:58:22 -0700754 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
755 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100756 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700757 fails += 1;
758 }
759
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100760 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700761 warn!("Failed second boot");
762 fails += 1;
763 }
764
David Brown84b49f72019-03-01 10:58:22 -0700765 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
766 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100767 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700768 fails += 1;
769 }
David Brown84b49f72019-03-01 10:58:22 -0700770 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700771 warn!("Failed image verification");
772 fails += 1;
773 }
774
775 if fails > 0 {
776 error!("Error running upgrade without revert");
777 }
778
779 fails > 0
780 }
781
David Brown2ee5f7f2020-01-13 14:04:01 -0700782 // Test that an upgrade is rejected. Assumes that the image was build
783 // such that the upgrade is instead a downgrade.
784 pub fn run_nodowngrade(&self) -> bool {
785 if !Caps::DowngradePrevention.present() {
786 return false;
787 }
788
789 let mut flash = self.flash.clone();
790 let mut fails = 0;
791
792 info!("Try no downgrade");
793
794 // First, do a normal upgrade.
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100795 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700796 warn!("Failed first boot");
797 fails += 1;
798 }
799
800 if !self.verify_images(&flash, 0, 0) {
801 warn!("Failed verification after downgrade rejection");
802 fails += 1;
803 }
804
805 if fails > 0 {
806 error!("Error testing downgrade rejection");
807 }
808
809 fails > 0
810 }
811
David Vincze2d736ad2019-02-18 11:50:22 +0100812 // Tests a new image written to the primary slot that already has magic and
813 // image_ok set while there is no image on the secondary slot, so no revert
814 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700815 pub fn run_norevert_newimage(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600816 if !Caps::modifies_flash() {
817 info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
818 return false;
819 }
820
David Brown76101572019-02-28 11:29:03 -0700821 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700822 let mut fails = 0;
823
824 info!("Try non-revert on imgtool generated image");
825
David Brown84b49f72019-03-01 10:58:22 -0700826 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700827
David Vincze2d736ad2019-02-18 11:50:22 +0100828 // This simulates writing an image created by imgtool to
829 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700830 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
831 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100832 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700833 fails += 1;
834 }
835
836 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100837 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700838 warn!("Failed first boot");
839 fails += 1;
840 }
841
842 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700843 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700844 warn!("Failed image verification");
845 fails += 1;
846 }
David Brown84b49f72019-03-01 10:58:22 -0700847 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
848 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100849 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700850 fails += 1;
851 }
David Brown84b49f72019-03-01 10:58:22 -0700852 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
853 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100854 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700855 fails += 1;
856 }
857
858 if fails > 0 {
859 error!("Expected a non revert with new image");
860 }
861
862 fails > 0
863 }
864
David Vincze2d736ad2019-02-18 11:50:22 +0100865 // Tests a new image written to the primary slot that already has magic and
866 // image_ok set while there is no image on the secondary slot, so no revert
867 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700868 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700869 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700870 let mut fails = 0;
871
872 info!("Try upgrade image with bad signature");
873
David Brown6db44d72021-05-26 16:22:58 -0600874 // Only perform this test if an upgrade is expected to happen.
875 if !Caps::modifies_flash() {
876 info!("Skipping upgrade image with bad signature");
877 return false;
878 }
879
David Brown84b49f72019-03-01 10:58:22 -0700880 self.mark_upgrades(&mut flash, 0);
881 self.mark_permanent_upgrades(&mut flash, 0);
882 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700883
David Brown84b49f72019-03-01 10:58:22 -0700884 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
885 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100886 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700887 fails += 1;
888 }
889
890 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100891 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700892 warn!("Failed first boot");
893 fails += 1;
894 }
895
896 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700897 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700898 warn!("Failed image verification");
899 fails += 1;
900 }
David Brown84b49f72019-03-01 10:58:22 -0700901 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
902 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100903 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700904 fails += 1;
905 }
906
907 if fails > 0 {
908 error!("Expected an upgrade failure when image has bad signature");
909 }
910
911 fails > 0
912 }
913
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300914 // Should detect there is a leftover trailer in an otherwise erased
915 // secondary slot and erase its trailer.
916 pub fn run_secondary_leftover_trailer(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600917 if !Caps::modifies_flash() {
918 return false;
919 }
920
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300921 let mut flash = self.flash.clone();
922 let mut fails = 0;
923
924 info!("Try with a leftover trailer in the secondary; must be erased");
925
926 // Add a trailer on the secondary slot
927 self.mark_permanent_upgrades(&mut flash, 1);
928 self.mark_upgrades(&mut flash, 1);
929
930 // Run the bootloader...
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100931 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300932 warn!("Failed first boot");
933 fails += 1;
934 }
935
936 // State should not have changed
937 if !self.verify_images(&flash, 0, 0) {
938 warn!("Failed image verification");
939 fails += 1;
940 }
941 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
942 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
943 warn!("Mismatched trailer for the secondary slot");
944 fails += 1;
945 }
946
947 if fails > 0 {
948 error!("Expected trailer on secondary slot to be erased");
949 }
950
951 fails > 0
952 }
953
David Brown5c9e0f12019-01-09 16:34:33 -0700954 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300955 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700956 }
957
David Brown5c9e0f12019-01-09 16:34:33 -0700958 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300959 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700960 }
961
962 /// This test runs a simple upgrade with no fails in the images, but
963 /// allowing for fails in the status area. This should run to the end
964 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700965 pub fn run_with_status_fails_complete(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600966 if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700967 return false;
968 }
969
David Brown76101572019-02-28 11:29:03 -0700970 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700971 let mut fails = 0;
972
973 info!("Try swap with status fails");
974
David Brown84b49f72019-03-01 10:58:22 -0700975 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700976 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700977
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100978 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brownc423ac42021-06-04 13:47:34 -0600979 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700980 warn!("Failed!");
981 fails += 1;
982 }
983
984 // Failed writes to the marked "bad" region don't assert anymore.
985 // Any detected assert() is happening in another part of the code.
David Brownc423ac42021-06-04 13:47:34 -0600986 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -0700987 warn!("At least one assert() was called");
988 fails += 1;
989 }
990
David Brown84b49f72019-03-01 10:58:22 -0700991 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
992 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100993 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700994 fails += 1;
995 }
996
David Brown84b49f72019-03-01 10:58:22 -0700997 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700998 warn!("Failed image verification");
999 fails += 1;
1000 }
1001
David Vincze2d736ad2019-02-18 11:50:22 +01001002 info!("validate primary slot enabled; \
1003 re-run of boot_go should just work");
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001004 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -07001005 warn!("Failed!");
1006 fails += 1;
1007 }
1008
1009 if fails > 0 {
1010 error!("Error running upgrade with status write fails");
1011 }
1012
1013 fails > 0
1014 }
1015
1016 /// This test runs a simple upgrade with no fails in the images, but
1017 /// allowing for fails in the status area. This should run to the end
1018 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -07001019 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -06001020 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -07001021 false
David Vincze2d736ad2019-02-18 11:50:22 +01001022 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -07001023
David Brown76101572019-02-28 11:29:03 -07001024 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001025 let mut fails = 0;
1026 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -07001027
David Brown85904a82019-01-11 13:45:12 -07001028 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -07001029
David Brown85904a82019-01-11 13:45:12 -07001030 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -07001031
David Brown84b49f72019-03-01 10:58:22 -07001032 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001033 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -07001034
1035 // Should not fail, writing to bad regions does not assert
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001036 let asserts = c::boot_go(&mut flash, &self.areadesc,
1037 Some(&mut count), None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001038 if asserts != 0 {
1039 warn!("At least one assert() was called");
1040 fails += 1;
1041 }
1042
David Brown76101572019-02-28 11:29:03 -07001043 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -07001044
1045 info!("Resuming an interrupted swap operation");
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001046 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1047 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001048
1049 // This might throw no asserts, for large sector devices, where
1050 // a single failure writing is indistinguishable from no failure,
1051 // or throw a single assert for small sector devices that fail
1052 // multiple times...
1053 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +01001054 warn!("Expected single assert validating the primary slot, \
1055 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -07001056 fails += 1;
1057 }
1058
1059 if fails > 0 {
1060 error!("Error running upgrade with status write fails");
1061 }
1062
1063 fails > 0
1064 } else {
David Brown76101572019-02-28 11:29:03 -07001065 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001066 let mut fails = 0;
1067
1068 info!("Try interrupted swap with status fails");
1069
David Brown84b49f72019-03-01 10:58:22 -07001070 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001071 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -07001072
1073 // This is expected to fail while writing to bad regions...
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001074 let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1075 true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001076 if asserts == 0 {
1077 warn!("No assert() detected");
1078 fails += 1;
1079 }
1080
1081 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -07001082 }
David Brown5c9e0f12019-01-09 16:34:33 -07001083 }
1084
David Brown0dfb8102021-06-03 15:29:11 -06001085 /// Test the direct XIP configuration. With this mode, flash images are never moved, and the
1086 /// bootloader merely selects which partition is the proper one to boot.
1087 pub fn run_direct_xip(&self) -> bool {
1088 if !Caps::DirectXip.present() {
1089 return false;
1090 }
1091
1092 // Clone the flash so we can tell if unchanged.
1093 let mut flash = self.flash.clone();
1094
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001095 let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
David Brown0dfb8102021-06-03 15:29:11 -06001096
1097 // Ensure the boot was successful.
1098 let resp = if let Some(resp) = result.resp() {
1099 resp
1100 } else {
1101 panic!("Boot didn't return a valid result");
1102 };
1103
1104 // This configuration should always try booting from the first upgrade slot.
1105 if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
1106 assert_eq!(offset, resp.image_off as usize);
1107 assert_eq!(dev_id, resp.flash_dev_id);
1108 } else {
1109 panic!("Unable to find upgrade image");
1110 }
1111 false
1112 }
1113
David Brown8a4e23b2021-06-11 10:29:01 -06001114 /// Test the ram-loading.
1115 pub fn run_ram_load(&self) -> bool {
1116 if !Caps::RamLoad.present() {
1117 return false;
1118 }
1119
1120 // Clone the flash so we can tell if unchanged.
1121 let mut flash = self.flash.clone();
1122
David Brownf17d3912021-06-23 16:10:51 -06001123 // Setup ram based on the ram configuration we determined earlier for the images.
1124 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
David Brown8a4e23b2021-06-11 10:29:01 -06001125
David Brownf17d3912021-06-23 16:10:51 -06001126 // println!("Ram: {:#?}", self.ram);
David Brown8a4e23b2021-06-11 10:29:01 -06001127
David Brownf17d3912021-06-23 16:10:51 -06001128 // Verify that the images area loaded into this.
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001129 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None,
1130 None, true));
David Brown8a4e23b2021-06-11 10:29:01 -06001131 if !result.success() {
David Brownf17d3912021-06-23 16:10:51 -06001132 error!("Failed to execute ram-load");
David Brown8a4e23b2021-06-11 10:29:01 -06001133 return true;
1134 }
1135
David Brownf17d3912021-06-23 16:10:51 -06001136 // Verify each image.
1137 for image in &self.images {
1138 let place = self.ram.lookup(&image.slots[0]);
1139 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1140 place.size as usize);
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001141 let src_sz = image.upgrades.size();
1142 if src_sz > ram_image.len() {
David Brownf17d3912021-06-23 16:10:51 -06001143 error!("Image ended up too large, nonsensical");
1144 return true;
1145 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001146 let src_image = &image.upgrades.plain[0..src_sz];
1147 let ram_image = &ram_image[0..src_sz];
David Brownf17d3912021-06-23 16:10:51 -06001148 if ram_image != src_image {
1149 error!("Image not loaded correctly");
1150 return true;
1151 }
1152
1153 }
1154
1155 return false;
David Brown8a4e23b2021-06-11 10:29:01 -06001156 }
1157
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001158 /// Test the split ram-loading.
1159 pub fn run_split_ram_load(&self) -> bool {
1160 if !Caps::RamLoad.present() {
1161 return false;
1162 }
1163
1164 // Clone the flash so we can tell if unchanged.
1165 let mut flash = self.flash.clone();
1166
1167 // Setup ram based on the ram configuration we determined earlier for the images.
1168 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1169
1170 for (idx, _image) in (&self.images).iter().enumerate() {
1171 // Verify that the images area loaded into this.
1172 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc,
1173 None, Some(idx as i32), true));
1174 if !result.success() {
1175 error!("Failed to execute ram-load");
1176 return true;
1177 }
1178 }
1179
1180 // Verify each image.
1181 for image in &self.images {
1182 let place = self.ram.lookup(&image.slots[0]);
1183 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1184 place.size as usize);
1185 let src_sz = image.upgrades.size();
1186 if src_sz > ram_image.len() {
1187 error!("Image ended up too large, nonsensical");
1188 return true;
1189 }
1190 let src_image = &image.upgrades.plain[0..src_sz];
1191 let ram_image = &ram_image[0..src_sz];
1192 if ram_image != src_image {
1193 error!("Image not loaded correctly");
1194 return true;
1195 }
1196
1197 }
1198
1199 return false;
1200 }
1201
David Brown5c9e0f12019-01-09 16:34:33 -07001202 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -07001203 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001204 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -07001205 if Caps::OverwriteUpgrade.present() {
1206 return;
1207 }
1208
David Brown84b49f72019-03-01 10:58:22 -07001209 // Set this for each image.
1210 for image in &self.images {
1211 let dev_id = &image.slots[slot].dev_id;
1212 let dev = flash.get_mut(&dev_id).unwrap();
1213 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001214 let off = &image.slots[slot].base_off;
1215 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -07001216 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -07001217
David Brown84b49f72019-03-01 10:58:22 -07001218 // Mark the status area as a bad area
1219 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1220 }
David Brown5c9e0f12019-01-09 16:34:33 -07001221 }
1222
David Brown76101572019-02-28 11:29:03 -07001223 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001224 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001225 return;
1226 }
1227
David Brown84b49f72019-03-01 10:58:22 -07001228 for image in &self.images {
1229 let dev_id = &image.slots[slot].dev_id;
1230 let dev = flash.get_mut(&dev_id).unwrap();
1231 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001232
David Brown84b49f72019-03-01 10:58:22 -07001233 // Disabling write verification the only assert triggered by
1234 // boot_go should be checking for integrity of status bytes.
1235 dev.set_verify_writes(false);
1236 }
David Brown5c9e0f12019-01-09 16:34:33 -07001237 }
1238
David Browndb505822019-03-01 10:04:20 -07001239 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1240 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001241 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001242 // Clone the flash to have a new copy.
1243 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001244
Fabio Utziged4a5362019-07-30 12:43:23 -03001245 if permanent {
1246 self.mark_permanent_upgrades(&mut flash, 1);
1247 }
David Brown5c9e0f12019-01-09 16:34:33 -07001248
David Browndb505822019-03-01 10:04:20 -07001249 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001250
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001251 let (first_interrupted, count) = match c::boot_go(&mut flash,
1252 &self.areadesc,
1253 Some(&mut counter),
1254 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001255 x if x.interrupted() => (true, stop.unwrap()),
1256 x if x.success() => (false, -counter),
1257 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001258 };
David Brown5c9e0f12019-01-09 16:34:33 -07001259
David Browndb505822019-03-01 10:04:20 -07001260 counter = 0;
1261 if first_interrupted {
1262 // fl.dump();
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001263 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1264 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001265 x if x.interrupted() => panic!("Shouldn't stop again"),
1266 x if x.success() => (),
1267 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001268 }
1269 }
David Brown5c9e0f12019-01-09 16:34:33 -07001270
David Browndb505822019-03-01 10:04:20 -07001271 (flash, count - counter)
1272 }
1273
1274 fn try_revert(&self, count: usize) -> SimMultiFlash {
1275 let mut flash = self.flash.clone();
1276
1277 // fl.write_file("image0.bin").unwrap();
1278 for i in 0 .. count {
1279 info!("Running boot pass {}", i + 1);
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001280 assert!(c::boot_go(&mut flash, &self.areadesc, None, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001281 }
1282 flash
1283 }
1284
1285 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1286 let mut flash = self.flash.clone();
1287 let mut fails = 0;
1288
1289 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001290 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1291 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001292 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001293 fails += 1;
1294 }
1295
Fabio Utzig8af7f792019-07-30 12:40:01 -03001296 // In a multi-image setup, copy done might be set if any number of
1297 // images was already successfully swapped.
1298 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1299 warn!("copy_done should be unset");
1300 fails += 1;
1301 }
1302
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001303 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001304 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001305 fails += 1;
1306 }
1307
David Brown84b49f72019-03-01 10:58:22 -07001308 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001309 warn!("Image in the primary slot before revert is invalid at stop={}",
1310 stop);
1311 fails += 1;
1312 }
David Brown84b49f72019-03-01 10:58:22 -07001313 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001314 warn!("Image in the secondary slot before revert is invalid at stop={}",
1315 stop);
1316 fails += 1;
1317 }
David Brown84b49f72019-03-01 10:58:22 -07001318 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1319 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001320 warn!("Mismatched trailer for the primary slot before revert");
1321 fails += 1;
1322 }
David Brown84b49f72019-03-01 10:58:22 -07001323 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1324 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001325 warn!("Mismatched trailer for the secondary slot before revert");
1326 fails += 1;
1327 }
1328
1329 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001330 let mut counter = stop;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001331 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1332 false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001333 warn!("Should have stopped revert at interruption point");
1334 fails += 1;
1335 }
1336
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001337 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001338 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001339 fails += 1;
1340 }
1341
David Brown84b49f72019-03-01 10:58:22 -07001342 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001343 warn!("Image in the primary slot after revert is invalid at stop={}",
1344 stop);
1345 fails += 1;
1346 }
David Brown84b49f72019-03-01 10:58:22 -07001347 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001348 warn!("Image in the secondary slot after revert is invalid at stop={}",
1349 stop);
1350 fails += 1;
1351 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001352
David Brown84b49f72019-03-01 10:58:22 -07001353 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1354 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001355 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001356 fails += 1;
1357 }
David Brown84b49f72019-03-01 10:58:22 -07001358 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1359 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001360 warn!("Mismatched trailer for the secondary slot after revert");
1361 fails += 1;
1362 }
1363
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001364 if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001365 warn!("Should have finished 3rd boot");
1366 fails += 1;
1367 }
1368
1369 if !self.verify_images(&flash, 0, 0) {
1370 warn!("Image in the primary slot is invalid on 1st boot after revert");
1371 fails += 1;
1372 }
1373 if !self.verify_images(&flash, 1, 1) {
1374 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1375 fails += 1;
1376 }
1377
David Browndb505822019-03-01 10:04:20 -07001378 fails > 0
1379 }
1380
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001381
David Browndb505822019-03-01 10:04:20 -07001382 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1383 let mut flash = self.flash.clone();
1384
David Brown84b49f72019-03-01 10:58:22 -07001385 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001386
1387 let mut rng = rand::thread_rng();
1388 let mut resets = vec![0i32; count];
1389 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001390 for reset in &mut resets {
David Brown9c6322f2021-08-19 13:03:39 -06001391 let reset_counter = rng.gen_range(1 ..= remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001392 let mut counter = reset_counter;
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001393 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1394 None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001395 x if x.interrupted() => (),
1396 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001397 }
1398 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001399 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001400 }
1401
Raef Coles3fd3ecc2021-10-15 11:14:12 +01001402 match c::boot_go(&mut flash, &self.areadesc, None, None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001403 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1404 x if x.success() => (),
1405 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001406 }
David Brown5c9e0f12019-01-09 16:34:33 -07001407
David Browndb505822019-03-01 10:04:20 -07001408 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001409 }
David Brown84b49f72019-03-01 10:58:22 -07001410
1411 /// Verify the image in the given flash device, the specified slot
1412 /// against the expected image.
1413 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001414 self.images.iter().all(|image| {
1415 verify_image(flash, &image.slots[slot],
1416 match against {
1417 0 => &image.primaries,
1418 1 => &image.upgrades,
1419 _ => panic!("Invalid 'against'")
1420 })
1421 })
David Brown84b49f72019-03-01 10:58:22 -07001422 }
1423
David Brownc3898d62019-08-05 14:20:02 -06001424 /// Verify the images, according to the dependency test.
1425 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1426 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1427 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1428 if !verify_image(flash, &image.slots[0],
1429 match upgrade {
1430 UpgradeInfo::Upgraded => &image.upgrades,
1431 UpgradeInfo::Held => &image.primaries,
1432 }) {
1433 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1434 return true;
1435 }
1436 }
1437
1438 false
1439 }
1440
Fabio Utzig8af7f792019-07-30 12:40:01 -03001441 /// Verify that at least one of the trailers of the images have the
1442 /// specified values.
1443 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1444 magic: Option<u8>, image_ok: Option<u8>,
1445 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001446 self.images.iter().any(|image| {
1447 verify_trailer(flash, &image.slots[slot],
1448 magic, image_ok, copy_done)
1449 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001450 }
1451
David Brown84b49f72019-03-01 10:58:22 -07001452 /// Verify that the trailers of the images have the specified
1453 /// values.
1454 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1455 magic: Option<u8>, image_ok: Option<u8>,
1456 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001457 self.images.iter().all(|image| {
1458 verify_trailer(flash, &image.slots[slot],
1459 magic, image_ok, copy_done)
1460 })
David Brown84b49f72019-03-01 10:58:22 -07001461 }
1462
1463 /// Mark each of the images for permanent upgrade.
1464 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1465 for image in &self.images {
1466 mark_permanent_upgrade(flash, &image.slots[slot]);
1467 }
1468 }
1469
1470 /// Mark each of the images for permanent upgrade.
1471 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1472 for image in &self.images {
1473 mark_upgrade(flash, &image.slots[slot]);
1474 }
1475 }
David Brown297029a2019-08-13 14:29:51 -06001476
1477 /// Dump out the flash image(s) to one or more files for debugging
1478 /// purposes. The names will be written as either "{prefix}.mcubin" or
1479 /// "{prefix}-001.mcubin" depending on how many images there are.
1480 pub fn debug_dump(&self, prefix: &str) {
1481 for (id, fdev) in &self.flash {
1482 let name = if self.flash.len() == 1 {
1483 format!("{}.mcubin", prefix)
1484 } else {
1485 format!("{}-{:>0}.mcubin", prefix, id)
1486 };
1487 fdev.write_file(&name).unwrap();
1488 }
1489 }
David Brown5c9e0f12019-01-09 16:34:33 -07001490}
1491
David Brownbf32c272021-06-16 17:11:37 -06001492impl RamData {
David Brownf17d3912021-06-23 16:10:51 -06001493 // TODO: This is not correct. The second slot of each image should be at the same address as
1494 // the primary.
David Brownbf32c272021-06-16 17:11:37 -06001495 fn new(slots: &[[SlotInfo; 2]]) -> RamData {
1496 let mut addr = RAM_LOAD_ADDR;
1497 let mut places = BTreeMap::new();
David Brownf17d3912021-06-23 16:10:51 -06001498 // println!("Setup:-------------");
David Brownbf32c272021-06-16 17:11:37 -06001499 for imgs in slots {
1500 for si in imgs {
David Brownf17d3912021-06-23 16:10:51 -06001501 // println!("Setup: si: {:?}", si);
David Brownbf32c272021-06-16 17:11:37 -06001502 let offset = addr;
1503 let size = si.len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001504 places.insert(SlotKey {
1505 dev_id: si.dev_id,
David Brownf17d3912021-06-23 16:10:51 -06001506 base_off: si.base_off,
David Brownbf32c272021-06-16 17:11:37 -06001507 }, SlotPlace { offset, size });
David Brownf17d3912021-06-23 16:10:51 -06001508 // println!(" load: offset: {}, size: {}", offset, size);
David Brownbf32c272021-06-16 17:11:37 -06001509 }
David Brownf17d3912021-06-23 16:10:51 -06001510 addr += imgs[0].len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001511 }
1512 RamData {
1513 places,
1514 total: addr,
1515 }
1516 }
David Brownf17d3912021-06-23 16:10:51 -06001517
1518 /// Lookup the ram data associated with a given flash partition. We just panic if not present,
1519 /// because all slots used should be in the map.
1520 fn lookup(&self, slot: &SlotInfo) -> &SlotPlace {
1521 self.places.get(&SlotKey{dev_id: slot.dev_id, base_off: slot.base_off})
1522 .expect("RamData should contain all slots")
1523 }
David Brownbf32c272021-06-16 17:11:37 -06001524}
1525
David Brown5c9e0f12019-01-09 16:34:33 -07001526/// Show the flash layout.
1527#[allow(dead_code)]
1528fn show_flash(flash: &dyn Flash) {
1529 println!("---- Flash configuration ----");
1530 for sector in flash.sector_iter() {
1531 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1532 sector.num, sector.base, sector.size);
1533 }
David Brown599b2db2021-03-10 05:23:26 -07001534 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001535}
1536
David Browna62c3eb2021-10-25 16:32:40 -06001537#[derive(Debug)]
1538enum ImageSize {
1539 /// Make the image the specified given size.
1540 Given(usize),
1541 /// Make the image as large as it can be for the partition/device.
1542 Largest,
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001543 /// Make the image quite larger than it can be for the partition/device/
1544 Oversized,
David Browna62c3eb2021-10-25 16:32:40 -06001545}
1546
Andrzej Puzdrowski5b90dc82022-08-08 12:49:24 +02001547#[cfg(not(feature = "max-align-32"))]
1548fn tralier_estimation(dev: &dyn Flash) -> usize {
Andrzej Puzdrowski5b90dc82022-08-08 12:49:24 +02001549 c::boot_trailer_sz(dev.align() as u32) as usize
1550}
1551
1552#[cfg(feature = "max-align-32")]
1553fn tralier_estimation(dev: &dyn Flash) -> usize {
1554
1555 let sector_size = dev.sector_iter().next().unwrap().size as u32;
1556
1557 align_up(c::boot_trailer_sz(dev.align() as u32), sector_size) as usize
1558}
1559
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001560fn image_largest_trailer(dev: &dyn Flash) -> usize {
1561 // Using the header size we know, the trailer size, and the slot size, we can compute
1562 // the largest image possible.
1563 let trailer = if Caps::OverwriteUpgrade.present() {
1564 // This computation is incorrect, and we need to figure out the correct size.
1565 // c::boot_status_sz(dev.align() as u32) as usize
1566 16 + 4 * dev.align()
1567 } else if Caps::SwapUsingMove.present() {
1568 let sector_size = dev.sector_iter().next().unwrap().size as u32;
1569 align_up(c::boot_trailer_sz(dev.align() as u32), sector_size) as usize
1570 } else if Caps::SwapUsingScratch.present() {
1571 tralier_estimation(dev)
1572 } else {
1573 panic!("The maximum image size can't be calculated.")
1574 };
1575
1576 trailer
1577}
1578
David Brown5c9e0f12019-01-09 16:34:33 -07001579/// Install a "program" into the given image. This fakes the image header, or at least all of the
1580/// fields used by the given code. Returns a copy of the image that was written.
David Browna62c3eb2021-10-25 16:32:40 -06001581fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: ImageSize,
David Brownf17d3912021-06-23 16:10:51 -06001582 ram: &RamData,
David Brownc3898d62019-08-05 14:20:02 -06001583 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001584 let offset = slot.base_off;
1585 let slot_len = slot.len;
1586 let dev_id = slot.dev_id;
David Brown07dd5f02021-10-26 16:43:15 -06001587 let dev = flash.get_mut(&dev_id).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001588
David Brown43643dd2019-01-11 15:43:28 -07001589 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001590
David Brownc3898d62019-08-05 14:20:02 -06001591 // Add the dependencies early to the tlv.
1592 for dep in deps.my_deps(offset, slot.index) {
1593 tlv.add_dependency(deps.other_id(), &dep);
1594 }
1595
David Brown5c9e0f12019-01-09 16:34:33 -07001596 const HDR_SIZE: usize = 32;
1597
David Brownf17d3912021-06-23 16:10:51 -06001598 let place = ram.lookup(&slot);
1599 let load_addr = if Caps::RamLoad.present() {
1600 place.offset
1601 } else {
1602 0
1603 };
1604
David Browna62c3eb2021-10-25 16:32:40 -06001605 let len = match len {
1606 ImageSize::Given(size) => size,
David Brown07dd5f02021-10-26 16:43:15 -06001607 ImageSize::Largest => {
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001608 let trailer = image_largest_trailer(dev);
David Brown07dd5f02021-10-26 16:43:15 -06001609 let tlv_len = tlv.estimate_size();
1610 info!("slot: 0x{:x}, HDR: 0x{:x}, trailer: 0x{:x}",
1611 slot_len, HDR_SIZE, trailer);
1612 slot_len - HDR_SIZE - trailer - tlv_len
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001613 },
1614 ImageSize::Oversized => {
1615 let trailer = image_largest_trailer(dev);
1616 let tlv_len = tlv.estimate_size();
1617 info!("slot: 0x{:x}, HDR: 0x{:x}, trailer: 0x{:x}",
1618 slot_len, HDR_SIZE, trailer);
1619 // the overflow size is rougly estimated to work for all
1620 // configurations. It might be precise if tlv_len will be maked precise.
1621 slot_len - HDR_SIZE - trailer - tlv_len + dev.align()*4
David Brown07dd5f02021-10-26 16:43:15 -06001622 }
Andrzej Puzdrowski26d19d32022-08-10 18:11:53 +02001623
David Browna62c3eb2021-10-25 16:32:40 -06001624 };
1625
David Brown5c9e0f12019-01-09 16:34:33 -07001626 // Generate a boot header. Note that the size doesn't include the header.
1627 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001628 magic: tlv.get_magic(),
David Brownf17d3912021-06-23 16:10:51 -06001629 load_addr,
David Brown5c9e0f12019-01-09 16:34:33 -07001630 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001631 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001632 img_size: len as u32,
1633 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001634 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001635 _pad2: 0,
1636 };
1637
1638 let mut b_header = [0; HDR_SIZE];
1639 b_header[..32].clone_from_slice(header.as_raw());
1640 assert_eq!(b_header.len(), HDR_SIZE);
1641
1642 tlv.add_bytes(&b_header);
1643
1644 // The core of the image itself is just pseudorandom data.
1645 let mut b_img = vec![0; len];
1646 splat(&mut b_img, offset);
1647
David Browncb47dd72019-08-05 14:21:49 -06001648 // Add some information at the start of the payload to make it easier
1649 // to see what it is. This will fail if the image itself is too small.
1650 {
1651 let mut wr = Cursor::new(&mut b_img);
1652 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1653 offset, dev_id, slot).unwrap();
1654 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1655 }
1656
David Brown5c9e0f12019-01-09 16:34:33 -07001657 // TLV signatures work over plain image
1658 tlv.add_bytes(&b_img);
1659
1660 // Generate encrypted images
Salome Thirot6fdbf552021-05-14 16:46:14 +01001661 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1662 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001663 let mut b_encimg = vec![];
1664 if is_encrypted {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001665 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1666 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001667 tlv.generate_enc_key();
1668 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001669 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001670 b_encimg = b_img.clone();
Salome Thirot6fdbf552021-05-14 16:46:14 +01001671 if aes256 {
1672 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001673 let block = Aes256::new(&key);
1674 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001675 cipher.apply_keystream(&mut b_encimg);
1676 } else {
1677 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001678 let block = Aes128::new(&key);
1679 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001680 cipher.apply_keystream(&mut b_encimg);
1681 }
David Brown5c9e0f12019-01-09 16:34:33 -07001682 }
1683
1684 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001685 if bad_sig {
1686 tlv.corrupt_sig();
1687 }
1688 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001689
David Brown5c9e0f12019-01-09 16:34:33 -07001690 let mut buf = vec![];
1691 buf.append(&mut b_header.to_vec());
1692 buf.append(&mut b_img);
1693 buf.append(&mut b_tlv.clone());
1694
David Brown95de4502019-11-15 12:01:34 -07001695 // Pad the buffer to a multiple of the flash alignment.
1696 let align = dev.align();
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001697 let image_sz = buf.len();
David Brown95de4502019-11-15 12:01:34 -07001698 while buf.len() % align != 0 {
1699 buf.push(dev.erased_val());
1700 }
1701
David Brown5c9e0f12019-01-09 16:34:33 -07001702 let mut encbuf = vec![];
1703 if is_encrypted {
1704 encbuf.append(&mut b_header.to_vec());
1705 encbuf.append(&mut b_encimg);
1706 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001707
1708 while encbuf.len() % align != 0 {
1709 encbuf.push(dev.erased_val());
1710 }
David Brown5c9e0f12019-01-09 16:34:33 -07001711 }
1712
David Vincze2d736ad2019-02-18 11:50:22 +01001713 // Since images are always non-encrypted in the primary slot, we first write
1714 // an encrypted image, re-read to use for verification, erase + flash
1715 // un-encrypted. In the secondary slot the image is written un-encrypted,
1716 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001717
David Brown3b090212019-07-30 15:59:28 -06001718 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001719 let enc_copy: Option<Vec<u8>>;
1720
1721 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001722 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001723
1724 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001725 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001726
1727 enc_copy = Some(enc);
1728
David Brown76101572019-02-28 11:29:03 -07001729 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001730 } else {
1731 enc_copy = None;
1732 }
1733
David Brown76101572019-02-28 11:29:03 -07001734 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001735
1736 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001737 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001738
David Brownca234692019-02-28 11:22:19 -07001739 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001740 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001741 plain: copy,
1742 cipher: enc_copy,
1743 }
David Brown5c9e0f12019-01-09 16:34:33 -07001744 } else {
1745
David Brown76101572019-02-28 11:29:03 -07001746 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001747
1748 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001749 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001750
1751 let enc_copy: Option<Vec<u8>>;
1752
1753 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001754 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001755
David Brown76101572019-02-28 11:29:03 -07001756 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001757
1758 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001759 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001760
1761 enc_copy = Some(enc);
1762 } else {
1763 enc_copy = None;
1764 }
1765
David Brownca234692019-02-28 11:22:19 -07001766 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001767 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001768 plain: copy,
1769 cipher: enc_copy,
1770 }
David Brown5c9e0f12019-01-09 16:34:33 -07001771 }
David Brown5c9e0f12019-01-09 16:34:33 -07001772}
1773
David Brown873be312019-09-03 12:22:32 -06001774/// Install no image. This is used when no upgrade happens.
1775fn install_no_image() -> ImageData {
1776 ImageData {
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001777 size: 0,
David Brown873be312019-09-03 12:22:32 -06001778 plain: vec![],
1779 cipher: None,
1780 }
1781}
1782
David Brown0bd8c6b2021-10-22 16:33:06 -06001783/// Construct a TLV generator based on how MCUboot is currently configured. The returned
1784/// ManifestGen will generate the appropriate entries based on this configuration.
David Brown5c9e0f12019-01-09 16:34:33 -07001785fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001786 if Caps::EcdsaP224.present() {
1787 panic!("Ecdsa P224 not supported in Simulator");
1788 }
David Brownac655bb2021-10-22 16:33:27 -06001789 let aes_key_size = if Caps::Aes256.present() { 256 } else { 128 };
David Brown5c9e0f12019-01-09 16:34:33 -07001790
David Brownb8882112019-01-11 14:04:11 -07001791 if Caps::EncKw.present() {
1792 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001793 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001794 } else if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001795 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001796 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001797 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001798 }
1799 } else if Caps::EncRsa.present() {
1800 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001801 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001802 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001803 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001804 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001805 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001806 if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001807 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001808 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001809 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001810 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001811 } else if Caps::EncX25519.present() {
1812 if Caps::Ed25519.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001813 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001814 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001815 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001816 }
David Brownb8882112019-01-11 14:04:11 -07001817 } else {
1818 // The non-encrypted configuration.
1819 if Caps::RSA2048.present() {
1820 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001821 } else if Caps::RSA3072.present() {
1822 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001823 } else if Caps::EcdsaP256.present() {
1824 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001825 } else if Caps::Ed25519.present() {
1826 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001827 } else {
1828 TlvGen::new_hash_only()
1829 }
1830 }
David Brown5c9e0f12019-01-09 16:34:33 -07001831}
1832
David Brownca234692019-02-28 11:22:19 -07001833impl ImageData {
1834 /// Find the image contents for the given slot. This assumes that slot 0
1835 /// is unencrypted, and slot 1 is encrypted.
1836 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001837 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001838 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001839 match (encrypted, slot) {
1840 (false, _) => &self.plain,
1841 (true, 0) => &self.plain,
1842 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1843 _ => panic!("Invalid slot requested"),
1844 }
David Brown5c9e0f12019-01-09 16:34:33 -07001845 }
Fabio Utzig66ed29f2021-10-07 08:44:48 -03001846
1847 fn size(&self) -> usize {
1848 self.size
1849 }
David Brown5c9e0f12019-01-09 16:34:33 -07001850}
1851
David Brown5c9e0f12019-01-09 16:34:33 -07001852/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001853fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1854 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001855 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001856 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001857
1858 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001859 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001860 let dev = flash.get(&dev_id).unwrap();
1861 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001862
1863 if buf != &copy[..] {
1864 for i in 0 .. buf.len() {
1865 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001866 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1867 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001868 break;
1869 }
1870 }
1871 false
1872 } else {
1873 true
1874 }
1875}
1876
David Brown3b090212019-07-30 15:59:28 -06001877fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001878 magic: Option<u8>, image_ok: Option<u8>,
1879 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001880 if Caps::OverwriteUpgrade.present() {
1881 return true;
1882 }
David Brown5c9e0f12019-01-09 16:34:33 -07001883
David Brown3b090212019-07-30 15:59:28 -06001884 let offset = slot.trailer_off + c::boot_max_align();
1885 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001886 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001887 let mut failed = false;
1888
David Brown76101572019-02-28 11:29:03 -07001889 let dev = flash.get(&dev_id).unwrap();
1890 let erased_val = dev.erased_val();
1891 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001892
1893 failed |= match magic {
1894 Some(v) => {
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03001895 let magic_off = (c::boot_max_align() * 3) + (c::boot_magic_sz() - MAGIC.len());
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001896 if v == 1 && &copy[magic_off..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001897 warn!("\"magic\" mismatch at {:#x}", offset);
1898 true
1899 } else if v == 3 {
1900 let expected = [erased_val; 16];
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001901 if copy[magic_off..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001902 warn!("\"magic\" mismatch at {:#x}", offset);
1903 true
1904 } else {
1905 false
1906 }
1907 } else {
1908 false
1909 }
1910 },
1911 None => false,
1912 };
1913
1914 failed |= match image_ok {
1915 Some(v) => {
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001916 let image_ok_off = c::boot_max_align() * 2;
1917 if (v == 1 && copy[image_ok_off] != v) || (v == 3 && copy[image_ok_off] != erased_val) {
1918 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[image_ok_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07001919 true
1920 } else {
1921 false
1922 }
1923 },
1924 None => false,
1925 };
1926
1927 failed |= match copy_done {
1928 Some(v) => {
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03001929 let copy_done_off = c::boot_max_align();
1930 if (v == 1 && copy[copy_done_off] != v) || (v == 3 && copy[copy_done_off] != erased_val) {
1931 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[copy_done_off]);
David Brown5c9e0f12019-01-09 16:34:33 -07001932 true
1933 } else {
1934 false
1935 }
1936 },
1937 None => false,
1938 };
1939
1940 !failed
1941}
1942
David Brown297029a2019-08-13 14:29:51 -06001943/// Install a partition table. This is a simplified partition table that
1944/// we write at the beginning of flash so make it easier for external tools
1945/// to analyze these images.
1946fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1947 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1948 for &id in &ids {
1949 // If there are any partitions in this device that start at 0, and
1950 // aren't marked as the BootLoader partition, avoid adding the
1951 // partition table. This makes it harder to view the image, but
1952 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07001953 let skip_ptable = areadesc
1954 .iter_areas()
1955 .any(|area| {
1956 area.device_id == id &&
1957 area.off == 0 &&
1958 area.flash_id != FlashId::BootLoader
1959 });
1960 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06001961 if log_enabled!(Info) {
1962 let special: Vec<FlashId> = areadesc.iter_areas()
1963 .filter(|area| area.device_id == id && area.off == 0)
1964 .map(|area| area.flash_id)
1965 .collect();
1966 info!("Skipping partition table: {:?}", special);
1967 }
1968 break;
1969 }
1970
1971 let mut buf: Vec<u8> = vec![];
1972 write!(&mut buf, "mcuboot\0").unwrap();
1973
1974 // Iterate through all of the partitions in that device, and encode
1975 // into the table.
1976 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1977 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1978
1979 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1980 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1981 buf.write_u32::<LittleEndian>(area.off).unwrap();
1982 buf.write_u32::<LittleEndian>(area.size).unwrap();
1983 buf.write_u32::<LittleEndian>(0).unwrap();
1984 }
1985
1986 let dev = flash.get_mut(&id).unwrap();
1987
1988 // Pad to alignment.
1989 while buf.len() % dev.align() != 0 {
1990 buf.push(0);
1991 }
1992
1993 dev.write(0, &buf).unwrap();
1994 }
1995}
1996
David Brown5c9e0f12019-01-09 16:34:33 -07001997/// The image header
1998#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001999#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002000pub struct ImageHeader {
2001 magic: u32,
2002 load_addr: u32,
2003 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06002004 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07002005 img_size: u32,
2006 flags: u32,
2007 ver: ImageVersion,
2008 _pad2: u32,
2009}
2010
2011impl AsRaw for ImageHeader {}
2012
2013#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06002014#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002015pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06002016 pub major: u8,
2017 pub minor: u8,
2018 pub revision: u16,
2019 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07002020}
2021
David Brownc3898d62019-08-05 14:20:02 -06002022#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07002023pub struct SlotInfo {
2024 pub base_off: usize,
2025 pub trailer_off: usize,
2026 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06002027 // Which slot within this device.
2028 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07002029 pub dev_id: u8,
2030}
2031
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002032#[cfg(not(feature = "max-align-32"))]
David Brown347dc572019-11-15 11:37:25 -07002033const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
2034 0x60, 0xd2, 0xef, 0x7f,
2035 0x35, 0x52, 0x50, 0x0f,
2036 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07002037
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002038#[cfg(feature = "max-align-32")]
2039const MAGIC: &[u8] = &[0x20, 0x00, 0x2d, 0xe1,
2040 0x5d, 0x29, 0x41, 0x0b,
2041 0x8d, 0x77, 0x67, 0x9c,
2042 0x11, 0x0f, 0x1f, 0x8a];
2043
David Brown5c9e0f12019-01-09 16:34:33 -07002044// Replicates defines found in bootutil.h
2045const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
2046const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
2047
2048const BOOT_FLAG_SET: Option<u8> = Some(1);
2049const BOOT_FLAG_UNSET: Option<u8> = Some(3);
2050
2051/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07002052pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
2053 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07002054 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07002055 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07002056 if offset % align != 0 || MAGIC.len() % align != 0 {
2057 // The write size is larger than the magic value. Fill a buffer
2058 // with the erased value, put the MAGIC in it, and write it in its
2059 // entirety.
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002060 let mut buf = vec![dev.erased_val(); c::boot_max_align()];
2061 let magic_off = (offset % align) + (c::boot_magic_sz() - MAGIC.len());
2062 buf[magic_off..].copy_from_slice(MAGIC);
David Brown95de4502019-11-15 12:01:34 -07002063 dev.write(offset - (offset % align), &buf).unwrap();
2064 } else {
2065 dev.write(offset, MAGIC).unwrap();
2066 }
David Brown5c9e0f12019-01-09 16:34:33 -07002067}
2068
2069/// Writes the image_ok flag which, guess what, tells the bootloader
2070/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07002071fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07002072 // Overwrite mode always is permanent, and only the magic is used in
2073 // the trailer. To avoid problems with large write sizes, don't try to
2074 // set anything in this case.
2075 if Caps::OverwriteUpgrade.present() {
2076 return;
2077 }
2078
David Brown76101572019-02-28 11:29:03 -07002079 let dev = flash.get_mut(&slot.dev_id).unwrap();
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002080 let align = dev.align();
2081 let mut ok = vec![dev.erased_val(); align];
David Brown5c9e0f12019-01-09 16:34:33 -07002082 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07002083 let off = slot.trailer_off + c::boot_max_align() * 3;
Gustavo Henrique Nihei1d7f4962021-11-30 09:25:15 -03002084 dev.write(off, &ok).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07002085}
2086
2087// Drop some pseudo-random gibberish onto the data.
2088fn splat(data: &mut [u8], seed: usize) {
David Brown9c6322f2021-08-19 13:03:39 -06002089 let mut seed_block = [0u8; 32];
David Browncd842842020-07-09 15:46:53 -06002090 let mut buf = Cursor::new(&mut seed_block[..]);
2091 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
2092 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
2093 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
2094 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
2095 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07002096 rng.fill_bytes(data);
2097}
2098
2099/// Return a read-only view into the raw bytes of this object
2100trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07002101 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07002102 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
2103 mem::size_of::<Self>()) }
2104 }
2105}
2106
David Brown07dd5f02021-10-26 16:43:15 -06002107/// Determine whether it makes sense to test this configuration with a maximally-sized image.
2108/// Returns an ImageSize representing the best size to test, possibly just with the given size.
2109fn maximal(size: usize) -> ImageSize {
2110 if Caps::OverwriteUpgrade.present() ||
2111 Caps::SwapUsingMove.present()
2112 {
2113 ImageSize::Given(size)
2114 } else {
2115 ImageSize::Largest
2116 }
2117}
2118
David Brown5c9e0f12019-01-09 16:34:33 -07002119pub fn show_sizes() {
2120 // This isn't panic safe.
2121 for min in &[1, 2, 4, 8] {
2122 let msize = c::boot_trailer_sz(*min);
2123 println!("{:2}: {} (0x{:x})", min, msize, msize);
2124 }
2125}
David Brown95de4502019-11-15 12:01:34 -07002126
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002127#[cfg(not(feature = "max-align-32"))]
David Brown95de4502019-11-15 12:01:34 -07002128fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07002129 &[1, 2, 4, 8]
2130}
2131
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002132#[cfg(feature = "max-align-32")]
David Brown95de4502019-11-15 12:01:34 -07002133fn test_alignments() -> &'static [usize] {
Gustavo Henrique Nihei7bfd14b2021-11-24 23:27:22 -03002134 &[32]
David Brown95de4502019-11-15 12:01:34 -07002135}