blob: c3f8452ca9d860df47174f6f47275a9eb5fee540 [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 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,
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 Browne5133242019-02-28 11:05:19 -070038use mcuboot_sys::{c, AreaDesc, FlashId};
39use 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 Browne5133242019-02-28 11:05:19 -070056/// A builder for Images. This describes a single run of the simulator,
57/// capturing the configuration of a particular set of devices, including
58/// the flash simulator(s) and the information about the slots.
59#[derive(Clone)]
60pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070061 flash: SimMultiFlash,
David Browne5133242019-02-28 11:05:19 -070062 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070063 slots: Vec<[SlotInfo; 2]>,
David Browne5133242019-02-28 11:05:19 -070064}
65
David Brown998aa8d2019-02-28 10:54:50 -070066/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070067/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070068/// and upgrades hold the expected contents of these images.
69pub struct Images {
David Brown76101572019-02-28 11:29:03 -070070 flash: SimMultiFlash,
David Brownca234692019-02-28 11:22:19 -070071 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070072 images: Vec<OneImage>,
73 total_count: Option<i32>,
74}
75
76/// When doing multi-image, there is an instance of this information for
77/// each of the images. Single image there will be one of these.
78struct OneImage {
David Brownca234692019-02-28 11:22:19 -070079 slots: [SlotInfo; 2],
80 primaries: ImageData,
81 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070082}
83
84/// The Rust-side representation of an image. For unencrypted images, this
85/// is just the unencrypted payload. For encrypted images, we store both
86/// the encrypted and the plaintext.
87struct ImageData {
88 plain: Vec<u8>,
89 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -070090}
91
David Browne5133242019-02-28 11:05:19 -070092impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -070093 /// Construct a new image builder for the given device. Returns
94 /// Some(builder) if is possible to test this configuration, or None if
95 /// not possible (for example, if there aren't enough image slots).
Fabio Utzig114a6472019-11-28 10:24:09 -030096 pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
97 let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
98
99 for cap in unsupported_caps {
100 if cap.present() {
101 return Err(format!("unsupported {:?}", cap));
102 }
103 }
David Browne5133242019-02-28 11:05:19 -0700104
David Brown06ef06e2019-03-05 12:28:10 -0700105 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -0700106
David Brown06ef06e2019-03-05 12:28:10 -0700107 let mut slots = Vec::with_capacity(num_images);
108 for image in 0..num_images {
109 // This mapping must match that defined in
110 // `boot/zephyr/include/sysflash/sysflash.h`.
111 let id0 = match image {
112 0 => FlashId::Image0,
113 1 => FlashId::Image2,
114 _ => panic!("More than 2 images not supported"),
115 };
116 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
117 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300118 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700119 };
120 let id1 = match image {
121 0 => FlashId::Image1,
122 1 => FlashId::Image3,
123 _ => panic!("More than 2 images not supported"),
124 };
125 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
126 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300127 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700128 };
David Browne5133242019-02-28 11:05:19 -0700129
Christopher Collinsa1c12042019-05-23 14:00:28 -0700130 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700131
David Brown06ef06e2019-03-05 12:28:10 -0700132 // Construct a primary image.
133 let primary = SlotInfo {
134 base_off: primary_base as usize,
135 trailer_off: primary_base + primary_len - offset_from_end,
136 len: primary_len as usize,
137 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600138 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700139 };
140
141 // And an upgrade image.
142 let secondary = SlotInfo {
143 base_off: secondary_base as usize,
144 trailer_off: secondary_base + secondary_len - offset_from_end,
145 len: secondary_len as usize,
146 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600147 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700148 };
149
150 slots.push([primary, secondary]);
151 }
David Browne5133242019-02-28 11:05:19 -0700152
Fabio Utzig114a6472019-11-28 10:24:09 -0300153 Ok(ImagesBuilder {
David Brown4dfb33c2021-03-10 05:15:45 -0700154 flash,
155 areadesc,
156 slots,
David Brown5bc62c62019-03-05 12:11:48 -0700157 })
David Browne5133242019-02-28 11:05:19 -0700158 }
159
160 pub fn each_device<F>(f: F)
161 where F: Fn(Self)
162 {
163 for &dev in ALL_DEVICES {
David Brown95de4502019-11-15 12:01:34 -0700164 for &align in test_alignments() {
David Browne5133242019-02-28 11:05:19 -0700165 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700166 match Self::new(dev, align, erased_val) {
Fabio Utzig114a6472019-11-28 10:24:09 -0300167 Ok(run) => f(run),
168 Err(msg) => warn!("Skipping {}: {}", dev, msg),
David Brown5bc62c62019-03-05 12:11:48 -0700169 }
David Browne5133242019-02-28 11:05:19 -0700170 }
171 }
172 }
173 }
174
175 /// Construct an `Images` that doesn't expect an upgrade to happen.
David Brownc3898d62019-08-05 14:20:02 -0600176 pub fn make_no_upgrade_image(self, deps: &DepTest) -> Images {
177 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700178 let mut flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600179 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
180 let dep: Box<dyn Depender> = if num_images > 1 {
181 Box::new(PairDep::new(num_images, image_num, deps))
182 } else {
David Brown2ee5f7f2020-01-13 14:04:01 -0700183 Box::new(BoringDep::new(image_num, deps))
David Brownc3898d62019-08-05 14:20:02 -0600184 };
185 let primaries = install_image(&mut flash, &slots[0], 42784, &*dep, false);
David Brown873be312019-09-03 12:22:32 -0600186 let upgrades = match deps.depends[image_num] {
187 DepType::NoUpgrade => install_no_image(),
188 _ => install_image(&mut flash, &slots[1], 46928, &*dep, false)
189 };
David Brown84b49f72019-03-01 10:58:22 -0700190 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700191 slots,
192 primaries,
193 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700194 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600195 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700196 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700197 flash,
David Browne5133242019-02-28 11:05:19 -0700198 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700199 images,
David Browne5133242019-02-28 11:05:19 -0700200 total_count: None,
201 }
202 }
203
David Brownc3898d62019-08-05 14:20:02 -0600204 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
205 let mut images = self.make_no_upgrade_image(deps);
David Brown84b49f72019-03-01 10:58:22 -0700206 for image in &images.images {
207 mark_upgrade(&mut images.flash, &image.slots[1]);
208 }
David Browne5133242019-02-28 11:05:19 -0700209
David Brown6db44d72021-05-26 16:22:58 -0600210 // The count is meaningless if no flash operations are performed.
211 if !Caps::modifies_flash() {
212 return images;
213 }
214
David Browne5133242019-02-28 11:05:19 -0700215 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300216 let total_count = match images.run_basic_upgrade(permanent) {
David Brown8973f552021-03-10 05:21:11 -0700217 Some(v) => v,
218 None =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600219 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
220 0
221 } else {
222 panic!("Unable to perform basic upgrade");
223 }
David Browne5133242019-02-28 11:05:19 -0700224 };
225
226 images.total_count = Some(total_count);
227 images
228 }
229
230 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700231 let mut bad_flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600232 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
David Brown2ee5f7f2020-01-13 14:04:01 -0700233 let dep = BoringDep::new(image_num, &NO_DEPS);
David Brownc3898d62019-08-05 14:20:02 -0600234 let primaries = install_image(&mut bad_flash, &slots[0], 32784, &dep, false);
235 let upgrades = install_image(&mut bad_flash, &slots[1], 41928, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700236 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700237 slots,
238 primaries,
239 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700240 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700241 Images {
David Brown76101572019-02-28 11:29:03 -0700242 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700243 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700244 images,
David Browne5133242019-02-28 11:05:19 -0700245 total_count: None,
246 }
247 }
248
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300249 pub fn make_erased_secondary_image(self) -> Images {
250 let mut flash = self.flash;
251 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
252 let dep = BoringDep::new(image_num, &NO_DEPS);
253 let primaries = install_image(&mut flash, &slots[0], 32784, &dep, false);
254 let upgrades = install_no_image();
255 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700256 slots,
257 primaries,
258 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300259 }}).collect();
260 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700261 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300262 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700263 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300264 total_count: None,
265 }
266 }
267
Fabio Utzigd0157342020-10-02 15:22:11 -0300268 pub fn make_bootstrap_image(self) -> Images {
269 let mut flash = self.flash;
270 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
271 let dep = BoringDep::new(image_num, &NO_DEPS);
272 let primaries = install_no_image();
273 let upgrades = install_image(&mut flash, &slots[1], 32784, &dep, false);
274 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700275 slots,
276 primaries,
277 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300278 }}).collect();
279 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700280 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300281 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700282 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300283 total_count: None,
284 }
285 }
286
David Browne5133242019-02-28 11:05:19 -0700287 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300288 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700289 match device {
290 DeviceName::Stm32f4 => {
291 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700292 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
293 64 * 1024,
294 128 * 1024, 128 * 1024, 128 * 1024],
295 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700296 let dev_id = 0;
297 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700298 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700299 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
300 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
301 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
302
David Brown76101572019-02-28 11:29:03 -0700303 let mut flash = SimMultiFlash::new();
304 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300305 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700306 }
307 DeviceName::K64f => {
308 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700309 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700310
311 let dev_id = 0;
312 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700313 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700314 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
315 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
316 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
317
David Brown76101572019-02-28 11:29:03 -0700318 let mut flash = SimMultiFlash::new();
319 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300320 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700321 }
322 DeviceName::K64fBig => {
323 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
324 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700325 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700326
327 let dev_id = 0;
328 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700329 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700330 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
331 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
332 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
333
David Brown76101572019-02-28 11:29:03 -0700334 let mut flash = SimMultiFlash::new();
335 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300336 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700337 }
338 DeviceName::Nrf52840 => {
339 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
340 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700341 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700342
343 let dev_id = 0;
344 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700345 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700346 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
347 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
348 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
349
David Brown76101572019-02-28 11:29:03 -0700350 let mut flash = SimMultiFlash::new();
351 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300352 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700353 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300354 DeviceName::Nrf52840UnequalSlots => {
355 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
356
357 let dev_id = 0;
358 let mut areadesc = AreaDesc::new();
359 areadesc.add_flash_sectors(dev_id, &dev);
360 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
361 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
362
363 let mut flash = SimMultiFlash::new();
364 flash.insert(dev_id, dev);
365 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
366 }
David Browne5133242019-02-28 11:05:19 -0700367 DeviceName::Nrf52840SpiFlash => {
368 // 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);
Fabio Utzig114a6472019-11-28 10:24:09 -0300384 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700385 }
David Brown2bff6472019-03-05 13:58:35 -0700386 DeviceName::K64fMulti => {
387 // NXP style flash, but larger, to support multiple images.
388 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
389
390 let dev_id = 0;
391 let mut areadesc = AreaDesc::new();
392 areadesc.add_flash_sectors(dev_id, &dev);
393 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
394 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
395 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
396 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
397 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
398
399 let mut flash = SimMultiFlash::new();
400 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300401 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700402 }
David Browne5133242019-02-28 11:05:19 -0700403 }
404 }
David Brownc3898d62019-08-05 14:20:02 -0600405
406 pub fn num_images(&self) -> usize {
407 self.slots.len()
408 }
David Browne5133242019-02-28 11:05:19 -0700409}
410
David Brown5c9e0f12019-01-09 16:34:33 -0700411impl Images {
412 /// A simple upgrade without forced failures.
413 ///
414 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700415 /// inject failures at chosen steps. Returns None if it was unable to
416 /// count the operations in a basic upgrade.
417 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300418 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700419 info!("Total flash operation count={}", total_count);
420
David Brown84b49f72019-03-01 10:58:22 -0700421 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700422 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700423 None
David Brown5c9e0f12019-01-09 16:34:33 -0700424 } else {
David Brown8973f552021-03-10 05:21:11 -0700425 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700426 }
427 }
428
Fabio Utzigd0157342020-10-02 15:22:11 -0300429 pub fn run_bootstrap(&self) -> bool {
430 let mut flash = self.flash.clone();
431 let mut fails = 0;
432
433 if Caps::Bootstrap.present() {
434 info!("Try bootstraping image in the primary");
435
David Brownc423ac42021-06-04 13:47:34 -0600436 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigd0157342020-10-02 15:22:11 -0300437 warn!("Failed first boot");
438 fails += 1;
439 }
440
441 if !self.verify_images(&flash, 0, 1) {
442 warn!("Image in the first slot was not bootstrapped");
443 fails += 1;
444 }
445
446 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
447 BOOT_FLAG_SET, BOOT_FLAG_SET) {
448 warn!("Mismatched trailer for the primary slot");
449 fails += 1;
450 }
451 }
452
453 if fails > 0 {
454 error!("Expected trailer on secondary slot to be erased");
455 }
456
457 fails > 0
458 }
459
460
David Brownc3898d62019-08-05 14:20:02 -0600461 /// Test a simple upgrade, with dependencies given, and verify that the
462 /// image does as is described in the test.
463 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600464 if !Caps::modifies_flash() {
465 return false;
466 }
467
David Brownc3898d62019-08-05 14:20:02 -0600468 let (flash, _) = self.try_upgrade(None, true);
469
470 self.verify_dep_images(&flash, deps)
471 }
472
Fabio Utzigf5480c72019-11-28 10:41:57 -0300473 fn is_swap_upgrade(&self) -> bool {
474 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
475 }
476
David Brown5c9e0f12019-01-09 16:34:33 -0700477 pub fn run_basic_revert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600478 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700479 return false;
480 }
David Brown5c9e0f12019-01-09 16:34:33 -0700481
David Brown5c9e0f12019-01-09 16:34:33 -0700482 let mut fails = 0;
483
484 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300485 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700486 for count in 2 .. 5 {
487 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700488 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700489 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700490 error!("Revert failure on count {}", count);
491 fails += 1;
492 }
493 }
494 }
495
496 fails > 0
497 }
498
499 pub fn run_perm_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600500 if !Caps::modifies_flash() {
501 return false;
502 }
503
David Brown5c9e0f12019-01-09 16:34:33 -0700504 let mut fails = 0;
505 let total_flash_ops = self.total_count.unwrap();
506
507 // Let's try an image halfway through.
508 for i in 1 .. total_flash_ops {
509 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300510 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700511 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700512 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700513 warn!("FAIL at step {} of {}", i, total_flash_ops);
514 fails += 1;
515 }
516
David Brown84b49f72019-03-01 10:58:22 -0700517 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
518 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100519 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700520 fails += 1;
521 }
522
David Brown84b49f72019-03-01 10:58:22 -0700523 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
524 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100525 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700526 fails += 1;
527 }
528
David Brownaec56b22021-03-10 05:22:07 -0700529 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
530 warn!("Secondary slot FAIL at step {} of {}",
531 i, total_flash_ops);
532 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700533 }
534 }
535
536 if fails > 0 {
537 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
538 fails as f32 * 100.0 / total_flash_ops as f32);
539 }
540
541 fails > 0
542 }
543
David Brown5c9e0f12019-01-09 16:34:33 -0700544 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600545 if !Caps::modifies_flash() {
546 return false;
547 }
548
David Brown5c9e0f12019-01-09 16:34:33 -0700549 let mut fails = 0;
550 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700551 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700552 info!("Random interruptions at reset points={:?}", total_counts);
553
David Brown84b49f72019-03-01 10:58:22 -0700554 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300555 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700556 // TODO: This result is ignored.
557 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700558 } else {
559 true
560 };
David Vincze2d736ad2019-02-18 11:50:22 +0100561 if !primary_slot_ok || !secondary_slot_ok {
562 error!("Image mismatch after random interrupts: primary slot={} \
563 secondary slot={}",
564 if primary_slot_ok { "ok" } else { "fail" },
565 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700566 fails += 1;
567 }
David Brown84b49f72019-03-01 10:58:22 -0700568 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
569 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100570 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700571 fails += 1;
572 }
David Brown84b49f72019-03-01 10:58:22 -0700573 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
574 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100575 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700576 fails += 1;
577 }
578
579 if fails > 0 {
580 error!("Error testing perm upgrade with {} fails", total_fails);
581 }
582
583 fails > 0
584 }
585
David Brown5c9e0f12019-01-09 16:34:33 -0700586 pub fn run_revert_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600587 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700588 return false;
589 }
David Brown5c9e0f12019-01-09 16:34:33 -0700590
David Brown5c9e0f12019-01-09 16:34:33 -0700591 let mut fails = 0;
592
Fabio Utzigf5480c72019-11-28 10:41:57 -0300593 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300594 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700595 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700596 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700597 error!("Revert failed at interruption {}", i);
598 fails += 1;
599 }
600 }
601 }
602
603 fails > 0
604 }
605
David Brown5c9e0f12019-01-09 16:34:33 -0700606 pub fn run_norevert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600607 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700608 return false;
609 }
David Brown5c9e0f12019-01-09 16:34:33 -0700610
David Brown76101572019-02-28 11:29:03 -0700611 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700612 let mut fails = 0;
613
614 info!("Try norevert");
615
616 // First do a normal upgrade...
David Brownc423ac42021-06-04 13:47:34 -0600617 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700618 warn!("Failed first boot");
619 fails += 1;
620 }
621
622 //FIXME: copy_done is written by boot_go, is it ok if no copy
623 // was ever done?
624
David Brown84b49f72019-03-01 10:58:22 -0700625 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100626 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700627 fails += 1;
628 }
David Brown84b49f72019-03-01 10:58:22 -0700629 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
630 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100631 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700632 fails += 1;
633 }
David Brown84b49f72019-03-01 10:58:22 -0700634 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
635 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100636 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700637 fails += 1;
638 }
639
David Vincze2d736ad2019-02-18 11:50:22 +0100640 // Marks image in the primary slot as permanent,
641 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700642 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700643
David Brown84b49f72019-03-01 10:58:22 -0700644 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
645 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100646 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700647 fails += 1;
648 }
649
David Brownc423ac42021-06-04 13:47:34 -0600650 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700651 warn!("Failed second boot");
652 fails += 1;
653 }
654
David Brown84b49f72019-03-01 10:58:22 -0700655 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
656 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100657 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700658 fails += 1;
659 }
David Brown84b49f72019-03-01 10:58:22 -0700660 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700661 warn!("Failed image verification");
662 fails += 1;
663 }
664
665 if fails > 0 {
666 error!("Error running upgrade without revert");
667 }
668
669 fails > 0
670 }
671
David Brown2ee5f7f2020-01-13 14:04:01 -0700672 // Test that an upgrade is rejected. Assumes that the image was build
673 // such that the upgrade is instead a downgrade.
674 pub fn run_nodowngrade(&self) -> bool {
675 if !Caps::DowngradePrevention.present() {
676 return false;
677 }
678
679 let mut flash = self.flash.clone();
680 let mut fails = 0;
681
682 info!("Try no downgrade");
683
684 // First, do a normal upgrade.
David Brownc423ac42021-06-04 13:47:34 -0600685 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700686 warn!("Failed first boot");
687 fails += 1;
688 }
689
690 if !self.verify_images(&flash, 0, 0) {
691 warn!("Failed verification after downgrade rejection");
692 fails += 1;
693 }
694
695 if fails > 0 {
696 error!("Error testing downgrade rejection");
697 }
698
699 fails > 0
700 }
701
David Vincze2d736ad2019-02-18 11:50:22 +0100702 // Tests a new image written to the primary slot that already has magic and
703 // image_ok set while there is no image on the secondary slot, so no revert
704 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700705 pub fn run_norevert_newimage(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600706 if !Caps::modifies_flash() {
707 info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
708 return false;
709 }
710
David Brown76101572019-02-28 11:29:03 -0700711 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700712 let mut fails = 0;
713
714 info!("Try non-revert on imgtool generated image");
715
David Brown84b49f72019-03-01 10:58:22 -0700716 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700717
David Vincze2d736ad2019-02-18 11:50:22 +0100718 // This simulates writing an image created by imgtool to
719 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700720 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
721 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100722 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700723 fails += 1;
724 }
725
726 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600727 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700728 warn!("Failed first boot");
729 fails += 1;
730 }
731
732 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700733 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700734 warn!("Failed image verification");
735 fails += 1;
736 }
David Brown84b49f72019-03-01 10:58:22 -0700737 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
738 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100739 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700740 fails += 1;
741 }
David Brown84b49f72019-03-01 10:58:22 -0700742 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
743 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100744 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700745 fails += 1;
746 }
747
748 if fails > 0 {
749 error!("Expected a non revert with new image");
750 }
751
752 fails > 0
753 }
754
David Vincze2d736ad2019-02-18 11:50:22 +0100755 // Tests a new image written to the primary slot that already has magic and
756 // image_ok set while there is no image on the secondary slot, so no revert
757 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700758 pub fn run_signfail_upgrade(&self) -> bool {
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 upgrade image with bad signature");
763
David Brown6db44d72021-05-26 16:22:58 -0600764 // Only perform this test if an upgrade is expected to happen.
765 if !Caps::modifies_flash() {
766 info!("Skipping upgrade image with bad signature");
767 return false;
768 }
769
David Brown84b49f72019-03-01 10:58:22 -0700770 self.mark_upgrades(&mut flash, 0);
771 self.mark_permanent_upgrades(&mut flash, 0);
772 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700773
David Brown84b49f72019-03-01 10:58:22 -0700774 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
775 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100776 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700777 fails += 1;
778 }
779
780 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600781 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700782 warn!("Failed first boot");
783 fails += 1;
784 }
785
786 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700787 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700788 warn!("Failed image verification");
789 fails += 1;
790 }
David Brown84b49f72019-03-01 10:58:22 -0700791 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
792 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100793 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700794 fails += 1;
795 }
796
797 if fails > 0 {
798 error!("Expected an upgrade failure when image has bad signature");
799 }
800
801 fails > 0
802 }
803
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300804 // Should detect there is a leftover trailer in an otherwise erased
805 // secondary slot and erase its trailer.
806 pub fn run_secondary_leftover_trailer(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600807 if !Caps::modifies_flash() {
808 return false;
809 }
810
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300811 let mut flash = self.flash.clone();
812 let mut fails = 0;
813
814 info!("Try with a leftover trailer in the secondary; must be erased");
815
816 // Add a trailer on the secondary slot
817 self.mark_permanent_upgrades(&mut flash, 1);
818 self.mark_upgrades(&mut flash, 1);
819
820 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600821 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300822 warn!("Failed first boot");
823 fails += 1;
824 }
825
826 // State should not have changed
827 if !self.verify_images(&flash, 0, 0) {
828 warn!("Failed image verification");
829 fails += 1;
830 }
831 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
832 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
833 warn!("Mismatched trailer for the secondary slot");
834 fails += 1;
835 }
836
837 if fails > 0 {
838 error!("Expected trailer on secondary slot to be erased");
839 }
840
841 fails > 0
842 }
843
David Brown5c9e0f12019-01-09 16:34:33 -0700844 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300845 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700846 }
847
David Brown5c9e0f12019-01-09 16:34:33 -0700848 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300849 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700850 }
851
852 /// This test runs a simple upgrade with no fails in the images, but
853 /// allowing for fails in the status area. This should run to the end
854 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700855 pub fn run_with_status_fails_complete(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600856 if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700857 return false;
858 }
859
David Brown76101572019-02-28 11:29:03 -0700860 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700861 let mut fails = 0;
862
863 info!("Try swap with status fails");
864
David Brown84b49f72019-03-01 10:58:22 -0700865 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700866 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700867
David Brownc423ac42021-06-04 13:47:34 -0600868 let result = c::boot_go(&mut flash, &self.areadesc, None, true);
869 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700870 warn!("Failed!");
871 fails += 1;
872 }
873
874 // Failed writes to the marked "bad" region don't assert anymore.
875 // Any detected assert() is happening in another part of the code.
David Brownc423ac42021-06-04 13:47:34 -0600876 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -0700877 warn!("At least one assert() was called");
878 fails += 1;
879 }
880
David Brown84b49f72019-03-01 10:58:22 -0700881 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
882 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100883 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700884 fails += 1;
885 }
886
David Brown84b49f72019-03-01 10:58:22 -0700887 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700888 warn!("Failed image verification");
889 fails += 1;
890 }
891
David Vincze2d736ad2019-02-18 11:50:22 +0100892 info!("validate primary slot enabled; \
893 re-run of boot_go should just work");
David Brownc423ac42021-06-04 13:47:34 -0600894 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700895 warn!("Failed!");
896 fails += 1;
897 }
898
899 if fails > 0 {
900 error!("Error running upgrade with status write fails");
901 }
902
903 fails > 0
904 }
905
906 /// This test runs a simple upgrade with no fails in the images, but
907 /// allowing for fails in the status area. This should run to the end
908 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700909 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600910 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700911 false
David Vincze2d736ad2019-02-18 11:50:22 +0100912 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700913
David Brown76101572019-02-28 11:29:03 -0700914 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700915 let mut fails = 0;
916 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700917
David Brown85904a82019-01-11 13:45:12 -0700918 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700919
David Brown85904a82019-01-11 13:45:12 -0700920 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700921
David Brown84b49f72019-03-01 10:58:22 -0700922 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700923 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700924
925 // Should not fail, writing to bad regions does not assert
David Brownc423ac42021-06-04 13:47:34 -0600926 let asserts = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700927 if asserts != 0 {
928 warn!("At least one assert() was called");
929 fails += 1;
930 }
931
David Brown76101572019-02-28 11:29:03 -0700932 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700933
934 info!("Resuming an interrupted swap operation");
David Brownc423ac42021-06-04 13:47:34 -0600935 let asserts = c::boot_go(&mut flash, &self.areadesc, None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700936
937 // This might throw no asserts, for large sector devices, where
938 // a single failure writing is indistinguishable from no failure,
939 // or throw a single assert for small sector devices that fail
940 // multiple times...
941 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100942 warn!("Expected single assert validating the primary slot, \
943 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700944 fails += 1;
945 }
946
947 if fails > 0 {
948 error!("Error running upgrade with status write fails");
949 }
950
951 fails > 0
952 } else {
David Brown76101572019-02-28 11:29:03 -0700953 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700954 let mut fails = 0;
955
956 info!("Try interrupted swap with status fails");
957
David Brown84b49f72019-03-01 10:58:22 -0700958 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700959 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700960
961 // This is expected to fail while writing to bad regions...
David Brownc423ac42021-06-04 13:47:34 -0600962 let asserts = c::boot_go(&mut flash, &self.areadesc, None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700963 if asserts == 0 {
964 warn!("No assert() detected");
965 fails += 1;
966 }
967
968 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700969 }
David Brown5c9e0f12019-01-09 16:34:33 -0700970 }
971
David Brown0dfb8102021-06-03 15:29:11 -0600972 /// Test the direct XIP configuration. With this mode, flash images are never moved, and the
973 /// bootloader merely selects which partition is the proper one to boot.
974 pub fn run_direct_xip(&self) -> bool {
975 if !Caps::DirectXip.present() {
976 return false;
977 }
978
979 // Clone the flash so we can tell if unchanged.
980 let mut flash = self.flash.clone();
981
982 let result = c::boot_go(&mut flash, &self.areadesc, None, true);
983
984 // Ensure the boot was successful.
985 let resp = if let Some(resp) = result.resp() {
986 resp
987 } else {
988 panic!("Boot didn't return a valid result");
989 };
990
991 // This configuration should always try booting from the first upgrade slot.
992 if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
993 assert_eq!(offset, resp.image_off as usize);
994 assert_eq!(dev_id, resp.flash_dev_id);
995 } else {
996 panic!("Unable to find upgrade image");
997 }
998 false
999 }
1000
David Brown5c9e0f12019-01-09 16:34:33 -07001001 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -07001002 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001003 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -07001004 if Caps::OverwriteUpgrade.present() {
1005 return;
1006 }
1007
David Brown84b49f72019-03-01 10:58:22 -07001008 // Set this for each image.
1009 for image in &self.images {
1010 let dev_id = &image.slots[slot].dev_id;
1011 let dev = flash.get_mut(&dev_id).unwrap();
1012 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001013 let off = &image.slots[slot].base_off;
1014 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -07001015 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -07001016
David Brown84b49f72019-03-01 10:58:22 -07001017 // Mark the status area as a bad area
1018 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1019 }
David Brown5c9e0f12019-01-09 16:34:33 -07001020 }
1021
David Brown76101572019-02-28 11:29:03 -07001022 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001023 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001024 return;
1025 }
1026
David Brown84b49f72019-03-01 10:58:22 -07001027 for image in &self.images {
1028 let dev_id = &image.slots[slot].dev_id;
1029 let dev = flash.get_mut(&dev_id).unwrap();
1030 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001031
David Brown84b49f72019-03-01 10:58:22 -07001032 // Disabling write verification the only assert triggered by
1033 // boot_go should be checking for integrity of status bytes.
1034 dev.set_verify_writes(false);
1035 }
David Brown5c9e0f12019-01-09 16:34:33 -07001036 }
1037
David Browndb505822019-03-01 10:04:20 -07001038 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1039 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001040 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001041 // Clone the flash to have a new copy.
1042 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001043
Fabio Utziged4a5362019-07-30 12:43:23 -03001044 if permanent {
1045 self.mark_permanent_upgrades(&mut flash, 1);
1046 }
David Brown5c9e0f12019-01-09 16:34:33 -07001047
David Browndb505822019-03-01 10:04:20 -07001048 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001049
David Browndb505822019-03-01 10:04:20 -07001050 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001051 x if x.interrupted() => (true, stop.unwrap()),
1052 x if x.success() => (false, -counter),
1053 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001054 };
David Brown5c9e0f12019-01-09 16:34:33 -07001055
David Browndb505822019-03-01 10:04:20 -07001056 counter = 0;
1057 if first_interrupted {
1058 // fl.dump();
1059 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001060 x if x.interrupted() => panic!("Shouldn't stop again"),
1061 x if x.success() => (),
1062 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001063 }
1064 }
David Brown5c9e0f12019-01-09 16:34:33 -07001065
David Browndb505822019-03-01 10:04:20 -07001066 (flash, count - counter)
1067 }
1068
1069 fn try_revert(&self, count: usize) -> SimMultiFlash {
1070 let mut flash = self.flash.clone();
1071
1072 // fl.write_file("image0.bin").unwrap();
1073 for i in 0 .. count {
1074 info!("Running boot pass {}", i + 1);
David Brownc423ac42021-06-04 13:47:34 -06001075 assert!(c::boot_go(&mut flash, &self.areadesc, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001076 }
1077 flash
1078 }
1079
1080 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1081 let mut flash = self.flash.clone();
1082 let mut fails = 0;
1083
1084 let mut counter = stop;
David Brownc423ac42021-06-04 13:47:34 -06001085 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001086 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001087 fails += 1;
1088 }
1089
Fabio Utzig8af7f792019-07-30 12:40:01 -03001090 // In a multi-image setup, copy done might be set if any number of
1091 // images was already successfully swapped.
1092 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1093 warn!("copy_done should be unset");
1094 fails += 1;
1095 }
1096
David Brownc423ac42021-06-04 13:47:34 -06001097 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001098 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001099 fails += 1;
1100 }
1101
David Brown84b49f72019-03-01 10:58:22 -07001102 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001103 warn!("Image in the primary slot before revert is invalid at stop={}",
1104 stop);
1105 fails += 1;
1106 }
David Brown84b49f72019-03-01 10:58:22 -07001107 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001108 warn!("Image in the secondary slot before revert is invalid at stop={}",
1109 stop);
1110 fails += 1;
1111 }
David Brown84b49f72019-03-01 10:58:22 -07001112 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1113 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001114 warn!("Mismatched trailer for the primary slot before revert");
1115 fails += 1;
1116 }
David Brown84b49f72019-03-01 10:58:22 -07001117 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1118 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001119 warn!("Mismatched trailer for the secondary slot before revert");
1120 fails += 1;
1121 }
1122
1123 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001124 let mut counter = stop;
David Brownc423ac42021-06-04 13:47:34 -06001125 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001126 warn!("Should have stopped revert at interruption point");
1127 fails += 1;
1128 }
1129
David Brownc423ac42021-06-04 13:47:34 -06001130 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001131 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001132 fails += 1;
1133 }
1134
David Brown84b49f72019-03-01 10:58:22 -07001135 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001136 warn!("Image in the primary slot after revert is invalid at stop={}",
1137 stop);
1138 fails += 1;
1139 }
David Brown84b49f72019-03-01 10:58:22 -07001140 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001141 warn!("Image in the secondary slot after revert is invalid at stop={}",
1142 stop);
1143 fails += 1;
1144 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001145
David Brown84b49f72019-03-01 10:58:22 -07001146 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1147 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001148 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001149 fails += 1;
1150 }
David Brown84b49f72019-03-01 10:58:22 -07001151 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1152 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001153 warn!("Mismatched trailer for the secondary slot after revert");
1154 fails += 1;
1155 }
1156
David Brownc423ac42021-06-04 13:47:34 -06001157 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001158 warn!("Should have finished 3rd boot");
1159 fails += 1;
1160 }
1161
1162 if !self.verify_images(&flash, 0, 0) {
1163 warn!("Image in the primary slot is invalid on 1st boot after revert");
1164 fails += 1;
1165 }
1166 if !self.verify_images(&flash, 1, 1) {
1167 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1168 fails += 1;
1169 }
1170
David Browndb505822019-03-01 10:04:20 -07001171 fails > 0
1172 }
1173
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001174
David Browndb505822019-03-01 10:04:20 -07001175 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1176 let mut flash = self.flash.clone();
1177
David Brown84b49f72019-03-01 10:58:22 -07001178 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001179
1180 let mut rng = rand::thread_rng();
1181 let mut resets = vec![0i32; count];
1182 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001183 for reset in &mut resets {
David Browncd842842020-07-09 15:46:53 -06001184 let reset_counter = rng.gen_range(1, remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001185 let mut counter = reset_counter;
1186 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001187 x if x.interrupted() => (),
1188 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001189 }
1190 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001191 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001192 }
1193
1194 match c::boot_go(&mut flash, &self.areadesc, None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001195 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1196 x if x.success() => (),
1197 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001198 }
David Brown5c9e0f12019-01-09 16:34:33 -07001199
David Browndb505822019-03-01 10:04:20 -07001200 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001201 }
David Brown84b49f72019-03-01 10:58:22 -07001202
1203 /// Verify the image in the given flash device, the specified slot
1204 /// against the expected image.
1205 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001206 self.images.iter().all(|image| {
1207 verify_image(flash, &image.slots[slot],
1208 match against {
1209 0 => &image.primaries,
1210 1 => &image.upgrades,
1211 _ => panic!("Invalid 'against'")
1212 })
1213 })
David Brown84b49f72019-03-01 10:58:22 -07001214 }
1215
David Brownc3898d62019-08-05 14:20:02 -06001216 /// Verify the images, according to the dependency test.
1217 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1218 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1219 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1220 if !verify_image(flash, &image.slots[0],
1221 match upgrade {
1222 UpgradeInfo::Upgraded => &image.upgrades,
1223 UpgradeInfo::Held => &image.primaries,
1224 }) {
1225 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1226 return true;
1227 }
1228 }
1229
1230 false
1231 }
1232
Fabio Utzig8af7f792019-07-30 12:40:01 -03001233 /// Verify that at least one of the trailers of the images have the
1234 /// specified values.
1235 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1236 magic: Option<u8>, image_ok: Option<u8>,
1237 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001238 self.images.iter().any(|image| {
1239 verify_trailer(flash, &image.slots[slot],
1240 magic, image_ok, copy_done)
1241 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001242 }
1243
David Brown84b49f72019-03-01 10:58:22 -07001244 /// Verify that the trailers of the images have the specified
1245 /// values.
1246 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1247 magic: Option<u8>, image_ok: Option<u8>,
1248 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001249 self.images.iter().all(|image| {
1250 verify_trailer(flash, &image.slots[slot],
1251 magic, image_ok, copy_done)
1252 })
David Brown84b49f72019-03-01 10:58:22 -07001253 }
1254
1255 /// Mark each of the images for permanent upgrade.
1256 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1257 for image in &self.images {
1258 mark_permanent_upgrade(flash, &image.slots[slot]);
1259 }
1260 }
1261
1262 /// Mark each of the images for permanent upgrade.
1263 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1264 for image in &self.images {
1265 mark_upgrade(flash, &image.slots[slot]);
1266 }
1267 }
David Brown297029a2019-08-13 14:29:51 -06001268
1269 /// Dump out the flash image(s) to one or more files for debugging
1270 /// purposes. The names will be written as either "{prefix}.mcubin" or
1271 /// "{prefix}-001.mcubin" depending on how many images there are.
1272 pub fn debug_dump(&self, prefix: &str) {
1273 for (id, fdev) in &self.flash {
1274 let name = if self.flash.len() == 1 {
1275 format!("{}.mcubin", prefix)
1276 } else {
1277 format!("{}-{:>0}.mcubin", prefix, id)
1278 };
1279 fdev.write_file(&name).unwrap();
1280 }
1281 }
David Brown5c9e0f12019-01-09 16:34:33 -07001282}
1283
1284/// Show the flash layout.
1285#[allow(dead_code)]
1286fn show_flash(flash: &dyn Flash) {
1287 println!("---- Flash configuration ----");
1288 for sector in flash.sector_iter() {
1289 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1290 sector.num, sector.base, sector.size);
1291 }
David Brown599b2db2021-03-10 05:23:26 -07001292 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001293}
1294
1295/// Install a "program" into the given image. This fakes the image header, or at least all of the
1296/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001297fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownc3898d62019-08-05 14:20:02 -06001298 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001299 let offset = slot.base_off;
1300 let slot_len = slot.len;
1301 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001302
David Brown43643dd2019-01-11 15:43:28 -07001303 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001304
David Brownc3898d62019-08-05 14:20:02 -06001305 // Add the dependencies early to the tlv.
1306 for dep in deps.my_deps(offset, slot.index) {
1307 tlv.add_dependency(deps.other_id(), &dep);
1308 }
1309
David Brown5c9e0f12019-01-09 16:34:33 -07001310 const HDR_SIZE: usize = 32;
1311
1312 // Generate a boot header. Note that the size doesn't include the header.
1313 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001314 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -07001315 load_addr: 0,
1316 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001317 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001318 img_size: len as u32,
1319 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001320 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001321 _pad2: 0,
1322 };
1323
1324 let mut b_header = [0; HDR_SIZE];
1325 b_header[..32].clone_from_slice(header.as_raw());
1326 assert_eq!(b_header.len(), HDR_SIZE);
1327
1328 tlv.add_bytes(&b_header);
1329
1330 // The core of the image itself is just pseudorandom data.
1331 let mut b_img = vec![0; len];
1332 splat(&mut b_img, offset);
1333
David Browncb47dd72019-08-05 14:21:49 -06001334 // Add some information at the start of the payload to make it easier
1335 // to see what it is. This will fail if the image itself is too small.
1336 {
1337 let mut wr = Cursor::new(&mut b_img);
1338 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1339 offset, dev_id, slot).unwrap();
1340 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1341 }
1342
David Brown5c9e0f12019-01-09 16:34:33 -07001343 // TLV signatures work over plain image
1344 tlv.add_bytes(&b_img);
1345
1346 // Generate encrypted images
Salome Thirot6fdbf552021-05-14 16:46:14 +01001347 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1348 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001349 let mut b_encimg = vec![];
1350 if is_encrypted {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001351 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1352 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001353 tlv.generate_enc_key();
1354 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001355 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001356 b_encimg = b_img.clone();
Salome Thirot6fdbf552021-05-14 16:46:14 +01001357 if aes256 {
1358 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
1359 let mut cipher = Aes256Ctr::new(&key, &nonce);
1360 cipher.apply_keystream(&mut b_encimg);
1361 } else {
1362 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
1363 let mut cipher = Aes128Ctr::new(&key, &nonce);
1364 cipher.apply_keystream(&mut b_encimg);
1365 }
David Brown5c9e0f12019-01-09 16:34:33 -07001366 }
1367
1368 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001369 if bad_sig {
1370 tlv.corrupt_sig();
1371 }
1372 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001373
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001374 let dev = flash.get_mut(&dev_id).unwrap();
1375
David Brown5c9e0f12019-01-09 16:34:33 -07001376 let mut buf = vec![];
1377 buf.append(&mut b_header.to_vec());
1378 buf.append(&mut b_img);
1379 buf.append(&mut b_tlv.clone());
1380
David Brown95de4502019-11-15 12:01:34 -07001381 // Pad the buffer to a multiple of the flash alignment.
1382 let align = dev.align();
1383 while buf.len() % align != 0 {
1384 buf.push(dev.erased_val());
1385 }
1386
David Brown5c9e0f12019-01-09 16:34:33 -07001387 let mut encbuf = vec![];
1388 if is_encrypted {
1389 encbuf.append(&mut b_header.to_vec());
1390 encbuf.append(&mut b_encimg);
1391 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001392
1393 while encbuf.len() % align != 0 {
1394 encbuf.push(dev.erased_val());
1395 }
David Brown5c9e0f12019-01-09 16:34:33 -07001396 }
1397
David Vincze2d736ad2019-02-18 11:50:22 +01001398 // Since images are always non-encrypted in the primary slot, we first write
1399 // an encrypted image, re-read to use for verification, erase + flash
1400 // un-encrypted. In the secondary slot the image is written un-encrypted,
1401 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001402
David Brown3b090212019-07-30 15:59:28 -06001403 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001404 let enc_copy: Option<Vec<u8>>;
1405
1406 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001407 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001408
1409 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001410 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001411
1412 enc_copy = Some(enc);
1413
David Brown76101572019-02-28 11:29:03 -07001414 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001415 } else {
1416 enc_copy = None;
1417 }
1418
David Brown76101572019-02-28 11:29:03 -07001419 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001420
1421 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001422 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001423
David Brownca234692019-02-28 11:22:19 -07001424 ImageData {
1425 plain: copy,
1426 cipher: enc_copy,
1427 }
David Brown5c9e0f12019-01-09 16:34:33 -07001428 } else {
1429
David Brown76101572019-02-28 11:29:03 -07001430 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001431
1432 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001433 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001434
1435 let enc_copy: Option<Vec<u8>>;
1436
1437 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001438 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001439
David Brown76101572019-02-28 11:29:03 -07001440 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001441
1442 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001443 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001444
1445 enc_copy = Some(enc);
1446 } else {
1447 enc_copy = None;
1448 }
1449
David Brownca234692019-02-28 11:22:19 -07001450 ImageData {
1451 plain: copy,
1452 cipher: enc_copy,
1453 }
David Brown5c9e0f12019-01-09 16:34:33 -07001454 }
David Brown5c9e0f12019-01-09 16:34:33 -07001455}
1456
David Brown873be312019-09-03 12:22:32 -06001457/// Install no image. This is used when no upgrade happens.
1458fn install_no_image() -> ImageData {
1459 ImageData {
1460 plain: vec![],
1461 cipher: None,
1462 }
1463}
1464
David Brown5c9e0f12019-01-09 16:34:33 -07001465fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001466 if Caps::EcdsaP224.present() {
1467 panic!("Ecdsa P224 not supported in Simulator");
1468 }
Salome Thirot6fdbf552021-05-14 16:46:14 +01001469 let mut aes_key_size = 128;
1470 if Caps::Aes256.present() {
1471 aes_key_size = 256;
1472 }
David Brown5c9e0f12019-01-09 16:34:33 -07001473
David Brownb8882112019-01-11 14:04:11 -07001474 if Caps::EncKw.present() {
1475 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001476 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001477 } else if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001478 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001479 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001480 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001481 }
1482 } else if Caps::EncRsa.present() {
1483 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001484 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001485 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001486 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001487 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001488 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001489 if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001490 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001491 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001492 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001493 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001494 } else if Caps::EncX25519.present() {
1495 if Caps::Ed25519.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001496 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001497 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001498 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001499 }
David Brownb8882112019-01-11 14:04:11 -07001500 } else {
1501 // The non-encrypted configuration.
1502 if Caps::RSA2048.present() {
1503 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001504 } else if Caps::RSA3072.present() {
1505 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001506 } else if Caps::EcdsaP256.present() {
1507 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001508 } else if Caps::Ed25519.present() {
1509 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001510 } else {
1511 TlvGen::new_hash_only()
1512 }
1513 }
David Brown5c9e0f12019-01-09 16:34:33 -07001514}
1515
David Brownca234692019-02-28 11:22:19 -07001516impl ImageData {
1517 /// Find the image contents for the given slot. This assumes that slot 0
1518 /// is unencrypted, and slot 1 is encrypted.
1519 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001520 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001521 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001522 match (encrypted, slot) {
1523 (false, _) => &self.plain,
1524 (true, 0) => &self.plain,
1525 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1526 _ => panic!("Invalid slot requested"),
1527 }
David Brown5c9e0f12019-01-09 16:34:33 -07001528 }
1529}
1530
David Brown5c9e0f12019-01-09 16:34:33 -07001531/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001532fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1533 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001534 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001535 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001536
1537 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001538 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001539 let dev = flash.get(&dev_id).unwrap();
1540 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001541
1542 if buf != &copy[..] {
1543 for i in 0 .. buf.len() {
1544 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001545 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1546 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001547 break;
1548 }
1549 }
1550 false
1551 } else {
1552 true
1553 }
1554}
1555
David Brown3b090212019-07-30 15:59:28 -06001556fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001557 magic: Option<u8>, image_ok: Option<u8>,
1558 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001559 if Caps::OverwriteUpgrade.present() {
1560 return true;
1561 }
David Brown5c9e0f12019-01-09 16:34:33 -07001562
David Brown3b090212019-07-30 15:59:28 -06001563 let offset = slot.trailer_off + c::boot_max_align();
1564 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001565 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001566 let mut failed = false;
1567
David Brown76101572019-02-28 11:29:03 -07001568 let dev = flash.get(&dev_id).unwrap();
1569 let erased_val = dev.erased_val();
1570 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001571
1572 failed |= match magic {
1573 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001574 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001575 warn!("\"magic\" mismatch at {:#x}", offset);
1576 true
1577 } else if v == 3 {
1578 let expected = [erased_val; 16];
David Brownd36f6b12021-03-10 05:23:56 -07001579 if copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001580 warn!("\"magic\" mismatch at {:#x}", offset);
1581 true
1582 } else {
1583 false
1584 }
1585 } else {
1586 false
1587 }
1588 },
1589 None => false,
1590 };
1591
1592 failed |= match image_ok {
1593 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001594 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001595 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1596 true
1597 } else {
1598 false
1599 }
1600 },
1601 None => false,
1602 };
1603
1604 failed |= match copy_done {
1605 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001606 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001607 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1608 true
1609 } else {
1610 false
1611 }
1612 },
1613 None => false,
1614 };
1615
1616 !failed
1617}
1618
David Brown297029a2019-08-13 14:29:51 -06001619/// Install a partition table. This is a simplified partition table that
1620/// we write at the beginning of flash so make it easier for external tools
1621/// to analyze these images.
1622fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1623 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1624 for &id in &ids {
1625 // If there are any partitions in this device that start at 0, and
1626 // aren't marked as the BootLoader partition, avoid adding the
1627 // partition table. This makes it harder to view the image, but
1628 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07001629 let skip_ptable = areadesc
1630 .iter_areas()
1631 .any(|area| {
1632 area.device_id == id &&
1633 area.off == 0 &&
1634 area.flash_id != FlashId::BootLoader
1635 });
1636 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06001637 if log_enabled!(Info) {
1638 let special: Vec<FlashId> = areadesc.iter_areas()
1639 .filter(|area| area.device_id == id && area.off == 0)
1640 .map(|area| area.flash_id)
1641 .collect();
1642 info!("Skipping partition table: {:?}", special);
1643 }
1644 break;
1645 }
1646
1647 let mut buf: Vec<u8> = vec![];
1648 write!(&mut buf, "mcuboot\0").unwrap();
1649
1650 // Iterate through all of the partitions in that device, and encode
1651 // into the table.
1652 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1653 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1654
1655 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1656 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1657 buf.write_u32::<LittleEndian>(area.off).unwrap();
1658 buf.write_u32::<LittleEndian>(area.size).unwrap();
1659 buf.write_u32::<LittleEndian>(0).unwrap();
1660 }
1661
1662 let dev = flash.get_mut(&id).unwrap();
1663
1664 // Pad to alignment.
1665 while buf.len() % dev.align() != 0 {
1666 buf.push(0);
1667 }
1668
1669 dev.write(0, &buf).unwrap();
1670 }
1671}
1672
David Brown5c9e0f12019-01-09 16:34:33 -07001673/// The image header
1674#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001675#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001676pub struct ImageHeader {
1677 magic: u32,
1678 load_addr: u32,
1679 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001680 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001681 img_size: u32,
1682 flags: u32,
1683 ver: ImageVersion,
1684 _pad2: u32,
1685}
1686
1687impl AsRaw for ImageHeader {}
1688
1689#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001690#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001691pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001692 pub major: u8,
1693 pub minor: u8,
1694 pub revision: u16,
1695 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001696}
1697
David Brownc3898d62019-08-05 14:20:02 -06001698#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001699pub struct SlotInfo {
1700 pub base_off: usize,
1701 pub trailer_off: usize,
1702 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001703 // Which slot within this device.
1704 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001705 pub dev_id: u8,
1706}
1707
David Brown347dc572019-11-15 11:37:25 -07001708const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1709 0x60, 0xd2, 0xef, 0x7f,
1710 0x35, 0x52, 0x50, 0x0f,
1711 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001712
1713// Replicates defines found in bootutil.h
1714const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1715const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1716
1717const BOOT_FLAG_SET: Option<u8> = Some(1);
1718const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1719
1720/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001721pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1722 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001723 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001724 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001725 if offset % align != 0 || MAGIC.len() % align != 0 {
1726 // The write size is larger than the magic value. Fill a buffer
1727 // with the erased value, put the MAGIC in it, and write it in its
1728 // entirety.
1729 let mut buf = vec![dev.erased_val(); align];
1730 buf[(offset % align)..].copy_from_slice(MAGIC);
1731 dev.write(offset - (offset % align), &buf).unwrap();
1732 } else {
1733 dev.write(offset, MAGIC).unwrap();
1734 }
David Brown5c9e0f12019-01-09 16:34:33 -07001735}
1736
1737/// Writes the image_ok flag which, guess what, tells the bootloader
1738/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001739fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001740 // Overwrite mode always is permanent, and only the magic is used in
1741 // the trailer. To avoid problems with large write sizes, don't try to
1742 // set anything in this case.
1743 if Caps::OverwriteUpgrade.present() {
1744 return;
1745 }
1746
David Brown76101572019-02-28 11:29:03 -07001747 let dev = flash.get_mut(&slot.dev_id).unwrap();
1748 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001749 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001750 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001751 let align = dev.align();
1752 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001753}
1754
1755// Drop some pseudo-random gibberish onto the data.
1756fn splat(data: &mut [u8], seed: usize) {
David Browncd842842020-07-09 15:46:53 -06001757 let mut seed_block = [0u8; 16];
1758 let mut buf = Cursor::new(&mut seed_block[..]);
1759 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
1760 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
1761 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
1762 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
1763 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07001764 rng.fill_bytes(data);
1765}
1766
1767/// Return a read-only view into the raw bytes of this object
1768trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07001769 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07001770 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1771 mem::size_of::<Self>()) }
1772 }
1773}
1774
1775pub fn show_sizes() {
1776 // This isn't panic safe.
1777 for min in &[1, 2, 4, 8] {
1778 let msize = c::boot_trailer_sz(*min);
1779 println!("{:2}: {} (0x{:x})", min, msize, msize);
1780 }
1781}
David Brown95de4502019-11-15 12:01:34 -07001782
1783#[cfg(not(feature = "large-write"))]
1784fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001785 &[1, 2, 4, 8]
1786}
1787
1788#[cfg(feature = "large-write")]
1789fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001790 &[1, 2, 4, 8, 128, 512]
1791}