blob: f191c1d8d817cc3d3ab6a74c57892f4371d0d87d [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};
27use aes_ctr::{
28 Aes128Ctr,
Salome Thirot6fdbf552021-05-14 16:46:14 +010029 Aes256Ctr,
David Brown5c9e0f12019-01-09 16:34:33 -070030 stream_cipher::{
31 generic_array::GenericArray,
David Brown8a99adf2020-07-09 16:52:38 -060032 NewStreamCipher,
33 SyncStreamCipher,
David Brown5c9e0f12019-01-09 16:34:33 -070034 },
35};
36
David Brown76101572019-02-28 11:29:03 -070037use simflash::{Flash, SimFlash, SimMultiFlash};
David Brown8a4e23b2021-06-11 10:29:01 -060038use mcuboot_sys::{c, AreaDesc, FlashId, RamBlock};
David Browne5133242019-02-28 11:05:19 -070039use crate::{
40 ALL_DEVICES,
41 DeviceName,
42};
David Brown5c9e0f12019-01-09 16:34:33 -070043use crate::caps::Caps;
David Brownc3898d62019-08-05 14:20:02 -060044use crate::depends::{
45 BoringDep,
46 Depender,
47 DepTest,
David Brown873be312019-09-03 12:22:32 -060048 DepType,
David Brown2ee5f7f2020-01-13 14:04:01 -070049 NO_DEPS,
David Brownc3898d62019-08-05 14:20:02 -060050 PairDep,
51 UpgradeInfo,
52};
Fabio Utzig90f449e2019-10-24 07:43:53 -030053use crate::tlv::{ManifestGen, TlvGen, TlvFlags};
Salome Thirot6fdbf552021-05-14 16:46:14 +010054use typenum::{U32, U16};
David Brown5c9e0f12019-01-09 16:34:33 -070055
David Brown8a4e23b2021-06-11 10:29:01 -060056/// For testing, use a non-zero offset for the ram-load, to make sure the offset is getting used
57/// properly, but the value is not really that important.
58const RAM_LOAD_ADDR: u32 = 1024;
59
60fn ram_load_addr() -> u32 {
61 if Caps::RamLoad.present() {
62 RAM_LOAD_ADDR
63 } else {
64 0
65 }
66}
67
David Browne5133242019-02-28 11:05:19 -070068/// A builder for Images. This describes a single run of the simulator,
69/// capturing the configuration of a particular set of devices, including
70/// the flash simulator(s) and the information about the slots.
71#[derive(Clone)]
72pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070073 flash: SimMultiFlash,
David Browne5133242019-02-28 11:05:19 -070074 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070075 slots: Vec<[SlotInfo; 2]>,
David Brownbf32c272021-06-16 17:11:37 -060076 ram: RamData,
David Browne5133242019-02-28 11:05:19 -070077}
78
David Brown998aa8d2019-02-28 10:54:50 -070079/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070080/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070081/// and upgrades hold the expected contents of these images.
82pub struct Images {
David Brown76101572019-02-28 11:29:03 -070083 flash: SimMultiFlash,
David Brownca234692019-02-28 11:22:19 -070084 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070085 images: Vec<OneImage>,
86 total_count: Option<i32>,
David Brownbf32c272021-06-16 17:11:37 -060087 ram: RamData,
David Brown84b49f72019-03-01 10:58:22 -070088}
89
90/// When doing multi-image, there is an instance of this information for
91/// each of the images. Single image there will be one of these.
92struct OneImage {
David Brownca234692019-02-28 11:22:19 -070093 slots: [SlotInfo; 2],
94 primaries: ImageData,
95 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070096}
97
98/// The Rust-side representation of an image. For unencrypted images, this
99/// is just the unencrypted payload. For encrypted images, we store both
100/// the encrypted and the plaintext.
101struct ImageData {
102 plain: Vec<u8>,
103 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -0700104}
105
David Brownbf32c272021-06-16 17:11:37 -0600106/// For the RamLoad test cases, we need a contiguous area of RAM to load these images into. For
107/// multi-image builds, these may not correspond with the offsets. This has to be computed early,
108/// before images are built, because each image contains the offset where the image is to be loaded
109/// in the header, which is contained within the signature.
110#[derive(Clone, Debug)]
111struct RamData {
112 places: BTreeMap<SlotKey, SlotPlace>,
113 total: u32,
114}
115
116/// Every slot is indexed by this key.
117#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
118struct SlotKey {
119 dev_id: u8,
120 index: usize,
121}
122
123#[derive(Clone, Debug)]
124struct SlotPlace {
125 offset: u32,
126 size: u32,
127}
128
David Browne5133242019-02-28 11:05:19 -0700129impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -0700130 /// Construct a new image builder for the given device. Returns
131 /// Some(builder) if is possible to test this configuration, or None if
132 /// not possible (for example, if there aren't enough image slots).
Fabio Utzig114a6472019-11-28 10:24:09 -0300133 pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
134 let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
135
136 for cap in unsupported_caps {
137 if cap.present() {
138 return Err(format!("unsupported {:?}", cap));
139 }
140 }
David Browne5133242019-02-28 11:05:19 -0700141
David Brown06ef06e2019-03-05 12:28:10 -0700142 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -0700143
David Brown06ef06e2019-03-05 12:28:10 -0700144 let mut slots = Vec::with_capacity(num_images);
145 for image in 0..num_images {
146 // This mapping must match that defined in
147 // `boot/zephyr/include/sysflash/sysflash.h`.
148 let id0 = match image {
149 0 => FlashId::Image0,
150 1 => FlashId::Image2,
151 _ => panic!("More than 2 images not supported"),
152 };
153 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
154 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300155 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700156 };
157 let id1 = match image {
158 0 => FlashId::Image1,
159 1 => FlashId::Image3,
160 _ => panic!("More than 2 images not supported"),
161 };
162 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
163 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300164 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700165 };
David Browne5133242019-02-28 11:05:19 -0700166
Christopher Collinsa1c12042019-05-23 14:00:28 -0700167 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700168
David Brown06ef06e2019-03-05 12:28:10 -0700169 // Construct a primary image.
170 let primary = SlotInfo {
171 base_off: primary_base as usize,
172 trailer_off: primary_base + primary_len - offset_from_end,
173 len: primary_len as usize,
174 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600175 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700176 };
177
178 // And an upgrade image.
179 let secondary = SlotInfo {
180 base_off: secondary_base as usize,
181 trailer_off: secondary_base + secondary_len - offset_from_end,
182 len: secondary_len as usize,
183 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600184 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700185 };
186
187 slots.push([primary, secondary]);
188 }
David Browne5133242019-02-28 11:05:19 -0700189
David Brownbf32c272021-06-16 17:11:37 -0600190 let ram = RamData::new(&slots);
191
Fabio Utzig114a6472019-11-28 10:24:09 -0300192 Ok(ImagesBuilder {
David Brown4dfb33c2021-03-10 05:15:45 -0700193 flash,
194 areadesc,
195 slots,
David Brownbf32c272021-06-16 17:11:37 -0600196 ram,
David Brown5bc62c62019-03-05 12:11:48 -0700197 })
David Browne5133242019-02-28 11:05:19 -0700198 }
199
200 pub fn each_device<F>(f: F)
201 where F: Fn(Self)
202 {
203 for &dev in ALL_DEVICES {
David Brown95de4502019-11-15 12:01:34 -0700204 for &align in test_alignments() {
David Browne5133242019-02-28 11:05:19 -0700205 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700206 match Self::new(dev, align, erased_val) {
Fabio Utzig114a6472019-11-28 10:24:09 -0300207 Ok(run) => f(run),
208 Err(msg) => warn!("Skipping {}: {}", dev, msg),
David Brown5bc62c62019-03-05 12:11:48 -0700209 }
David Browne5133242019-02-28 11:05:19 -0700210 }
211 }
212 }
213 }
214
215 /// Construct an `Images` that doesn't expect an upgrade to happen.
David Brownc3898d62019-08-05 14:20:02 -0600216 pub fn make_no_upgrade_image(self, deps: &DepTest) -> Images {
217 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700218 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600219 let ram = self.ram.clone(); // TODO: This is wasteful.
David Brownc3898d62019-08-05 14:20:02 -0600220 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
221 let dep: Box<dyn Depender> = if num_images > 1 {
222 Box::new(PairDep::new(num_images, image_num, deps))
223 } else {
David Brown2ee5f7f2020-01-13 14:04:01 -0700224 Box::new(BoringDep::new(image_num, deps))
David Brownc3898d62019-08-05 14:20:02 -0600225 };
David Brownbf32c272021-06-16 17:11:37 -0600226 let primaries = install_image(&mut flash, &slots[0], 42784, &ram, &*dep, false);
David Brown873be312019-09-03 12:22:32 -0600227 let upgrades = match deps.depends[image_num] {
228 DepType::NoUpgrade => install_no_image(),
David Brownbf32c272021-06-16 17:11:37 -0600229 _ => install_image(&mut flash, &slots[1], 46928, &ram, &*dep, false)
David Brown873be312019-09-03 12:22:32 -0600230 };
David Brown84b49f72019-03-01 10:58:22 -0700231 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700232 slots,
233 primaries,
234 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700235 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600236 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700237 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700238 flash,
David Browne5133242019-02-28 11:05:19 -0700239 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700240 images,
David Browne5133242019-02-28 11:05:19 -0700241 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600242 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700243 }
244 }
245
David Brownc3898d62019-08-05 14:20:02 -0600246 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
247 let mut images = self.make_no_upgrade_image(deps);
David Brown84b49f72019-03-01 10:58:22 -0700248 for image in &images.images {
249 mark_upgrade(&mut images.flash, &image.slots[1]);
250 }
David Browne5133242019-02-28 11:05:19 -0700251
David Brown6db44d72021-05-26 16:22:58 -0600252 // The count is meaningless if no flash operations are performed.
253 if !Caps::modifies_flash() {
254 return images;
255 }
256
David Browne5133242019-02-28 11:05:19 -0700257 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300258 let total_count = match images.run_basic_upgrade(permanent) {
David Brown8973f552021-03-10 05:21:11 -0700259 Some(v) => v,
260 None =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600261 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
262 0
263 } else {
264 panic!("Unable to perform basic upgrade");
265 }
David Browne5133242019-02-28 11:05:19 -0700266 };
267
268 images.total_count = Some(total_count);
269 images
270 }
271
272 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700273 let mut bad_flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600274 let ram = self.ram.clone(); // TODO: Avoid this clone.
David Brownc3898d62019-08-05 14:20:02 -0600275 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
David Brown2ee5f7f2020-01-13 14:04:01 -0700276 let dep = BoringDep::new(image_num, &NO_DEPS);
David Brownbf32c272021-06-16 17:11:37 -0600277 let primaries = install_image(&mut bad_flash, &slots[0], 32784, &ram, &dep, false);
278 let upgrades = install_image(&mut bad_flash, &slots[1], 41928, &ram, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700279 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700280 slots,
281 primaries,
282 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700283 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700284 Images {
David Brown76101572019-02-28 11:29:03 -0700285 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700286 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700287 images,
David Browne5133242019-02-28 11:05:19 -0700288 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600289 ram: self.ram,
David Browne5133242019-02-28 11:05:19 -0700290 }
291 }
292
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300293 pub fn make_erased_secondary_image(self) -> Images {
294 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600295 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300296 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
297 let dep = BoringDep::new(image_num, &NO_DEPS);
David Brownbf32c272021-06-16 17:11:37 -0600298 let primaries = install_image(&mut flash, &slots[0], 32784, &ram, &dep, false);
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300299 let upgrades = install_no_image();
300 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700301 slots,
302 primaries,
303 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300304 }}).collect();
305 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700306 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300307 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700308 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300309 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600310 ram: self.ram,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300311 }
312 }
313
Fabio Utzigd0157342020-10-02 15:22:11 -0300314 pub fn make_bootstrap_image(self) -> Images {
315 let mut flash = self.flash;
David Brownbf32c272021-06-16 17:11:37 -0600316 let ram = self.ram.clone(); // TODO: Avoid this clone.
Fabio Utzigd0157342020-10-02 15:22:11 -0300317 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
318 let dep = BoringDep::new(image_num, &NO_DEPS);
319 let primaries = install_no_image();
David Brownbf32c272021-06-16 17:11:37 -0600320 let upgrades = install_image(&mut flash, &slots[1], 32784, &ram, &dep, false);
Fabio Utzigd0157342020-10-02 15:22:11 -0300321 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700322 slots,
323 primaries,
324 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300325 }}).collect();
326 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700327 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300328 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700329 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300330 total_count: None,
David Brownbf32c272021-06-16 17:11:37 -0600331 ram: self.ram,
Fabio Utzigd0157342020-10-02 15:22:11 -0300332 }
333 }
334
David Browne5133242019-02-28 11:05:19 -0700335 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300336 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700337 match device {
338 DeviceName::Stm32f4 => {
339 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700340 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
341 64 * 1024,
342 128 * 1024, 128 * 1024, 128 * 1024],
343 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700344 let dev_id = 0;
345 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700346 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700347 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
348 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
349 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
350
David Brown76101572019-02-28 11:29:03 -0700351 let mut flash = SimMultiFlash::new();
352 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300353 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700354 }
355 DeviceName::K64f => {
356 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700357 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700358
359 let dev_id = 0;
360 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700361 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700362 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
363 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
364 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
365
David Brown76101572019-02-28 11:29:03 -0700366 let mut flash = SimMultiFlash::new();
367 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300368 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700369 }
370 DeviceName::K64fBig => {
371 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
372 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700373 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700374
375 let dev_id = 0;
376 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700377 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700378 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
379 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
380 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
381
David Brown76101572019-02-28 11:29:03 -0700382 let mut flash = SimMultiFlash::new();
383 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300384 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700385 }
386 DeviceName::Nrf52840 => {
387 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
388 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700389 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700390
391 let dev_id = 0;
392 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700393 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700394 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
395 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
396 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
397
David Brown76101572019-02-28 11:29:03 -0700398 let mut flash = SimMultiFlash::new();
399 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300400 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700401 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300402 DeviceName::Nrf52840UnequalSlots => {
403 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
404
405 let dev_id = 0;
406 let mut areadesc = AreaDesc::new();
407 areadesc.add_flash_sectors(dev_id, &dev);
408 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
409 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
410
411 let mut flash = SimMultiFlash::new();
412 flash.insert(dev_id, dev);
413 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
414 }
David Browne5133242019-02-28 11:05:19 -0700415 DeviceName::Nrf52840SpiFlash => {
416 // Simulate nrf52840 with external SPI flash. The external SPI flash
417 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700418 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
419 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700420
421 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700422 areadesc.add_flash_sectors(0, &dev0);
423 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700424
425 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
426 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
427 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
428
David Brown76101572019-02-28 11:29:03 -0700429 let mut flash = SimMultiFlash::new();
430 flash.insert(0, dev0);
431 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300432 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700433 }
David Brown2bff6472019-03-05 13:58:35 -0700434 DeviceName::K64fMulti => {
435 // NXP style flash, but larger, to support multiple images.
436 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
437
438 let dev_id = 0;
439 let mut areadesc = AreaDesc::new();
440 areadesc.add_flash_sectors(dev_id, &dev);
441 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
442 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
443 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
444 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
445 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
446
447 let mut flash = SimMultiFlash::new();
448 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300449 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700450 }
David Browne5133242019-02-28 11:05:19 -0700451 }
452 }
David Brownc3898d62019-08-05 14:20:02 -0600453
454 pub fn num_images(&self) -> usize {
455 self.slots.len()
456 }
David Browne5133242019-02-28 11:05:19 -0700457}
458
David Brown5c9e0f12019-01-09 16:34:33 -0700459impl Images {
460 /// A simple upgrade without forced failures.
461 ///
462 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700463 /// inject failures at chosen steps. Returns None if it was unable to
464 /// count the operations in a basic upgrade.
465 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300466 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700467 info!("Total flash operation count={}", total_count);
468
David Brown84b49f72019-03-01 10:58:22 -0700469 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700470 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700471 None
David Brown5c9e0f12019-01-09 16:34:33 -0700472 } else {
David Brown8973f552021-03-10 05:21:11 -0700473 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700474 }
475 }
476
Fabio Utzigd0157342020-10-02 15:22:11 -0300477 pub fn run_bootstrap(&self) -> bool {
478 let mut flash = self.flash.clone();
479 let mut fails = 0;
480
481 if Caps::Bootstrap.present() {
482 info!("Try bootstraping image in the primary");
483
David Brownc423ac42021-06-04 13:47:34 -0600484 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigd0157342020-10-02 15:22:11 -0300485 warn!("Failed first boot");
486 fails += 1;
487 }
488
489 if !self.verify_images(&flash, 0, 1) {
490 warn!("Image in the first slot was not bootstrapped");
491 fails += 1;
492 }
493
494 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
495 BOOT_FLAG_SET, BOOT_FLAG_SET) {
496 warn!("Mismatched trailer for the primary slot");
497 fails += 1;
498 }
499 }
500
501 if fails > 0 {
502 error!("Expected trailer on secondary slot to be erased");
503 }
504
505 fails > 0
506 }
507
508
David Brownc3898d62019-08-05 14:20:02 -0600509 /// Test a simple upgrade, with dependencies given, and verify that the
510 /// image does as is described in the test.
511 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600512 if !Caps::modifies_flash() {
513 return false;
514 }
515
David Brownc3898d62019-08-05 14:20:02 -0600516 let (flash, _) = self.try_upgrade(None, true);
517
518 self.verify_dep_images(&flash, deps)
519 }
520
Fabio Utzigf5480c72019-11-28 10:41:57 -0300521 fn is_swap_upgrade(&self) -> bool {
522 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
523 }
524
David Brown5c9e0f12019-01-09 16:34:33 -0700525 pub fn run_basic_revert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600526 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700527 return false;
528 }
David Brown5c9e0f12019-01-09 16:34:33 -0700529
David Brown5c9e0f12019-01-09 16:34:33 -0700530 let mut fails = 0;
531
532 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300533 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700534 for count in 2 .. 5 {
535 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700536 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700537 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700538 error!("Revert failure on count {}", count);
539 fails += 1;
540 }
541 }
542 }
543
544 fails > 0
545 }
546
547 pub fn run_perm_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600548 if !Caps::modifies_flash() {
549 return false;
550 }
551
David Brown5c9e0f12019-01-09 16:34:33 -0700552 let mut fails = 0;
553 let total_flash_ops = self.total_count.unwrap();
554
555 // Let's try an image halfway through.
556 for i in 1 .. total_flash_ops {
557 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300558 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700559 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700560 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700561 warn!("FAIL at step {} of {}", i, total_flash_ops);
562 fails += 1;
563 }
564
David Brown84b49f72019-03-01 10:58:22 -0700565 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
566 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100567 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700568 fails += 1;
569 }
570
David Brown84b49f72019-03-01 10:58:22 -0700571 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
572 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100573 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700574 fails += 1;
575 }
576
David Brownaec56b22021-03-10 05:22:07 -0700577 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
578 warn!("Secondary slot FAIL at step {} of {}",
579 i, total_flash_ops);
580 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700581 }
582 }
583
584 if fails > 0 {
585 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
586 fails as f32 * 100.0 / total_flash_ops as f32);
587 }
588
589 fails > 0
590 }
591
David Brown5c9e0f12019-01-09 16:34:33 -0700592 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600593 if !Caps::modifies_flash() {
594 return false;
595 }
596
David Brown5c9e0f12019-01-09 16:34:33 -0700597 let mut fails = 0;
598 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700599 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700600 info!("Random interruptions at reset points={:?}", total_counts);
601
David Brown84b49f72019-03-01 10:58:22 -0700602 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300603 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700604 // TODO: This result is ignored.
605 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700606 } else {
607 true
608 };
David Vincze2d736ad2019-02-18 11:50:22 +0100609 if !primary_slot_ok || !secondary_slot_ok {
610 error!("Image mismatch after random interrupts: primary slot={} \
611 secondary slot={}",
612 if primary_slot_ok { "ok" } else { "fail" },
613 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700614 fails += 1;
615 }
David Brown84b49f72019-03-01 10:58:22 -0700616 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
617 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100618 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700619 fails += 1;
620 }
David Brown84b49f72019-03-01 10:58:22 -0700621 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
622 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100623 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700624 fails += 1;
625 }
626
627 if fails > 0 {
628 error!("Error testing perm upgrade with {} fails", total_fails);
629 }
630
631 fails > 0
632 }
633
David Brown5c9e0f12019-01-09 16:34:33 -0700634 pub fn run_revert_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600635 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700636 return false;
637 }
David Brown5c9e0f12019-01-09 16:34:33 -0700638
David Brown5c9e0f12019-01-09 16:34:33 -0700639 let mut fails = 0;
640
Fabio Utzigf5480c72019-11-28 10:41:57 -0300641 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300642 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700643 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700644 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700645 error!("Revert failed at interruption {}", i);
646 fails += 1;
647 }
648 }
649 }
650
651 fails > 0
652 }
653
David Brown5c9e0f12019-01-09 16:34:33 -0700654 pub fn run_norevert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600655 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700656 return false;
657 }
David Brown5c9e0f12019-01-09 16:34:33 -0700658
David Brown76101572019-02-28 11:29:03 -0700659 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700660 let mut fails = 0;
661
662 info!("Try norevert");
663
664 // First do a normal upgrade...
David Brownc423ac42021-06-04 13:47:34 -0600665 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700666 warn!("Failed first boot");
667 fails += 1;
668 }
669
670 //FIXME: copy_done is written by boot_go, is it ok if no copy
671 // was ever done?
672
David Brown84b49f72019-03-01 10:58:22 -0700673 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100674 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700675 fails += 1;
676 }
David Brown84b49f72019-03-01 10:58:22 -0700677 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
678 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100679 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700680 fails += 1;
681 }
David Brown84b49f72019-03-01 10:58:22 -0700682 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
683 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100684 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700685 fails += 1;
686 }
687
David Vincze2d736ad2019-02-18 11:50:22 +0100688 // Marks image in the primary slot as permanent,
689 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700690 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700691
David Brown84b49f72019-03-01 10:58:22 -0700692 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
693 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100694 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700695 fails += 1;
696 }
697
David Brownc423ac42021-06-04 13:47:34 -0600698 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700699 warn!("Failed second boot");
700 fails += 1;
701 }
702
David Brown84b49f72019-03-01 10:58:22 -0700703 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
704 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100705 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700706 fails += 1;
707 }
David Brown84b49f72019-03-01 10:58:22 -0700708 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700709 warn!("Failed image verification");
710 fails += 1;
711 }
712
713 if fails > 0 {
714 error!("Error running upgrade without revert");
715 }
716
717 fails > 0
718 }
719
David Brown2ee5f7f2020-01-13 14:04:01 -0700720 // Test that an upgrade is rejected. Assumes that the image was build
721 // such that the upgrade is instead a downgrade.
722 pub fn run_nodowngrade(&self) -> bool {
723 if !Caps::DowngradePrevention.present() {
724 return false;
725 }
726
727 let mut flash = self.flash.clone();
728 let mut fails = 0;
729
730 info!("Try no downgrade");
731
732 // First, do a normal upgrade.
David Brownc423ac42021-06-04 13:47:34 -0600733 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700734 warn!("Failed first boot");
735 fails += 1;
736 }
737
738 if !self.verify_images(&flash, 0, 0) {
739 warn!("Failed verification after downgrade rejection");
740 fails += 1;
741 }
742
743 if fails > 0 {
744 error!("Error testing downgrade rejection");
745 }
746
747 fails > 0
748 }
749
David Vincze2d736ad2019-02-18 11:50:22 +0100750 // Tests a new image written to the primary slot that already has magic and
751 // image_ok set while there is no image on the secondary slot, so no revert
752 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700753 pub fn run_norevert_newimage(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600754 if !Caps::modifies_flash() {
755 info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
756 return false;
757 }
758
David Brown76101572019-02-28 11:29:03 -0700759 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700760 let mut fails = 0;
761
762 info!("Try non-revert on imgtool generated image");
763
David Brown84b49f72019-03-01 10:58:22 -0700764 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700765
David Vincze2d736ad2019-02-18 11:50:22 +0100766 // This simulates writing an image created by imgtool to
767 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700768 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
769 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100770 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700771 fails += 1;
772 }
773
774 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600775 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700776 warn!("Failed first boot");
777 fails += 1;
778 }
779
780 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700781 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700782 warn!("Failed image verification");
783 fails += 1;
784 }
David Brown84b49f72019-03-01 10:58:22 -0700785 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
786 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100787 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700788 fails += 1;
789 }
David Brown84b49f72019-03-01 10:58:22 -0700790 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
791 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100792 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700793 fails += 1;
794 }
795
796 if fails > 0 {
797 error!("Expected a non revert with new image");
798 }
799
800 fails > 0
801 }
802
David Vincze2d736ad2019-02-18 11:50:22 +0100803 // Tests a new image written to the primary slot that already has magic and
804 // image_ok set while there is no image on the secondary slot, so no revert
805 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700806 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700807 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700808 let mut fails = 0;
809
810 info!("Try upgrade image with bad signature");
811
David Brown6db44d72021-05-26 16:22:58 -0600812 // Only perform this test if an upgrade is expected to happen.
813 if !Caps::modifies_flash() {
814 info!("Skipping upgrade image with bad signature");
815 return false;
816 }
817
David Brown84b49f72019-03-01 10:58:22 -0700818 self.mark_upgrades(&mut flash, 0);
819 self.mark_permanent_upgrades(&mut flash, 0);
820 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700821
David Brown84b49f72019-03-01 10:58:22 -0700822 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
823 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100824 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700825 fails += 1;
826 }
827
828 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600829 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700830 warn!("Failed first boot");
831 fails += 1;
832 }
833
834 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700835 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700836 warn!("Failed image verification");
837 fails += 1;
838 }
David Brown84b49f72019-03-01 10:58:22 -0700839 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
840 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100841 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700842 fails += 1;
843 }
844
845 if fails > 0 {
846 error!("Expected an upgrade failure when image has bad signature");
847 }
848
849 fails > 0
850 }
851
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300852 // Should detect there is a leftover trailer in an otherwise erased
853 // secondary slot and erase its trailer.
854 pub fn run_secondary_leftover_trailer(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600855 if !Caps::modifies_flash() {
856 return false;
857 }
858
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300859 let mut flash = self.flash.clone();
860 let mut fails = 0;
861
862 info!("Try with a leftover trailer in the secondary; must be erased");
863
864 // Add a trailer on the secondary slot
865 self.mark_permanent_upgrades(&mut flash, 1);
866 self.mark_upgrades(&mut flash, 1);
867
868 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600869 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300870 warn!("Failed first boot");
871 fails += 1;
872 }
873
874 // State should not have changed
875 if !self.verify_images(&flash, 0, 0) {
876 warn!("Failed image verification");
877 fails += 1;
878 }
879 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
880 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
881 warn!("Mismatched trailer for the secondary slot");
882 fails += 1;
883 }
884
885 if fails > 0 {
886 error!("Expected trailer on secondary slot to be erased");
887 }
888
889 fails > 0
890 }
891
David Brown5c9e0f12019-01-09 16:34:33 -0700892 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300893 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700894 }
895
David Brown5c9e0f12019-01-09 16:34:33 -0700896 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300897 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700898 }
899
900 /// This test runs a simple upgrade with no fails in the images, but
901 /// allowing for fails in the status area. This should run to the end
902 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700903 pub fn run_with_status_fails_complete(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600904 if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700905 return false;
906 }
907
David Brown76101572019-02-28 11:29:03 -0700908 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700909 let mut fails = 0;
910
911 info!("Try swap with status fails");
912
David Brown84b49f72019-03-01 10:58:22 -0700913 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700914 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700915
David Brownc423ac42021-06-04 13:47:34 -0600916 let result = c::boot_go(&mut flash, &self.areadesc, None, true);
917 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700918 warn!("Failed!");
919 fails += 1;
920 }
921
922 // Failed writes to the marked "bad" region don't assert anymore.
923 // Any detected assert() is happening in another part of the code.
David Brownc423ac42021-06-04 13:47:34 -0600924 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -0700925 warn!("At least one assert() was called");
926 fails += 1;
927 }
928
David Brown84b49f72019-03-01 10:58:22 -0700929 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
930 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100931 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700932 fails += 1;
933 }
934
David Brown84b49f72019-03-01 10:58:22 -0700935 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700936 warn!("Failed image verification");
937 fails += 1;
938 }
939
David Vincze2d736ad2019-02-18 11:50:22 +0100940 info!("validate primary slot enabled; \
941 re-run of boot_go should just work");
David Brownc423ac42021-06-04 13:47:34 -0600942 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700943 warn!("Failed!");
944 fails += 1;
945 }
946
947 if fails > 0 {
948 error!("Error running upgrade with status write fails");
949 }
950
951 fails > 0
952 }
953
954 /// This test runs a simple upgrade with no fails in the images, but
955 /// allowing for fails in the status area. This should run to the end
956 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700957 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600958 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700959 false
David Vincze2d736ad2019-02-18 11:50:22 +0100960 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700961
David Brown76101572019-02-28 11:29:03 -0700962 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700963 let mut fails = 0;
964 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700965
David Brown85904a82019-01-11 13:45:12 -0700966 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700967
David Brown85904a82019-01-11 13:45:12 -0700968 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700969
David Brown84b49f72019-03-01 10:58:22 -0700970 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700971 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700972
973 // Should not fail, writing to bad regions does not assert
David Brownc423ac42021-06-04 13:47:34 -0600974 let asserts = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700975 if asserts != 0 {
976 warn!("At least one assert() was called");
977 fails += 1;
978 }
979
David Brown76101572019-02-28 11:29:03 -0700980 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700981
982 info!("Resuming an interrupted swap operation");
David Brownc423ac42021-06-04 13:47:34 -0600983 let asserts = c::boot_go(&mut flash, &self.areadesc, None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700984
985 // This might throw no asserts, for large sector devices, where
986 // a single failure writing is indistinguishable from no failure,
987 // or throw a single assert for small sector devices that fail
988 // multiple times...
989 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100990 warn!("Expected single assert validating the primary slot, \
991 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700992 fails += 1;
993 }
994
995 if fails > 0 {
996 error!("Error running upgrade with status write fails");
997 }
998
999 fails > 0
1000 } else {
David Brown76101572019-02-28 11:29:03 -07001001 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -07001002 let mut fails = 0;
1003
1004 info!("Try interrupted swap with status fails");
1005
David Brown84b49f72019-03-01 10:58:22 -07001006 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -07001007 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -07001008
1009 // This is expected to fail while writing to bad regions...
David Brownc423ac42021-06-04 13:47:34 -06001010 let asserts = c::boot_go(&mut flash, &self.areadesc, None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -07001011 if asserts == 0 {
1012 warn!("No assert() detected");
1013 fails += 1;
1014 }
1015
1016 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -07001017 }
David Brown5c9e0f12019-01-09 16:34:33 -07001018 }
1019
David Brown0dfb8102021-06-03 15:29:11 -06001020 /// Test the direct XIP configuration. With this mode, flash images are never moved, and the
1021 /// bootloader merely selects which partition is the proper one to boot.
1022 pub fn run_direct_xip(&self) -> bool {
1023 if !Caps::DirectXip.present() {
1024 return false;
1025 }
1026
1027 // Clone the flash so we can tell if unchanged.
1028 let mut flash = self.flash.clone();
1029
1030 let result = c::boot_go(&mut flash, &self.areadesc, None, true);
1031
1032 // Ensure the boot was successful.
1033 let resp = if let Some(resp) = result.resp() {
1034 resp
1035 } else {
1036 panic!("Boot didn't return a valid result");
1037 };
1038
1039 // This configuration should always try booting from the first upgrade slot.
1040 if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
1041 assert_eq!(offset, resp.image_off as usize);
1042 assert_eq!(dev_id, resp.flash_dev_id);
1043 } else {
1044 panic!("Unable to find upgrade image");
1045 }
1046 false
1047 }
1048
David Brown8a4e23b2021-06-11 10:29:01 -06001049 /// Test the ram-loading.
1050 pub fn run_ram_load(&self) -> bool {
1051 if !Caps::RamLoad.present() {
1052 return false;
1053 }
1054
1055 // Clone the flash so we can tell if unchanged.
1056 let mut flash = self.flash.clone();
1057
1058 let image = &self.images[0].primaries;
1059
1060 // Test with the minimal size.
1061
1062 // First verify that if the RAM is too small, we reject it.
1063 let ram = RamBlock::new(image.plain.len() as u32 - 1, RAM_LOAD_ADDR);
1064 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None, true));
1065 if result.success() {
1066 error!("Failed to detect RAM too small");
1067 return true;
1068 }
1069 drop(ram);
1070
1071 // TODO: The code will erase the flash if it doesn't fit. Either verify this, or change
1072 // this behavior.
1073
1074 let mut flash = self.flash.clone();
1075
1076 let ram = RamBlock::new(image.plain.len() as u32, RAM_LOAD_ADDR);
1077 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None, true));
1078 if !result.success() {
1079 error!("Failed to ram-load image");
1080 return true;
1081 }
1082 println!("Result: {:?}", result);
1083
1084 // Verify the image was loaded correctly.
1085 if ram.borrow() != &image.plain {
1086 error!("Image not loaded correctly");
1087 return true;
1088 }
1089
1090 false
1091 }
1092
David Brown5c9e0f12019-01-09 16:34:33 -07001093 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -07001094 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001095 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -07001096 if Caps::OverwriteUpgrade.present() {
1097 return;
1098 }
1099
David Brown84b49f72019-03-01 10:58:22 -07001100 // Set this for each image.
1101 for image in &self.images {
1102 let dev_id = &image.slots[slot].dev_id;
1103 let dev = flash.get_mut(&dev_id).unwrap();
1104 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001105 let off = &image.slots[slot].base_off;
1106 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -07001107 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -07001108
David Brown84b49f72019-03-01 10:58:22 -07001109 // Mark the status area as a bad area
1110 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1111 }
David Brown5c9e0f12019-01-09 16:34:33 -07001112 }
1113
David Brown76101572019-02-28 11:29:03 -07001114 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001115 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001116 return;
1117 }
1118
David Brown84b49f72019-03-01 10:58:22 -07001119 for image in &self.images {
1120 let dev_id = &image.slots[slot].dev_id;
1121 let dev = flash.get_mut(&dev_id).unwrap();
1122 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001123
David Brown84b49f72019-03-01 10:58:22 -07001124 // Disabling write verification the only assert triggered by
1125 // boot_go should be checking for integrity of status bytes.
1126 dev.set_verify_writes(false);
1127 }
David Brown5c9e0f12019-01-09 16:34:33 -07001128 }
1129
David Browndb505822019-03-01 10:04:20 -07001130 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1131 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001132 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001133 // Clone the flash to have a new copy.
1134 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001135
Fabio Utziged4a5362019-07-30 12:43:23 -03001136 if permanent {
1137 self.mark_permanent_upgrades(&mut flash, 1);
1138 }
David Brown5c9e0f12019-01-09 16:34:33 -07001139
David Browndb505822019-03-01 10:04:20 -07001140 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001141
David Browndb505822019-03-01 10:04:20 -07001142 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001143 x if x.interrupted() => (true, stop.unwrap()),
1144 x if x.success() => (false, -counter),
1145 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001146 };
David Brown5c9e0f12019-01-09 16:34:33 -07001147
David Browndb505822019-03-01 10:04:20 -07001148 counter = 0;
1149 if first_interrupted {
1150 // fl.dump();
1151 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001152 x if x.interrupted() => panic!("Shouldn't stop again"),
1153 x if x.success() => (),
1154 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001155 }
1156 }
David Brown5c9e0f12019-01-09 16:34:33 -07001157
David Browndb505822019-03-01 10:04:20 -07001158 (flash, count - counter)
1159 }
1160
1161 fn try_revert(&self, count: usize) -> SimMultiFlash {
1162 let mut flash = self.flash.clone();
1163
1164 // fl.write_file("image0.bin").unwrap();
1165 for i in 0 .. count {
1166 info!("Running boot pass {}", i + 1);
David Brownc423ac42021-06-04 13:47:34 -06001167 assert!(c::boot_go(&mut flash, &self.areadesc, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001168 }
1169 flash
1170 }
1171
1172 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1173 let mut flash = self.flash.clone();
1174 let mut fails = 0;
1175
1176 let mut counter = stop;
David Brownc423ac42021-06-04 13:47:34 -06001177 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001178 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001179 fails += 1;
1180 }
1181
Fabio Utzig8af7f792019-07-30 12:40:01 -03001182 // In a multi-image setup, copy done might be set if any number of
1183 // images was already successfully swapped.
1184 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1185 warn!("copy_done should be unset");
1186 fails += 1;
1187 }
1188
David Brownc423ac42021-06-04 13:47:34 -06001189 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001190 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001191 fails += 1;
1192 }
1193
David Brown84b49f72019-03-01 10:58:22 -07001194 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001195 warn!("Image in the primary slot before revert is invalid at stop={}",
1196 stop);
1197 fails += 1;
1198 }
David Brown84b49f72019-03-01 10:58:22 -07001199 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001200 warn!("Image in the secondary slot before revert is invalid at stop={}",
1201 stop);
1202 fails += 1;
1203 }
David Brown84b49f72019-03-01 10:58:22 -07001204 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1205 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001206 warn!("Mismatched trailer for the primary slot before revert");
1207 fails += 1;
1208 }
David Brown84b49f72019-03-01 10:58:22 -07001209 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1210 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001211 warn!("Mismatched trailer for the secondary slot before revert");
1212 fails += 1;
1213 }
1214
1215 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001216 let mut counter = stop;
David Brownc423ac42021-06-04 13:47:34 -06001217 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001218 warn!("Should have stopped revert at interruption point");
1219 fails += 1;
1220 }
1221
David Brownc423ac42021-06-04 13:47:34 -06001222 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001223 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001224 fails += 1;
1225 }
1226
David Brown84b49f72019-03-01 10:58:22 -07001227 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001228 warn!("Image in the primary slot after revert is invalid at stop={}",
1229 stop);
1230 fails += 1;
1231 }
David Brown84b49f72019-03-01 10:58:22 -07001232 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001233 warn!("Image in the secondary slot after revert is invalid at stop={}",
1234 stop);
1235 fails += 1;
1236 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001237
David Brown84b49f72019-03-01 10:58:22 -07001238 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1239 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001240 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001241 fails += 1;
1242 }
David Brown84b49f72019-03-01 10:58:22 -07001243 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1244 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001245 warn!("Mismatched trailer for the secondary slot after revert");
1246 fails += 1;
1247 }
1248
David Brownc423ac42021-06-04 13:47:34 -06001249 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001250 warn!("Should have finished 3rd boot");
1251 fails += 1;
1252 }
1253
1254 if !self.verify_images(&flash, 0, 0) {
1255 warn!("Image in the primary slot is invalid on 1st boot after revert");
1256 fails += 1;
1257 }
1258 if !self.verify_images(&flash, 1, 1) {
1259 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1260 fails += 1;
1261 }
1262
David Browndb505822019-03-01 10:04:20 -07001263 fails > 0
1264 }
1265
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001266
David Browndb505822019-03-01 10:04:20 -07001267 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1268 let mut flash = self.flash.clone();
1269
David Brown84b49f72019-03-01 10:58:22 -07001270 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001271
1272 let mut rng = rand::thread_rng();
1273 let mut resets = vec![0i32; count];
1274 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001275 for reset in &mut resets {
David Browncd842842020-07-09 15:46:53 -06001276 let reset_counter = rng.gen_range(1, remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001277 let mut counter = reset_counter;
1278 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001279 x if x.interrupted() => (),
1280 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001281 }
1282 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001283 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001284 }
1285
1286 match c::boot_go(&mut flash, &self.areadesc, None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001287 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1288 x if x.success() => (),
1289 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001290 }
David Brown5c9e0f12019-01-09 16:34:33 -07001291
David Browndb505822019-03-01 10:04:20 -07001292 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001293 }
David Brown84b49f72019-03-01 10:58:22 -07001294
1295 /// Verify the image in the given flash device, the specified slot
1296 /// against the expected image.
1297 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001298 self.images.iter().all(|image| {
1299 verify_image(flash, &image.slots[slot],
1300 match against {
1301 0 => &image.primaries,
1302 1 => &image.upgrades,
1303 _ => panic!("Invalid 'against'")
1304 })
1305 })
David Brown84b49f72019-03-01 10:58:22 -07001306 }
1307
David Brownc3898d62019-08-05 14:20:02 -06001308 /// Verify the images, according to the dependency test.
1309 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1310 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1311 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1312 if !verify_image(flash, &image.slots[0],
1313 match upgrade {
1314 UpgradeInfo::Upgraded => &image.upgrades,
1315 UpgradeInfo::Held => &image.primaries,
1316 }) {
1317 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1318 return true;
1319 }
1320 }
1321
1322 false
1323 }
1324
Fabio Utzig8af7f792019-07-30 12:40:01 -03001325 /// Verify that at least one of the trailers of the images have the
1326 /// specified values.
1327 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1328 magic: Option<u8>, image_ok: Option<u8>,
1329 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001330 self.images.iter().any(|image| {
1331 verify_trailer(flash, &image.slots[slot],
1332 magic, image_ok, copy_done)
1333 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001334 }
1335
David Brown84b49f72019-03-01 10:58:22 -07001336 /// Verify that the trailers of the images have the specified
1337 /// values.
1338 fn verify_trailers(&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().all(|image| {
1342 verify_trailer(flash, &image.slots[slot],
1343 magic, image_ok, copy_done)
1344 })
David Brown84b49f72019-03-01 10:58:22 -07001345 }
1346
1347 /// Mark each of the images for permanent upgrade.
1348 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1349 for image in &self.images {
1350 mark_permanent_upgrade(flash, &image.slots[slot]);
1351 }
1352 }
1353
1354 /// Mark each of the images for permanent upgrade.
1355 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1356 for image in &self.images {
1357 mark_upgrade(flash, &image.slots[slot]);
1358 }
1359 }
David Brown297029a2019-08-13 14:29:51 -06001360
1361 /// Dump out the flash image(s) to one or more files for debugging
1362 /// purposes. The names will be written as either "{prefix}.mcubin" or
1363 /// "{prefix}-001.mcubin" depending on how many images there are.
1364 pub fn debug_dump(&self, prefix: &str) {
1365 for (id, fdev) in &self.flash {
1366 let name = if self.flash.len() == 1 {
1367 format!("{}.mcubin", prefix)
1368 } else {
1369 format!("{}-{:>0}.mcubin", prefix, id)
1370 };
1371 fdev.write_file(&name).unwrap();
1372 }
1373 }
David Brown5c9e0f12019-01-09 16:34:33 -07001374}
1375
David Brownbf32c272021-06-16 17:11:37 -06001376impl RamData {
1377 fn new(slots: &[[SlotInfo; 2]]) -> RamData {
1378 let mut addr = RAM_LOAD_ADDR;
1379 let mut places = BTreeMap::new();
1380 for imgs in slots {
1381 for si in imgs {
1382 let offset = addr;
1383 let size = si.len as u32;
1384 addr += size;
1385 places.insert(SlotKey {
1386 dev_id: si.dev_id,
1387 index: si.index,
1388 }, SlotPlace { offset, size });
1389 }
1390 }
1391 RamData {
1392 places,
1393 total: addr,
1394 }
1395 }
1396}
1397
David Brown5c9e0f12019-01-09 16:34:33 -07001398/// Show the flash layout.
1399#[allow(dead_code)]
1400fn show_flash(flash: &dyn Flash) {
1401 println!("---- Flash configuration ----");
1402 for sector in flash.sector_iter() {
1403 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1404 sector.num, sector.base, sector.size);
1405 }
David Brown599b2db2021-03-10 05:23:26 -07001406 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001407}
1408
1409/// Install a "program" into the given image. This fakes the image header, or at least all of the
1410/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001411fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownbf32c272021-06-16 17:11:37 -06001412 _ram: &RamData,
David Brownc3898d62019-08-05 14:20:02 -06001413 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001414 let offset = slot.base_off;
1415 let slot_len = slot.len;
1416 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001417
David Brown43643dd2019-01-11 15:43:28 -07001418 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001419
David Brownc3898d62019-08-05 14:20:02 -06001420 // Add the dependencies early to the tlv.
1421 for dep in deps.my_deps(offset, slot.index) {
1422 tlv.add_dependency(deps.other_id(), &dep);
1423 }
1424
David Brown5c9e0f12019-01-09 16:34:33 -07001425 const HDR_SIZE: usize = 32;
1426
1427 // Generate a boot header. Note that the size doesn't include the header.
1428 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001429 magic: tlv.get_magic(),
David Brown8a4e23b2021-06-11 10:29:01 -06001430 load_addr: if Caps::RamLoad.present() { ram_load_addr() } else { 0 },
David Brown5c9e0f12019-01-09 16:34:33 -07001431 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001432 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001433 img_size: len as u32,
1434 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001435 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001436 _pad2: 0,
1437 };
1438
1439 let mut b_header = [0; HDR_SIZE];
1440 b_header[..32].clone_from_slice(header.as_raw());
1441 assert_eq!(b_header.len(), HDR_SIZE);
1442
1443 tlv.add_bytes(&b_header);
1444
1445 // The core of the image itself is just pseudorandom data.
1446 let mut b_img = vec![0; len];
1447 splat(&mut b_img, offset);
1448
David Browncb47dd72019-08-05 14:21:49 -06001449 // Add some information at the start of the payload to make it easier
1450 // to see what it is. This will fail if the image itself is too small.
1451 {
1452 let mut wr = Cursor::new(&mut b_img);
1453 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1454 offset, dev_id, slot).unwrap();
1455 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1456 }
1457
David Brown5c9e0f12019-01-09 16:34:33 -07001458 // TLV signatures work over plain image
1459 tlv.add_bytes(&b_img);
1460
1461 // Generate encrypted images
Salome Thirot6fdbf552021-05-14 16:46:14 +01001462 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1463 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001464 let mut b_encimg = vec![];
1465 if is_encrypted {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001466 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1467 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001468 tlv.generate_enc_key();
1469 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001470 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001471 b_encimg = b_img.clone();
Salome Thirot6fdbf552021-05-14 16:46:14 +01001472 if aes256 {
1473 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
1474 let mut cipher = Aes256Ctr::new(&key, &nonce);
1475 cipher.apply_keystream(&mut b_encimg);
1476 } else {
1477 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
1478 let mut cipher = Aes128Ctr::new(&key, &nonce);
1479 cipher.apply_keystream(&mut b_encimg);
1480 }
David Brown5c9e0f12019-01-09 16:34:33 -07001481 }
1482
1483 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001484 if bad_sig {
1485 tlv.corrupt_sig();
1486 }
1487 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001488
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001489 let dev = flash.get_mut(&dev_id).unwrap();
1490
David Brown5c9e0f12019-01-09 16:34:33 -07001491 let mut buf = vec![];
1492 buf.append(&mut b_header.to_vec());
1493 buf.append(&mut b_img);
1494 buf.append(&mut b_tlv.clone());
1495
David Brown95de4502019-11-15 12:01:34 -07001496 // Pad the buffer to a multiple of the flash alignment.
1497 let align = dev.align();
1498 while buf.len() % align != 0 {
1499 buf.push(dev.erased_val());
1500 }
1501
David Brown5c9e0f12019-01-09 16:34:33 -07001502 let mut encbuf = vec![];
1503 if is_encrypted {
1504 encbuf.append(&mut b_header.to_vec());
1505 encbuf.append(&mut b_encimg);
1506 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001507
1508 while encbuf.len() % align != 0 {
1509 encbuf.push(dev.erased_val());
1510 }
David Brown5c9e0f12019-01-09 16:34:33 -07001511 }
1512
David Vincze2d736ad2019-02-18 11:50:22 +01001513 // Since images are always non-encrypted in the primary slot, we first write
1514 // an encrypted image, re-read to use for verification, erase + flash
1515 // un-encrypted. In the secondary slot the image is written un-encrypted,
1516 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001517
David Brown3b090212019-07-30 15:59:28 -06001518 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001519 let enc_copy: Option<Vec<u8>>;
1520
1521 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001522 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001523
1524 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001525 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001526
1527 enc_copy = Some(enc);
1528
David Brown76101572019-02-28 11:29:03 -07001529 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001530 } else {
1531 enc_copy = None;
1532 }
1533
David Brown76101572019-02-28 11:29:03 -07001534 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001535
1536 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001537 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001538
David Brownca234692019-02-28 11:22:19 -07001539 ImageData {
1540 plain: copy,
1541 cipher: enc_copy,
1542 }
David Brown5c9e0f12019-01-09 16:34:33 -07001543 } else {
1544
David Brown76101572019-02-28 11:29:03 -07001545 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001546
1547 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001548 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001549
1550 let enc_copy: Option<Vec<u8>>;
1551
1552 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001553 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001554
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 } else {
1562 enc_copy = None;
1563 }
1564
David Brownca234692019-02-28 11:22:19 -07001565 ImageData {
1566 plain: copy,
1567 cipher: enc_copy,
1568 }
David Brown5c9e0f12019-01-09 16:34:33 -07001569 }
David Brown5c9e0f12019-01-09 16:34:33 -07001570}
1571
David Brown873be312019-09-03 12:22:32 -06001572/// Install no image. This is used when no upgrade happens.
1573fn install_no_image() -> ImageData {
1574 ImageData {
1575 plain: vec![],
1576 cipher: None,
1577 }
1578}
1579
David Brown5c9e0f12019-01-09 16:34:33 -07001580fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001581 if Caps::EcdsaP224.present() {
1582 panic!("Ecdsa P224 not supported in Simulator");
1583 }
Salome Thirot6fdbf552021-05-14 16:46:14 +01001584 let mut aes_key_size = 128;
1585 if Caps::Aes256.present() {
1586 aes_key_size = 256;
1587 }
David Brown5c9e0f12019-01-09 16:34:33 -07001588
David Brownb8882112019-01-11 14:04:11 -07001589 if Caps::EncKw.present() {
1590 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001591 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001592 } else if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001593 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001594 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001595 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001596 }
1597 } else if Caps::EncRsa.present() {
1598 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001599 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001600 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001601 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001602 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001603 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001604 if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001605 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001606 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001607 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001608 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001609 } else if Caps::EncX25519.present() {
1610 if Caps::Ed25519.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001611 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001612 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001613 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001614 }
David Brownb8882112019-01-11 14:04:11 -07001615 } else {
1616 // The non-encrypted configuration.
1617 if Caps::RSA2048.present() {
1618 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001619 } else if Caps::RSA3072.present() {
1620 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001621 } else if Caps::EcdsaP256.present() {
1622 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001623 } else if Caps::Ed25519.present() {
1624 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001625 } else {
1626 TlvGen::new_hash_only()
1627 }
1628 }
David Brown5c9e0f12019-01-09 16:34:33 -07001629}
1630
David Brownca234692019-02-28 11:22:19 -07001631impl ImageData {
1632 /// Find the image contents for the given slot. This assumes that slot 0
1633 /// is unencrypted, and slot 1 is encrypted.
1634 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001635 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001636 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001637 match (encrypted, slot) {
1638 (false, _) => &self.plain,
1639 (true, 0) => &self.plain,
1640 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1641 _ => panic!("Invalid slot requested"),
1642 }
David Brown5c9e0f12019-01-09 16:34:33 -07001643 }
1644}
1645
David Brown5c9e0f12019-01-09 16:34:33 -07001646/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001647fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1648 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001649 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001650 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001651
1652 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001653 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001654 let dev = flash.get(&dev_id).unwrap();
1655 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001656
1657 if buf != &copy[..] {
1658 for i in 0 .. buf.len() {
1659 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001660 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1661 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001662 break;
1663 }
1664 }
1665 false
1666 } else {
1667 true
1668 }
1669}
1670
David Brown3b090212019-07-30 15:59:28 -06001671fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001672 magic: Option<u8>, image_ok: Option<u8>,
1673 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001674 if Caps::OverwriteUpgrade.present() {
1675 return true;
1676 }
David Brown5c9e0f12019-01-09 16:34:33 -07001677
David Brown3b090212019-07-30 15:59:28 -06001678 let offset = slot.trailer_off + c::boot_max_align();
1679 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001680 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001681 let mut failed = false;
1682
David Brown76101572019-02-28 11:29:03 -07001683 let dev = flash.get(&dev_id).unwrap();
1684 let erased_val = dev.erased_val();
1685 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001686
1687 failed |= match magic {
1688 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001689 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001690 warn!("\"magic\" mismatch at {:#x}", offset);
1691 true
1692 } else if v == 3 {
1693 let expected = [erased_val; 16];
David Brownd36f6b12021-03-10 05:23:56 -07001694 if copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001695 warn!("\"magic\" mismatch at {:#x}", offset);
1696 true
1697 } else {
1698 false
1699 }
1700 } else {
1701 false
1702 }
1703 },
1704 None => false,
1705 };
1706
1707 failed |= match image_ok {
1708 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001709 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001710 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1711 true
1712 } else {
1713 false
1714 }
1715 },
1716 None => false,
1717 };
1718
1719 failed |= match copy_done {
1720 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001721 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001722 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1723 true
1724 } else {
1725 false
1726 }
1727 },
1728 None => false,
1729 };
1730
1731 !failed
1732}
1733
David Brown297029a2019-08-13 14:29:51 -06001734/// Install a partition table. This is a simplified partition table that
1735/// we write at the beginning of flash so make it easier for external tools
1736/// to analyze these images.
1737fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1738 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1739 for &id in &ids {
1740 // If there are any partitions in this device that start at 0, and
1741 // aren't marked as the BootLoader partition, avoid adding the
1742 // partition table. This makes it harder to view the image, but
1743 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07001744 let skip_ptable = areadesc
1745 .iter_areas()
1746 .any(|area| {
1747 area.device_id == id &&
1748 area.off == 0 &&
1749 area.flash_id != FlashId::BootLoader
1750 });
1751 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06001752 if log_enabled!(Info) {
1753 let special: Vec<FlashId> = areadesc.iter_areas()
1754 .filter(|area| area.device_id == id && area.off == 0)
1755 .map(|area| area.flash_id)
1756 .collect();
1757 info!("Skipping partition table: {:?}", special);
1758 }
1759 break;
1760 }
1761
1762 let mut buf: Vec<u8> = vec![];
1763 write!(&mut buf, "mcuboot\0").unwrap();
1764
1765 // Iterate through all of the partitions in that device, and encode
1766 // into the table.
1767 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1768 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1769
1770 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1771 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1772 buf.write_u32::<LittleEndian>(area.off).unwrap();
1773 buf.write_u32::<LittleEndian>(area.size).unwrap();
1774 buf.write_u32::<LittleEndian>(0).unwrap();
1775 }
1776
1777 let dev = flash.get_mut(&id).unwrap();
1778
1779 // Pad to alignment.
1780 while buf.len() % dev.align() != 0 {
1781 buf.push(0);
1782 }
1783
1784 dev.write(0, &buf).unwrap();
1785 }
1786}
1787
David Brown5c9e0f12019-01-09 16:34:33 -07001788/// The image header
1789#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001790#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001791pub struct ImageHeader {
1792 magic: u32,
1793 load_addr: u32,
1794 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001795 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001796 img_size: u32,
1797 flags: u32,
1798 ver: ImageVersion,
1799 _pad2: u32,
1800}
1801
1802impl AsRaw for ImageHeader {}
1803
1804#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001805#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001806pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001807 pub major: u8,
1808 pub minor: u8,
1809 pub revision: u16,
1810 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001811}
1812
David Brownc3898d62019-08-05 14:20:02 -06001813#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001814pub struct SlotInfo {
1815 pub base_off: usize,
1816 pub trailer_off: usize,
1817 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001818 // Which slot within this device.
1819 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001820 pub dev_id: u8,
1821}
1822
David Brown347dc572019-11-15 11:37:25 -07001823const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1824 0x60, 0xd2, 0xef, 0x7f,
1825 0x35, 0x52, 0x50, 0x0f,
1826 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001827
1828// Replicates defines found in bootutil.h
1829const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1830const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1831
1832const BOOT_FLAG_SET: Option<u8> = Some(1);
1833const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1834
1835/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001836pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1837 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001838 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001839 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001840 if offset % align != 0 || MAGIC.len() % align != 0 {
1841 // The write size is larger than the magic value. Fill a buffer
1842 // with the erased value, put the MAGIC in it, and write it in its
1843 // entirety.
1844 let mut buf = vec![dev.erased_val(); align];
1845 buf[(offset % align)..].copy_from_slice(MAGIC);
1846 dev.write(offset - (offset % align), &buf).unwrap();
1847 } else {
1848 dev.write(offset, MAGIC).unwrap();
1849 }
David Brown5c9e0f12019-01-09 16:34:33 -07001850}
1851
1852/// Writes the image_ok flag which, guess what, tells the bootloader
1853/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001854fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001855 // Overwrite mode always is permanent, and only the magic is used in
1856 // the trailer. To avoid problems with large write sizes, don't try to
1857 // set anything in this case.
1858 if Caps::OverwriteUpgrade.present() {
1859 return;
1860 }
1861
David Brown76101572019-02-28 11:29:03 -07001862 let dev = flash.get_mut(&slot.dev_id).unwrap();
1863 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001864 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001865 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001866 let align = dev.align();
1867 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001868}
1869
1870// Drop some pseudo-random gibberish onto the data.
1871fn splat(data: &mut [u8], seed: usize) {
David Browncd842842020-07-09 15:46:53 -06001872 let mut seed_block = [0u8; 16];
1873 let mut buf = Cursor::new(&mut seed_block[..]);
1874 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
1875 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
1876 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
1877 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
1878 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07001879 rng.fill_bytes(data);
1880}
1881
1882/// Return a read-only view into the raw bytes of this object
1883trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07001884 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07001885 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1886 mem::size_of::<Self>()) }
1887 }
1888}
1889
1890pub fn show_sizes() {
1891 // This isn't panic safe.
1892 for min in &[1, 2, 4, 8] {
1893 let msize = c::boot_trailer_sz(*min);
1894 println!("{:2}: {} (0x{:x})", min, msize, msize);
1895 }
1896}
David Brown95de4502019-11-15 12:01:34 -07001897
1898#[cfg(not(feature = "large-write"))]
1899fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001900 &[1, 2, 4, 8]
1901}
1902
1903#[cfg(feature = "large-write")]
1904fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001905 &[1, 2, 4, 8, 128, 512]
1906}