blob: 6bd14c54d3a5042952b143ff829c74357cd3d2ab [file] [log] [blame]
David Browne2acfae2020-01-21 16:45:01 -07001// Copyright (c) 2019 Linaro LTD
2// Copyright (c) 2019-2020 JUUL Labs
3// Copyright (c) 2019 Arm Limited
4//
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 Brown297029a2019-08-13 14:29:51 -060022 collections::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,
29 stream_cipher::{
30 generic_array::GenericArray,
David Brown8a99adf2020-07-09 16:52:38 -060031 NewStreamCipher,
32 SyncStreamCipher,
David Brown5c9e0f12019-01-09 16:34:33 -070033 },
34};
35
David Brown76101572019-02-28 11:29:03 -070036use simflash::{Flash, SimFlash, SimMultiFlash};
David Browne5133242019-02-28 11:05:19 -070037use mcuboot_sys::{c, AreaDesc, FlashId};
38use crate::{
39 ALL_DEVICES,
40 DeviceName,
41};
David Brown5c9e0f12019-01-09 16:34:33 -070042use crate::caps::Caps;
David Brownc3898d62019-08-05 14:20:02 -060043use crate::depends::{
44 BoringDep,
45 Depender,
46 DepTest,
David Brown873be312019-09-03 12:22:32 -060047 DepType,
David Brown2ee5f7f2020-01-13 14:04:01 -070048 NO_DEPS,
David Brownc3898d62019-08-05 14:20:02 -060049 PairDep,
50 UpgradeInfo,
51};
Fabio Utzig90f449e2019-10-24 07:43:53 -030052use crate::tlv::{ManifestGen, TlvGen, TlvFlags};
David Brown5c9e0f12019-01-09 16:34:33 -070053
David Browne5133242019-02-28 11:05:19 -070054/// A builder for Images. This describes a single run of the simulator,
55/// capturing the configuration of a particular set of devices, including
56/// the flash simulator(s) and the information about the slots.
57#[derive(Clone)]
58pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070059 flash: SimMultiFlash,
David Browne5133242019-02-28 11:05:19 -070060 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070061 slots: Vec<[SlotInfo; 2]>,
David Browne5133242019-02-28 11:05:19 -070062}
63
David Brown998aa8d2019-02-28 10:54:50 -070064/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070065/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070066/// and upgrades hold the expected contents of these images.
67pub struct Images {
David Brown76101572019-02-28 11:29:03 -070068 flash: SimMultiFlash,
David Brownca234692019-02-28 11:22:19 -070069 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070070 images: Vec<OneImage>,
71 total_count: Option<i32>,
72}
73
74/// When doing multi-image, there is an instance of this information for
75/// each of the images. Single image there will be one of these.
76struct OneImage {
David Brownca234692019-02-28 11:22:19 -070077 slots: [SlotInfo; 2],
78 primaries: ImageData,
79 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070080}
81
82/// The Rust-side representation of an image. For unencrypted images, this
83/// is just the unencrypted payload. For encrypted images, we store both
84/// the encrypted and the plaintext.
85struct ImageData {
86 plain: Vec<u8>,
87 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -070088}
89
David Browne5133242019-02-28 11:05:19 -070090impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -070091 /// Construct a new image builder for the given device. Returns
92 /// Some(builder) if is possible to test this configuration, or None if
93 /// not possible (for example, if there aren't enough image slots).
Fabio Utzig114a6472019-11-28 10:24:09 -030094 pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
95 let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
96
97 for cap in unsupported_caps {
98 if cap.present() {
99 return Err(format!("unsupported {:?}", cap));
100 }
101 }
David Browne5133242019-02-28 11:05:19 -0700102
David Brown06ef06e2019-03-05 12:28:10 -0700103 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -0700104
David Brown06ef06e2019-03-05 12:28:10 -0700105 let mut slots = Vec::with_capacity(num_images);
106 for image in 0..num_images {
107 // This mapping must match that defined in
108 // `boot/zephyr/include/sysflash/sysflash.h`.
109 let id0 = match image {
110 0 => FlashId::Image0,
111 1 => FlashId::Image2,
112 _ => panic!("More than 2 images not supported"),
113 };
114 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
115 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300116 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700117 };
118 let id1 = match image {
119 0 => FlashId::Image1,
120 1 => FlashId::Image3,
121 _ => panic!("More than 2 images not supported"),
122 };
123 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
124 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300125 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700126 };
David Browne5133242019-02-28 11:05:19 -0700127
Christopher Collinsa1c12042019-05-23 14:00:28 -0700128 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700129
David Brown06ef06e2019-03-05 12:28:10 -0700130 // Construct a primary image.
131 let primary = SlotInfo {
132 base_off: primary_base as usize,
133 trailer_off: primary_base + primary_len - offset_from_end,
134 len: primary_len as usize,
135 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600136 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700137 };
138
139 // And an upgrade image.
140 let secondary = SlotInfo {
141 base_off: secondary_base as usize,
142 trailer_off: secondary_base + secondary_len - offset_from_end,
143 len: secondary_len as usize,
144 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600145 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700146 };
147
148 slots.push([primary, secondary]);
149 }
David Browne5133242019-02-28 11:05:19 -0700150
Fabio Utzig114a6472019-11-28 10:24:09 -0300151 Ok(ImagesBuilder {
David Brown4dfb33c2021-03-10 05:15:45 -0700152 flash,
153 areadesc,
154 slots,
David Brown5bc62c62019-03-05 12:11:48 -0700155 })
David Browne5133242019-02-28 11:05:19 -0700156 }
157
158 pub fn each_device<F>(f: F)
159 where F: Fn(Self)
160 {
161 for &dev in ALL_DEVICES {
David Brown95de4502019-11-15 12:01:34 -0700162 for &align in test_alignments() {
David Browne5133242019-02-28 11:05:19 -0700163 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700164 match Self::new(dev, align, erased_val) {
Fabio Utzig114a6472019-11-28 10:24:09 -0300165 Ok(run) => f(run),
166 Err(msg) => warn!("Skipping {}: {}", dev, msg),
David Brown5bc62c62019-03-05 12:11:48 -0700167 }
David Browne5133242019-02-28 11:05:19 -0700168 }
169 }
170 }
171 }
172
173 /// Construct an `Images` that doesn't expect an upgrade to happen.
David Brownc3898d62019-08-05 14:20:02 -0600174 pub fn make_no_upgrade_image(self, deps: &DepTest) -> Images {
175 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700176 let mut flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600177 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
178 let dep: Box<dyn Depender> = if num_images > 1 {
179 Box::new(PairDep::new(num_images, image_num, deps))
180 } else {
David Brown2ee5f7f2020-01-13 14:04:01 -0700181 Box::new(BoringDep::new(image_num, deps))
David Brownc3898d62019-08-05 14:20:02 -0600182 };
183 let primaries = install_image(&mut flash, &slots[0], 42784, &*dep, false);
David Brown873be312019-09-03 12:22:32 -0600184 let upgrades = match deps.depends[image_num] {
185 DepType::NoUpgrade => install_no_image(),
186 _ => install_image(&mut flash, &slots[1], 46928, &*dep, false)
187 };
David Brown84b49f72019-03-01 10:58:22 -0700188 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700189 slots,
190 primaries,
191 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700192 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600193 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700194 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700195 flash,
David Browne5133242019-02-28 11:05:19 -0700196 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700197 images,
David Browne5133242019-02-28 11:05:19 -0700198 total_count: None,
199 }
200 }
201
David Brownc3898d62019-08-05 14:20:02 -0600202 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
203 let mut images = self.make_no_upgrade_image(deps);
David Brown84b49f72019-03-01 10:58:22 -0700204 for image in &images.images {
205 mark_upgrade(&mut images.flash, &image.slots[1]);
206 }
David Browne5133242019-02-28 11:05:19 -0700207
208 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300209 let total_count = match images.run_basic_upgrade(permanent) {
David Brown8973f552021-03-10 05:21:11 -0700210 Some(v) => v,
211 None =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600212 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
213 0
214 } else {
215 panic!("Unable to perform basic upgrade");
216 }
David Browne5133242019-02-28 11:05:19 -0700217 };
218
219 images.total_count = Some(total_count);
220 images
221 }
222
223 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700224 let mut bad_flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600225 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
David Brown2ee5f7f2020-01-13 14:04:01 -0700226 let dep = BoringDep::new(image_num, &NO_DEPS);
David Brownc3898d62019-08-05 14:20:02 -0600227 let primaries = install_image(&mut bad_flash, &slots[0], 32784, &dep, false);
228 let upgrades = install_image(&mut bad_flash, &slots[1], 41928, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700229 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700230 slots,
231 primaries,
232 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700233 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700234 Images {
David Brown76101572019-02-28 11:29:03 -0700235 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700236 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700237 images,
David Browne5133242019-02-28 11:05:19 -0700238 total_count: None,
239 }
240 }
241
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300242 pub fn make_erased_secondary_image(self) -> Images {
243 let mut flash = self.flash;
244 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
245 let dep = BoringDep::new(image_num, &NO_DEPS);
246 let primaries = install_image(&mut flash, &slots[0], 32784, &dep, false);
247 let upgrades = install_no_image();
248 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700249 slots,
250 primaries,
251 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300252 }}).collect();
253 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700254 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300255 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700256 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300257 total_count: None,
258 }
259 }
260
Fabio Utzigd0157342020-10-02 15:22:11 -0300261 pub fn make_bootstrap_image(self) -> Images {
262 let mut flash = self.flash;
263 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
264 let dep = BoringDep::new(image_num, &NO_DEPS);
265 let primaries = install_no_image();
266 let upgrades = install_image(&mut flash, &slots[1], 32784, &dep, false);
267 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700268 slots,
269 primaries,
270 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300271 }}).collect();
272 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700273 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300274 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700275 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300276 total_count: None,
277 }
278 }
279
David Browne5133242019-02-28 11:05:19 -0700280 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300281 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200282 info!(" +++ Make new device...");
David Browne5133242019-02-28 11:05:19 -0700283 match device {
284 DeviceName::Stm32f4 => {
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200285 info!("DeviceName::Stm32f4");
David Browne5133242019-02-28 11:05:19 -0700286 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700287 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
288 64 * 1024,
289 128 * 1024, 128 * 1024, 128 * 1024],
290 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700291 let dev_id = 0;
292 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700293 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700294 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
295 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
296 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
297
David Brown76101572019-02-28 11:29:03 -0700298 let mut flash = SimMultiFlash::new();
299 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200300 (flash, areadesc, &[Caps::SwapUsingMove, Caps::SwapUsingStatus])
David Browne5133242019-02-28 11:05:19 -0700301 }
302 DeviceName::K64f => {
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200303 info!("DeviceName::K64f");
David Browne5133242019-02-28 11:05:19 -0700304 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700305 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700306
307 let dev_id = 0;
308 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700309 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700310 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
311 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
312 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
313
David Brown76101572019-02-28 11:29:03 -0700314 let mut flash = SimMultiFlash::new();
315 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200316 (flash, areadesc, &[Caps::SwapUsingStatus])
David Browne5133242019-02-28 11:05:19 -0700317 }
318 DeviceName::K64fBig => {
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200319 info!("DeviceName::K64fBig");
David Browne5133242019-02-28 11:05:19 -0700320 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
321 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700322 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700323
324 let dev_id = 0;
325 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700326 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700327 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
328 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
329 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
330
David Brown76101572019-02-28 11:29:03 -0700331 let mut flash = SimMultiFlash::new();
332 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200333 (flash, areadesc, &[Caps::SwapUsingMove, Caps::SwapUsingStatus])
David Browne5133242019-02-28 11:05:19 -0700334 }
335 DeviceName::Nrf52840 => {
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200336 info!("DeviceName::Nrf52840");
David Browne5133242019-02-28 11:05:19 -0700337 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
338 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700339 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700340
341 let dev_id = 0;
342 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700343 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700344 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
345 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
346 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
347
David Brown76101572019-02-28 11:29:03 -0700348 let mut flash = SimMultiFlash::new();
349 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200350 (flash, areadesc, &[Caps::SwapUsingStatus])
David Browne5133242019-02-28 11:05:19 -0700351 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300352 DeviceName::Nrf52840UnequalSlots => {
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200353 info!("DeviceName::Nrf52840UnequalSlots");
Fabio Utzigc659ec52020-07-13 21:18:48 -0300354 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
355
356 let dev_id = 0;
357 let mut areadesc = AreaDesc::new();
358 areadesc.add_flash_sectors(dev_id, &dev);
359 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
360 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
361
362 let mut flash = SimMultiFlash::new();
363 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200364 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade, Caps::SwapUsingStatus])
Fabio Utzigc659ec52020-07-13 21:18:48 -0300365 }
David Browne5133242019-02-28 11:05:19 -0700366 DeviceName::Nrf52840SpiFlash => {
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200367 info!("DeviceName::Nrf52840SpiFlash");
David Browne5133242019-02-28 11:05:19 -0700368 // Simulate nrf52840 with external SPI flash. The external SPI flash
369 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700370 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
371 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700372
373 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700374 areadesc.add_flash_sectors(0, &dev0);
375 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700376
377 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
378 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
379 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
380
David Brown76101572019-02-28 11:29:03 -0700381 let mut flash = SimMultiFlash::new();
382 flash.insert(0, dev0);
383 flash.insert(1, dev1);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200384 (flash, areadesc, &[Caps::SwapUsingMove, Caps::SwapUsingStatus])
David Browne5133242019-02-28 11:05:19 -0700385 }
David Brown2bff6472019-03-05 13:58:35 -0700386 DeviceName::K64fMulti => {
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200387 info!("DeviceName::K64fMulti");
David Brown2bff6472019-03-05 13:58:35 -0700388 // NXP style flash, but larger, to support multiple images.
389 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
390
391 let dev_id = 0;
392 let mut areadesc = AreaDesc::new();
393 areadesc.add_flash_sectors(dev_id, &dev);
394 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
395 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
396 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
397 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
398 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
399
400 let mut flash = SimMultiFlash::new();
401 flash.insert(dev_id, dev);
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200402 (flash, areadesc, &[Caps::SwapUsingStatus])
403 }
404 DeviceName::PSoC6Multi => {
405 info!("DeviceName::PSoC6Multi");
406 // NXP style flash, but larger, to support multiple images.
407
408 let mut areadesc = AreaDesc::new();
409 let mut flash = SimMultiFlash::new();
410
411 // let dev0 = SimFlash::new(vec![4096; 256], align as usize, 0);
412 let mut dev0 = SimFlash::new(vec![512; 1024], align as usize, 0);
413 dev0.set_verify_writes(false);
414 dev0.set_erase_by_sector(true);
415
416 areadesc.add_flash_sectors(0, &dev0);
417 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, 0);
418 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, 0);
419 areadesc.add_image(0x060000, 0x008000, FlashId::ImageScratch, 0);
420 flash.insert(0, dev0);
421
422 // let dev1 = SimFlash::new(vec![4096; 256], align as usize, erased_val);
423 // areadesc.add_flash_sectors(1, &dev1);
424 // areadesc.add_image(0x080000, 0x020000, FlashId::Image2, 0);
425 // areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, 1);
426 // flash.insert(1, dev1);
427
428 // (flash, areadesc, &[])
429 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::SwapUsingMove])
David Brown2bff6472019-03-05 13:58:35 -0700430 }
David Browne5133242019-02-28 11:05:19 -0700431 }
432 }
David Brownc3898d62019-08-05 14:20:02 -0600433
434 pub fn num_images(&self) -> usize {
435 self.slots.len()
436 }
David Browne5133242019-02-28 11:05:19 -0700437}
438
David Brown5c9e0f12019-01-09 16:34:33 -0700439impl Images {
440 /// A simple upgrade without forced failures.
441 ///
442 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700443 /// inject failures at chosen steps. Returns None if it was unable to
444 /// count the operations in a basic upgrade.
445 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300446 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700447 info!("Total flash operation count={}", total_count);
448
David Brown84b49f72019-03-01 10:58:22 -0700449 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700450 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700451 None
David Brown5c9e0f12019-01-09 16:34:33 -0700452 } else {
David Brown8973f552021-03-10 05:21:11 -0700453 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700454 }
455 }
456
Fabio Utzigd0157342020-10-02 15:22:11 -0300457 pub fn run_bootstrap(&self) -> bool {
458 let mut flash = self.flash.clone();
459 let mut fails = 0;
460
461 if Caps::Bootstrap.present() {
462 info!("Try bootstraping image in the primary");
463
464 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
465 if result != 0 {
466 warn!("Failed first boot");
467 fails += 1;
468 }
469
470 if !self.verify_images(&flash, 0, 1) {
471 warn!("Image in the first slot was not bootstrapped");
472 fails += 1;
473 }
474
475 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
476 BOOT_FLAG_SET, BOOT_FLAG_SET) {
477 warn!("Mismatched trailer for the primary slot");
478 fails += 1;
479 }
480 }
481
482 if fails > 0 {
483 error!("Expected trailer on secondary slot to be erased");
484 }
485
486 fails > 0
487 }
488
489
David Brownc3898d62019-08-05 14:20:02 -0600490 /// Test a simple upgrade, with dependencies given, and verify that the
491 /// image does as is described in the test.
492 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
493 let (flash, _) = self.try_upgrade(None, true);
494
495 self.verify_dep_images(&flash, deps)
496 }
497
Fabio Utzigf5480c72019-11-28 10:41:57 -0300498 fn is_swap_upgrade(&self) -> bool {
Roman Okhrimenko13f79ed2021-03-11 19:05:41 +0200499 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present() || Caps::SwapUsingStatus.present()
Fabio Utzigf5480c72019-11-28 10:41:57 -0300500 }
501
David Brown5c9e0f12019-01-09 16:34:33 -0700502 pub fn run_basic_revert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700503 if Caps::OverwriteUpgrade.present() {
504 return false;
505 }
David Brown5c9e0f12019-01-09 16:34:33 -0700506
David Brown5c9e0f12019-01-09 16:34:33 -0700507 let mut fails = 0;
508
509 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300510 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700511 for count in 2 .. 5 {
512 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700513 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700514 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700515 error!("Revert failure on count {}", count);
516 fails += 1;
517 }
518 }
519 }
520
521 fails > 0
522 }
523
524 pub fn run_perm_with_fails(&self) -> bool {
525 let mut fails = 0;
526 let total_flash_ops = self.total_count.unwrap();
527
528 // Let's try an image halfway through.
529 for i in 1 .. total_flash_ops {
530 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300531 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700532 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700533 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700534 warn!("FAIL at step {} of {}", i, total_flash_ops);
535 fails += 1;
536 }
537
David Brown84b49f72019-03-01 10:58:22 -0700538 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
539 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100540 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700541 fails += 1;
542 }
543
David Brown84b49f72019-03-01 10:58:22 -0700544 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
545 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100546 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700547 fails += 1;
548 }
549
David Brownaec56b22021-03-10 05:22:07 -0700550 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
551 warn!("Secondary slot FAIL at step {} of {}",
552 i, total_flash_ops);
553 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700554 }
555 }
556
557 if fails > 0 {
558 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
559 fails as f32 * 100.0 / total_flash_ops as f32);
560 }
561
562 fails > 0
563 }
564
David Brown5c9e0f12019-01-09 16:34:33 -0700565 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
566 let mut fails = 0;
567 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700568 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700569 info!("Random interruptions at reset points={:?}", total_counts);
570
David Brown84b49f72019-03-01 10:58:22 -0700571 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300572 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700573 // TODO: This result is ignored.
574 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700575 } else {
576 true
577 };
David Vincze2d736ad2019-02-18 11:50:22 +0100578 if !primary_slot_ok || !secondary_slot_ok {
579 error!("Image mismatch after random interrupts: primary slot={} \
580 secondary slot={}",
581 if primary_slot_ok { "ok" } else { "fail" },
582 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700583 fails += 1;
584 }
David Brown84b49f72019-03-01 10:58:22 -0700585 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
586 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100587 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700588 fails += 1;
589 }
David Brown84b49f72019-03-01 10:58:22 -0700590 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
591 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100592 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700593 fails += 1;
594 }
595
596 if fails > 0 {
597 error!("Error testing perm upgrade with {} fails", total_fails);
598 }
599
600 fails > 0
601 }
602
David Brown5c9e0f12019-01-09 16:34:33 -0700603 pub fn run_revert_with_fails(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700604 if Caps::OverwriteUpgrade.present() {
605 return false;
606 }
David Brown5c9e0f12019-01-09 16:34:33 -0700607
David Brown5c9e0f12019-01-09 16:34:33 -0700608 let mut fails = 0;
609
Fabio Utzigf5480c72019-11-28 10:41:57 -0300610 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300611 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700612 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700613 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700614 error!("Revert failed at interruption {}", i);
615 fails += 1;
616 }
617 }
618 }
619
620 fails > 0
621 }
622
David Brown5c9e0f12019-01-09 16:34:33 -0700623 pub fn run_norevert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700624 if Caps::OverwriteUpgrade.present() {
625 return false;
626 }
David Brown5c9e0f12019-01-09 16:34:33 -0700627
David Brown76101572019-02-28 11:29:03 -0700628 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700629 let mut fails = 0;
630
631 info!("Try norevert");
632
633 // First do a normal upgrade...
David Brown76101572019-02-28 11:29:03 -0700634 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700635 if result != 0 {
636 warn!("Failed first boot");
637 fails += 1;
638 }
639
640 //FIXME: copy_done is written by boot_go, is it ok if no copy
641 // was ever done?
642
David Brown84b49f72019-03-01 10:58:22 -0700643 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100644 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700645 fails += 1;
646 }
David Brown84b49f72019-03-01 10:58:22 -0700647 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
648 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100649 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700650 fails += 1;
651 }
David Brown84b49f72019-03-01 10:58:22 -0700652 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
653 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100654 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700655 fails += 1;
656 }
657
David Vincze2d736ad2019-02-18 11:50:22 +0100658 // Marks image in the primary slot as permanent,
659 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700660 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700661
David Brown84b49f72019-03-01 10:58:22 -0700662 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
663 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100664 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700665 fails += 1;
666 }
667
David Brown76101572019-02-28 11:29:03 -0700668 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700669 if result != 0 {
670 warn!("Failed second boot");
671 fails += 1;
672 }
673
David Brown84b49f72019-03-01 10:58:22 -0700674 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
675 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100676 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700677 fails += 1;
678 }
David Brown84b49f72019-03-01 10:58:22 -0700679 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700680 warn!("Failed image verification");
681 fails += 1;
682 }
683
684 if fails > 0 {
685 error!("Error running upgrade without revert");
686 }
687
688 fails > 0
689 }
690
David Brown2ee5f7f2020-01-13 14:04:01 -0700691 // Test that an upgrade is rejected. Assumes that the image was build
692 // such that the upgrade is instead a downgrade.
693 pub fn run_nodowngrade(&self) -> bool {
694 if !Caps::DowngradePrevention.present() {
695 return false;
696 }
697
698 let mut flash = self.flash.clone();
699 let mut fails = 0;
700
701 info!("Try no downgrade");
702
703 // First, do a normal upgrade.
704 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
705 if result != 0 {
706 warn!("Failed first boot");
707 fails += 1;
708 }
709
710 if !self.verify_images(&flash, 0, 0) {
711 warn!("Failed verification after downgrade rejection");
712 fails += 1;
713 }
714
715 if fails > 0 {
716 error!("Error testing downgrade rejection");
717 }
718
719 fails > 0
720 }
721
David Vincze2d736ad2019-02-18 11:50:22 +0100722 // Tests a new image written to the primary slot that already has magic and
723 // image_ok set while there is no image on the secondary slot, so no revert
724 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700725 pub fn run_norevert_newimage(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700726 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700727 let mut fails = 0;
728
729 info!("Try non-revert on imgtool generated image");
730
David Brown84b49f72019-03-01 10:58:22 -0700731 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700732
David Vincze2d736ad2019-02-18 11:50:22 +0100733 // This simulates writing an image created by imgtool to
734 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700735 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
736 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100737 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700738 fails += 1;
739 }
740
741 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700742 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700743 if result != 0 {
744 warn!("Failed first boot");
745 fails += 1;
746 }
747
748 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700749 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700750 warn!("Failed image verification");
751 fails += 1;
752 }
David Brown84b49f72019-03-01 10:58:22 -0700753 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
754 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100755 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700756 fails += 1;
757 }
David Brown84b49f72019-03-01 10:58:22 -0700758 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
759 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100760 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700761 fails += 1;
762 }
763
764 if fails > 0 {
765 error!("Expected a non revert with new image");
766 }
767
768 fails > 0
769 }
770
David Vincze2d736ad2019-02-18 11:50:22 +0100771 // Tests a new image written to the primary slot that already has magic and
772 // image_ok set while there is no image on the secondary slot, so no revert
773 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700774 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700775 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700776 let mut fails = 0;
777
778 info!("Try upgrade image with bad signature");
779
David Brown84b49f72019-03-01 10:58:22 -0700780 self.mark_upgrades(&mut flash, 0);
781 self.mark_permanent_upgrades(&mut flash, 0);
782 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700783
David Brown84b49f72019-03-01 10:58:22 -0700784 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
785 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100786 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700787 fails += 1;
788 }
789
790 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700791 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700792 if result != 0 {
793 warn!("Failed first boot");
794 fails += 1;
795 }
796
797 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700798 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700799 warn!("Failed image verification");
800 fails += 1;
801 }
David Brown84b49f72019-03-01 10:58:22 -0700802 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
803 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100804 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700805 fails += 1;
806 }
807
808 if fails > 0 {
809 error!("Expected an upgrade failure when image has bad signature");
810 }
811
812 fails > 0
813 }
814
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300815 // Should detect there is a leftover trailer in an otherwise erased
816 // secondary slot and erase its trailer.
817 pub fn run_secondary_leftover_trailer(&self) -> bool {
818 let mut flash = self.flash.clone();
819 let mut fails = 0;
820
821 info!("Try with a leftover trailer in the secondary; must be erased");
822
823 // Add a trailer on the secondary slot
824 self.mark_permanent_upgrades(&mut flash, 1);
825 self.mark_upgrades(&mut flash, 1);
826
827 // Run the bootloader...
828 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
829 if result != 0 {
830 warn!("Failed first boot");
831 fails += 1;
832 }
833
834 // State should not have changed
835 if !self.verify_images(&flash, 0, 0) {
836 warn!("Failed image verification");
837 fails += 1;
838 }
839 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
840 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
841 warn!("Mismatched trailer for the secondary slot");
842 fails += 1;
843 }
844
845 if fails > 0 {
846 error!("Expected trailer on secondary slot to be erased");
847 }
848
849 fails > 0
850 }
851
David Brown5c9e0f12019-01-09 16:34:33 -0700852 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300853 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700854 }
855
David Brown5c9e0f12019-01-09 16:34:33 -0700856 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300857 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700858 }
859
860 /// This test runs a simple upgrade with no fails in the images, but
861 /// allowing for fails in the status area. This should run to the end
862 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700863 pub fn run_with_status_fails_complete(&self) -> bool {
David Vincze2d736ad2019-02-18 11:50:22 +0100864 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700865 return false;
866 }
867
David Brown76101572019-02-28 11:29:03 -0700868 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700869 let mut fails = 0;
870
871 info!("Try swap with status fails");
872
David Brown84b49f72019-03-01 10:58:22 -0700873 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700874 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700875
David Brown76101572019-02-28 11:29:03 -0700876 let (result, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown5c9e0f12019-01-09 16:34:33 -0700877 if result != 0 {
878 warn!("Failed!");
879 fails += 1;
880 }
881
882 // Failed writes to the marked "bad" region don't assert anymore.
883 // Any detected assert() is happening in another part of the code.
884 if asserts != 0 {
885 warn!("At least one assert() was called");
886 fails += 1;
887 }
888
David Brown84b49f72019-03-01 10:58:22 -0700889 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
890 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100891 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700892 fails += 1;
893 }
894
David Brown84b49f72019-03-01 10:58:22 -0700895 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700896 warn!("Failed image verification");
897 fails += 1;
898 }
899
David Vincze2d736ad2019-02-18 11:50:22 +0100900 info!("validate primary slot enabled; \
901 re-run of boot_go should just work");
David Brown76101572019-02-28 11:29:03 -0700902 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700903 if result != 0 {
904 warn!("Failed!");
905 fails += 1;
906 }
907
908 if fails > 0 {
909 error!("Error running upgrade with status write fails");
910 }
911
912 fails > 0
913 }
914
915 /// This test runs a simple upgrade with no fails in the images, but
916 /// allowing for fails in the status area. This should run to the end
917 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700918 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown85904a82019-01-11 13:45:12 -0700919 if Caps::OverwriteUpgrade.present() {
920 false
David Vincze2d736ad2019-02-18 11:50:22 +0100921 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700922
David Brown76101572019-02-28 11:29:03 -0700923 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700924 let mut fails = 0;
925 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700926
David Brown85904a82019-01-11 13:45:12 -0700927 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700928
David Brown85904a82019-01-11 13:45:12 -0700929 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700930
David Brown84b49f72019-03-01 10:58:22 -0700931 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700932 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700933
934 // Should not fail, writing to bad regions does not assert
David Brown76101572019-02-28 11:29:03 -0700935 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true);
David Brown85904a82019-01-11 13:45:12 -0700936 if asserts != 0 {
937 warn!("At least one assert() was called");
938 fails += 1;
939 }
940
David Brown76101572019-02-28 11:29:03 -0700941 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700942
943 info!("Resuming an interrupted swap operation");
David Brown76101572019-02-28 11:29:03 -0700944 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700945
946 // This might throw no asserts, for large sector devices, where
947 // a single failure writing is indistinguishable from no failure,
948 // or throw a single assert for small sector devices that fail
949 // multiple times...
950 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100951 warn!("Expected single assert validating the primary slot, \
952 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700953 fails += 1;
954 }
955
956 if fails > 0 {
957 error!("Error running upgrade with status write fails");
958 }
959
960 fails > 0
961 } else {
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
965 info!("Try interrupted swap with status fails");
966
David Brown84b49f72019-03-01 10:58:22 -0700967 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700968 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700969
970 // This is expected to fail while writing to bad regions...
David Brown76101572019-02-28 11:29:03 -0700971 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700972 if asserts == 0 {
973 warn!("No assert() detected");
974 fails += 1;
975 }
976
977 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700978 }
David Brown5c9e0f12019-01-09 16:34:33 -0700979 }
980
981 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -0700982 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -0700983 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -0700984 if Caps::OverwriteUpgrade.present() {
985 return;
986 }
987
David Brown84b49f72019-03-01 10:58:22 -0700988 // Set this for each image.
989 for image in &self.images {
990 let dev_id = &image.slots[slot].dev_id;
991 let dev = flash.get_mut(&dev_id).unwrap();
992 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -0700993 let off = &image.slots[slot].base_off;
994 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -0700995 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -0700996
David Brown84b49f72019-03-01 10:58:22 -0700997 // Mark the status area as a bad area
998 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
999 }
David Brown5c9e0f12019-01-09 16:34:33 -07001000 }
1001
David Brown76101572019-02-28 11:29:03 -07001002 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001003 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001004 return;
1005 }
1006
David Brown84b49f72019-03-01 10:58:22 -07001007 for image in &self.images {
1008 let dev_id = &image.slots[slot].dev_id;
1009 let dev = flash.get_mut(&dev_id).unwrap();
1010 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001011
David Brown84b49f72019-03-01 10:58:22 -07001012 // Disabling write verification the only assert triggered by
1013 // boot_go should be checking for integrity of status bytes.
1014 dev.set_verify_writes(false);
1015 }
David Brown5c9e0f12019-01-09 16:34:33 -07001016 }
1017
David Browndb505822019-03-01 10:04:20 -07001018 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1019 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001020 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001021 // Clone the flash to have a new copy.
1022 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001023
Fabio Utziged4a5362019-07-30 12:43:23 -03001024 if permanent {
1025 self.mark_permanent_upgrades(&mut flash, 1);
1026 }
David Brown5c9e0f12019-01-09 16:34:33 -07001027
David Browndb505822019-03-01 10:04:20 -07001028 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001029
David Browndb505822019-03-01 10:04:20 -07001030 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
1031 (-0x13579, _) => (true, stop.unwrap()),
1032 (0, _) => (false, -counter),
1033 (x, _) => panic!("Unknown return: {}", x),
1034 };
David Brown5c9e0f12019-01-09 16:34:33 -07001035
David Browndb505822019-03-01 10:04:20 -07001036 counter = 0;
1037 if first_interrupted {
1038 // fl.dump();
1039 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
1040 (-0x13579, _) => panic!("Shouldn't stop again"),
1041 (0, _) => (),
1042 (x, _) => panic!("Unknown return: {}", x),
1043 }
1044 }
David Brown5c9e0f12019-01-09 16:34:33 -07001045
David Browndb505822019-03-01 10:04:20 -07001046 (flash, count - counter)
1047 }
1048
1049 fn try_revert(&self, count: usize) -> SimMultiFlash {
1050 let mut flash = self.flash.clone();
1051
1052 // fl.write_file("image0.bin").unwrap();
1053 for i in 0 .. count {
1054 info!("Running boot pass {}", i + 1);
1055 assert_eq!(c::boot_go(&mut flash, &self.areadesc, None, false), (0, 0));
1056 }
1057 flash
1058 }
1059
1060 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1061 let mut flash = self.flash.clone();
1062 let mut fails = 0;
1063
1064 let mut counter = stop;
1065 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
1066 if x != -0x13579 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001067 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001068 fails += 1;
1069 }
1070
Fabio Utzig8af7f792019-07-30 12:40:01 -03001071 // In a multi-image setup, copy done might be set if any number of
1072 // images was already successfully swapped.
1073 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1074 warn!("copy_done should be unset");
1075 fails += 1;
1076 }
1077
David Browndb505822019-03-01 10:04:20 -07001078 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
1079 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001080 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001081 fails += 1;
1082 }
1083
David Brown84b49f72019-03-01 10:58:22 -07001084 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001085 warn!("Image in the primary slot before revert is invalid at stop={}",
1086 stop);
1087 fails += 1;
1088 }
David Brown84b49f72019-03-01 10:58:22 -07001089 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001090 warn!("Image in the secondary slot before revert is invalid at stop={}",
1091 stop);
1092 fails += 1;
1093 }
David Brown84b49f72019-03-01 10:58:22 -07001094 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1095 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001096 warn!("Mismatched trailer for the primary slot before revert");
1097 fails += 1;
1098 }
David Brown84b49f72019-03-01 10:58:22 -07001099 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1100 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001101 warn!("Mismatched trailer for the secondary slot before revert");
1102 fails += 1;
1103 }
1104
1105 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001106 let mut counter = stop;
1107 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
1108 if x != -0x13579 {
1109 warn!("Should have stopped revert at interruption point");
1110 fails += 1;
1111 }
1112
David Browndb505822019-03-01 10:04:20 -07001113 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
1114 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001115 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001116 fails += 1;
1117 }
1118
David Brown84b49f72019-03-01 10:58:22 -07001119 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001120 warn!("Image in the primary slot after revert is invalid at stop={}",
1121 stop);
1122 fails += 1;
1123 }
David Brown84b49f72019-03-01 10:58:22 -07001124 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001125 warn!("Image in the secondary slot after revert is invalid at stop={}",
1126 stop);
1127 fails += 1;
1128 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001129
David Brown84b49f72019-03-01 10:58:22 -07001130 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1131 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001132 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001133 fails += 1;
1134 }
David Brown84b49f72019-03-01 10:58:22 -07001135 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1136 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001137 warn!("Mismatched trailer for the secondary slot after revert");
1138 fails += 1;
1139 }
1140
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001141 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
1142 if x != 0 {
1143 warn!("Should have finished 3rd boot");
1144 fails += 1;
1145 }
1146
1147 if !self.verify_images(&flash, 0, 0) {
1148 warn!("Image in the primary slot is invalid on 1st boot after revert");
1149 fails += 1;
1150 }
1151 if !self.verify_images(&flash, 1, 1) {
1152 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1153 fails += 1;
1154 }
1155
David Browndb505822019-03-01 10:04:20 -07001156 fails > 0
1157 }
1158
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001159
David Browndb505822019-03-01 10:04:20 -07001160 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1161 let mut flash = self.flash.clone();
1162
David Brown84b49f72019-03-01 10:58:22 -07001163 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001164
1165 let mut rng = rand::thread_rng();
1166 let mut resets = vec![0i32; count];
1167 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001168 for reset in &mut resets {
David Browncd842842020-07-09 15:46:53 -06001169 let reset_counter = rng.gen_range(1, remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001170 let mut counter = reset_counter;
1171 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
1172 (0, _) | (-0x13579, _) => (),
1173 (x, _) => panic!("Unknown return: {}", x),
1174 }
1175 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001176 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001177 }
1178
1179 match c::boot_go(&mut flash, &self.areadesc, None, false) {
1180 (-0x13579, _) => panic!("Should not be have been interrupted!"),
David Brown5c9e0f12019-01-09 16:34:33 -07001181 (0, _) => (),
1182 (x, _) => panic!("Unknown return: {}", x),
1183 }
David Brown5c9e0f12019-01-09 16:34:33 -07001184
David Browndb505822019-03-01 10:04:20 -07001185 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001186 }
David Brown84b49f72019-03-01 10:58:22 -07001187
1188 /// Verify the image in the given flash device, the specified slot
1189 /// against the expected image.
1190 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001191 self.images.iter().all(|image| {
1192 verify_image(flash, &image.slots[slot],
1193 match against {
1194 0 => &image.primaries,
1195 1 => &image.upgrades,
1196 _ => panic!("Invalid 'against'")
1197 })
1198 })
David Brown84b49f72019-03-01 10:58:22 -07001199 }
1200
David Brownc3898d62019-08-05 14:20:02 -06001201 /// Verify the images, according to the dependency test.
1202 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1203 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1204 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1205 if !verify_image(flash, &image.slots[0],
1206 match upgrade {
1207 UpgradeInfo::Upgraded => &image.upgrades,
1208 UpgradeInfo::Held => &image.primaries,
1209 }) {
1210 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1211 return true;
1212 }
1213 }
1214
1215 false
1216 }
1217
Fabio Utzig8af7f792019-07-30 12:40:01 -03001218 /// Verify that at least one of the trailers of the images have the
1219 /// specified values.
1220 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1221 magic: Option<u8>, image_ok: Option<u8>,
1222 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001223 self.images.iter().any(|image| {
1224 verify_trailer(flash, &image.slots[slot],
1225 magic, image_ok, copy_done)
1226 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001227 }
1228
David Brown84b49f72019-03-01 10:58:22 -07001229 /// Verify that the trailers of the images have the specified
1230 /// values.
1231 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1232 magic: Option<u8>, image_ok: Option<u8>,
1233 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001234 self.images.iter().all(|image| {
1235 verify_trailer(flash, &image.slots[slot],
1236 magic, image_ok, copy_done)
1237 })
David Brown84b49f72019-03-01 10:58:22 -07001238 }
1239
1240 /// Mark each of the images for permanent upgrade.
1241 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1242 for image in &self.images {
1243 mark_permanent_upgrade(flash, &image.slots[slot]);
1244 }
1245 }
1246
1247 /// Mark each of the images for permanent upgrade.
1248 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1249 for image in &self.images {
1250 mark_upgrade(flash, &image.slots[slot]);
1251 }
1252 }
David Brown297029a2019-08-13 14:29:51 -06001253
1254 /// Dump out the flash image(s) to one or more files for debugging
1255 /// purposes. The names will be written as either "{prefix}.mcubin" or
1256 /// "{prefix}-001.mcubin" depending on how many images there are.
1257 pub fn debug_dump(&self, prefix: &str) {
1258 for (id, fdev) in &self.flash {
1259 let name = if self.flash.len() == 1 {
1260 format!("{}.mcubin", prefix)
1261 } else {
1262 format!("{}-{:>0}.mcubin", prefix, id)
1263 };
1264 fdev.write_file(&name).unwrap();
1265 }
1266 }
David Brown5c9e0f12019-01-09 16:34:33 -07001267}
1268
1269/// Show the flash layout.
1270#[allow(dead_code)]
1271fn show_flash(flash: &dyn Flash) {
1272 println!("---- Flash configuration ----");
1273 for sector in flash.sector_iter() {
1274 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1275 sector.num, sector.base, sector.size);
1276 }
David Brown599b2db2021-03-10 05:23:26 -07001277 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001278}
1279
1280/// Install a "program" into the given image. This fakes the image header, or at least all of the
1281/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001282fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownc3898d62019-08-05 14:20:02 -06001283 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001284 let offset = slot.base_off;
1285 let slot_len = slot.len;
1286 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001287
David Brown43643dd2019-01-11 15:43:28 -07001288 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001289
David Brownc3898d62019-08-05 14:20:02 -06001290 // Add the dependencies early to the tlv.
1291 for dep in deps.my_deps(offset, slot.index) {
1292 tlv.add_dependency(deps.other_id(), &dep);
1293 }
1294
David Brown5c9e0f12019-01-09 16:34:33 -07001295 const HDR_SIZE: usize = 32;
1296
1297 // Generate a boot header. Note that the size doesn't include the header.
1298 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001299 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -07001300 load_addr: 0,
1301 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001302 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001303 img_size: len as u32,
1304 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001305 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001306 _pad2: 0,
1307 };
1308
1309 let mut b_header = [0; HDR_SIZE];
1310 b_header[..32].clone_from_slice(header.as_raw());
1311 assert_eq!(b_header.len(), HDR_SIZE);
1312
1313 tlv.add_bytes(&b_header);
1314
1315 // The core of the image itself is just pseudorandom data.
1316 let mut b_img = vec![0; len];
1317 splat(&mut b_img, offset);
1318
David Browncb47dd72019-08-05 14:21:49 -06001319 // Add some information at the start of the payload to make it easier
1320 // to see what it is. This will fail if the image itself is too small.
1321 {
1322 let mut wr = Cursor::new(&mut b_img);
1323 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1324 offset, dev_id, slot).unwrap();
1325 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1326 }
1327
David Brown5c9e0f12019-01-09 16:34:33 -07001328 // TLV signatures work over plain image
1329 tlv.add_bytes(&b_img);
1330
1331 // Generate encrypted images
1332 let flag = TlvFlags::ENCRYPTED as u32;
1333 let is_encrypted = (tlv.get_flags() & flag) == flag;
1334 let mut b_encimg = vec![];
1335 if is_encrypted {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001336 tlv.generate_enc_key();
1337 let enc_key = tlv.get_enc_key();
1338 let key = GenericArray::from_slice(enc_key.as_slice());
David Brown5c9e0f12019-01-09 16:34:33 -07001339 let nonce = GenericArray::from_slice(&[0; 16]);
1340 let mut cipher = Aes128Ctr::new(&key, &nonce);
1341 b_encimg = b_img.clone();
1342 cipher.apply_keystream(&mut b_encimg);
1343 }
1344
1345 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001346 if bad_sig {
1347 tlv.corrupt_sig();
1348 }
1349 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001350
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001351 let dev = flash.get_mut(&dev_id).unwrap();
1352
David Brown5c9e0f12019-01-09 16:34:33 -07001353 let mut buf = vec![];
1354 buf.append(&mut b_header.to_vec());
1355 buf.append(&mut b_img);
1356 buf.append(&mut b_tlv.clone());
1357
David Brown95de4502019-11-15 12:01:34 -07001358 // Pad the buffer to a multiple of the flash alignment.
1359 let align = dev.align();
1360 while buf.len() % align != 0 {
1361 buf.push(dev.erased_val());
1362 }
1363
David Brown5c9e0f12019-01-09 16:34:33 -07001364 let mut encbuf = vec![];
1365 if is_encrypted {
1366 encbuf.append(&mut b_header.to_vec());
1367 encbuf.append(&mut b_encimg);
1368 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001369
1370 while encbuf.len() % align != 0 {
1371 encbuf.push(dev.erased_val());
1372 }
David Brown5c9e0f12019-01-09 16:34:33 -07001373 }
1374
David Vincze2d736ad2019-02-18 11:50:22 +01001375 // Since images are always non-encrypted in the primary slot, we first write
1376 // an encrypted image, re-read to use for verification, erase + flash
1377 // un-encrypted. In the secondary slot the image is written un-encrypted,
1378 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001379
David Brown3b090212019-07-30 15:59:28 -06001380 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001381 let enc_copy: Option<Vec<u8>>;
1382
1383 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001384 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001385
1386 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001387 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001388
1389 enc_copy = Some(enc);
1390
David Brown76101572019-02-28 11:29:03 -07001391 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001392 } else {
1393 enc_copy = None;
1394 }
1395
David Brown76101572019-02-28 11:29:03 -07001396 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001397
1398 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001399 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001400
David Brownca234692019-02-28 11:22:19 -07001401 ImageData {
1402 plain: copy,
1403 cipher: enc_copy,
1404 }
David Brown5c9e0f12019-01-09 16:34:33 -07001405 } else {
1406
David Brown76101572019-02-28 11:29:03 -07001407 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001408
1409 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001410 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001411
1412 let enc_copy: Option<Vec<u8>>;
1413
1414 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001415 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001416
David Brown76101572019-02-28 11:29:03 -07001417 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001418
1419 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001420 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001421
1422 enc_copy = Some(enc);
1423 } else {
1424 enc_copy = None;
1425 }
1426
David Brownca234692019-02-28 11:22:19 -07001427 ImageData {
1428 plain: copy,
1429 cipher: enc_copy,
1430 }
David Brown5c9e0f12019-01-09 16:34:33 -07001431 }
David Brown5c9e0f12019-01-09 16:34:33 -07001432}
1433
David Brown873be312019-09-03 12:22:32 -06001434/// Install no image. This is used when no upgrade happens.
1435fn install_no_image() -> ImageData {
1436 ImageData {
1437 plain: vec![],
1438 cipher: None,
1439 }
1440}
1441
David Brown5c9e0f12019-01-09 16:34:33 -07001442fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001443 if Caps::EcdsaP224.present() {
1444 panic!("Ecdsa P224 not supported in Simulator");
1445 }
David Brown5c9e0f12019-01-09 16:34:33 -07001446
David Brownb8882112019-01-11 14:04:11 -07001447 if Caps::EncKw.present() {
1448 if Caps::RSA2048.present() {
1449 TlvGen::new_rsa_kw()
1450 } else if Caps::EcdsaP256.present() {
1451 TlvGen::new_ecdsa_kw()
1452 } else {
1453 TlvGen::new_enc_kw()
1454 }
1455 } else if Caps::EncRsa.present() {
1456 if Caps::RSA2048.present() {
1457 TlvGen::new_sig_enc_rsa()
1458 } else {
1459 TlvGen::new_enc_rsa()
1460 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001461 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001462 if Caps::EcdsaP256.present() {
1463 TlvGen::new_ecdsa_ecies_p256()
1464 } else {
1465 TlvGen::new_ecies_p256()
1466 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001467 } else if Caps::EncX25519.present() {
1468 if Caps::Ed25519.present() {
1469 TlvGen::new_ed25519_ecies_x25519()
1470 } else {
1471 TlvGen::new_ecies_x25519()
1472 }
David Brownb8882112019-01-11 14:04:11 -07001473 } else {
1474 // The non-encrypted configuration.
1475 if Caps::RSA2048.present() {
1476 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001477 } else if Caps::RSA3072.present() {
1478 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001479 } else if Caps::EcdsaP256.present() {
1480 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001481 } else if Caps::Ed25519.present() {
1482 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001483 } else {
1484 TlvGen::new_hash_only()
1485 }
1486 }
David Brown5c9e0f12019-01-09 16:34:33 -07001487}
1488
David Brownca234692019-02-28 11:22:19 -07001489impl ImageData {
1490 /// Find the image contents for the given slot. This assumes that slot 0
1491 /// is unencrypted, and slot 1 is encrypted.
1492 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001493 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001494 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001495 match (encrypted, slot) {
1496 (false, _) => &self.plain,
1497 (true, 0) => &self.plain,
1498 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1499 _ => panic!("Invalid slot requested"),
1500 }
David Brown5c9e0f12019-01-09 16:34:33 -07001501 }
1502}
1503
David Brown5c9e0f12019-01-09 16:34:33 -07001504/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001505fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1506 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001507 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001508 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001509
1510 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001511 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001512 let dev = flash.get(&dev_id).unwrap();
1513 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001514
1515 if buf != &copy[..] {
1516 for i in 0 .. buf.len() {
1517 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001518 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1519 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001520 break;
1521 }
1522 }
1523 false
1524 } else {
1525 true
1526 }
1527}
1528
David Brown3b090212019-07-30 15:59:28 -06001529fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001530 magic: Option<u8>, image_ok: Option<u8>,
1531 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001532 if Caps::OverwriteUpgrade.present() {
1533 return true;
1534 }
David Brown5c9e0f12019-01-09 16:34:33 -07001535
David Brown3b090212019-07-30 15:59:28 -06001536 let offset = slot.trailer_off + c::boot_max_align();
1537 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001538 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001539 let mut failed = false;
1540
David Brown76101572019-02-28 11:29:03 -07001541 let dev = flash.get(&dev_id).unwrap();
1542 let erased_val = dev.erased_val();
1543 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001544
1545 failed |= match magic {
1546 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001547 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001548 warn!("\"magic\" mismatch at {:#x}", offset);
1549 true
1550 } else if v == 3 {
1551 let expected = [erased_val; 16];
David Brownd36f6b12021-03-10 05:23:56 -07001552 if copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001553 warn!("\"magic\" mismatch at {:#x}", offset);
1554 true
1555 } else {
1556 false
1557 }
1558 } else {
1559 false
1560 }
1561 },
1562 None => false,
1563 };
1564
1565 failed |= match image_ok {
1566 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001567 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001568 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1569 true
1570 } else {
1571 false
1572 }
1573 },
1574 None => false,
1575 };
1576
1577 failed |= match copy_done {
1578 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001579 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001580 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1581 true
1582 } else {
1583 false
1584 }
1585 },
1586 None => false,
1587 };
1588
1589 !failed
1590}
1591
David Brown297029a2019-08-13 14:29:51 -06001592/// Install a partition table. This is a simplified partition table that
1593/// we write at the beginning of flash so make it easier for external tools
1594/// to analyze these images.
1595fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1596 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1597 for &id in &ids {
1598 // If there are any partitions in this device that start at 0, and
1599 // aren't marked as the BootLoader partition, avoid adding the
1600 // partition table. This makes it harder to view the image, but
1601 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07001602 let skip_ptable = areadesc
1603 .iter_areas()
1604 .any(|area| {
1605 area.device_id == id &&
1606 area.off == 0 &&
1607 area.flash_id != FlashId::BootLoader
1608 });
1609 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06001610 if log_enabled!(Info) {
1611 let special: Vec<FlashId> = areadesc.iter_areas()
1612 .filter(|area| area.device_id == id && area.off == 0)
1613 .map(|area| area.flash_id)
1614 .collect();
1615 info!("Skipping partition table: {:?}", special);
1616 }
1617 break;
1618 }
1619
1620 let mut buf: Vec<u8> = vec![];
1621 write!(&mut buf, "mcuboot\0").unwrap();
1622
1623 // Iterate through all of the partitions in that device, and encode
1624 // into the table.
1625 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1626 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1627
1628 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1629 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1630 buf.write_u32::<LittleEndian>(area.off).unwrap();
1631 buf.write_u32::<LittleEndian>(area.size).unwrap();
1632 buf.write_u32::<LittleEndian>(0).unwrap();
1633 }
1634
1635 let dev = flash.get_mut(&id).unwrap();
1636
1637 // Pad to alignment.
1638 while buf.len() % dev.align() != 0 {
1639 buf.push(0);
1640 }
1641
1642 dev.write(0, &buf).unwrap();
1643 }
1644}
1645
David Brown5c9e0f12019-01-09 16:34:33 -07001646/// The image header
1647#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001648#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001649pub struct ImageHeader {
1650 magic: u32,
1651 load_addr: u32,
1652 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001653 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001654 img_size: u32,
1655 flags: u32,
1656 ver: ImageVersion,
1657 _pad2: u32,
1658}
1659
1660impl AsRaw for ImageHeader {}
1661
1662#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001663#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001664pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001665 pub major: u8,
1666 pub minor: u8,
1667 pub revision: u16,
1668 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001669}
1670
David Brownc3898d62019-08-05 14:20:02 -06001671#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001672pub struct SlotInfo {
1673 pub base_off: usize,
1674 pub trailer_off: usize,
1675 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001676 // Which slot within this device.
1677 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001678 pub dev_id: u8,
1679}
1680
David Brown347dc572019-11-15 11:37:25 -07001681const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1682 0x60, 0xd2, 0xef, 0x7f,
1683 0x35, 0x52, 0x50, 0x0f,
1684 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001685
1686// Replicates defines found in bootutil.h
1687const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1688const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1689
1690const BOOT_FLAG_SET: Option<u8> = Some(1);
1691const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1692
1693/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001694pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1695 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001696 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001697 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001698 if offset % align != 0 || MAGIC.len() % align != 0 {
1699 // The write size is larger than the magic value. Fill a buffer
1700 // with the erased value, put the MAGIC in it, and write it in its
1701 // entirety.
1702 let mut buf = vec![dev.erased_val(); align];
1703 buf[(offset % align)..].copy_from_slice(MAGIC);
1704 dev.write(offset - (offset % align), &buf).unwrap();
1705 } else {
1706 dev.write(offset, MAGIC).unwrap();
1707 }
David Brown5c9e0f12019-01-09 16:34:33 -07001708}
1709
1710/// Writes the image_ok flag which, guess what, tells the bootloader
1711/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001712fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001713 // Overwrite mode always is permanent, and only the magic is used in
1714 // the trailer. To avoid problems with large write sizes, don't try to
1715 // set anything in this case.
1716 if Caps::OverwriteUpgrade.present() {
1717 return;
1718 }
1719
David Brown76101572019-02-28 11:29:03 -07001720 let dev = flash.get_mut(&slot.dev_id).unwrap();
1721 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001722 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001723 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001724 let align = dev.align();
1725 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001726}
1727
1728// Drop some pseudo-random gibberish onto the data.
1729fn splat(data: &mut [u8], seed: usize) {
David Browncd842842020-07-09 15:46:53 -06001730 let mut seed_block = [0u8; 16];
1731 let mut buf = Cursor::new(&mut seed_block[..]);
1732 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
1733 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
1734 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
1735 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
1736 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07001737 rng.fill_bytes(data);
1738}
1739
1740/// Return a read-only view into the raw bytes of this object
1741trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07001742 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07001743 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1744 mem::size_of::<Self>()) }
1745 }
1746}
1747
1748pub fn show_sizes() {
1749 // This isn't panic safe.
1750 for min in &[1, 2, 4, 8] {
1751 let msize = c::boot_trailer_sz(*min);
1752 println!("{:2}: {} (0x{:x})", min, msize, msize);
1753 }
1754}
David Brown95de4502019-11-15 12:01:34 -07001755
1756#[cfg(not(feature = "large-write"))]
1757fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001758 &[1, 2, 4, 8]
1759}
1760
1761#[cfg(feature = "large-write")]
1762fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001763 &[1, 2, 4, 8, 128, 512]
1764}