blob: 02ceb2958940b8d1262237dbbb094392710bbe61 [file] [log] [blame]
David Browne2acfae2020-01-21 16:45:01 -07001// Copyright (c) 2019 Linaro LTD
2// Copyright (c) 2019-2020 JUUL Labs
Salome Thirot6fdbf552021-05-14 16:46:14 +01003// Copyright (c) 2019-2021 Arm Limited
David Browne2acfae2020-01-21 16:45:01 -07004//
5// SPDX-License-Identifier: Apache-2.0
6
David Brown297029a2019-08-13 14:29:51 -06007use byteorder::{
8 LittleEndian, WriteBytesExt,
9};
10use log::{
11 Level::Info,
12 error,
13 info,
14 log_enabled,
15 warn,
16};
David Brown5c9e0f12019-01-09 16:34:33 -070017use rand::{
David Browncd842842020-07-09 15:46:53 -060018 Rng, RngCore, SeedableRng,
19 rngs::SmallRng,
David Brown5c9e0f12019-01-09 16:34:33 -070020};
21use std::{
David Brownbf32c272021-06-16 17:11:37 -060022 collections::{BTreeMap, HashSet},
David Browncb47dd72019-08-05 14:21:49 -060023 io::{Cursor, Write},
David Brown5c9e0f12019-01-09 16:34:33 -070024 mem,
25 slice,
26};
David Brown9c6322f2021-08-19 13:03:39 -060027use aes::{
28 Aes128,
David Brown5c9e0f12019-01-09 16:34:33 -070029 Aes128Ctr,
David Brown9c6322f2021-08-19 13:03:39 -060030 Aes256,
Salome Thirot6fdbf552021-05-14 16:46:14 +010031 Aes256Ctr,
David Brown9c6322f2021-08-19 13:03:39 -060032 NewBlockCipher,
David Brown5c9e0f12019-01-09 16:34:33 -070033};
David Brown9c6322f2021-08-19 13:03:39 -060034use cipher::{
35 FromBlockCipher,
36 generic_array::GenericArray,
37 StreamCipher,
38 };
David Brown5c9e0f12019-01-09 16:34:33 -070039
David Brown76101572019-02-28 11:29:03 -070040use simflash::{Flash, SimFlash, SimMultiFlash};
David Brown8a4e23b2021-06-11 10:29:01 -060041use mcuboot_sys::{c, AreaDesc, FlashId, RamBlock};
David Browne5133242019-02-28 11:05:19 -070042use crate::{
43 ALL_DEVICES,
44 DeviceName,
45};
David Brown5c9e0f12019-01-09 16:34:33 -070046use crate::caps::Caps;
David Brownc3898d62019-08-05 14:20:02 -060047use crate::depends::{
48 BoringDep,
49 Depender,
50 DepTest,
David Brown873be312019-09-03 12:22:32 -060051 DepType,
David Brown2ee5f7f2020-01-13 14:04:01 -070052 NO_DEPS,
David Brownc3898d62019-08-05 14:20:02 -060053 PairDep,
54 UpgradeInfo,
55};
Fabio Utzig90f449e2019-10-24 07:43:53 -030056use crate::tlv::{ManifestGen, TlvGen, TlvFlags};
Salome Thirot6fdbf552021-05-14 16:46:14 +010057use typenum::{U32, U16};
David Brown5c9e0f12019-01-09 16:34:33 -070058
David Brown8a4e23b2021-06-11 10:29:01 -060059/// For testing, use a non-zero offset for the ram-load, to make sure the offset is getting used
60/// properly, but the value is not really that important.
61const RAM_LOAD_ADDR: u32 = 1024;
62
David Browne5133242019-02-28 11:05:19 -070063/// A builder for Images. This describes a single run of the simulator,
64/// capturing the configuration of a particular set of devices, including
65/// the flash simulator(s) and the information about the slots.
66#[derive(Clone)]
67pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070068 flash: SimMultiFlash,
David Browne5133242019-02-28 11:05:19 -070069 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070070 slots: Vec<[SlotInfo; 2]>,
David Brownbf32c272021-06-16 17:11:37 -060071 ram: RamData,
David Browne5133242019-02-28 11:05:19 -070072}
73
David Brown998aa8d2019-02-28 10:54:50 -070074/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070075/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070076/// and upgrades hold the expected contents of these images.
77pub struct Images {
David Brown76101572019-02-28 11:29:03 -070078 flash: SimMultiFlash,
David Brownca234692019-02-28 11:22:19 -070079 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070080 images: Vec<OneImage>,
81 total_count: Option<i32>,
David Brownbf32c272021-06-16 17:11:37 -060082 ram: RamData,
David Brown84b49f72019-03-01 10:58:22 -070083}
84
85/// When doing multi-image, there is an instance of this information for
86/// each of the images. Single image there will be one of these.
87struct OneImage {
David Brownca234692019-02-28 11:22:19 -070088 slots: [SlotInfo; 2],
89 primaries: ImageData,
90 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070091}
92
93/// The Rust-side representation of an image. For unencrypted images, this
94/// is just the unencrypted payload. For encrypted images, we store both
95/// the encrypted and the plaintext.
96struct ImageData {
97 plain: Vec<u8>,
98 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -070099}
100
David Brownbf32c272021-06-16 17:11:37 -0600101/// For the RamLoad test cases, we need a contiguous area of RAM to load these images into. For
102/// multi-image builds, these may not correspond with the offsets. This has to be computed early,
103/// before images are built, because each image contains the offset where the image is to be loaded
104/// in the header, which is contained within the signature.
105#[derive(Clone, Debug)]
106struct RamData {
107 places: BTreeMap<SlotKey, SlotPlace>,
108 total: u32,
109}
110
111/// Every slot is indexed by this key.
112#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
113struct SlotKey {
114 dev_id: u8,
David Brownf17d3912021-06-23 16:10:51 -0600115 base_off: usize,
David Brownbf32c272021-06-16 17:11:37 -0600116}
117
118#[derive(Clone, Debug)]
119struct SlotPlace {
120 offset: u32,
121 size: u32,
122}
123
David Browne5133242019-02-28 11:05:19 -0700124impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -0700125 /// Construct a new image builder for the given device. Returns
126 /// Some(builder) if is possible to test this configuration, or None if
127 /// not possible (for example, if there aren't enough image slots).
Fabio Utzig114a6472019-11-28 10:24:09 -0300128 pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
129 let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
130
131 for cap in unsupported_caps {
132 if cap.present() {
133 return Err(format!("unsupported {:?}", cap));
134 }
135 }
David Browne5133242019-02-28 11:05:19 -0700136
David Brown06ef06e2019-03-05 12:28:10 -0700137 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -0700138
David Brown06ef06e2019-03-05 12:28:10 -0700139 let mut slots = Vec::with_capacity(num_images);
140 for image in 0..num_images {
141 // This mapping must match that defined in
142 // `boot/zephyr/include/sysflash/sysflash.h`.
143 let id0 = match image {
144 0 => FlashId::Image0,
145 1 => FlashId::Image2,
146 _ => panic!("More than 2 images not supported"),
147 };
148 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
149 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300150 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700151 };
152 let id1 = match image {
153 0 => FlashId::Image1,
154 1 => FlashId::Image3,
155 _ => panic!("More than 2 images not supported"),
156 };
157 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
158 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300159 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700160 };
David Browne5133242019-02-28 11:05:19 -0700161
Christopher Collinsa1c12042019-05-23 14:00:28 -0700162 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700163
David Brown06ef06e2019-03-05 12:28:10 -0700164 // Construct a primary image.
165 let primary = SlotInfo {
166 base_off: primary_base as usize,
167 trailer_off: primary_base + primary_len - offset_from_end,
168 len: primary_len as usize,
169 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600170 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700171 };
172
173 // And an upgrade image.
174 let secondary = SlotInfo {
175 base_off: secondary_base as usize,
176 trailer_off: secondary_base + secondary_len - offset_from_end,
177 len: secondary_len as usize,
178 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600179 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700180 };
181
182 slots.push([primary, secondary]);
183 }
David Browne5133242019-02-28 11:05:19 -0700184
David Brownbf32c272021-06-16 17:11:37 -0600185 let ram = RamData::new(&slots);
186
Fabio Utzig114a6472019-11-28 10:24:09 -0300187 Ok(ImagesBuilder {
David Brown4dfb33c2021-03-10 05:15:45 -0700188 flash,
189 areadesc,
190 slots,
David Brownbf32c272021-06-16 17:11:37 -0600191 ram,
David Brown5bc62c62019-03-05 12:11:48 -0700192 })
David Browne5133242019-02-28 11:05:19 -0700193 }
194
195 pub fn each_device<F>(f: F)
196 where F: Fn(Self)
197 {
198 for &dev in ALL_DEVICES {
David Brown95de4502019-11-15 12:01:34 -0700199 for &align in test_alignments() {
David Browne5133242019-02-28 11:05:19 -0700200 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700201 match Self::new(dev, align, erased_val) {
Fabio Utzig114a6472019-11-28 10:24:09 -0300202 Ok(run) => f(run),
203 Err(msg) => warn!("Skipping {}: {}", dev, msg),
David Brown5bc62c62019-03-05 12:11:48 -0700204 }
David Browne5133242019-02-28 11:05:19 -0700205 }
206 }
207 }
208 }
209
210 /// Construct an `Images` that doesn't expect an upgrade to happen.
David Brownc3898d62019-08-05 14:20:02 -0600211 pub fn make_no_upgrade_image(self, deps: &DepTest) -> Images {
212 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700213 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600214 let ram = self.ram.clone(); // TODO: This is wasteful.
David Brownc3898d62019-08-05 14:20:02 -0600215 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
216 let dep: Box<dyn Depender> = if num_images > 1 {
217 Box::new(PairDep::new(num_images, image_num, deps))
218 } else {
David Brown2ee5f7f2020-01-13 14:04:01 -0700219 Box::new(BoringDep::new(image_num, deps))
David Brownc3898d62019-08-05 14:20:02 -0600220 };
David Brownbf32c272021-06-16 17:11:37 -0600221 let primaries = install_image(&mut flash, &slots[0], 42784, &ram, &*dep, false);
David Brown873be312019-09-03 12:22:32 -0600222 let upgrades = match deps.depends[image_num] {
223 DepType::NoUpgrade => install_no_image(),
David Brownbf32c272021-06-16 17:11:37 -0600224 _ => install_image(&mut flash, &slots[1], 46928, &ram, &*dep, false)
David Brown873be312019-09-03 12:22:32 -0600225 };
David Brown84b49f72019-03-01 10:58:22 -0700226 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700227 slots,
228 primaries,
229 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700230 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600231 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700232 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700233 flash,
David Browne5133242019-02-28 11:05:19 -0700234 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700235 images,
David Browne5133242019-02-28 11:05:19 -0700236 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600237 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700238 }
239 }
240
David Brownc3898d62019-08-05 14:20:02 -0600241 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
242 let mut images = self.make_no_upgrade_image(deps);
David Brown84b49f72019-03-01 10:58:22 -0700243 for image in &images.images {
244 mark_upgrade(&mut images.flash, &image.slots[1]);
245 }
David Browne5133242019-02-28 11:05:19 -0700246
David Brown6db44d72021-05-26 16:22:58 -0600247 // The count is meaningless if no flash operations are performed.
248 if !Caps::modifies_flash() {
249 return images;
250 }
251
David Browne5133242019-02-28 11:05:19 -0700252 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300253 let total_count = match images.run_basic_upgrade(permanent) {
David Brown8973f552021-03-10 05:21:11 -0700254 Some(v) => v,
255 None =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600256 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
257 0
258 } else {
259 panic!("Unable to perform basic upgrade");
260 }
David Browne5133242019-02-28 11:05:19 -0700261 };
262
263 images.total_count = Some(total_count);
264 images
265 }
266
267 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700268 let mut bad_flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600269 let ram = self.ram.clone(); // TODO: Avoid this clone.
David Brownc3898d62019-08-05 14:20:02 -0600270 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
David Brown2ee5f7f2020-01-13 14:04:01 -0700271 let dep = BoringDep::new(image_num, &NO_DEPS);
David Brownbf32c272021-06-16 17:11:37 -0600272 let primaries = install_image(&mut bad_flash, &slots[0], 32784, &ram, &dep, false);
273 let upgrades = install_image(&mut bad_flash, &slots[1], 41928, &ram, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700274 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700275 slots,
276 primaries,
277 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700278 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700279 Images {
David Brown76101572019-02-28 11:29:03 -0700280 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700281 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700282 images,
David Browne5133242019-02-28 11:05:19 -0700283 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600284 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700285 }
286 }
287
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300288 pub fn make_erased_secondary_image(self) -> Images {
289 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600290 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300291 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
292 let dep = BoringDep::new(image_num, &NO_DEPS);
David Brownbf32c272021-06-16 17:11:37 -0600293 let primaries = install_image(&mut flash, &slots[0], 32784, &ram, &dep, false);
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300294 let upgrades = install_no_image();
295 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700296 slots,
297 primaries,
298 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300299 }}).collect();
300 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700301 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300302 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700303 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300304 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600305 ram: self.ram,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300306 }
307 }
308
Fabio Utzigd0157342020-10-02 15:22:11 -0300309 pub fn make_bootstrap_image(self) -> Images {
310 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600311 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzigd0157342020-10-02 15:22:11 -0300312 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
313 let dep = BoringDep::new(image_num, &NO_DEPS);
314 let primaries = install_no_image();
David Brownbf32c272021-06-16 17:11:37 -0600315 let upgrades = install_image(&mut flash, &slots[1], 32784, &ram, &dep, false);
Fabio Utzigd0157342020-10-02 15:22:11 -0300316 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700317 slots,
318 primaries,
319 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300320 }}).collect();
321 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700322 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300323 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700324 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300325 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600326 ram: self.ram,
Fabio Utzigd0157342020-10-02 15:22:11 -0300327 }
328 }
329
David Browne5133242019-02-28 11:05:19 -0700330 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300331 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700332 match device {
333 DeviceName::Stm32f4 => {
334 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700335 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
336 64 * 1024,
337 128 * 1024, 128 * 1024, 128 * 1024],
338 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700339 let dev_id = 0;
340 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700341 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700342 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
343 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
344 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
345
David Brown76101572019-02-28 11:29:03 -0700346 let mut flash = SimMultiFlash::new();
347 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300348 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700349 }
350 DeviceName::K64f => {
351 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700352 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700353
354 let dev_id = 0;
355 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700356 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700357 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
358 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
359 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
360
David Brown76101572019-02-28 11:29:03 -0700361 let mut flash = SimMultiFlash::new();
362 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300363 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700364 }
365 DeviceName::K64fBig => {
366 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
367 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700368 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700369
370 let dev_id = 0;
371 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700372 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700373 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
374 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
375 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
376
David Brown76101572019-02-28 11:29:03 -0700377 let mut flash = SimMultiFlash::new();
378 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300379 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700380 }
381 DeviceName::Nrf52840 => {
382 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
383 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700384 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700385
386 let dev_id = 0;
387 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700388 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700389 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
390 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
391 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
392
David Brown76101572019-02-28 11:29:03 -0700393 let mut flash = SimMultiFlash::new();
394 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300395 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700396 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300397 DeviceName::Nrf52840UnequalSlots => {
398 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
399
400 let dev_id = 0;
401 let mut areadesc = AreaDesc::new();
402 areadesc.add_flash_sectors(dev_id, &dev);
403 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
404 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
405
406 let mut flash = SimMultiFlash::new();
407 flash.insert(dev_id, dev);
408 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
409 }
David Browne5133242019-02-28 11:05:19 -0700410 DeviceName::Nrf52840SpiFlash => {
411 // Simulate nrf52840 with external SPI flash. The external SPI flash
412 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700413 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
414 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700415
416 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700417 areadesc.add_flash_sectors(0, &dev0);
418 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700419
420 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
421 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
422 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
423
David Brown76101572019-02-28 11:29:03 -0700424 let mut flash = SimMultiFlash::new();
425 flash.insert(0, dev0);
426 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300427 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700428 }
David Brown2bff6472019-03-05 13:58:35 -0700429 DeviceName::K64fMulti => {
430 // NXP style flash, but larger, to support multiple images.
431 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
432
433 let dev_id = 0;
434 let mut areadesc = AreaDesc::new();
435 areadesc.add_flash_sectors(dev_id, &dev);
436 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
437 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
438 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
439 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
440 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
441
442 let mut flash = SimMultiFlash::new();
443 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300444 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700445 }
David Browne5133242019-02-28 11:05:19 -0700446 }
447 }
David Brownc3898d62019-08-05 14:20:02 -0600448
449 pub fn num_images(&self) -> usize {
450 self.slots.len()
451 }
David Browne5133242019-02-28 11:05:19 -0700452}
453
David Brown5c9e0f12019-01-09 16:34:33 -0700454impl Images {
455 /// A simple upgrade without forced failures.
456 ///
457 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700458 /// inject failures at chosen steps. Returns None if it was unable to
459 /// count the operations in a basic upgrade.
460 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300461 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700462 info!("Total flash operation count={}", total_count);
463
David Brown84b49f72019-03-01 10:58:22 -0700464 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700465 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700466 None
David Brown5c9e0f12019-01-09 16:34:33 -0700467 } else {
David Brown8973f552021-03-10 05:21:11 -0700468 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700469 }
470 }
471
Fabio Utzigd0157342020-10-02 15:22:11 -0300472 pub fn run_bootstrap(&self) -> bool {
473 let mut flash = self.flash.clone();
474 let mut fails = 0;
475
476 if Caps::Bootstrap.present() {
477 info!("Try bootstraping image in the primary");
478
David Brownc423ac42021-06-04 13:47:34 -0600479 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigd0157342020-10-02 15:22:11 -0300480 warn!("Failed first boot");
481 fails += 1;
482 }
483
484 if !self.verify_images(&flash, 0, 1) {
485 warn!("Image in the first slot was not bootstrapped");
486 fails += 1;
487 }
488
489 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
490 BOOT_FLAG_SET, BOOT_FLAG_SET) {
491 warn!("Mismatched trailer for the primary slot");
492 fails += 1;
493 }
494 }
495
496 if fails > 0 {
497 error!("Expected trailer on secondary slot to be erased");
498 }
499
500 fails > 0
501 }
502
503
David Brownc3898d62019-08-05 14:20:02 -0600504 /// Test a simple upgrade, with dependencies given, and verify that the
505 /// image does as is described in the test.
506 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600507 if !Caps::modifies_flash() {
508 return false;
509 }
510
David Brownc3898d62019-08-05 14:20:02 -0600511 let (flash, _) = self.try_upgrade(None, true);
512
513 self.verify_dep_images(&flash, deps)
514 }
515
Fabio Utzigf5480c72019-11-28 10:41:57 -0300516 fn is_swap_upgrade(&self) -> bool {
517 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
518 }
519
David Brown5c9e0f12019-01-09 16:34:33 -0700520 pub fn run_basic_revert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600521 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700522 return false;
523 }
David Brown5c9e0f12019-01-09 16:34:33 -0700524
David Brown5c9e0f12019-01-09 16:34:33 -0700525 let mut fails = 0;
526
527 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300528 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700529 for count in 2 .. 5 {
530 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700531 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700532 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700533 error!("Revert failure on count {}", count);
534 fails += 1;
535 }
536 }
537 }
538
539 fails > 0
540 }
541
542 pub fn run_perm_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600543 if !Caps::modifies_flash() {
544 return false;
545 }
546
David Brown5c9e0f12019-01-09 16:34:33 -0700547 let mut fails = 0;
548 let total_flash_ops = self.total_count.unwrap();
549
550 // Let's try an image halfway through.
551 for i in 1 .. total_flash_ops {
552 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300553 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700554 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700555 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700556 warn!("FAIL at step {} of {}", i, total_flash_ops);
557 fails += 1;
558 }
559
David Brown84b49f72019-03-01 10:58:22 -0700560 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
561 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100562 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700563 fails += 1;
564 }
565
David Brown84b49f72019-03-01 10:58:22 -0700566 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
567 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100568 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700569 fails += 1;
570 }
571
David Brownaec56b22021-03-10 05:22:07 -0700572 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
573 warn!("Secondary slot FAIL at step {} of {}",
574 i, total_flash_ops);
575 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700576 }
577 }
578
579 if fails > 0 {
580 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
581 fails as f32 * 100.0 / total_flash_ops as f32);
582 }
583
584 fails > 0
585 }
586
David Brown5c9e0f12019-01-09 16:34:33 -0700587 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600588 if !Caps::modifies_flash() {
589 return false;
590 }
591
David Brown5c9e0f12019-01-09 16:34:33 -0700592 let mut fails = 0;
593 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700594 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700595 info!("Random interruptions at reset points={:?}", total_counts);
596
David Brown84b49f72019-03-01 10:58:22 -0700597 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300598 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700599 // TODO: This result is ignored.
600 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700601 } else {
602 true
603 };
David Vincze2d736ad2019-02-18 11:50:22 +0100604 if !primary_slot_ok || !secondary_slot_ok {
605 error!("Image mismatch after random interrupts: primary slot={} \
606 secondary slot={}",
607 if primary_slot_ok { "ok" } else { "fail" },
608 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700609 fails += 1;
610 }
David Brown84b49f72019-03-01 10:58:22 -0700611 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
612 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100613 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700614 fails += 1;
615 }
David Brown84b49f72019-03-01 10:58:22 -0700616 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
617 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100618 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700619 fails += 1;
620 }
621
622 if fails > 0 {
623 error!("Error testing perm upgrade with {} fails", total_fails);
624 }
625
626 fails > 0
627 }
628
David Brown5c9e0f12019-01-09 16:34:33 -0700629 pub fn run_revert_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600630 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700631 return false;
632 }
David Brown5c9e0f12019-01-09 16:34:33 -0700633
David Brown5c9e0f12019-01-09 16:34:33 -0700634 let mut fails = 0;
635
Fabio Utzigf5480c72019-11-28 10:41:57 -0300636 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300637 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700638 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700639 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700640 error!("Revert failed at interruption {}", i);
641 fails += 1;
642 }
643 }
644 }
645
646 fails > 0
647 }
648
David Brown5c9e0f12019-01-09 16:34:33 -0700649 pub fn run_norevert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600650 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700651 return false;
652 }
David Brown5c9e0f12019-01-09 16:34:33 -0700653
David Brown76101572019-02-28 11:29:03 -0700654 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700655 let mut fails = 0;
656
657 info!("Try norevert");
658
659 // First do a normal upgrade...
David Brownc423ac42021-06-04 13:47:34 -0600660 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700661 warn!("Failed first boot");
662 fails += 1;
663 }
664
665 //FIXME: copy_done is written by boot_go, is it ok if no copy
666 // was ever done?
667
David Brown84b49f72019-03-01 10:58:22 -0700668 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100669 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700670 fails += 1;
671 }
David Brown84b49f72019-03-01 10:58:22 -0700672 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
673 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100674 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700675 fails += 1;
676 }
David Brown84b49f72019-03-01 10:58:22 -0700677 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
678 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100679 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700680 fails += 1;
681 }
682
David Vincze2d736ad2019-02-18 11:50:22 +0100683 // Marks image in the primary slot as permanent,
684 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700685 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700686
David Brown84b49f72019-03-01 10:58:22 -0700687 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
688 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100689 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700690 fails += 1;
691 }
692
David Brownc423ac42021-06-04 13:47:34 -0600693 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700694 warn!("Failed second boot");
695 fails += 1;
696 }
697
David Brown84b49f72019-03-01 10:58:22 -0700698 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
699 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100700 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700701 fails += 1;
702 }
David Brown84b49f72019-03-01 10:58:22 -0700703 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700704 warn!("Failed image verification");
705 fails += 1;
706 }
707
708 if fails > 0 {
709 error!("Error running upgrade without revert");
710 }
711
712 fails > 0
713 }
714
David Brown2ee5f7f2020-01-13 14:04:01 -0700715 // Test that an upgrade is rejected. Assumes that the image was build
716 // such that the upgrade is instead a downgrade.
717 pub fn run_nodowngrade(&self) -> bool {
718 if !Caps::DowngradePrevention.present() {
719 return false;
720 }
721
722 let mut flash = self.flash.clone();
723 let mut fails = 0;
724
725 info!("Try no downgrade");
726
727 // First, do a normal upgrade.
David Brownc423ac42021-06-04 13:47:34 -0600728 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700729 warn!("Failed first boot");
730 fails += 1;
731 }
732
733 if !self.verify_images(&flash, 0, 0) {
734 warn!("Failed verification after downgrade rejection");
735 fails += 1;
736 }
737
738 if fails > 0 {
739 error!("Error testing downgrade rejection");
740 }
741
742 fails > 0
743 }
744
David Vincze2d736ad2019-02-18 11:50:22 +0100745 // Tests a new image written to the primary slot that already has magic and
746 // image_ok set while there is no image on the secondary slot, so no revert
747 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700748 pub fn run_norevert_newimage(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600749 if !Caps::modifies_flash() {
750 info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
751 return false;
752 }
753
David Brown76101572019-02-28 11:29:03 -0700754 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700755 let mut fails = 0;
756
757 info!("Try non-revert on imgtool generated image");
758
David Brown84b49f72019-03-01 10:58:22 -0700759 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700760
David Vincze2d736ad2019-02-18 11:50:22 +0100761 // This simulates writing an image created by imgtool to
762 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700763 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
764 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100765 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700766 fails += 1;
767 }
768
769 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600770 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700771 warn!("Failed first boot");
772 fails += 1;
773 }
774
775 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700776 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700777 warn!("Failed image verification");
778 fails += 1;
779 }
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 }
David Brown84b49f72019-03-01 10:58:22 -0700785 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
786 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100787 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700788 fails += 1;
789 }
790
791 if fails > 0 {
792 error!("Expected a non revert with new image");
793 }
794
795 fails > 0
796 }
797
David Vincze2d736ad2019-02-18 11:50:22 +0100798 // Tests a new image written to the primary slot that already has magic and
799 // image_ok set while there is no image on the secondary slot, so no revert
800 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700801 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700802 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700803 let mut fails = 0;
804
805 info!("Try upgrade image with bad signature");
806
David Brown6db44d72021-05-26 16:22:58 -0600807 // Only perform this test if an upgrade is expected to happen.
808 if !Caps::modifies_flash() {
809 info!("Skipping upgrade image with bad signature");
810 return false;
811 }
812
David Brown84b49f72019-03-01 10:58:22 -0700813 self.mark_upgrades(&mut flash, 0);
814 self.mark_permanent_upgrades(&mut flash, 0);
815 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700816
David Brown84b49f72019-03-01 10:58:22 -0700817 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
818 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100819 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700820 fails += 1;
821 }
822
823 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600824 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700825 warn!("Failed first boot");
826 fails += 1;
827 }
828
829 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700830 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700831 warn!("Failed image verification");
832 fails += 1;
833 }
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 if fails > 0 {
841 error!("Expected an upgrade failure when image has bad signature");
842 }
843
844 fails > 0
845 }
846
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300847 // Should detect there is a leftover trailer in an otherwise erased
848 // secondary slot and erase its trailer.
849 pub fn run_secondary_leftover_trailer(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600850 if !Caps::modifies_flash() {
851 return false;
852 }
853
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300854 let mut flash = self.flash.clone();
855 let mut fails = 0;
856
857 info!("Try with a leftover trailer in the secondary; must be erased");
858
859 // Add a trailer on the secondary slot
860 self.mark_permanent_upgrades(&mut flash, 1);
861 self.mark_upgrades(&mut flash, 1);
862
863 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600864 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300865 warn!("Failed first boot");
866 fails += 1;
867 }
868
869 // State should not have changed
870 if !self.verify_images(&flash, 0, 0) {
871 warn!("Failed image verification");
872 fails += 1;
873 }
874 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
875 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
876 warn!("Mismatched trailer for the secondary slot");
877 fails += 1;
878 }
879
880 if fails > 0 {
881 error!("Expected trailer on secondary slot to be erased");
882 }
883
884 fails > 0
885 }
886
David Brown5c9e0f12019-01-09 16:34:33 -0700887 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300888 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700889 }
890
David Brown5c9e0f12019-01-09 16:34:33 -0700891 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300892 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700893 }
894
895 /// This test runs a simple upgrade with no fails in the images, but
896 /// allowing for fails in the status area. This should run to the end
897 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700898 pub fn run_with_status_fails_complete(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600899 if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700900 return false;
901 }
902
David Brown76101572019-02-28 11:29:03 -0700903 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700904 let mut fails = 0;
905
906 info!("Try swap with status fails");
907
David Brown84b49f72019-03-01 10:58:22 -0700908 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700909 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700910
David Brownc423ac42021-06-04 13:47:34 -0600911 let result = c::boot_go(&mut flash, &self.areadesc, None, true);
912 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700913 warn!("Failed!");
914 fails += 1;
915 }
916
917 // Failed writes to the marked "bad" region don't assert anymore.
918 // Any detected assert() is happening in another part of the code.
David Brownc423ac42021-06-04 13:47:34 -0600919 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -0700920 warn!("At least one assert() was called");
921 fails += 1;
922 }
923
David Brown84b49f72019-03-01 10:58:22 -0700924 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
925 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100926 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700927 fails += 1;
928 }
929
David Brown84b49f72019-03-01 10:58:22 -0700930 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700931 warn!("Failed image verification");
932 fails += 1;
933 }
934
David Vincze2d736ad2019-02-18 11:50:22 +0100935 info!("validate primary slot enabled; \
936 re-run of boot_go should just work");
David Brownc423ac42021-06-04 13:47:34 -0600937 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700938 warn!("Failed!");
939 fails += 1;
940 }
941
942 if fails > 0 {
943 error!("Error running upgrade with status write fails");
944 }
945
946 fails > 0
947 }
948
949 /// This test runs a simple upgrade with no fails in the images, but
950 /// allowing for fails in the status area. This should run to the end
951 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700952 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600953 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700954 false
David Vincze2d736ad2019-02-18 11:50:22 +0100955 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700956
David Brown76101572019-02-28 11:29:03 -0700957 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700958 let mut fails = 0;
959 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700960
David Brown85904a82019-01-11 13:45:12 -0700961 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700962
David Brown85904a82019-01-11 13:45:12 -0700963 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700964
David Brown84b49f72019-03-01 10:58:22 -0700965 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700966 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700967
968 // Should not fail, writing to bad regions does not assert
David Brownc423ac42021-06-04 13:47:34 -0600969 let asserts = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700970 if asserts != 0 {
971 warn!("At least one assert() was called");
972 fails += 1;
973 }
974
David Brown76101572019-02-28 11:29:03 -0700975 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700976
977 info!("Resuming an interrupted swap operation");
David Brownc423ac42021-06-04 13:47:34 -0600978 let asserts = c::boot_go(&mut flash, &self.areadesc, None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700979
980 // This might throw no asserts, for large sector devices, where
981 // a single failure writing is indistinguishable from no failure,
982 // or throw a single assert for small sector devices that fail
983 // multiple times...
984 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100985 warn!("Expected single assert validating the primary slot, \
986 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700987 fails += 1;
988 }
989
990 if fails > 0 {
991 error!("Error running upgrade with status write fails");
992 }
993
994 fails > 0
995 } else {
David Brown76101572019-02-28 11:29:03 -0700996 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700997 let mut fails = 0;
998
999 info!("Try interrupted swap with status fails");
1000
David Brown84b49f72019-03-01 10:58:22 -07001001 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001002 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -07001003
1004 // This is expected to fail while writing to bad regions...
David Brownc423ac42021-06-04 13:47:34 -06001005 let asserts = c::boot_go(&mut flash, &self.areadesc, None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001006 if asserts == 0 {
1007 warn!("No assert() detected");
1008 fails += 1;
1009 }
1010
1011 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -07001012 }
David Brown5c9e0f12019-01-09 16:34:33 -07001013 }
1014
David Brown0dfb8102021-06-03 15:29:11 -06001015 /// Test the direct XIP configuration. With this mode, flash images are never moved, and the
1016 /// bootloader merely selects which partition is the proper one to boot.
1017 pub fn run_direct_xip(&self) -> bool {
1018 if !Caps::DirectXip.present() {
1019 return false;
1020 }
1021
1022 // Clone the flash so we can tell if unchanged.
1023 let mut flash = self.flash.clone();
1024
1025 let result = c::boot_go(&mut flash, &self.areadesc, None, true);
1026
1027 // Ensure the boot was successful.
1028 let resp = if let Some(resp) = result.resp() {
1029 resp
1030 } else {
1031 panic!("Boot didn't return a valid result");
1032 };
1033
1034 // This configuration should always try booting from the first upgrade slot.
1035 if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
1036 assert_eq!(offset, resp.image_off as usize);
1037 assert_eq!(dev_id, resp.flash_dev_id);
1038 } else {
1039 panic!("Unable to find upgrade image");
1040 }
1041 false
1042 }
1043
David Brown8a4e23b2021-06-11 10:29:01 -06001044 /// Test the ram-loading.
1045 pub fn run_ram_load(&self) -> bool {
1046 if !Caps::RamLoad.present() {
1047 return false;
1048 }
1049
1050 // Clone the flash so we can tell if unchanged.
1051 let mut flash = self.flash.clone();
1052
David Brownf17d3912021-06-23 16:10:51 -06001053 // Setup ram based on the ram configuration we determined earlier for the images.
1054 let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
David Brown8a4e23b2021-06-11 10:29:01 -06001055
David Brownf17d3912021-06-23 16:10:51 -06001056 // println!("Ram: {:#?}", self.ram);
David Brown8a4e23b2021-06-11 10:29:01 -06001057
David Brownf17d3912021-06-23 16:10:51 -06001058 // Verify that the images area loaded into this.
David Brown8a4e23b2021-06-11 10:29:01 -06001059 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None, true));
1060 if !result.success() {
David Brownf17d3912021-06-23 16:10:51 -06001061 error!("Failed to execute ram-load");
David Brown8a4e23b2021-06-11 10:29:01 -06001062 return true;
1063 }
1064
David Brownf17d3912021-06-23 16:10:51 -06001065 // Verify each image.
1066 for image in &self.images {
1067 let place = self.ram.lookup(&image.slots[0]);
1068 let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1069 place.size as usize);
1070 let src_image = &image.upgrades.plain;
1071 if src_image.len() > ram_image.len() {
1072 error!("Image ended up too large, nonsensical");
1073 return true;
1074 }
1075
1076 let ram_image = &ram_image[0..src_image.len()];
1077 if ram_image != src_image {
1078 error!("Image not loaded correctly");
1079 return true;
1080 }
1081
1082 }
1083
1084 return false;
David Brown8a4e23b2021-06-11 10:29:01 -06001085 }
1086
David Brown5c9e0f12019-01-09 16:34:33 -07001087 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -07001088 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001089 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -07001090 if Caps::OverwriteUpgrade.present() {
1091 return;
1092 }
1093
David Brown84b49f72019-03-01 10:58:22 -07001094 // Set this for each image.
1095 for image in &self.images {
1096 let dev_id = &image.slots[slot].dev_id;
1097 let dev = flash.get_mut(&dev_id).unwrap();
1098 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001099 let off = &image.slots[slot].base_off;
1100 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -07001101 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -07001102
David Brown84b49f72019-03-01 10:58:22 -07001103 // Mark the status area as a bad area
1104 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1105 }
David Brown5c9e0f12019-01-09 16:34:33 -07001106 }
1107
David Brown76101572019-02-28 11:29:03 -07001108 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001109 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001110 return;
1111 }
1112
David Brown84b49f72019-03-01 10:58:22 -07001113 for image in &self.images {
1114 let dev_id = &image.slots[slot].dev_id;
1115 let dev = flash.get_mut(&dev_id).unwrap();
1116 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001117
David Brown84b49f72019-03-01 10:58:22 -07001118 // Disabling write verification the only assert triggered by
1119 // boot_go should be checking for integrity of status bytes.
1120 dev.set_verify_writes(false);
1121 }
David Brown5c9e0f12019-01-09 16:34:33 -07001122 }
1123
David Browndb505822019-03-01 10:04:20 -07001124 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1125 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001126 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001127 // Clone the flash to have a new copy.
1128 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001129
Fabio Utziged4a5362019-07-30 12:43:23 -03001130 if permanent {
1131 self.mark_permanent_upgrades(&mut flash, 1);
1132 }
David Brown5c9e0f12019-01-09 16:34:33 -07001133
David Browndb505822019-03-01 10:04:20 -07001134 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001135
David Browndb505822019-03-01 10:04:20 -07001136 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001137 x if x.interrupted() => (true, stop.unwrap()),
1138 x if x.success() => (false, -counter),
1139 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001140 };
David Brown5c9e0f12019-01-09 16:34:33 -07001141
David Browndb505822019-03-01 10:04:20 -07001142 counter = 0;
1143 if first_interrupted {
1144 // fl.dump();
1145 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001146 x if x.interrupted() => panic!("Shouldn't stop again"),
1147 x if x.success() => (),
1148 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001149 }
1150 }
David Brown5c9e0f12019-01-09 16:34:33 -07001151
David Browndb505822019-03-01 10:04:20 -07001152 (flash, count - counter)
1153 }
1154
1155 fn try_revert(&self, count: usize) -> SimMultiFlash {
1156 let mut flash = self.flash.clone();
1157
1158 // fl.write_file("image0.bin").unwrap();
1159 for i in 0 .. count {
1160 info!("Running boot pass {}", i + 1);
David Brownc423ac42021-06-04 13:47:34 -06001161 assert!(c::boot_go(&mut flash, &self.areadesc, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001162 }
1163 flash
1164 }
1165
1166 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1167 let mut flash = self.flash.clone();
1168 let mut fails = 0;
1169
1170 let mut counter = stop;
David Brownc423ac42021-06-04 13:47:34 -06001171 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001172 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001173 fails += 1;
1174 }
1175
Fabio Utzig8af7f792019-07-30 12:40:01 -03001176 // In a multi-image setup, copy done might be set if any number of
1177 // images was already successfully swapped.
1178 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1179 warn!("copy_done should be unset");
1180 fails += 1;
1181 }
1182
David Brownc423ac42021-06-04 13:47:34 -06001183 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001184 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001185 fails += 1;
1186 }
1187
David Brown84b49f72019-03-01 10:58:22 -07001188 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001189 warn!("Image in the primary slot before revert is invalid at stop={}",
1190 stop);
1191 fails += 1;
1192 }
David Brown84b49f72019-03-01 10:58:22 -07001193 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001194 warn!("Image in the secondary slot before revert is invalid at stop={}",
1195 stop);
1196 fails += 1;
1197 }
David Brown84b49f72019-03-01 10:58:22 -07001198 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1199 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001200 warn!("Mismatched trailer for the primary slot before revert");
1201 fails += 1;
1202 }
David Brown84b49f72019-03-01 10:58:22 -07001203 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1204 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001205 warn!("Mismatched trailer for the secondary slot before revert");
1206 fails += 1;
1207 }
1208
1209 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001210 let mut counter = stop;
David Brownc423ac42021-06-04 13:47:34 -06001211 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001212 warn!("Should have stopped revert at interruption point");
1213 fails += 1;
1214 }
1215
David Brownc423ac42021-06-04 13:47:34 -06001216 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001217 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001218 fails += 1;
1219 }
1220
David Brown84b49f72019-03-01 10:58:22 -07001221 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001222 warn!("Image in the primary slot after revert is invalid at stop={}",
1223 stop);
1224 fails += 1;
1225 }
David Brown84b49f72019-03-01 10:58:22 -07001226 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001227 warn!("Image in the secondary slot after revert is invalid at stop={}",
1228 stop);
1229 fails += 1;
1230 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001231
David Brown84b49f72019-03-01 10:58:22 -07001232 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1233 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001234 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001235 fails += 1;
1236 }
David Brown84b49f72019-03-01 10:58:22 -07001237 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1238 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001239 warn!("Mismatched trailer for the secondary slot after revert");
1240 fails += 1;
1241 }
1242
David Brownc423ac42021-06-04 13:47:34 -06001243 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001244 warn!("Should have finished 3rd boot");
1245 fails += 1;
1246 }
1247
1248 if !self.verify_images(&flash, 0, 0) {
1249 warn!("Image in the primary slot is invalid on 1st boot after revert");
1250 fails += 1;
1251 }
1252 if !self.verify_images(&flash, 1, 1) {
1253 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1254 fails += 1;
1255 }
1256
David Browndb505822019-03-01 10:04:20 -07001257 fails > 0
1258 }
1259
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001260
David Browndb505822019-03-01 10:04:20 -07001261 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1262 let mut flash = self.flash.clone();
1263
David Brown84b49f72019-03-01 10:58:22 -07001264 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001265
1266 let mut rng = rand::thread_rng();
1267 let mut resets = vec![0i32; count];
1268 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001269 for reset in &mut resets {
David Brown9c6322f2021-08-19 13:03:39 -06001270 let reset_counter = rng.gen_range(1 ..= remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001271 let mut counter = reset_counter;
1272 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001273 x if x.interrupted() => (),
1274 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001275 }
1276 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001277 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001278 }
1279
1280 match c::boot_go(&mut flash, &self.areadesc, None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001281 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1282 x if x.success() => (),
1283 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001284 }
David Brown5c9e0f12019-01-09 16:34:33 -07001285
David Browndb505822019-03-01 10:04:20 -07001286 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001287 }
David Brown84b49f72019-03-01 10:58:22 -07001288
1289 /// Verify the image in the given flash device, the specified slot
1290 /// against the expected image.
1291 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001292 self.images.iter().all(|image| {
1293 verify_image(flash, &image.slots[slot],
1294 match against {
1295 0 => &image.primaries,
1296 1 => &image.upgrades,
1297 _ => panic!("Invalid 'against'")
1298 })
1299 })
David Brown84b49f72019-03-01 10:58:22 -07001300 }
1301
David Brownc3898d62019-08-05 14:20:02 -06001302 /// Verify the images, according to the dependency test.
1303 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1304 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1305 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1306 if !verify_image(flash, &image.slots[0],
1307 match upgrade {
1308 UpgradeInfo::Upgraded => &image.upgrades,
1309 UpgradeInfo::Held => &image.primaries,
1310 }) {
1311 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1312 return true;
1313 }
1314 }
1315
1316 false
1317 }
1318
Fabio Utzig8af7f792019-07-30 12:40:01 -03001319 /// Verify that at least one of the trailers of the images have the
1320 /// specified values.
1321 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1322 magic: Option<u8>, image_ok: Option<u8>,
1323 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001324 self.images.iter().any(|image| {
1325 verify_trailer(flash, &image.slots[slot],
1326 magic, image_ok, copy_done)
1327 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001328 }
1329
David Brown84b49f72019-03-01 10:58:22 -07001330 /// Verify that the trailers of the images have the specified
1331 /// values.
1332 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1333 magic: Option<u8>, image_ok: Option<u8>,
1334 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001335 self.images.iter().all(|image| {
1336 verify_trailer(flash, &image.slots[slot],
1337 magic, image_ok, copy_done)
1338 })
David Brown84b49f72019-03-01 10:58:22 -07001339 }
1340
1341 /// Mark each of the images for permanent upgrade.
1342 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1343 for image in &self.images {
1344 mark_permanent_upgrade(flash, &image.slots[slot]);
1345 }
1346 }
1347
1348 /// Mark each of the images for permanent upgrade.
1349 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1350 for image in &self.images {
1351 mark_upgrade(flash, &image.slots[slot]);
1352 }
1353 }
David Brown297029a2019-08-13 14:29:51 -06001354
1355 /// Dump out the flash image(s) to one or more files for debugging
1356 /// purposes. The names will be written as either "{prefix}.mcubin" or
1357 /// "{prefix}-001.mcubin" depending on how many images there are.
1358 pub fn debug_dump(&self, prefix: &str) {
1359 for (id, fdev) in &self.flash {
1360 let name = if self.flash.len() == 1 {
1361 format!("{}.mcubin", prefix)
1362 } else {
1363 format!("{}-{:>0}.mcubin", prefix, id)
1364 };
1365 fdev.write_file(&name).unwrap();
1366 }
1367 }
David Brown5c9e0f12019-01-09 16:34:33 -07001368}
1369
David Brownbf32c272021-06-16 17:11:37 -06001370impl RamData {
David Brownf17d3912021-06-23 16:10:51 -06001371 // TODO: This is not correct. The second slot of each image should be at the same address as
1372 // the primary.
David Brownbf32c272021-06-16 17:11:37 -06001373 fn new(slots: &[[SlotInfo; 2]]) -> RamData {
1374 let mut addr = RAM_LOAD_ADDR;
1375 let mut places = BTreeMap::new();
David Brownf17d3912021-06-23 16:10:51 -06001376 // println!("Setup:-------------");
David Brownbf32c272021-06-16 17:11:37 -06001377 for imgs in slots {
1378 for si in imgs {
David Brownf17d3912021-06-23 16:10:51 -06001379 // println!("Setup: si: {:?}", si);
David Brownbf32c272021-06-16 17:11:37 -06001380 let offset = addr;
1381 let size = si.len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001382 places.insert(SlotKey {
1383 dev_id: si.dev_id,
David Brownf17d3912021-06-23 16:10:51 -06001384 base_off: si.base_off,
David Brownbf32c272021-06-16 17:11:37 -06001385 }, SlotPlace { offset, size });
David Brownf17d3912021-06-23 16:10:51 -06001386 // println!(" load: offset: {}, size: {}", offset, size);
David Brownbf32c272021-06-16 17:11:37 -06001387 }
David Brownf17d3912021-06-23 16:10:51 -06001388 addr += imgs[0].len as u32;
David Brownbf32c272021-06-16 17:11:37 -06001389 }
1390 RamData {
1391 places,
1392 total: addr,
1393 }
1394 }
David Brownf17d3912021-06-23 16:10:51 -06001395
1396 /// Lookup the ram data associated with a given flash partition. We just panic if not present,
1397 /// because all slots used should be in the map.
1398 fn lookup(&self, slot: &SlotInfo) -> &SlotPlace {
1399 self.places.get(&SlotKey{dev_id: slot.dev_id, base_off: slot.base_off})
1400 .expect("RamData should contain all slots")
1401 }
David Brownbf32c272021-06-16 17:11:37 -06001402}
1403
David Brown5c9e0f12019-01-09 16:34:33 -07001404/// Show the flash layout.
1405#[allow(dead_code)]
1406fn show_flash(flash: &dyn Flash) {
1407 println!("---- Flash configuration ----");
1408 for sector in flash.sector_iter() {
1409 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1410 sector.num, sector.base, sector.size);
1411 }
David Brown599b2db2021-03-10 05:23:26 -07001412 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001413}
1414
1415/// Install a "program" into the given image. This fakes the image header, or at least all of the
1416/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001417fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownf17d3912021-06-23 16:10:51 -06001418 ram: &RamData,
David Brownc3898d62019-08-05 14:20:02 -06001419 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001420 let offset = slot.base_off;
1421 let slot_len = slot.len;
1422 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001423
David Brown43643dd2019-01-11 15:43:28 -07001424 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001425
David Brownc3898d62019-08-05 14:20:02 -06001426 // Add the dependencies early to the tlv.
1427 for dep in deps.my_deps(offset, slot.index) {
1428 tlv.add_dependency(deps.other_id(), &dep);
1429 }
1430
David Brown5c9e0f12019-01-09 16:34:33 -07001431 const HDR_SIZE: usize = 32;
1432
David Brownf17d3912021-06-23 16:10:51 -06001433 let place = ram.lookup(&slot);
1434 let load_addr = if Caps::RamLoad.present() {
1435 place.offset
1436 } else {
1437 0
1438 };
1439
David Brown5c9e0f12019-01-09 16:34:33 -07001440 // Generate a boot header. Note that the size doesn't include the header.
1441 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001442 magic: tlv.get_magic(),
David Brownf17d3912021-06-23 16:10:51 -06001443 load_addr,
David Brown5c9e0f12019-01-09 16:34:33 -07001444 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001445 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001446 img_size: len as u32,
1447 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001448 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001449 _pad2: 0,
1450 };
1451
1452 let mut b_header = [0; HDR_SIZE];
1453 b_header[..32].clone_from_slice(header.as_raw());
1454 assert_eq!(b_header.len(), HDR_SIZE);
1455
1456 tlv.add_bytes(&b_header);
1457
1458 // The core of the image itself is just pseudorandom data.
1459 let mut b_img = vec![0; len];
1460 splat(&mut b_img, offset);
1461
David Browncb47dd72019-08-05 14:21:49 -06001462 // Add some information at the start of the payload to make it easier
1463 // to see what it is. This will fail if the image itself is too small.
1464 {
1465 let mut wr = Cursor::new(&mut b_img);
1466 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1467 offset, dev_id, slot).unwrap();
1468 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1469 }
1470
David Brown5c9e0f12019-01-09 16:34:33 -07001471 // TLV signatures work over plain image
1472 tlv.add_bytes(&b_img);
1473
1474 // Generate encrypted images
Salome Thirot6fdbf552021-05-14 16:46:14 +01001475 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1476 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001477 let mut b_encimg = vec![];
1478 if is_encrypted {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001479 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1480 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001481 tlv.generate_enc_key();
1482 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001483 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001484 b_encimg = b_img.clone();
Salome Thirot6fdbf552021-05-14 16:46:14 +01001485 if aes256 {
1486 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001487 let block = Aes256::new(&key);
1488 let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001489 cipher.apply_keystream(&mut b_encimg);
1490 } else {
1491 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
David Brown9c6322f2021-08-19 13:03:39 -06001492 let block = Aes128::new(&key);
1493 let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
Salome Thirot6fdbf552021-05-14 16:46:14 +01001494 cipher.apply_keystream(&mut b_encimg);
1495 }
David Brown5c9e0f12019-01-09 16:34:33 -07001496 }
1497
1498 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001499 if bad_sig {
1500 tlv.corrupt_sig();
1501 }
1502 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001503
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001504 let dev = flash.get_mut(&dev_id).unwrap();
1505
David Brown5c9e0f12019-01-09 16:34:33 -07001506 let mut buf = vec![];
1507 buf.append(&mut b_header.to_vec());
1508 buf.append(&mut b_img);
1509 buf.append(&mut b_tlv.clone());
1510
David Brown95de4502019-11-15 12:01:34 -07001511 // Pad the buffer to a multiple of the flash alignment.
1512 let align = dev.align();
1513 while buf.len() % align != 0 {
1514 buf.push(dev.erased_val());
1515 }
1516
David Brown5c9e0f12019-01-09 16:34:33 -07001517 let mut encbuf = vec![];
1518 if is_encrypted {
1519 encbuf.append(&mut b_header.to_vec());
1520 encbuf.append(&mut b_encimg);
1521 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001522
1523 while encbuf.len() % align != 0 {
1524 encbuf.push(dev.erased_val());
1525 }
David Brown5c9e0f12019-01-09 16:34:33 -07001526 }
1527
David Vincze2d736ad2019-02-18 11:50:22 +01001528 // Since images are always non-encrypted in the primary slot, we first write
1529 // an encrypted image, re-read to use for verification, erase + flash
1530 // un-encrypted. In the secondary slot the image is written un-encrypted,
1531 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001532
David Brown3b090212019-07-30 15:59:28 -06001533 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001534 let enc_copy: Option<Vec<u8>>;
1535
1536 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001537 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001538
1539 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001540 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001541
1542 enc_copy = Some(enc);
1543
David Brown76101572019-02-28 11:29:03 -07001544 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001545 } else {
1546 enc_copy = None;
1547 }
1548
David Brown76101572019-02-28 11:29:03 -07001549 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001550
1551 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001552 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001553
David Brownca234692019-02-28 11:22:19 -07001554 ImageData {
1555 plain: copy,
1556 cipher: enc_copy,
1557 }
David Brown5c9e0f12019-01-09 16:34:33 -07001558 } else {
1559
David Brown76101572019-02-28 11:29:03 -07001560 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001561
1562 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001563 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001564
1565 let enc_copy: Option<Vec<u8>>;
1566
1567 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001568 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001569
David Brown76101572019-02-28 11:29:03 -07001570 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001571
1572 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001573 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001574
1575 enc_copy = Some(enc);
1576 } else {
1577 enc_copy = None;
1578 }
1579
David Brownca234692019-02-28 11:22:19 -07001580 ImageData {
1581 plain: copy,
1582 cipher: enc_copy,
1583 }
David Brown5c9e0f12019-01-09 16:34:33 -07001584 }
David Brown5c9e0f12019-01-09 16:34:33 -07001585}
1586
David Brown873be312019-09-03 12:22:32 -06001587/// Install no image. This is used when no upgrade happens.
1588fn install_no_image() -> ImageData {
1589 ImageData {
1590 plain: vec![],
1591 cipher: None,
1592 }
1593}
1594
David Brown5c9e0f12019-01-09 16:34:33 -07001595fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001596 if Caps::EcdsaP224.present() {
1597 panic!("Ecdsa P224 not supported in Simulator");
1598 }
Salome Thirot6fdbf552021-05-14 16:46:14 +01001599 let mut aes_key_size = 128;
1600 if Caps::Aes256.present() {
1601 aes_key_size = 256;
1602 }
David Brown5c9e0f12019-01-09 16:34:33 -07001603
David Brownb8882112019-01-11 14:04:11 -07001604 if Caps::EncKw.present() {
1605 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001606 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001607 } else if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001608 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001609 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001610 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001611 }
1612 } else if Caps::EncRsa.present() {
1613 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001614 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001615 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001616 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001617 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001618 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001619 if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001620 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001621 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001622 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001623 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001624 } else if Caps::EncX25519.present() {
1625 if Caps::Ed25519.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001626 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001627 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001628 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001629 }
David Brownb8882112019-01-11 14:04:11 -07001630 } else {
1631 // The non-encrypted configuration.
1632 if Caps::RSA2048.present() {
1633 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001634 } else if Caps::RSA3072.present() {
1635 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001636 } else if Caps::EcdsaP256.present() {
1637 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001638 } else if Caps::Ed25519.present() {
1639 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001640 } else {
1641 TlvGen::new_hash_only()
1642 }
1643 }
David Brown5c9e0f12019-01-09 16:34:33 -07001644}
1645
David Brownca234692019-02-28 11:22:19 -07001646impl ImageData {
1647 /// Find the image contents for the given slot. This assumes that slot 0
1648 /// is unencrypted, and slot 1 is encrypted.
1649 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001650 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001651 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001652 match (encrypted, slot) {
1653 (false, _) => &self.plain,
1654 (true, 0) => &self.plain,
1655 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1656 _ => panic!("Invalid slot requested"),
1657 }
David Brown5c9e0f12019-01-09 16:34:33 -07001658 }
1659}
1660
David Brown5c9e0f12019-01-09 16:34:33 -07001661/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001662fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1663 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001664 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001665 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001666
1667 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001668 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001669 let dev = flash.get(&dev_id).unwrap();
1670 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001671
1672 if buf != &copy[..] {
1673 for i in 0 .. buf.len() {
1674 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001675 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1676 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001677 break;
1678 }
1679 }
1680 false
1681 } else {
1682 true
1683 }
1684}
1685
David Brown3b090212019-07-30 15:59:28 -06001686fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001687 magic: Option<u8>, image_ok: Option<u8>,
1688 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001689 if Caps::OverwriteUpgrade.present() {
1690 return true;
1691 }
David Brown5c9e0f12019-01-09 16:34:33 -07001692
David Brown3b090212019-07-30 15:59:28 -06001693 let offset = slot.trailer_off + c::boot_max_align();
1694 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001695 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001696 let mut failed = false;
1697
David Brown76101572019-02-28 11:29:03 -07001698 let dev = flash.get(&dev_id).unwrap();
1699 let erased_val = dev.erased_val();
1700 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001701
1702 failed |= match magic {
1703 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001704 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001705 warn!("\"magic\" mismatch at {:#x}", offset);
1706 true
1707 } else if v == 3 {
1708 let expected = [erased_val; 16];
David Brownd36f6b12021-03-10 05:23:56 -07001709 if copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001710 warn!("\"magic\" mismatch at {:#x}", offset);
1711 true
1712 } else {
1713 false
1714 }
1715 } else {
1716 false
1717 }
1718 },
1719 None => false,
1720 };
1721
1722 failed |= match image_ok {
1723 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001724 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001725 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1726 true
1727 } else {
1728 false
1729 }
1730 },
1731 None => false,
1732 };
1733
1734 failed |= match copy_done {
1735 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001736 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001737 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1738 true
1739 } else {
1740 false
1741 }
1742 },
1743 None => false,
1744 };
1745
1746 !failed
1747}
1748
David Brown297029a2019-08-13 14:29:51 -06001749/// Install a partition table. This is a simplified partition table that
1750/// we write at the beginning of flash so make it easier for external tools
1751/// to analyze these images.
1752fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1753 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1754 for &id in &ids {
1755 // If there are any partitions in this device that start at 0, and
1756 // aren't marked as the BootLoader partition, avoid adding the
1757 // partition table. This makes it harder to view the image, but
1758 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07001759 let skip_ptable = areadesc
1760 .iter_areas()
1761 .any(|area| {
1762 area.device_id == id &&
1763 area.off == 0 &&
1764 area.flash_id != FlashId::BootLoader
1765 });
1766 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06001767 if log_enabled!(Info) {
1768 let special: Vec<FlashId> = areadesc.iter_areas()
1769 .filter(|area| area.device_id == id && area.off == 0)
1770 .map(|area| area.flash_id)
1771 .collect();
1772 info!("Skipping partition table: {:?}", special);
1773 }
1774 break;
1775 }
1776
1777 let mut buf: Vec<u8> = vec![];
1778 write!(&mut buf, "mcuboot\0").unwrap();
1779
1780 // Iterate through all of the partitions in that device, and encode
1781 // into the table.
1782 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1783 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1784
1785 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1786 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1787 buf.write_u32::<LittleEndian>(area.off).unwrap();
1788 buf.write_u32::<LittleEndian>(area.size).unwrap();
1789 buf.write_u32::<LittleEndian>(0).unwrap();
1790 }
1791
1792 let dev = flash.get_mut(&id).unwrap();
1793
1794 // Pad to alignment.
1795 while buf.len() % dev.align() != 0 {
1796 buf.push(0);
1797 }
1798
1799 dev.write(0, &buf).unwrap();
1800 }
1801}
1802
David Brown5c9e0f12019-01-09 16:34:33 -07001803/// The image header
1804#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001805#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001806pub struct ImageHeader {
1807 magic: u32,
1808 load_addr: u32,
1809 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001810 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001811 img_size: u32,
1812 flags: u32,
1813 ver: ImageVersion,
1814 _pad2: u32,
1815}
1816
1817impl AsRaw for ImageHeader {}
1818
1819#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001820#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001821pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001822 pub major: u8,
1823 pub minor: u8,
1824 pub revision: u16,
1825 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001826}
1827
David Brownc3898d62019-08-05 14:20:02 -06001828#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001829pub struct SlotInfo {
1830 pub base_off: usize,
1831 pub trailer_off: usize,
1832 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001833 // Which slot within this device.
1834 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001835 pub dev_id: u8,
1836}
1837
David Brown347dc572019-11-15 11:37:25 -07001838const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1839 0x60, 0xd2, 0xef, 0x7f,
1840 0x35, 0x52, 0x50, 0x0f,
1841 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001842
1843// Replicates defines found in bootutil.h
1844const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1845const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1846
1847const BOOT_FLAG_SET: Option<u8> = Some(1);
1848const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1849
1850/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001851pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1852 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001853 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001854 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001855 if offset % align != 0 || MAGIC.len() % align != 0 {
1856 // The write size is larger than the magic value. Fill a buffer
1857 // with the erased value, put the MAGIC in it, and write it in its
1858 // entirety.
1859 let mut buf = vec![dev.erased_val(); align];
1860 buf[(offset % align)..].copy_from_slice(MAGIC);
1861 dev.write(offset - (offset % align), &buf).unwrap();
1862 } else {
1863 dev.write(offset, MAGIC).unwrap();
1864 }
David Brown5c9e0f12019-01-09 16:34:33 -07001865}
1866
1867/// Writes the image_ok flag which, guess what, tells the bootloader
1868/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001869fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001870 // Overwrite mode always is permanent, and only the magic is used in
1871 // the trailer. To avoid problems with large write sizes, don't try to
1872 // set anything in this case.
1873 if Caps::OverwriteUpgrade.present() {
1874 return;
1875 }
1876
David Brown76101572019-02-28 11:29:03 -07001877 let dev = flash.get_mut(&slot.dev_id).unwrap();
1878 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001879 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001880 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001881 let align = dev.align();
1882 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001883}
1884
1885// Drop some pseudo-random gibberish onto the data.
1886fn splat(data: &mut [u8], seed: usize) {
David Brown9c6322f2021-08-19 13:03:39 -06001887 let mut seed_block = [0u8; 32];
David Browncd842842020-07-09 15:46:53 -06001888 let mut buf = Cursor::new(&mut seed_block[..]);
1889 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
1890 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
1891 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
1892 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
1893 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07001894 rng.fill_bytes(data);
1895}
1896
1897/// Return a read-only view into the raw bytes of this object
1898trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07001899 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07001900 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1901 mem::size_of::<Self>()) }
1902 }
1903}
1904
1905pub fn show_sizes() {
1906 // This isn't panic safe.
1907 for min in &[1, 2, 4, 8] {
1908 let msize = c::boot_trailer_sz(*min);
1909 println!("{:2}: {} (0x{:x})", min, msize, msize);
1910 }
1911}
David Brown95de4502019-11-15 12:01:34 -07001912
1913#[cfg(not(feature = "large-write"))]
1914fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001915 &[1, 2, 4, 8]
1916}
1917
1918#[cfg(feature = "large-write")]
1919fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001920 &[1, 2, 4, 8, 128, 512]
1921}