blob: 29ddedd86afc0681fbdd27627060f63164feb21f [file] [log] [blame]
David Browne2acfae2020-01-21 16:45:01 -07001// Copyright (c) 2019 Linaro LTD
2// Copyright (c) 2019-2020 JUUL Labs
Roman Okhrimenko977b3752022-03-31 14:40:48 +03003// 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::{
Roman Okhrimenko977b3752022-03-31 14:40:48 +030022 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};
Roman Okhrimenko977b3752022-03-31 14:40:48 +030027use aes::{
28 Aes128,
David Brown5c9e0f12019-01-09 16:34:33 -070029 Aes128Ctr,
Roman Okhrimenko977b3752022-03-31 14:40:48 +030030 Aes256,
31 Aes256Ctr,
32 NewBlockCipher,
David Brown5c9e0f12019-01-09 16:34:33 -070033};
Roman Okhrimenko977b3752022-03-31 14:40:48 +030034use 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};
Roman Okhrimenko977b3752022-03-31 14:40:48 +030041use 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};
Roman Okhrimenko977b3752022-03-31 14:40:48 +030057use typenum::{U32, U16};
58
59/// For testing, use a non-zero offset for the ram-load, to make sure the offset is getting used
60/// properly, but the value is not really that important.
61const RAM_LOAD_ADDR: u32 = 1024;
David Brown5c9e0f12019-01-09 16:34:33 -070062
David Browne5133242019-02-28 11:05:19 -070063/// A builder for Images. This describes a single run of the simulator,
64/// capturing the configuration of a particular set of devices, including
65/// the flash simulator(s) and the information about the slots.
66#[derive(Clone)]
67pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070068 flash: SimMultiFlash,
David Browne5133242019-02-28 11:05:19 -070069 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070070 slots: Vec<[SlotInfo; 2]>,
Roman Okhrimenko977b3752022-03-31 14:40:48 +030071 ram: RamData,
David Browne5133242019-02-28 11:05:19 -070072}
73
David Brown998aa8d2019-02-28 10:54:50 -070074/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070075/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070076/// and upgrades hold the expected contents of these images.
77pub struct Images {
David Brown76101572019-02-28 11:29:03 -070078 flash: SimMultiFlash,
David Brownca234692019-02-28 11:22:19 -070079 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070080 images: Vec<OneImage>,
81 total_count: Option<i32>,
Roman Okhrimenko977b3752022-03-31 14:40:48 +030082 ram: RamData,
David Brown84b49f72019-03-01 10:58:22 -070083}
84
85/// When doing multi-image, there is an instance of this information for
86/// each of the images. Single image there will be one of these.
87struct OneImage {
David Brownca234692019-02-28 11:22:19 -070088 slots: [SlotInfo; 2],
89 primaries: ImageData,
90 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070091}
92
93/// The Rust-side representation of an image. For unencrypted images, this
94/// is just the unencrypted payload. For encrypted images, we store both
95/// the encrypted and the plaintext.
96struct ImageData {
Roman Okhrimenko977b3752022-03-31 14:40:48 +030097 size: usize,
David Brownca234692019-02-28 11:22:19 -070098 plain: Vec<u8>,
99 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -0700100}
101
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300102/// For the RamLoad test cases, we need a contiguous area of RAM to load these images into. For
103/// multi-image builds, these may not correspond with the offsets. This has to be computed early,
104/// before images are built, because each image contains the offset where the image is to be loaded
105/// in the header, which is contained within the signature.
106#[derive(Clone, Debug)]
107struct RamData {
108 places: BTreeMap<SlotKey, SlotPlace>,
109 total: u32,
110}
111
112/// Every slot is indexed by this key.
113#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
114struct SlotKey {
115 dev_id: u8,
116 base_off: usize,
117}
118
119#[derive(Clone, Debug)]
120struct SlotPlace {
121 offset: u32,
122 size: u32,
123}
124
David Browne5133242019-02-28 11:05:19 -0700125impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -0700126 /// Construct a new image builder for the given device. Returns
127 /// Some(builder) if is possible to test this configuration, or None if
128 /// not possible (for example, if there aren't enough image slots).
Fabio Utzig114a6472019-11-28 10:24:09 -0300129 pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
130 let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
131
132 for cap in unsupported_caps {
133 if cap.present() {
134 return Err(format!("unsupported {:?}", cap));
135 }
136 }
David Browne5133242019-02-28 11:05:19 -0700137
David Brown06ef06e2019-03-05 12:28:10 -0700138 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -0700139
David Brown06ef06e2019-03-05 12:28:10 -0700140 let mut slots = Vec::with_capacity(num_images);
141 for image in 0..num_images {
142 // This mapping must match that defined in
143 // `boot/zephyr/include/sysflash/sysflash.h`.
144 let id0 = match image {
145 0 => FlashId::Image0,
146 1 => FlashId::Image2,
147 _ => panic!("More than 2 images not supported"),
148 };
149 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
150 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300151 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700152 };
153 let id1 = match image {
154 0 => FlashId::Image1,
155 1 => FlashId::Image3,
156 _ => panic!("More than 2 images not supported"),
157 };
158 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
159 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300160 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700161 };
David Browne5133242019-02-28 11:05:19 -0700162
Christopher Collinsa1c12042019-05-23 14:00:28 -0700163 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700164
David Brown06ef06e2019-03-05 12:28:10 -0700165 // Construct a primary image.
166 let primary = SlotInfo {
167 base_off: primary_base as usize,
168 trailer_off: primary_base + primary_len - offset_from_end,
169 len: primary_len as usize,
170 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600171 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700172 };
173
174 // And an upgrade image.
175 let secondary = SlotInfo {
176 base_off: secondary_base as usize,
177 trailer_off: secondary_base + secondary_len - offset_from_end,
178 len: secondary_len as usize,
179 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600180 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700181 };
182
183 slots.push([primary, secondary]);
184 }
David Browne5133242019-02-28 11:05:19 -0700185
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300186 let ram = RamData::new(&slots);
187
Fabio Utzig114a6472019-11-28 10:24:09 -0300188 Ok(ImagesBuilder {
David Brown4dfb33c2021-03-10 05:15:45 -0700189 flash,
190 areadesc,
191 slots,
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300192 ram,
David Brown5bc62c62019-03-05 12:11:48 -0700193 })
David Browne5133242019-02-28 11:05:19 -0700194 }
195
196 pub fn each_device<F>(f: F)
197 where F: Fn(Self)
198 {
199 for &dev in ALL_DEVICES {
David Brown95de4502019-11-15 12:01:34 -0700200 for &align in test_alignments() {
David Browne5133242019-02-28 11:05:19 -0700201 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700202 match Self::new(dev, align, erased_val) {
Fabio Utzig114a6472019-11-28 10:24:09 -0300203 Ok(run) => f(run),
204 Err(msg) => warn!("Skipping {}: {}", dev, msg),
David Brown5bc62c62019-03-05 12:11:48 -0700205 }
David Browne5133242019-02-28 11:05:19 -0700206 }
207 }
208 }
209 }
210
211 /// Construct an `Images` that doesn't expect an upgrade to happen.
David Brownc3898d62019-08-05 14:20:02 -0600212 pub fn make_no_upgrade_image(self, deps: &DepTest) -> Images {
213 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700214 let mut flash = self.flash;
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300215 let ram = self.ram.clone(); // TODO: This is wasteful.
David Brownc3898d62019-08-05 14:20:02 -0600216 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
217 let dep: Box<dyn Depender> = if num_images > 1 {
218 Box::new(PairDep::new(num_images, image_num, deps))
219 } else {
David Brown2ee5f7f2020-01-13 14:04:01 -0700220 Box::new(BoringDep::new(image_num, deps))
David Brownc3898d62019-08-05 14:20:02 -0600221 };
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300222 let primaries = install_image(&mut flash, &slots[0], 42784, &ram, &*dep, false);
David Brown873be312019-09-03 12:22:32 -0600223 let upgrades = match deps.depends[image_num] {
224 DepType::NoUpgrade => install_no_image(),
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300225 _ => install_image(&mut flash, &slots[1], 46928, &ram, &*dep, false)
David Brown873be312019-09-03 12:22:32 -0600226 };
David Brown84b49f72019-03-01 10:58:22 -0700227 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700228 slots,
229 primaries,
230 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700231 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600232 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700233 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700234 flash,
David Browne5133242019-02-28 11:05:19 -0700235 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700236 images,
David Browne5133242019-02-28 11:05:19 -0700237 total_count: None,
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300238 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700239 }
240 }
241
David Brownc3898d62019-08-05 14:20:02 -0600242 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
243 let mut images = self.make_no_upgrade_image(deps);
David Brown84b49f72019-03-01 10:58:22 -0700244 for image in &images.images {
245 mark_upgrade(&mut images.flash, &image.slots[1]);
246 }
David Browne5133242019-02-28 11:05:19 -0700247
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300248 // The count is meaningless if no flash operations are performed.
249 if !Caps::modifies_flash() {
250 return images;
251 }
252
David Browne5133242019-02-28 11:05:19 -0700253 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300254 let total_count = match images.run_basic_upgrade(permanent) {
David Brown8973f552021-03-10 05:21:11 -0700255 Some(v) => v,
256 None =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600257 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
258 0
259 } else {
260 panic!("Unable to perform basic upgrade");
261 }
David Browne5133242019-02-28 11:05:19 -0700262 };
263
264 images.total_count = Some(total_count);
265 images
266 }
267
268 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700269 let mut bad_flash = self.flash;
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300270 let ram = self.ram.clone(); // TODO: Avoid this clone.
David Brownc3898d62019-08-05 14:20:02 -0600271 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
David Brown2ee5f7f2020-01-13 14:04:01 -0700272 let dep = BoringDep::new(image_num, &NO_DEPS);
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300273 let primaries = install_image(&mut bad_flash, &slots[0], 32784, &ram, &dep, false);
274 let upgrades = install_image(&mut bad_flash, &slots[1], 41928, &ram, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700275 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700276 slots,
277 primaries,
278 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700279 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700280 Images {
David Brown76101572019-02-28 11:29:03 -0700281 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700282 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700283 images,
David Browne5133242019-02-28 11:05:19 -0700284 total_count: None,
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300285 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700286 }
287 }
288
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300289 pub fn make_erased_secondary_image(self) -> Images {
290 let mut flash = self.flash;
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300291 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300292 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
293 let dep = BoringDep::new(image_num, &NO_DEPS);
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300294 let primaries = install_image(&mut flash, &slots[0], 32784, &ram, &dep, false);
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300295 let upgrades = install_no_image();
296 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700297 slots,
298 primaries,
299 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300300 }}).collect();
301 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700302 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300303 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700304 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300305 total_count: None,
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300306 ram: self.ram,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300307 }
308 }
309
Fabio Utzigd0157342020-10-02 15:22:11 -0300310 pub fn make_bootstrap_image(self) -> Images {
311 let mut flash = self.flash;
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300312 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzigd0157342020-10-02 15:22:11 -0300313 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
314 let dep = BoringDep::new(image_num, &NO_DEPS);
315 let primaries = install_no_image();
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300316 let upgrades = install_image(&mut flash, &slots[1], 32784, &ram, &dep, false);
Fabio Utzigd0157342020-10-02 15:22:11 -0300317 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700318 slots,
319 primaries,
320 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300321 }}).collect();
322 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700323 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300324 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700325 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300326 total_count: None,
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300327 ram: self.ram,
Fabio Utzigd0157342020-10-02 15:22:11 -0300328 }
329 }
330
David Browne5133242019-02-28 11:05:19 -0700331 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300332 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700333 match device {
334 DeviceName::Stm32f4 => {
335 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700336 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
337 64 * 1024,
338 128 * 1024, 128 * 1024, 128 * 1024],
339 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700340 let dev_id = 0;
341 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700342 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700343 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
344 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
345 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
346
David Brown76101572019-02-28 11:29:03 -0700347 let mut flash = SimMultiFlash::new();
348 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200349 (flash, areadesc, &[Caps::SwapUsingMove, Caps::SwapUsingStatus])
David Browne5133242019-02-28 11:05:19 -0700350 }
351 DeviceName::K64f => {
352 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700353 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700354
355 let dev_id = 0;
356 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700357 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700358 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
359 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
360 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
361
David Brown76101572019-02-28 11:29:03 -0700362 let mut flash = SimMultiFlash::new();
363 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200364 (flash, areadesc, &[Caps::SwapUsingStatus])
David Browne5133242019-02-28 11:05:19 -0700365 }
366 DeviceName::K64fBig => {
367 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
368 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700369 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700370
371 let dev_id = 0;
372 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700373 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700374 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
375 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
376 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
377
David Brown76101572019-02-28 11:29:03 -0700378 let mut flash = SimMultiFlash::new();
379 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200380 (flash, areadesc, &[Caps::SwapUsingMove, Caps::SwapUsingStatus])
David Browne5133242019-02-28 11:05:19 -0700381 }
382 DeviceName::Nrf52840 => {
383 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
384 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700385 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700386
387 let dev_id = 0;
388 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700389 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700390 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
391 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
392 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
393
David Brown76101572019-02-28 11:29:03 -0700394 let mut flash = SimMultiFlash::new();
395 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200396 (flash, areadesc, &[Caps::SwapUsingStatus])
David Browne5133242019-02-28 11:05:19 -0700397 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300398 DeviceName::Nrf52840UnequalSlots => {
399 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
400
401 let dev_id = 0;
402 let mut areadesc = AreaDesc::new();
403 areadesc.add_flash_sectors(dev_id, &dev);
404 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
405 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
406
407 let mut flash = SimMultiFlash::new();
408 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200409 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade, Caps::SwapUsingStatus])
Fabio Utzigc659ec52020-07-13 21:18:48 -0300410 }
David Browne5133242019-02-28 11:05:19 -0700411 DeviceName::Nrf52840SpiFlash => {
412 // Simulate nrf52840 with external SPI flash. The external SPI flash
413 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700414 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
415 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700416
417 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700418 areadesc.add_flash_sectors(0, &dev0);
419 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700420
421 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
422 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
423 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
424
David Brown76101572019-02-28 11:29:03 -0700425 let mut flash = SimMultiFlash::new();
426 flash.insert(0, dev0);
427 flash.insert(1, dev1);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200428 (flash, areadesc, &[Caps::SwapUsingMove, Caps::SwapUsingStatus])
David Browne5133242019-02-28 11:05:19 -0700429 }
David Brown2bff6472019-03-05 13:58:35 -0700430 DeviceName::K64fMulti => {
431 // NXP style flash, but larger, to support multiple images.
432 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
433
434 let dev_id = 0;
435 let mut areadesc = AreaDesc::new();
436 areadesc.add_flash_sectors(dev_id, &dev);
437 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
438 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
439 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
440 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
441 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
442
443 let mut flash = SimMultiFlash::new();
444 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200445 (flash, areadesc, &[Caps::SwapUsingStatus])
446 }
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300447 DeviceName::PSoC6 => {
448 // PSoC style flash of 512K, single-image case
449 let dev = SimFlash::new(vec![512; 1024], align as usize, erased_val);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200450
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300451 let dev_id = 0;
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200452 let mut areadesc = AreaDesc::new();
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300453 areadesc.add_flash_sectors(dev_id, &dev);
454 areadesc.add_image(0x018000, 0x010000, FlashId::Image0, dev_id);
455 areadesc.add_image(0x028000, 0x010000, FlashId::Image1, dev_id);
456 areadesc.add_image(0x039800, 0x001000, FlashId::ImageScratch, dev_id);
457 areadesc.add_image(0x038000, 0x001800, FlashId::ImageSwapStatus, dev_id);
458
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200459 let mut flash = SimMultiFlash::new();
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300460 flash.insert(dev_id, dev);
461 (flash, areadesc, &[Caps::SwapUsingMove])
David Brown2bff6472019-03-05 13:58:35 -0700462 }
David Browne5133242019-02-28 11:05:19 -0700463 }
464 }
David Brownc3898d62019-08-05 14:20:02 -0600465
466 pub fn num_images(&self) -> usize {
467 self.slots.len()
468 }
David Browne5133242019-02-28 11:05:19 -0700469}
470
David Brown5c9e0f12019-01-09 16:34:33 -0700471impl Images {
472 /// A simple upgrade without forced failures.
473 ///
474 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700475 /// inject failures at chosen steps. Returns None if it was unable to
476 /// count the operations in a basic upgrade.
477 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300478 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700479 info!("Total flash operation count={}", total_count);
480
David Brown84b49f72019-03-01 10:58:22 -0700481 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700482 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700483 None
David Brown5c9e0f12019-01-09 16:34:33 -0700484 } else {
David Brown8973f552021-03-10 05:21:11 -0700485 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700486 }
487 }
488
Fabio Utzigd0157342020-10-02 15:22:11 -0300489 pub fn run_bootstrap(&self) -> bool {
490 let mut flash = self.flash.clone();
491 let mut fails = 0;
492
493 if Caps::Bootstrap.present() {
494 info!("Try bootstraping image in the primary");
495
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300496 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigd0157342020-10-02 15:22:11 -0300497 warn!("Failed first boot");
498 fails += 1;
499 }
500
501 if !self.verify_images(&flash, 0, 1) {
502 warn!("Image in the first slot was not bootstrapped");
503 fails += 1;
504 }
505
506 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
507 BOOT_FLAG_SET, BOOT_FLAG_SET) {
508 warn!("Mismatched trailer for the primary slot");
509 fails += 1;
510 }
511 }
512
513 if fails > 0 {
514 error!("Expected trailer on secondary slot to be erased");
515 }
516
517 fails > 0
518 }
519
520
David Brownc3898d62019-08-05 14:20:02 -0600521 /// Test a simple upgrade, with dependencies given, and verify that the
522 /// image does as is described in the test.
523 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300524 if !Caps::modifies_flash() {
525 return false;
526 }
527
David Brownc3898d62019-08-05 14:20:02 -0600528 let (flash, _) = self.try_upgrade(None, true);
529
530 self.verify_dep_images(&flash, deps)
531 }
532
Fabio Utzigf5480c72019-11-28 10:41:57 -0300533 fn is_swap_upgrade(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300534 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
Fabio Utzigf5480c72019-11-28 10:41:57 -0300535 }
536
David Brown5c9e0f12019-01-09 16:34:33 -0700537 pub fn run_basic_revert(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300538 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700539 return false;
540 }
David Brown5c9e0f12019-01-09 16:34:33 -0700541
David Brown5c9e0f12019-01-09 16:34:33 -0700542 let mut fails = 0;
543
544 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300545 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700546 for count in 2 .. 5 {
547 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700548 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700549 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700550 error!("Revert failure on count {}", count);
551 fails += 1;
552 }
553 }
554 }
555
556 fails > 0
557 }
558
559 pub fn run_perm_with_fails(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300560 if !Caps::modifies_flash() {
561 return false;
562 }
563
David Brown5c9e0f12019-01-09 16:34:33 -0700564 let mut fails = 0;
565 let total_flash_ops = self.total_count.unwrap();
566
567 // Let's try an image halfway through.
568 for i in 1 .. total_flash_ops {
569 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300570 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700571 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700572 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700573 warn!("FAIL at step {} of {}", i, total_flash_ops);
574 fails += 1;
575 }
576
David Brown84b49f72019-03-01 10:58:22 -0700577 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
578 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100579 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700580 fails += 1;
581 }
582
David Brown84b49f72019-03-01 10:58:22 -0700583 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
584 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100585 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700586 fails += 1;
587 }
588
David Brownaec56b22021-03-10 05:22:07 -0700589 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
590 warn!("Secondary slot FAIL at step {} of {}",
591 i, total_flash_ops);
592 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700593 }
594 }
595
596 if fails > 0 {
597 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
598 fails as f32 * 100.0 / total_flash_ops as f32);
599 }
600
601 fails > 0
602 }
603
David Brown5c9e0f12019-01-09 16:34:33 -0700604 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300605 if !Caps::modifies_flash() {
606 return false;
607 }
608
David Brown5c9e0f12019-01-09 16:34:33 -0700609 let mut fails = 0;
610 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700611 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700612 info!("Random interruptions at reset points={:?}", total_counts);
613
David Brown84b49f72019-03-01 10:58:22 -0700614 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300615 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700616 // TODO: This result is ignored.
617 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700618 } else {
619 true
620 };
David Vincze2d736ad2019-02-18 11:50:22 +0100621 if !primary_slot_ok || !secondary_slot_ok {
622 error!("Image mismatch after random interrupts: primary slot={} \
623 secondary slot={}",
624 if primary_slot_ok { "ok" } else { "fail" },
625 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700626 fails += 1;
627 }
David Brown84b49f72019-03-01 10:58:22 -0700628 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
629 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100630 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700631 fails += 1;
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 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700636 fails += 1;
637 }
638
639 if fails > 0 {
640 error!("Error testing perm upgrade with {} fails", total_fails);
641 }
642
643 fails > 0
644 }
645
David Brown5c9e0f12019-01-09 16:34:33 -0700646 pub fn run_revert_with_fails(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300647 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700648 return false;
649 }
David Brown5c9e0f12019-01-09 16:34:33 -0700650
David Brown5c9e0f12019-01-09 16:34:33 -0700651 let mut fails = 0;
652
Fabio Utzigf5480c72019-11-28 10:41:57 -0300653 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300654 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700655 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700656 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700657 error!("Revert failed at interruption {}", i);
658 fails += 1;
659 }
660 }
661 }
662
663 fails > 0
664 }
665
David Brown5c9e0f12019-01-09 16:34:33 -0700666 pub fn run_norevert(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300667 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700668 return false;
669 }
David Brown5c9e0f12019-01-09 16:34:33 -0700670
David Brown76101572019-02-28 11:29:03 -0700671 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700672 let mut fails = 0;
673
674 info!("Try norevert");
675
676 // First do a normal upgrade...
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300677 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700678 warn!("Failed first boot");
679 fails += 1;
680 }
681
682 //FIXME: copy_done is written by boot_go, is it ok if no copy
683 // was ever done?
684
David Brown84b49f72019-03-01 10:58:22 -0700685 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100686 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700687 fails += 1;
688 }
David Brown84b49f72019-03-01 10:58:22 -0700689 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
690 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100691 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700692 fails += 1;
693 }
David Brown84b49f72019-03-01 10:58:22 -0700694 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
695 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100696 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700697 fails += 1;
698 }
699
David Vincze2d736ad2019-02-18 11:50:22 +0100700 // Marks image in the primary slot as permanent,
701 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700702 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700703
David Brown84b49f72019-03-01 10:58:22 -0700704 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
705 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100706 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700707 fails += 1;
708 }
709
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300710 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700711 warn!("Failed second boot");
712 fails += 1;
713 }
714
David Brown84b49f72019-03-01 10:58:22 -0700715 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
716 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100717 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700718 fails += 1;
719 }
David Brown84b49f72019-03-01 10:58:22 -0700720 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700721 warn!("Failed image verification");
722 fails += 1;
723 }
724
725 if fails > 0 {
726 error!("Error running upgrade without revert");
727 }
728
729 fails > 0
730 }
731
David Brown2ee5f7f2020-01-13 14:04:01 -0700732 // Test that an upgrade is rejected. Assumes that the image was build
733 // such that the upgrade is instead a downgrade.
734 pub fn run_nodowngrade(&self) -> bool {
735 if !Caps::DowngradePrevention.present() {
736 return false;
737 }
738
739 let mut flash = self.flash.clone();
740 let mut fails = 0;
741
742 info!("Try no downgrade");
743
744 // First, do a normal upgrade.
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300745 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700746 warn!("Failed first boot");
747 fails += 1;
748 }
749
750 if !self.verify_images(&flash, 0, 0) {
751 warn!("Failed verification after downgrade rejection");
752 fails += 1;
753 }
754
755 if fails > 0 {
756 error!("Error testing downgrade rejection");
757 }
758
759 fails > 0
760 }
761
David Vincze2d736ad2019-02-18 11:50:22 +0100762 // Tests a new image written to the primary slot that already has magic and
763 // image_ok set while there is no image on the secondary slot, so no revert
764 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700765 pub fn run_norevert_newimage(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300766 if !Caps::modifies_flash() {
767 info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
768 return false;
769 }
770
David Brown76101572019-02-28 11:29:03 -0700771 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700772 let mut fails = 0;
773
774 info!("Try non-revert on imgtool generated image");
775
David Brown84b49f72019-03-01 10:58:22 -0700776 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700777
David Vincze2d736ad2019-02-18 11:50:22 +0100778 // This simulates writing an image created by imgtool to
779 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700780 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
781 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100782 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700783 fails += 1;
784 }
785
786 // Run the bootloader...
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300787 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700788 warn!("Failed first boot");
789 fails += 1;
790 }
791
792 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700793 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700794 warn!("Failed image verification");
795 fails += 1;
796 }
David Brown84b49f72019-03-01 10:58:22 -0700797 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
798 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100799 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700800 fails += 1;
801 }
David Brown84b49f72019-03-01 10:58:22 -0700802 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
803 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100804 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700805 fails += 1;
806 }
807
808 if fails > 0 {
809 error!("Expected a non revert with new image");
810 }
811
812 fails > 0
813 }
814
David Vincze2d736ad2019-02-18 11:50:22 +0100815 // Tests a new image written to the primary slot that already has magic and
816 // image_ok set while there is no image on the secondary slot, so no revert
817 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700818 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700819 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700820 let mut fails = 0;
821
822 info!("Try upgrade image with bad signature");
823
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300824 // Only perform this test if an upgrade is expected to happen.
825 if !Caps::modifies_flash() {
826 info!("Skipping upgrade image with bad signature");
827 return false;
828 }
829
David Brown84b49f72019-03-01 10:58:22 -0700830 self.mark_upgrades(&mut flash, 0);
831 self.mark_permanent_upgrades(&mut flash, 0);
832 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700833
David Brown84b49f72019-03-01 10:58:22 -0700834 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
835 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100836 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700837 fails += 1;
838 }
839
840 // Run the bootloader...
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300841 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700842 warn!("Failed first boot");
843 fails += 1;
844 }
845
846 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700847 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700848 warn!("Failed image verification");
849 fails += 1;
850 }
David Brown84b49f72019-03-01 10:58:22 -0700851 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
852 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100853 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700854 fails += 1;
855 }
856
857 if fails > 0 {
858 error!("Expected an upgrade failure when image has bad signature");
859 }
860
861 fails > 0
862 }
863
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300864 // Should detect there is a leftover trailer in an otherwise erased
865 // secondary slot and erase its trailer.
866 pub fn run_secondary_leftover_trailer(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300867 if !Caps::modifies_flash() {
868 return false;
869 }
870
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300871 let mut flash = self.flash.clone();
872 let mut fails = 0;
873
874 info!("Try with a leftover trailer in the secondary; must be erased");
875
876 // Add a trailer on the secondary slot
877 self.mark_permanent_upgrades(&mut flash, 1);
878 self.mark_upgrades(&mut flash, 1);
879
880 // Run the bootloader...
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300881 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300882 warn!("Failed first boot");
883 fails += 1;
884 }
885
886 // State should not have changed
887 if !self.verify_images(&flash, 0, 0) {
888 warn!("Failed image verification");
889 fails += 1;
890 }
891 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
892 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
893 warn!("Mismatched trailer for the secondary slot");
894 fails += 1;
895 }
896
897 if fails > 0 {
898 error!("Expected trailer on secondary slot to be erased");
899 }
900
901 fails > 0
902 }
903
David Brown5c9e0f12019-01-09 16:34:33 -0700904 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300905 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700906 }
907
David Brown5c9e0f12019-01-09 16:34:33 -0700908 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300909 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700910 }
911
912 /// This test runs a simple upgrade with no fails in the images, but
913 /// allowing for fails in the status area. This should run to the end
914 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700915 pub fn run_with_status_fails_complete(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300916 if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700917 return false;
918 }
919
David Brown76101572019-02-28 11:29:03 -0700920 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700921 let mut fails = 0;
922
923 info!("Try swap with status fails");
924
David Brown84b49f72019-03-01 10:58:22 -0700925 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700926 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700927
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300928 let result = c::boot_go(&mut flash, &self.areadesc, None, true);
929 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700930 warn!("Failed!");
931 fails += 1;
932 }
933
934 // Failed writes to the marked "bad" region don't assert anymore.
935 // Any detected assert() is happening in another part of the code.
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300936 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -0700937 warn!("At least one assert() was called");
938 fails += 1;
939 }
940
David Brown84b49f72019-03-01 10:58:22 -0700941 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
942 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100943 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700944 fails += 1;
945 }
946
David Brown84b49f72019-03-01 10:58:22 -0700947 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700948 warn!("Failed image verification");
949 fails += 1;
950 }
951
David Vincze2d736ad2019-02-18 11:50:22 +0100952 info!("validate primary slot enabled; \
953 re-run of boot_go should just work");
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300954 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700955 warn!("Failed!");
956 fails += 1;
957 }
958
959 if fails > 0 {
960 error!("Error running upgrade with status write fails");
961 }
962
963 fails > 0
964 }
965
966 /// This test runs a simple upgrade with no fails in the images, but
967 /// allowing for fails in the status area. This should run to the end
968 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700969 pub fn run_with_status_fails_with_reset(&self) -> bool {
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300970 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700971 false
David Vincze2d736ad2019-02-18 11:50:22 +0100972 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700973
David Brown76101572019-02-28 11:29:03 -0700974 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700975 let mut fails = 0;
976 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700977
David Brown85904a82019-01-11 13:45:12 -0700978 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700979
David Brown85904a82019-01-11 13:45:12 -0700980 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700981
David Brown84b49f72019-03-01 10:58:22 -0700982 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700983 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700984
985 // Should not fail, writing to bad regions does not assert
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300986 let asserts = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700987 if asserts != 0 {
988 warn!("At least one assert() was called");
989 fails += 1;
990 }
991
David Brown76101572019-02-28 11:29:03 -0700992 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700993
994 info!("Resuming an interrupted swap operation");
Roman Okhrimenko977b3752022-03-31 14:40:48 +0300995 let asserts = c::boot_go(&mut flash, &self.areadesc, None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700996
997 // This might throw no asserts, for large sector devices, where
998 // a single failure writing is indistinguishable from no failure,
999 // or throw a single assert for small sector devices that fail
1000 // multiple times...
1001 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +01001002 warn!("Expected single assert validating the primary slot, \
1003 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -07001004 fails += 1;
1005 }
1006
1007 if fails > 0 {
1008 error!("Error running upgrade with status write fails");
1009 }
1010
1011 fails > 0
1012 } else {
David Brown76101572019-02-28 11:29:03 -07001013 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001014 let mut fails = 0;
1015
1016 info!("Try interrupted swap with status fails");
1017
David Brown84b49f72019-03-01 10:58:22 -07001018 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001019 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -07001020
1021 // This is expected to fail while writing to bad regions...
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001022 let asserts = c::boot_go(&mut flash, &self.areadesc, None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001023 if asserts == 0 {
1024 warn!("No assert() detected");
1025 fails += 1;
1026 }
1027
1028 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -07001029 }
David Brown5c9e0f12019-01-09 16:34:33 -07001030 }
1031
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001032 /// Test the direct XIP configuration. With this mode, flash images are never moved, and the
1033 /// bootloader merely selects which partition is the proper one to boot.
1034 pub fn run_direct_xip(&self) -> bool {
1035 if !Caps::DirectXip.present() {
1036 return false;
1037 }
1038
1039 // Clone the flash so we can tell if unchanged.
1040 let mut flash = self.flash.clone();
1041
1042 let result = c::boot_go(&mut flash, &self.areadesc, None, true);
1043
1044 // Ensure the boot was successful.
1045 let resp = if let Some(resp) = result.resp() {
1046 resp
1047 } else {
1048 panic!("Boot didn't return a valid result");
1049 };
1050
1051 // This configuration should always try booting from the first upgrade slot.
1052 if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
1053 assert_eq!(offset, resp.image_off as usize);
1054 assert_eq!(dev_id, resp.flash_dev_id);
1055 } else {
1056 panic!("Unable to find upgrade image");
1057 }
1058 false
1059 }
1060
1061 /// Test the ram-loading.
1062 pub fn run_ram_load(&self) -> bool {
1063 if !Caps::RamLoad.present() {
1064 return false;
1065 }
1066
1067 // Clone the flash so we can tell if unchanged.
1068 let mut flash = self.flash.clone();
1069
1070 // Setup ram based on the ram configuration we determined earlier for the images.
1071 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1072
1073 // println!("Ram: {:#?}", self.ram);
1074
1075 // Verify that the images area loaded into this.
1076 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None, true));
1077 if !result.success() {
1078 error!("Failed to execute ram-load");
1079 return true;
1080 }
1081
1082 // Verify each image.
1083 for image in &self.images {
1084 let place = self.ram.lookup(&image.slots[0]);
1085 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1086 place.size as usize);
1087 let src_sz = image.upgrades.size();
1088 if src_sz > ram_image.len() {
1089 error!("Image ended up too large, nonsensical");
1090 return true;
1091 }
1092 let src_image = &image.upgrades.plain[0..src_sz];
1093 let ram_image = &ram_image[0..src_sz];
1094 if ram_image != src_image {
1095 error!("Image not loaded correctly");
1096 return true;
1097 }
1098
1099 }
1100
1101 return false;
1102 }
1103
David Brown5c9e0f12019-01-09 16:34:33 -07001104 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -07001105 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001106 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -07001107 if Caps::OverwriteUpgrade.present() {
1108 return;
1109 }
1110
David Brown84b49f72019-03-01 10:58:22 -07001111 // Set this for each image.
1112 for image in &self.images {
1113 let dev_id = &image.slots[slot].dev_id;
1114 let dev = flash.get_mut(&dev_id).unwrap();
1115 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001116 let off = &image.slots[slot].base_off;
1117 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -07001118 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -07001119
David Brown84b49f72019-03-01 10:58:22 -07001120 // Mark the status area as a bad area
1121 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1122 }
David Brown5c9e0f12019-01-09 16:34:33 -07001123 }
1124
David Brown76101572019-02-28 11:29:03 -07001125 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001126 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001127 return;
1128 }
1129
David Brown84b49f72019-03-01 10:58:22 -07001130 for image in &self.images {
1131 let dev_id = &image.slots[slot].dev_id;
1132 let dev = flash.get_mut(&dev_id).unwrap();
1133 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001134
David Brown84b49f72019-03-01 10:58:22 -07001135 // Disabling write verification the only assert triggered by
1136 // boot_go should be checking for integrity of status bytes.
1137 dev.set_verify_writes(false);
1138 }
David Brown5c9e0f12019-01-09 16:34:33 -07001139 }
1140
David Browndb505822019-03-01 10:04:20 -07001141 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1142 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001143 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001144 // Clone the flash to have a new copy.
1145 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001146
Fabio Utziged4a5362019-07-30 12:43:23 -03001147 if permanent {
1148 self.mark_permanent_upgrades(&mut flash, 1);
1149 }
David Brown5c9e0f12019-01-09 16:34:33 -07001150
David Browndb505822019-03-01 10:04:20 -07001151 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001152
David Browndb505822019-03-01 10:04:20 -07001153 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001154 x if x.interrupted() => (true, stop.unwrap()),
1155 x if x.success() => (false, -counter),
1156 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001157 };
David Brown5c9e0f12019-01-09 16:34:33 -07001158
David Browndb505822019-03-01 10:04:20 -07001159 counter = 0;
1160 if first_interrupted {
1161 // fl.dump();
1162 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001163 x if x.interrupted() => panic!("Shouldn't stop again"),
1164 x if x.success() => (),
1165 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001166 }
1167 }
David Brown5c9e0f12019-01-09 16:34:33 -07001168
David Browndb505822019-03-01 10:04:20 -07001169 (flash, count - counter)
1170 }
1171
1172 fn try_revert(&self, count: usize) -> SimMultiFlash {
1173 let mut flash = self.flash.clone();
1174
1175 // fl.write_file("image0.bin").unwrap();
1176 for i in 0 .. count {
1177 info!("Running boot pass {}", i + 1);
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001178 assert!(c::boot_go(&mut flash, &self.areadesc, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001179 }
1180 flash
1181 }
1182
1183 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1184 let mut flash = self.flash.clone();
1185 let mut fails = 0;
1186
1187 let mut counter = stop;
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001188 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001189 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001190 fails += 1;
1191 }
1192
Fabio Utzig8af7f792019-07-30 12:40:01 -03001193 // In a multi-image setup, copy done might be set if any number of
1194 // images was already successfully swapped.
1195 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1196 warn!("copy_done should be unset");
1197 fails += 1;
1198 }
1199
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001200 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001201 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001202 fails += 1;
1203 }
1204
David Brown84b49f72019-03-01 10:58:22 -07001205 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001206 warn!("Image in the primary slot before revert is invalid at stop={}",
1207 stop);
1208 fails += 1;
1209 }
David Brown84b49f72019-03-01 10:58:22 -07001210 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001211 warn!("Image in the secondary slot before revert is invalid at stop={}",
1212 stop);
1213 fails += 1;
1214 }
David Brown84b49f72019-03-01 10:58:22 -07001215 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1216 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001217 warn!("Mismatched trailer for the primary slot before revert");
1218 fails += 1;
1219 }
David Brown84b49f72019-03-01 10:58:22 -07001220 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1221 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001222 warn!("Mismatched trailer for the secondary slot before revert");
1223 fails += 1;
1224 }
1225
1226 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001227 let mut counter = stop;
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001228 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001229 warn!("Should have stopped revert at interruption point");
1230 fails += 1;
1231 }
1232
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001233 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001234 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001235 fails += 1;
1236 }
1237
David Brown84b49f72019-03-01 10:58:22 -07001238 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001239 warn!("Image in the primary slot after revert is invalid at stop={}",
1240 stop);
1241 fails += 1;
1242 }
David Brown84b49f72019-03-01 10:58:22 -07001243 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001244 warn!("Image in the secondary slot after revert is invalid at stop={}",
1245 stop);
1246 fails += 1;
1247 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001248
David Brown84b49f72019-03-01 10:58:22 -07001249 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1250 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001251 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001252 fails += 1;
1253 }
David Brown84b49f72019-03-01 10:58:22 -07001254 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1255 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001256 warn!("Mismatched trailer for the secondary slot after revert");
1257 fails += 1;
1258 }
1259
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001260 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001261 warn!("Should have finished 3rd boot");
1262 fails += 1;
1263 }
1264
1265 if !self.verify_images(&flash, 0, 0) {
1266 warn!("Image in the primary slot is invalid on 1st boot after revert");
1267 fails += 1;
1268 }
1269 if !self.verify_images(&flash, 1, 1) {
1270 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1271 fails += 1;
1272 }
1273
David Browndb505822019-03-01 10:04:20 -07001274 fails > 0
1275 }
1276
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001277
David Browndb505822019-03-01 10:04:20 -07001278 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1279 let mut flash = self.flash.clone();
1280
David Brown84b49f72019-03-01 10:58:22 -07001281 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001282
1283 let mut rng = rand::thread_rng();
1284 let mut resets = vec![0i32; count];
1285 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001286 for reset in &mut resets {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001287 let reset_counter = rng.gen_range(1 ..= remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001288 let mut counter = reset_counter;
1289 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001290 x if x.interrupted() => (),
1291 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001292 }
1293 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001294 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001295 }
1296
1297 match c::boot_go(&mut flash, &self.areadesc, None, false) {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001298 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1299 x if x.success() => (),
1300 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001301 }
David Brown5c9e0f12019-01-09 16:34:33 -07001302
David Browndb505822019-03-01 10:04:20 -07001303 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001304 }
David Brown84b49f72019-03-01 10:58:22 -07001305
1306 /// Verify the image in the given flash device, the specified slot
1307 /// against the expected image.
1308 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001309 self.images.iter().all(|image| {
1310 verify_image(flash, &image.slots[slot],
1311 match against {
1312 0 => &image.primaries,
1313 1 => &image.upgrades,
1314 _ => panic!("Invalid 'against'")
1315 })
1316 })
David Brown84b49f72019-03-01 10:58:22 -07001317 }
1318
David Brownc3898d62019-08-05 14:20:02 -06001319 /// Verify the images, according to the dependency test.
1320 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1321 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1322 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1323 if !verify_image(flash, &image.slots[0],
1324 match upgrade {
1325 UpgradeInfo::Upgraded => &image.upgrades,
1326 UpgradeInfo::Held => &image.primaries,
1327 }) {
1328 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1329 return true;
1330 }
1331 }
1332
1333 false
1334 }
1335
Fabio Utzig8af7f792019-07-30 12:40:01 -03001336 /// Verify that at least one of the trailers of the images have the
1337 /// specified values.
1338 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1339 magic: Option<u8>, image_ok: Option<u8>,
1340 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001341 self.images.iter().any(|image| {
1342 verify_trailer(flash, &image.slots[slot],
1343 magic, image_ok, copy_done)
1344 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001345 }
1346
David Brown84b49f72019-03-01 10:58:22 -07001347 /// Verify that the trailers of the images have the specified
1348 /// values.
1349 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1350 magic: Option<u8>, image_ok: Option<u8>,
1351 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001352 self.images.iter().all(|image| {
1353 verify_trailer(flash, &image.slots[slot],
1354 magic, image_ok, copy_done)
1355 })
David Brown84b49f72019-03-01 10:58:22 -07001356 }
1357
1358 /// Mark each of the images for permanent upgrade.
1359 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1360 for image in &self.images {
1361 mark_permanent_upgrade(flash, &image.slots[slot]);
1362 }
1363 }
1364
1365 /// Mark each of the images for permanent upgrade.
1366 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1367 for image in &self.images {
1368 mark_upgrade(flash, &image.slots[slot]);
1369 }
1370 }
David Brown297029a2019-08-13 14:29:51 -06001371
1372 /// Dump out the flash image(s) to one or more files for debugging
1373 /// purposes. The names will be written as either "{prefix}.mcubin" or
1374 /// "{prefix}-001.mcubin" depending on how many images there are.
1375 pub fn debug_dump(&self, prefix: &str) {
1376 for (id, fdev) in &self.flash {
1377 let name = if self.flash.len() == 1 {
1378 format!("{}.mcubin", prefix)
1379 } else {
1380 format!("{}-{:>0}.mcubin", prefix, id)
1381 };
1382 fdev.write_file(&name).unwrap();
1383 }
1384 }
David Brown5c9e0f12019-01-09 16:34:33 -07001385}
1386
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001387impl RamData {
1388 // TODO: This is not correct. The second slot of each image should be at the same address as
1389 // the primary.
1390 fn new(slots: &[[SlotInfo; 2]]) -> RamData {
1391 let mut addr = RAM_LOAD_ADDR;
1392 let mut places = BTreeMap::new();
1393 // println!("Setup:-------------");
1394 for imgs in slots {
1395 for si in imgs {
1396 // println!("Setup: si: {:?}", si);
1397 let offset = addr;
1398 let size = si.len as u32;
1399 places.insert(SlotKey {
1400 dev_id: si.dev_id,
1401 base_off: si.base_off,
1402 }, SlotPlace { offset, size });
1403 // println!(" load: offset: {}, size: {}", offset, size);
1404 }
1405 addr += imgs[0].len as u32;
1406 }
1407 RamData {
1408 places,
1409 total: addr,
1410 }
1411 }
1412
1413 /// Lookup the ram data associated with a given flash partition. We just panic if not present,
1414 /// because all slots used should be in the map.
1415 fn lookup(&self, slot: &SlotInfo) -> &SlotPlace {
1416 self.places.get(&SlotKey{dev_id: slot.dev_id, base_off: slot.base_off})
1417 .expect("RamData should contain all slots")
1418 }
1419}
1420
David Brown5c9e0f12019-01-09 16:34:33 -07001421/// Show the flash layout.
1422#[allow(dead_code)]
1423fn show_flash(flash: &dyn Flash) {
1424 println!("---- Flash configuration ----");
1425 for sector in flash.sector_iter() {
1426 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1427 sector.num, sector.base, sector.size);
1428 }
David Brown599b2db2021-03-10 05:23:26 -07001429 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001430}
1431
1432/// Install a "program" into the given image. This fakes the image header, or at least all of the
1433/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001434fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001435 ram: &RamData,
David Brownc3898d62019-08-05 14:20:02 -06001436 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001437 let offset = slot.base_off;
1438 let slot_len = slot.len;
1439 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001440
David Brown43643dd2019-01-11 15:43:28 -07001441 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001442
David Brownc3898d62019-08-05 14:20:02 -06001443 // Add the dependencies early to the tlv.
1444 for dep in deps.my_deps(offset, slot.index) {
1445 tlv.add_dependency(deps.other_id(), &dep);
1446 }
1447
David Brown5c9e0f12019-01-09 16:34:33 -07001448 const HDR_SIZE: usize = 32;
1449
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001450 let place = ram.lookup(&slot);
1451 let load_addr = if Caps::RamLoad.present() {
1452 place.offset
1453 } else {
1454 0
1455 };
1456
David Brown5c9e0f12019-01-09 16:34:33 -07001457 // Generate a boot header. Note that the size doesn't include the header.
1458 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001459 magic: tlv.get_magic(),
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001460 load_addr,
David Brown5c9e0f12019-01-09 16:34:33 -07001461 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001462 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001463 img_size: len as u32,
1464 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001465 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001466 _pad2: 0,
1467 };
1468
1469 let mut b_header = [0; HDR_SIZE];
1470 b_header[..32].clone_from_slice(header.as_raw());
1471 assert_eq!(b_header.len(), HDR_SIZE);
1472
1473 tlv.add_bytes(&b_header);
1474
1475 // The core of the image itself is just pseudorandom data.
1476 let mut b_img = vec![0; len];
1477 splat(&mut b_img, offset);
1478
David Browncb47dd72019-08-05 14:21:49 -06001479 // Add some information at the start of the payload to make it easier
1480 // to see what it is. This will fail if the image itself is too small.
1481 {
1482 let mut wr = Cursor::new(&mut b_img);
1483 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1484 offset, dev_id, slot).unwrap();
1485 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1486 }
1487
David Brown5c9e0f12019-01-09 16:34:33 -07001488 // TLV signatures work over plain image
1489 tlv.add_bytes(&b_img);
1490
1491 // Generate encrypted images
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001492 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1493 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001494 let mut b_encimg = vec![];
1495 if is_encrypted {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001496 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1497 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001498 tlv.generate_enc_key();
1499 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001500 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001501 b_encimg = b_img.clone();
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001502 if aes256 {
1503 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
1504 let block = Aes256::new(&key);
1505 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
1506 cipher.apply_keystream(&mut b_encimg);
1507 } else {
1508 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
1509 let block = Aes128::new(&key);
1510 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
1511 cipher.apply_keystream(&mut b_encimg);
1512 }
David Brown5c9e0f12019-01-09 16:34:33 -07001513 }
1514
1515 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001516 if bad_sig {
1517 tlv.corrupt_sig();
1518 }
1519 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001520
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001521 let dev = flash.get_mut(&dev_id).unwrap();
1522
David Brown5c9e0f12019-01-09 16:34:33 -07001523 let mut buf = vec![];
1524 buf.append(&mut b_header.to_vec());
1525 buf.append(&mut b_img);
1526 buf.append(&mut b_tlv.clone());
1527
David Brown95de4502019-11-15 12:01:34 -07001528 // Pad the buffer to a multiple of the flash alignment.
1529 let align = dev.align();
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001530 let image_sz = buf.len();
David Brown95de4502019-11-15 12:01:34 -07001531 while buf.len() % align != 0 {
1532 buf.push(dev.erased_val());
1533 }
1534
David Brown5c9e0f12019-01-09 16:34:33 -07001535 let mut encbuf = vec![];
1536 if is_encrypted {
1537 encbuf.append(&mut b_header.to_vec());
1538 encbuf.append(&mut b_encimg);
1539 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001540
1541 while encbuf.len() % align != 0 {
1542 encbuf.push(dev.erased_val());
1543 }
David Brown5c9e0f12019-01-09 16:34:33 -07001544 }
1545
David Vincze2d736ad2019-02-18 11:50:22 +01001546 // Since images are always non-encrypted in the primary slot, we first write
1547 // an encrypted image, re-read to use for verification, erase + flash
1548 // un-encrypted. In the secondary slot the image is written un-encrypted,
1549 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001550
David Brown3b090212019-07-30 15:59:28 -06001551 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001552 let enc_copy: Option<Vec<u8>>;
1553
1554 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001555 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001556
1557 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001558 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001559
1560 enc_copy = Some(enc);
1561
David Brown76101572019-02-28 11:29:03 -07001562 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001563 } else {
1564 enc_copy = None;
1565 }
1566
David Brown76101572019-02-28 11:29:03 -07001567 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001568
1569 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001570 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001571
David Brownca234692019-02-28 11:22:19 -07001572 ImageData {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001573 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001574 plain: copy,
1575 cipher: enc_copy,
1576 }
David Brown5c9e0f12019-01-09 16:34:33 -07001577 } else {
1578
David Brown76101572019-02-28 11:29:03 -07001579 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001580
1581 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001582 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001583
1584 let enc_copy: Option<Vec<u8>>;
1585
1586 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001587 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001588
David Brown76101572019-02-28 11:29:03 -07001589 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001590
1591 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001592 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001593
1594 enc_copy = Some(enc);
1595 } else {
1596 enc_copy = None;
1597 }
1598
David Brownca234692019-02-28 11:22:19 -07001599 ImageData {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001600 size: image_sz,
David Brownca234692019-02-28 11:22:19 -07001601 plain: copy,
1602 cipher: enc_copy,
1603 }
David Brown5c9e0f12019-01-09 16:34:33 -07001604 }
David Brown5c9e0f12019-01-09 16:34:33 -07001605}
1606
David Brown873be312019-09-03 12:22:32 -06001607/// Install no image. This is used when no upgrade happens.
1608fn install_no_image() -> ImageData {
1609 ImageData {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001610 size: 0,
David Brown873be312019-09-03 12:22:32 -06001611 plain: vec![],
1612 cipher: None,
1613 }
1614}
1615
David Brown5c9e0f12019-01-09 16:34:33 -07001616fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001617 if Caps::EcdsaP224.present() {
1618 panic!("Ecdsa P224 not supported in Simulator");
1619 }
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001620 let mut aes_key_size = 128;
1621 if Caps::Aes256.present() {
1622 aes_key_size = 256;
1623 }
David Brown5c9e0f12019-01-09 16:34:33 -07001624
David Brownb8882112019-01-11 14:04:11 -07001625 if Caps::EncKw.present() {
1626 if Caps::RSA2048.present() {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001627 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001628 } else if Caps::EcdsaP256.present() {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001629 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001630 } else {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001631 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001632 }
1633 } else if Caps::EncRsa.present() {
1634 if Caps::RSA2048.present() {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001635 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001636 } else {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001637 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001638 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001639 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001640 if Caps::EcdsaP256.present() {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001641 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001642 } else {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001643 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001644 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001645 } else if Caps::EncX25519.present() {
1646 if Caps::Ed25519.present() {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001647 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001648 } else {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001649 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001650 }
David Brownb8882112019-01-11 14:04:11 -07001651 } else {
1652 // The non-encrypted configuration.
1653 if Caps::RSA2048.present() {
1654 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001655 } else if Caps::RSA3072.present() {
1656 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001657 } else if Caps::EcdsaP256.present() {
1658 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001659 } else if Caps::Ed25519.present() {
1660 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001661 } else {
1662 TlvGen::new_hash_only()
1663 }
1664 }
David Brown5c9e0f12019-01-09 16:34:33 -07001665}
1666
David Brownca234692019-02-28 11:22:19 -07001667impl ImageData {
1668 /// Find the image contents for the given slot. This assumes that slot 0
1669 /// is unencrypted, and slot 1 is encrypted.
1670 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001671 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001672 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001673 match (encrypted, slot) {
1674 (false, _) => &self.plain,
1675 (true, 0) => &self.plain,
1676 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1677 _ => panic!("Invalid slot requested"),
1678 }
David Brown5c9e0f12019-01-09 16:34:33 -07001679 }
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001680
1681 fn size(&self) -> usize {
1682 self.size
1683 }
David Brown5c9e0f12019-01-09 16:34:33 -07001684}
1685
David Brown5c9e0f12019-01-09 16:34:33 -07001686/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001687fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1688 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001689 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001690 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001691
1692 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001693 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001694 let dev = flash.get(&dev_id).unwrap();
1695 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001696
1697 if buf != &copy[..] {
1698 for i in 0 .. buf.len() {
1699 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001700 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1701 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001702 break;
1703 }
1704 }
1705 false
1706 } else {
1707 true
1708 }
1709}
1710
David Brown3b090212019-07-30 15:59:28 -06001711fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001712 magic: Option<u8>, image_ok: Option<u8>,
1713 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001714 if Caps::OverwriteUpgrade.present() {
1715 return true;
1716 }
David Brown5c9e0f12019-01-09 16:34:33 -07001717
David Brown3b090212019-07-30 15:59:28 -06001718 let offset = slot.trailer_off + c::boot_max_align();
1719 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001720 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001721 let mut failed = false;
1722
David Brown76101572019-02-28 11:29:03 -07001723 let dev = flash.get(&dev_id).unwrap();
1724 let erased_val = dev.erased_val();
1725 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001726
1727 failed |= match magic {
1728 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001729 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001730 warn!("\"magic\" mismatch at {:#x}", offset);
1731 true
1732 } else if v == 3 {
1733 let expected = [erased_val; 16];
David Brownd36f6b12021-03-10 05:23:56 -07001734 if copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001735 warn!("\"magic\" mismatch at {:#x}", offset);
1736 true
1737 } else {
1738 false
1739 }
1740 } else {
1741 false
1742 }
1743 },
1744 None => false,
1745 };
1746
1747 failed |= match image_ok {
1748 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001749 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001750 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1751 true
1752 } else {
1753 false
1754 }
1755 },
1756 None => false,
1757 };
1758
1759 failed |= match copy_done {
1760 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001761 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001762 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1763 true
1764 } else {
1765 false
1766 }
1767 },
1768 None => false,
1769 };
1770
1771 !failed
1772}
1773
David Brown297029a2019-08-13 14:29:51 -06001774/// Install a partition table. This is a simplified partition table that
1775/// we write at the beginning of flash so make it easier for external tools
1776/// to analyze these images.
1777fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1778 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1779 for &id in &ids {
1780 // If there are any partitions in this device that start at 0, and
1781 // aren't marked as the BootLoader partition, avoid adding the
1782 // partition table. This makes it harder to view the image, but
1783 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07001784 let skip_ptable = areadesc
1785 .iter_areas()
1786 .any(|area| {
1787 area.device_id == id &&
1788 area.off == 0 &&
1789 area.flash_id != FlashId::BootLoader
1790 });
1791 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06001792 if log_enabled!(Info) {
1793 let special: Vec<FlashId> = areadesc.iter_areas()
1794 .filter(|area| area.device_id == id && area.off == 0)
1795 .map(|area| area.flash_id)
1796 .collect();
1797 info!("Skipping partition table: {:?}", special);
1798 }
1799 break;
1800 }
1801
1802 let mut buf: Vec<u8> = vec![];
1803 write!(&mut buf, "mcuboot\0").unwrap();
1804
1805 // Iterate through all of the partitions in that device, and encode
1806 // into the table.
1807 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1808 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1809
1810 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1811 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1812 buf.write_u32::<LittleEndian>(area.off).unwrap();
1813 buf.write_u32::<LittleEndian>(area.size).unwrap();
1814 buf.write_u32::<LittleEndian>(0).unwrap();
1815 }
1816
1817 let dev = flash.get_mut(&id).unwrap();
1818
1819 // Pad to alignment.
1820 while buf.len() % dev.align() != 0 {
1821 buf.push(0);
1822 }
1823
1824 dev.write(0, &buf).unwrap();
1825 }
1826}
1827
David Brown5c9e0f12019-01-09 16:34:33 -07001828/// The image header
1829#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001830#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001831pub struct ImageHeader {
1832 magic: u32,
1833 load_addr: u32,
1834 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001835 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001836 img_size: u32,
1837 flags: u32,
1838 ver: ImageVersion,
1839 _pad2: u32,
1840}
1841
1842impl AsRaw for ImageHeader {}
1843
1844#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001845#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001846pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001847 pub major: u8,
1848 pub minor: u8,
1849 pub revision: u16,
1850 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001851}
1852
David Brownc3898d62019-08-05 14:20:02 -06001853#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001854pub struct SlotInfo {
1855 pub base_off: usize,
1856 pub trailer_off: usize,
1857 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001858 // Which slot within this device.
1859 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001860 pub dev_id: u8,
1861}
1862
David Brown347dc572019-11-15 11:37:25 -07001863const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1864 0x60, 0xd2, 0xef, 0x7f,
1865 0x35, 0x52, 0x50, 0x0f,
1866 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001867
1868// Replicates defines found in bootutil.h
1869const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1870const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1871
1872const BOOT_FLAG_SET: Option<u8> = Some(1);
1873const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1874
1875/// Write out the magic so that the loader tries doing an upgrade.
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001876#[cfg(not(feature = "swap-status"))]
David Brown76101572019-02-28 11:29:03 -07001877pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1878 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001879 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001880 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001881 if offset % align != 0 || MAGIC.len() % align != 0 {
1882 // The write size is larger than the magic value. Fill a buffer
1883 // with the erased value, put the MAGIC in it, and write it in its
1884 // entirety.
1885 let mut buf = vec![dev.erased_val(); align];
1886 buf[(offset % align)..].copy_from_slice(MAGIC);
1887 dev.write(offset - (offset % align), &buf).unwrap();
1888 } else {
1889 dev.write(offset, MAGIC).unwrap();
1890 }
David Brown5c9e0f12019-01-09 16:34:33 -07001891}
1892
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001893/// Write out the magic so that the loader tries doing an upgrade.
1894#[cfg(feature = "swap-status")]
1895pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1896 let dev = flash.get_mut(&slot.dev_id).unwrap();
1897 let align = dev.align();
1898 let offset = slot.trailer_off + c::boot_max_align() * 4;
1899 let mask = align - 1;
1900 let sector_off = offset & !mask;
1901 let mut buf = vec![dev.erased_val(); align];
1902 dev.read(sector_off, &mut buf).unwrap();
1903 buf[(offset & mask)..].copy_from_slice(MAGIC);
1904 dev.erase(sector_off, align).unwrap();
1905 dev.write(sector_off, &buf).unwrap();
1906}
1907
David Brown5c9e0f12019-01-09 16:34:33 -07001908/// Writes the image_ok flag which, guess what, tells the bootloader
1909/// the this image is ok (not a test, and no revert is to be performed).
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001910#[cfg(not(feature = "swap-status"))]
David Brown76101572019-02-28 11:29:03 -07001911fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001912 // Overwrite mode always is permanent, and only the magic is used in
1913 // the trailer. To avoid problems with large write sizes, don't try to
1914 // set anything in this case.
1915 if Caps::OverwriteUpgrade.present() {
1916 return;
1917 }
1918
David Brown76101572019-02-28 11:29:03 -07001919 let dev = flash.get_mut(&slot.dev_id).unwrap();
1920 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001921 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001922 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001923 let align = dev.align();
1924 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001925}
1926
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001927/// Writes the image_ok flag which, guess what, tells the bootloader
1928/// the this image is ok (not a test, and no revert is to be performed).
1929#[cfg(feature = "swap-status")]
1930fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1931 // Overwrite mode always is permanent, and only the magic is used in
1932 // the trailer. To avoid problems with large write sizes, don't try to
1933 // set anything in this case.
1934 if Caps::OverwriteUpgrade.present() {
1935 return;
1936 }
1937
1938 let dev = flash.get_mut(&slot.dev_id).unwrap();
1939 let align:usize = dev.align();
1940 let mask:usize = align - 1;
1941 let ok_off:usize = slot.trailer_off + c::boot_max_align() * 3;
1942 let sector_off:usize = ok_off & !mask;
1943 let mut buf = vec![dev.erased_val(); align];
1944 dev.read(sector_off, &mut buf).unwrap();
1945 buf[ok_off & mask] = 1u8;
1946 dev.erase(sector_off, align).unwrap();
1947 dev.write(sector_off, &buf[..align]).unwrap();
1948}
1949
David Brown5c9e0f12019-01-09 16:34:33 -07001950// Drop some pseudo-random gibberish onto the data.
1951fn splat(data: &mut [u8], seed: usize) {
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001952 let mut seed_block = [0u8; 32];
David Browncd842842020-07-09 15:46:53 -06001953 let mut buf = Cursor::new(&mut seed_block[..]);
1954 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
1955 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
1956 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
1957 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
1958 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07001959 rng.fill_bytes(data);
1960}
1961
1962/// Return a read-only view into the raw bytes of this object
1963trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07001964 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07001965 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1966 mem::size_of::<Self>()) }
1967 }
1968}
1969
1970pub fn show_sizes() {
1971 // This isn't panic safe.
1972 for min in &[1, 2, 4, 8] {
1973 let msize = c::boot_trailer_sz(*min);
1974 println!("{:2}: {} (0x{:x})", min, msize, msize);
1975 }
1976}
David Brown95de4502019-11-15 12:01:34 -07001977
1978#[cfg(not(feature = "large-write"))]
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001979#[cfg(not(feature = "swap-status"))]
David Brown95de4502019-11-15 12:01:34 -07001980fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001981 &[1, 2, 4, 8]
1982}
1983
1984#[cfg(feature = "large-write")]
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001985#[cfg(not(feature = "swap-status"))]
David Brown95de4502019-11-15 12:01:34 -07001986fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001987 &[1, 2, 4, 8, 128, 512]
1988}
Roman Okhrimenko977b3752022-03-31 14:40:48 +03001989
1990#[cfg(feature = "swap-status")]
1991fn test_alignments() -> &'static [usize] {
1992 &[512]
1993}