blob: 0e826dde2f10fbc5d61ddc8176ae4ec4583678b2 [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 Brown8a4e23b2021-06-11 10:29:01 -060038use mcuboot_sys::{c, AreaDesc, FlashId, RamBlock};
David Browne5133242019-02-28 11:05:19 -070039use crate::{
40 ALL_DEVICES,
41 DeviceName,
42};
David Brown5c9e0f12019-01-09 16:34:33 -070043use crate::caps::Caps;
David Brownc3898d62019-08-05 14:20:02 -060044use crate::depends::{
45 BoringDep,
46 Depender,
47 DepTest,
David Brown873be312019-09-03 12:22:32 -060048 DepType,
David Brown2ee5f7f2020-01-13 14:04:01 -070049 NO_DEPS,
David Brownc3898d62019-08-05 14:20:02 -060050 PairDep,
51 UpgradeInfo,
52};
Fabio Utzig90f449e2019-10-24 07:43:53 -030053use crate::tlv::{ManifestGen, TlvGen, TlvFlags};
Salome Thirot6fdbf552021-05-14 16:46:14 +010054use typenum::{U32, U16};
David Brown5c9e0f12019-01-09 16:34:33 -070055
David Brown8a4e23b2021-06-11 10:29:01 -060056/// For testing, use a non-zero offset for the ram-load, to make sure the offset is getting used
57/// properly, but the value is not really that important.
58const RAM_LOAD_ADDR: u32 = 1024;
59
60fn ram_load_addr() -> u32 {
61 if Caps::RamLoad.present() {
62 RAM_LOAD_ADDR
63 } else {
64 0
65 }
66}
67
David Browne5133242019-02-28 11:05:19 -070068/// A builder for Images. This describes a single run of the simulator,
69/// capturing the configuration of a particular set of devices, including
70/// the flash simulator(s) and the information about the slots.
71#[derive(Clone)]
72pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070073 flash: SimMultiFlash,
David Browne5133242019-02-28 11:05:19 -070074 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070075 slots: Vec<[SlotInfo; 2]>,
David Browne5133242019-02-28 11:05:19 -070076}
77
David Brown998aa8d2019-02-28 10:54:50 -070078/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070079/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070080/// and upgrades hold the expected contents of these images.
81pub struct Images {
David Brown76101572019-02-28 11:29:03 -070082 flash: SimMultiFlash,
David Brownca234692019-02-28 11:22:19 -070083 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070084 images: Vec<OneImage>,
85 total_count: Option<i32>,
86}
87
88/// When doing multi-image, there is an instance of this information for
89/// each of the images. Single image there will be one of these.
90struct OneImage {
David Brownca234692019-02-28 11:22:19 -070091 slots: [SlotInfo; 2],
92 primaries: ImageData,
93 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070094}
95
96/// The Rust-side representation of an image. For unencrypted images, this
97/// is just the unencrypted payload. For encrypted images, we store both
98/// the encrypted and the plaintext.
99struct ImageData {
100 plain: Vec<u8>,
101 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -0700102}
103
David Browne5133242019-02-28 11:05:19 -0700104impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -0700105 /// Construct a new image builder for the given device. Returns
106 /// Some(builder) if is possible to test this configuration, or None if
107 /// not possible (for example, if there aren't enough image slots).
Fabio Utzig114a6472019-11-28 10:24:09 -0300108 pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
109 let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
110
111 for cap in unsupported_caps {
112 if cap.present() {
113 return Err(format!("unsupported {:?}", cap));
114 }
115 }
David Browne5133242019-02-28 11:05:19 -0700116
David Brown06ef06e2019-03-05 12:28:10 -0700117 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -0700118
David Brown06ef06e2019-03-05 12:28:10 -0700119 let mut slots = Vec::with_capacity(num_images);
120 for image in 0..num_images {
121 // This mapping must match that defined in
122 // `boot/zephyr/include/sysflash/sysflash.h`.
123 let id0 = match image {
124 0 => FlashId::Image0,
125 1 => FlashId::Image2,
126 _ => panic!("More than 2 images not supported"),
127 };
128 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
129 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300130 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700131 };
132 let id1 = match image {
133 0 => FlashId::Image1,
134 1 => FlashId::Image3,
135 _ => panic!("More than 2 images not supported"),
136 };
137 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
138 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300139 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700140 };
David Browne5133242019-02-28 11:05:19 -0700141
Christopher Collinsa1c12042019-05-23 14:00:28 -0700142 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700143
David Brown06ef06e2019-03-05 12:28:10 -0700144 // Construct a primary image.
145 let primary = SlotInfo {
146 base_off: primary_base as usize,
147 trailer_off: primary_base + primary_len - offset_from_end,
148 len: primary_len as usize,
149 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600150 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700151 };
152
153 // And an upgrade image.
154 let secondary = SlotInfo {
155 base_off: secondary_base as usize,
156 trailer_off: secondary_base + secondary_len - offset_from_end,
157 len: secondary_len as usize,
158 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600159 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700160 };
161
162 slots.push([primary, secondary]);
163 }
David Browne5133242019-02-28 11:05:19 -0700164
Fabio Utzig114a6472019-11-28 10:24:09 -0300165 Ok(ImagesBuilder {
David Brown4dfb33c2021-03-10 05:15:45 -0700166 flash,
167 areadesc,
168 slots,
David Brown5bc62c62019-03-05 12:11:48 -0700169 })
David Browne5133242019-02-28 11:05:19 -0700170 }
171
172 pub fn each_device<F>(f: F)
173 where F: Fn(Self)
174 {
175 for &dev in ALL_DEVICES {
David Brown95de4502019-11-15 12:01:34 -0700176 for &align in test_alignments() {
David Browne5133242019-02-28 11:05:19 -0700177 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700178 match Self::new(dev, align, erased_val) {
Fabio Utzig114a6472019-11-28 10:24:09 -0300179 Ok(run) => f(run),
180 Err(msg) => warn!("Skipping {}: {}", dev, msg),
David Brown5bc62c62019-03-05 12:11:48 -0700181 }
David Browne5133242019-02-28 11:05:19 -0700182 }
183 }
184 }
185 }
186
187 /// Construct an `Images` that doesn't expect an upgrade to happen.
David Brownc3898d62019-08-05 14:20:02 -0600188 pub fn make_no_upgrade_image(self, deps: &DepTest) -> Images {
189 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700190 let mut flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600191 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
192 let dep: Box<dyn Depender> = if num_images > 1 {
193 Box::new(PairDep::new(num_images, image_num, deps))
194 } else {
David Brown2ee5f7f2020-01-13 14:04:01 -0700195 Box::new(BoringDep::new(image_num, deps))
David Brownc3898d62019-08-05 14:20:02 -0600196 };
197 let primaries = install_image(&mut flash, &slots[0], 42784, &*dep, false);
David Brown873be312019-09-03 12:22:32 -0600198 let upgrades = match deps.depends[image_num] {
199 DepType::NoUpgrade => install_no_image(),
200 _ => install_image(&mut flash, &slots[1], 46928, &*dep, false)
201 };
David Brown84b49f72019-03-01 10:58:22 -0700202 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700203 slots,
204 primaries,
205 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700206 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600207 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700208 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700209 flash,
David Browne5133242019-02-28 11:05:19 -0700210 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700211 images,
David Browne5133242019-02-28 11:05:19 -0700212 total_count: None,
213 }
214 }
215
David Brownc3898d62019-08-05 14:20:02 -0600216 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
217 let mut images = self.make_no_upgrade_image(deps);
David Brown84b49f72019-03-01 10:58:22 -0700218 for image in &images.images {
219 mark_upgrade(&mut images.flash, &image.slots[1]);
220 }
David Browne5133242019-02-28 11:05:19 -0700221
David Brown6db44d72021-05-26 16:22:58 -0600222 // The count is meaningless if no flash operations are performed.
223 if !Caps::modifies_flash() {
224 return images;
225 }
226
David Browne5133242019-02-28 11:05:19 -0700227 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300228 let total_count = match images.run_basic_upgrade(permanent) {
David Brown8973f552021-03-10 05:21:11 -0700229 Some(v) => v,
230 None =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600231 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
232 0
233 } else {
234 panic!("Unable to perform basic upgrade");
235 }
David Browne5133242019-02-28 11:05:19 -0700236 };
237
238 images.total_count = Some(total_count);
239 images
240 }
241
242 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700243 let mut bad_flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600244 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
David Brown2ee5f7f2020-01-13 14:04:01 -0700245 let dep = BoringDep::new(image_num, &NO_DEPS);
David Brownc3898d62019-08-05 14:20:02 -0600246 let primaries = install_image(&mut bad_flash, &slots[0], 32784, &dep, false);
247 let upgrades = install_image(&mut bad_flash, &slots[1], 41928, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700248 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700249 slots,
250 primaries,
251 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700252 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700253 Images {
David Brown76101572019-02-28 11:29:03 -0700254 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700255 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700256 images,
David Browne5133242019-02-28 11:05:19 -0700257 total_count: None,
258 }
259 }
260
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300261 pub fn make_erased_secondary_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_image(&mut flash, &slots[0], 32784, &dep, false);
266 let upgrades = install_no_image();
267 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700268 slots,
269 primaries,
270 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300271 }}).collect();
272 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700273 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300274 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700275 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300276 total_count: None,
277 }
278 }
279
Fabio Utzigd0157342020-10-02 15:22:11 -0300280 pub fn make_bootstrap_image(self) -> Images {
281 let mut flash = self.flash;
282 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
283 let dep = BoringDep::new(image_num, &NO_DEPS);
284 let primaries = install_no_image();
285 let upgrades = install_image(&mut flash, &slots[1], 32784, &dep, false);
286 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700287 slots,
288 primaries,
289 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300290 }}).collect();
291 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700292 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300293 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700294 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300295 total_count: None,
296 }
297 }
298
David Browne5133242019-02-28 11:05:19 -0700299 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300300 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700301 match device {
302 DeviceName::Stm32f4 => {
303 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700304 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
305 64 * 1024,
306 128 * 1024, 128 * 1024, 128 * 1024],
307 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700308 let dev_id = 0;
309 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700310 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700311 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
312 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
313 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
314
David Brown76101572019-02-28 11:29:03 -0700315 let mut flash = SimMultiFlash::new();
316 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300317 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700318 }
319 DeviceName::K64f => {
320 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700321 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700322
323 let dev_id = 0;
324 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700325 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700326 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
327 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
328 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
329
David Brown76101572019-02-28 11:29:03 -0700330 let mut flash = SimMultiFlash::new();
331 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300332 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700333 }
334 DeviceName::K64fBig => {
335 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
336 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700337 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700338
339 let dev_id = 0;
340 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700341 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700342 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
343 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
344 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
345
David Brown76101572019-02-28 11:29:03 -0700346 let mut flash = SimMultiFlash::new();
347 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300348 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700349 }
350 DeviceName::Nrf52840 => {
351 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
352 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700353 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700354
355 let dev_id = 0;
356 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700357 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700358 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
359 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
360 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
361
David Brown76101572019-02-28 11:29:03 -0700362 let mut flash = SimMultiFlash::new();
363 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300364 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700365 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300366 DeviceName::Nrf52840UnequalSlots => {
367 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
368
369 let dev_id = 0;
370 let mut areadesc = AreaDesc::new();
371 areadesc.add_flash_sectors(dev_id, &dev);
372 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
373 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
374
375 let mut flash = SimMultiFlash::new();
376 flash.insert(dev_id, dev);
377 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
378 }
David Browne5133242019-02-28 11:05:19 -0700379 DeviceName::Nrf52840SpiFlash => {
380 // Simulate nrf52840 with external SPI flash. The external SPI flash
381 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700382 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
383 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700384
385 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700386 areadesc.add_flash_sectors(0, &dev0);
387 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700388
389 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
390 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
391 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
392
David Brown76101572019-02-28 11:29:03 -0700393 let mut flash = SimMultiFlash::new();
394 flash.insert(0, dev0);
395 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300396 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700397 }
David Brown2bff6472019-03-05 13:58:35 -0700398 DeviceName::K64fMulti => {
399 // NXP style flash, but larger, to support multiple images.
400 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
401
402 let dev_id = 0;
403 let mut areadesc = AreaDesc::new();
404 areadesc.add_flash_sectors(dev_id, &dev);
405 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
406 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
407 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
408 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
409 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
410
411 let mut flash = SimMultiFlash::new();
412 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300413 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700414 }
David Browne5133242019-02-28 11:05:19 -0700415 }
416 }
David Brownc3898d62019-08-05 14:20:02 -0600417
418 pub fn num_images(&self) -> usize {
419 self.slots.len()
420 }
David Browne5133242019-02-28 11:05:19 -0700421}
422
David Brown5c9e0f12019-01-09 16:34:33 -0700423impl Images {
424 /// A simple upgrade without forced failures.
425 ///
426 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700427 /// inject failures at chosen steps. Returns None if it was unable to
428 /// count the operations in a basic upgrade.
429 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300430 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700431 info!("Total flash operation count={}", total_count);
432
David Brown84b49f72019-03-01 10:58:22 -0700433 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700434 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700435 None
David Brown5c9e0f12019-01-09 16:34:33 -0700436 } else {
David Brown8973f552021-03-10 05:21:11 -0700437 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700438 }
439 }
440
Fabio Utzigd0157342020-10-02 15:22:11 -0300441 pub fn run_bootstrap(&self) -> bool {
442 let mut flash = self.flash.clone();
443 let mut fails = 0;
444
445 if Caps::Bootstrap.present() {
446 info!("Try bootstraping image in the primary");
447
David Brownc423ac42021-06-04 13:47:34 -0600448 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigd0157342020-10-02 15:22:11 -0300449 warn!("Failed first boot");
450 fails += 1;
451 }
452
453 if !self.verify_images(&flash, 0, 1) {
454 warn!("Image in the first slot was not bootstrapped");
455 fails += 1;
456 }
457
458 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
459 BOOT_FLAG_SET, BOOT_FLAG_SET) {
460 warn!("Mismatched trailer for the primary slot");
461 fails += 1;
462 }
463 }
464
465 if fails > 0 {
466 error!("Expected trailer on secondary slot to be erased");
467 }
468
469 fails > 0
470 }
471
472
David Brownc3898d62019-08-05 14:20:02 -0600473 /// Test a simple upgrade, with dependencies given, and verify that the
474 /// image does as is described in the test.
475 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600476 if !Caps::modifies_flash() {
477 return false;
478 }
479
David Brownc3898d62019-08-05 14:20:02 -0600480 let (flash, _) = self.try_upgrade(None, true);
481
482 self.verify_dep_images(&flash, deps)
483 }
484
Fabio Utzigf5480c72019-11-28 10:41:57 -0300485 fn is_swap_upgrade(&self) -> bool {
486 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
487 }
488
David Brown5c9e0f12019-01-09 16:34:33 -0700489 pub fn run_basic_revert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600490 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700491 return false;
492 }
David Brown5c9e0f12019-01-09 16:34:33 -0700493
David Brown5c9e0f12019-01-09 16:34:33 -0700494 let mut fails = 0;
495
496 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300497 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700498 for count in 2 .. 5 {
499 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700500 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700501 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700502 error!("Revert failure on count {}", count);
503 fails += 1;
504 }
505 }
506 }
507
508 fails > 0
509 }
510
511 pub fn run_perm_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600512 if !Caps::modifies_flash() {
513 return false;
514 }
515
David Brown5c9e0f12019-01-09 16:34:33 -0700516 let mut fails = 0;
517 let total_flash_ops = self.total_count.unwrap();
518
519 // Let's try an image halfway through.
520 for i in 1 .. total_flash_ops {
521 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300522 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700523 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700524 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700525 warn!("FAIL at step {} of {}", i, total_flash_ops);
526 fails += 1;
527 }
528
David Brown84b49f72019-03-01 10:58:22 -0700529 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
530 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100531 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700532 fails += 1;
533 }
534
David Brown84b49f72019-03-01 10:58:22 -0700535 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
536 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100537 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700538 fails += 1;
539 }
540
David Brownaec56b22021-03-10 05:22:07 -0700541 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
542 warn!("Secondary slot FAIL at step {} of {}",
543 i, total_flash_ops);
544 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700545 }
546 }
547
548 if fails > 0 {
549 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
550 fails as f32 * 100.0 / total_flash_ops as f32);
551 }
552
553 fails > 0
554 }
555
David Brown5c9e0f12019-01-09 16:34:33 -0700556 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600557 if !Caps::modifies_flash() {
558 return false;
559 }
560
David Brown5c9e0f12019-01-09 16:34:33 -0700561 let mut fails = 0;
562 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700563 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700564 info!("Random interruptions at reset points={:?}", total_counts);
565
David Brown84b49f72019-03-01 10:58:22 -0700566 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300567 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700568 // TODO: This result is ignored.
569 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700570 } else {
571 true
572 };
David Vincze2d736ad2019-02-18 11:50:22 +0100573 if !primary_slot_ok || !secondary_slot_ok {
574 error!("Image mismatch after random interrupts: primary slot={} \
575 secondary slot={}",
576 if primary_slot_ok { "ok" } else { "fail" },
577 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700578 fails += 1;
579 }
David Brown84b49f72019-03-01 10:58:22 -0700580 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
581 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100582 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700583 fails += 1;
584 }
David Brown84b49f72019-03-01 10:58:22 -0700585 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
586 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100587 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700588 fails += 1;
589 }
590
591 if fails > 0 {
592 error!("Error testing perm upgrade with {} fails", total_fails);
593 }
594
595 fails > 0
596 }
597
David Brown5c9e0f12019-01-09 16:34:33 -0700598 pub fn run_revert_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600599 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700600 return false;
601 }
David Brown5c9e0f12019-01-09 16:34:33 -0700602
David Brown5c9e0f12019-01-09 16:34:33 -0700603 let mut fails = 0;
604
Fabio Utzigf5480c72019-11-28 10:41:57 -0300605 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300606 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700607 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700608 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700609 error!("Revert failed at interruption {}", i);
610 fails += 1;
611 }
612 }
613 }
614
615 fails > 0
616 }
617
David Brown5c9e0f12019-01-09 16:34:33 -0700618 pub fn run_norevert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600619 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700620 return false;
621 }
David Brown5c9e0f12019-01-09 16:34:33 -0700622
David Brown76101572019-02-28 11:29:03 -0700623 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700624 let mut fails = 0;
625
626 info!("Try norevert");
627
628 // First do a normal upgrade...
David Brownc423ac42021-06-04 13:47:34 -0600629 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700630 warn!("Failed first boot");
631 fails += 1;
632 }
633
634 //FIXME: copy_done is written by boot_go, is it ok if no copy
635 // was ever done?
636
David Brown84b49f72019-03-01 10:58:22 -0700637 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100638 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700639 fails += 1;
640 }
David Brown84b49f72019-03-01 10:58:22 -0700641 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
642 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100643 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700644 fails += 1;
645 }
David Brown84b49f72019-03-01 10:58:22 -0700646 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
647 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100648 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700649 fails += 1;
650 }
651
David Vincze2d736ad2019-02-18 11:50:22 +0100652 // Marks image in the primary slot as permanent,
653 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700654 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700655
David Brown84b49f72019-03-01 10:58:22 -0700656 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
657 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100658 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700659 fails += 1;
660 }
661
David Brownc423ac42021-06-04 13:47:34 -0600662 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700663 warn!("Failed second boot");
664 fails += 1;
665 }
666
David Brown84b49f72019-03-01 10:58:22 -0700667 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
668 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100669 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700670 fails += 1;
671 }
David Brown84b49f72019-03-01 10:58:22 -0700672 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700673 warn!("Failed image verification");
674 fails += 1;
675 }
676
677 if fails > 0 {
678 error!("Error running upgrade without revert");
679 }
680
681 fails > 0
682 }
683
David Brown2ee5f7f2020-01-13 14:04:01 -0700684 // Test that an upgrade is rejected. Assumes that the image was build
685 // such that the upgrade is instead a downgrade.
686 pub fn run_nodowngrade(&self) -> bool {
687 if !Caps::DowngradePrevention.present() {
688 return false;
689 }
690
691 let mut flash = self.flash.clone();
692 let mut fails = 0;
693
694 info!("Try no downgrade");
695
696 // First, do a normal upgrade.
David Brownc423ac42021-06-04 13:47:34 -0600697 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700698 warn!("Failed first boot");
699 fails += 1;
700 }
701
702 if !self.verify_images(&flash, 0, 0) {
703 warn!("Failed verification after downgrade rejection");
704 fails += 1;
705 }
706
707 if fails > 0 {
708 error!("Error testing downgrade rejection");
709 }
710
711 fails > 0
712 }
713
David Vincze2d736ad2019-02-18 11:50:22 +0100714 // Tests a new image written to the primary slot that already has magic and
715 // image_ok set while there is no image on the secondary slot, so no revert
716 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700717 pub fn run_norevert_newimage(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600718 if !Caps::modifies_flash() {
719 info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
720 return false;
721 }
722
David Brown76101572019-02-28 11:29:03 -0700723 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700724 let mut fails = 0;
725
726 info!("Try non-revert on imgtool generated image");
727
David Brown84b49f72019-03-01 10:58:22 -0700728 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700729
David Vincze2d736ad2019-02-18 11:50:22 +0100730 // This simulates writing an image created by imgtool to
731 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700732 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
733 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100734 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700735 fails += 1;
736 }
737
738 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600739 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700740 warn!("Failed first boot");
741 fails += 1;
742 }
743
744 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700745 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700746 warn!("Failed image verification");
747 fails += 1;
748 }
David Brown84b49f72019-03-01 10:58:22 -0700749 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
750 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100751 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700752 fails += 1;
753 }
David Brown84b49f72019-03-01 10:58:22 -0700754 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
755 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100756 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700757 fails += 1;
758 }
759
760 if fails > 0 {
761 error!("Expected a non revert with new image");
762 }
763
764 fails > 0
765 }
766
David Vincze2d736ad2019-02-18 11:50:22 +0100767 // Tests a new image written to the primary slot that already has magic and
768 // image_ok set while there is no image on the secondary slot, so no revert
769 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700770 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700771 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700772 let mut fails = 0;
773
774 info!("Try upgrade image with bad signature");
775
David Brown6db44d72021-05-26 16:22:58 -0600776 // Only perform this test if an upgrade is expected to happen.
777 if !Caps::modifies_flash() {
778 info!("Skipping upgrade image with bad signature");
779 return false;
780 }
781
David Brown84b49f72019-03-01 10:58:22 -0700782 self.mark_upgrades(&mut flash, 0);
783 self.mark_permanent_upgrades(&mut flash, 0);
784 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700785
David Brown84b49f72019-03-01 10:58:22 -0700786 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
787 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100788 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700789 fails += 1;
790 }
791
792 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600793 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700794 warn!("Failed first boot");
795 fails += 1;
796 }
797
798 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700799 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700800 warn!("Failed image verification");
801 fails += 1;
802 }
David Brown84b49f72019-03-01 10:58:22 -0700803 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
804 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100805 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700806 fails += 1;
807 }
808
809 if fails > 0 {
810 error!("Expected an upgrade failure when image has bad signature");
811 }
812
813 fails > 0
814 }
815
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300816 // Should detect there is a leftover trailer in an otherwise erased
817 // secondary slot and erase its trailer.
818 pub fn run_secondary_leftover_trailer(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600819 if !Caps::modifies_flash() {
820 return false;
821 }
822
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300823 let mut flash = self.flash.clone();
824 let mut fails = 0;
825
826 info!("Try with a leftover trailer in the secondary; must be erased");
827
828 // Add a trailer on the secondary slot
829 self.mark_permanent_upgrades(&mut flash, 1);
830 self.mark_upgrades(&mut flash, 1);
831
832 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600833 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300834 warn!("Failed first boot");
835 fails += 1;
836 }
837
838 // State should not have changed
839 if !self.verify_images(&flash, 0, 0) {
840 warn!("Failed image verification");
841 fails += 1;
842 }
843 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
844 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
845 warn!("Mismatched trailer for the secondary slot");
846 fails += 1;
847 }
848
849 if fails > 0 {
850 error!("Expected trailer on secondary slot to be erased");
851 }
852
853 fails > 0
854 }
855
David Brown5c9e0f12019-01-09 16:34:33 -0700856 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300857 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700858 }
859
David Brown5c9e0f12019-01-09 16:34:33 -0700860 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300861 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700862 }
863
864 /// This test runs a simple upgrade with no fails in the images, but
865 /// allowing for fails in the status area. This should run to the end
866 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700867 pub fn run_with_status_fails_complete(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600868 if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700869 return false;
870 }
871
David Brown76101572019-02-28 11:29:03 -0700872 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700873 let mut fails = 0;
874
875 info!("Try swap with status fails");
876
David Brown84b49f72019-03-01 10:58:22 -0700877 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700878 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700879
David Brownc423ac42021-06-04 13:47:34 -0600880 let result = c::boot_go(&mut flash, &self.areadesc, None, true);
881 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700882 warn!("Failed!");
883 fails += 1;
884 }
885
886 // Failed writes to the marked "bad" region don't assert anymore.
887 // Any detected assert() is happening in another part of the code.
David Brownc423ac42021-06-04 13:47:34 -0600888 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -0700889 warn!("At least one assert() was called");
890 fails += 1;
891 }
892
David Brown84b49f72019-03-01 10:58:22 -0700893 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
894 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100895 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700896 fails += 1;
897 }
898
David Brown84b49f72019-03-01 10:58:22 -0700899 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700900 warn!("Failed image verification");
901 fails += 1;
902 }
903
David Vincze2d736ad2019-02-18 11:50:22 +0100904 info!("validate primary slot enabled; \
905 re-run of boot_go should just work");
David Brownc423ac42021-06-04 13:47:34 -0600906 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700907 warn!("Failed!");
908 fails += 1;
909 }
910
911 if fails > 0 {
912 error!("Error running upgrade with status write fails");
913 }
914
915 fails > 0
916 }
917
918 /// This test runs a simple upgrade with no fails in the images, but
919 /// allowing for fails in the status area. This should run to the end
920 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700921 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600922 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700923 false
David Vincze2d736ad2019-02-18 11:50:22 +0100924 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700925
David Brown76101572019-02-28 11:29:03 -0700926 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700927 let mut fails = 0;
928 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700929
David Brown85904a82019-01-11 13:45:12 -0700930 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700931
David Brown85904a82019-01-11 13:45:12 -0700932 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700933
David Brown84b49f72019-03-01 10:58:22 -0700934 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700935 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700936
937 // Should not fail, writing to bad regions does not assert
David Brownc423ac42021-06-04 13:47:34 -0600938 let asserts = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700939 if asserts != 0 {
940 warn!("At least one assert() was called");
941 fails += 1;
942 }
943
David Brown76101572019-02-28 11:29:03 -0700944 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700945
946 info!("Resuming an interrupted swap operation");
David Brownc423ac42021-06-04 13:47:34 -0600947 let asserts = c::boot_go(&mut flash, &self.areadesc, None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700948
949 // This might throw no asserts, for large sector devices, where
950 // a single failure writing is indistinguishable from no failure,
951 // or throw a single assert for small sector devices that fail
952 // multiple times...
953 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100954 warn!("Expected single assert validating the primary slot, \
955 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700956 fails += 1;
957 }
958
959 if fails > 0 {
960 error!("Error running upgrade with status write fails");
961 }
962
963 fails > 0
964 } else {
David Brown76101572019-02-28 11:29:03 -0700965 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700966 let mut fails = 0;
967
968 info!("Try interrupted swap with status fails");
969
David Brown84b49f72019-03-01 10:58:22 -0700970 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700971 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700972
973 // This is expected to fail while writing to bad regions...
David Brownc423ac42021-06-04 13:47:34 -0600974 let asserts = c::boot_go(&mut flash, &self.areadesc, None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700975 if asserts == 0 {
976 warn!("No assert() detected");
977 fails += 1;
978 }
979
980 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700981 }
David Brown5c9e0f12019-01-09 16:34:33 -0700982 }
983
David Brown0dfb8102021-06-03 15:29:11 -0600984 /// Test the direct XIP configuration. With this mode, flash images are never moved, and the
985 /// bootloader merely selects which partition is the proper one to boot.
986 pub fn run_direct_xip(&self) -> bool {
987 if !Caps::DirectXip.present() {
988 return false;
989 }
990
991 // Clone the flash so we can tell if unchanged.
992 let mut flash = self.flash.clone();
993
994 let result = c::boot_go(&mut flash, &self.areadesc, None, true);
995
996 // Ensure the boot was successful.
997 let resp = if let Some(resp) = result.resp() {
998 resp
999 } else {
1000 panic!("Boot didn't return a valid result");
1001 };
1002
1003 // This configuration should always try booting from the first upgrade slot.
1004 if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
1005 assert_eq!(offset, resp.image_off as usize);
1006 assert_eq!(dev_id, resp.flash_dev_id);
1007 } else {
1008 panic!("Unable to find upgrade image");
1009 }
1010 false
1011 }
1012
David Brown8a4e23b2021-06-11 10:29:01 -06001013 /// Test the ram-loading.
1014 pub fn run_ram_load(&self) -> bool {
1015 if !Caps::RamLoad.present() {
1016 return false;
1017 }
1018
1019 // Clone the flash so we can tell if unchanged.
1020 let mut flash = self.flash.clone();
1021
1022 let image = &self.images[0].primaries;
1023
1024 // Test with the minimal size.
1025
1026 // First verify that if the RAM is too small, we reject it.
1027 let ram = RamBlock::new(image.plain.len() as u32 - 1, RAM_LOAD_ADDR);
1028 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None, true));
1029 if result.success() {
1030 error!("Failed to detect RAM too small");
1031 return true;
1032 }
1033 drop(ram);
1034
1035 // TODO: The code will erase the flash if it doesn't fit. Either verify this, or change
1036 // this behavior.
1037
1038 let mut flash = self.flash.clone();
1039
1040 let ram = RamBlock::new(image.plain.len() as u32, RAM_LOAD_ADDR);
1041 let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None, true));
1042 if !result.success() {
1043 error!("Failed to ram-load image");
1044 return true;
1045 }
1046 println!("Result: {:?}", result);
1047
1048 // Verify the image was loaded correctly.
1049 if ram.borrow() != &image.plain {
1050 error!("Image not loaded correctly");
1051 return true;
1052 }
1053
1054 false
1055 }
1056
David Brown5c9e0f12019-01-09 16:34:33 -07001057 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -07001058 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001059 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -07001060 if Caps::OverwriteUpgrade.present() {
1061 return;
1062 }
1063
David Brown84b49f72019-03-01 10:58:22 -07001064 // Set this for each image.
1065 for image in &self.images {
1066 let dev_id = &image.slots[slot].dev_id;
1067 let dev = flash.get_mut(&dev_id).unwrap();
1068 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001069 let off = &image.slots[slot].base_off;
1070 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -07001071 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -07001072
David Brown84b49f72019-03-01 10:58:22 -07001073 // Mark the status area as a bad area
1074 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1075 }
David Brown5c9e0f12019-01-09 16:34:33 -07001076 }
1077
David Brown76101572019-02-28 11:29:03 -07001078 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +01001079 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -07001080 return;
1081 }
1082
David Brown84b49f72019-03-01 10:58:22 -07001083 for image in &self.images {
1084 let dev_id = &image.slots[slot].dev_id;
1085 let dev = flash.get_mut(&dev_id).unwrap();
1086 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001087
David Brown84b49f72019-03-01 10:58:22 -07001088 // Disabling write verification the only assert triggered by
1089 // boot_go should be checking for integrity of status bytes.
1090 dev.set_verify_writes(false);
1091 }
David Brown5c9e0f12019-01-09 16:34:33 -07001092 }
1093
David Browndb505822019-03-01 10:04:20 -07001094 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1095 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001096 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001097 // Clone the flash to have a new copy.
1098 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001099
Fabio Utziged4a5362019-07-30 12:43:23 -03001100 if permanent {
1101 self.mark_permanent_upgrades(&mut flash, 1);
1102 }
David Brown5c9e0f12019-01-09 16:34:33 -07001103
David Browndb505822019-03-01 10:04:20 -07001104 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001105
David Browndb505822019-03-01 10:04:20 -07001106 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001107 x if x.interrupted() => (true, stop.unwrap()),
1108 x if x.success() => (false, -counter),
1109 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001110 };
David Brown5c9e0f12019-01-09 16:34:33 -07001111
David Browndb505822019-03-01 10:04:20 -07001112 counter = 0;
1113 if first_interrupted {
1114 // fl.dump();
1115 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001116 x if x.interrupted() => panic!("Shouldn't stop again"),
1117 x if x.success() => (),
1118 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001119 }
1120 }
David Brown5c9e0f12019-01-09 16:34:33 -07001121
David Browndb505822019-03-01 10:04:20 -07001122 (flash, count - counter)
1123 }
1124
1125 fn try_revert(&self, count: usize) -> SimMultiFlash {
1126 let mut flash = self.flash.clone();
1127
1128 // fl.write_file("image0.bin").unwrap();
1129 for i in 0 .. count {
1130 info!("Running boot pass {}", i + 1);
David Brownc423ac42021-06-04 13:47:34 -06001131 assert!(c::boot_go(&mut flash, &self.areadesc, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001132 }
1133 flash
1134 }
1135
1136 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1137 let mut flash = self.flash.clone();
1138 let mut fails = 0;
1139
1140 let mut counter = stop;
David Brownc423ac42021-06-04 13:47:34 -06001141 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001142 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001143 fails += 1;
1144 }
1145
Fabio Utzig8af7f792019-07-30 12:40:01 -03001146 // In a multi-image setup, copy done might be set if any number of
1147 // images was already successfully swapped.
1148 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1149 warn!("copy_done should be unset");
1150 fails += 1;
1151 }
1152
David Brownc423ac42021-06-04 13:47:34 -06001153 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001154 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001155 fails += 1;
1156 }
1157
David Brown84b49f72019-03-01 10:58:22 -07001158 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001159 warn!("Image in the primary slot before revert is invalid at stop={}",
1160 stop);
1161 fails += 1;
1162 }
David Brown84b49f72019-03-01 10:58:22 -07001163 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001164 warn!("Image in the secondary slot before revert is invalid at stop={}",
1165 stop);
1166 fails += 1;
1167 }
David Brown84b49f72019-03-01 10:58:22 -07001168 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1169 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001170 warn!("Mismatched trailer for the primary slot before revert");
1171 fails += 1;
1172 }
David Brown84b49f72019-03-01 10:58:22 -07001173 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1174 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001175 warn!("Mismatched trailer for the secondary slot before revert");
1176 fails += 1;
1177 }
1178
1179 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001180 let mut counter = stop;
David Brownc423ac42021-06-04 13:47:34 -06001181 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001182 warn!("Should have stopped revert at interruption point");
1183 fails += 1;
1184 }
1185
David Brownc423ac42021-06-04 13:47:34 -06001186 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001187 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001188 fails += 1;
1189 }
1190
David Brown84b49f72019-03-01 10:58:22 -07001191 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001192 warn!("Image in the primary slot after revert is invalid at stop={}",
1193 stop);
1194 fails += 1;
1195 }
David Brown84b49f72019-03-01 10:58:22 -07001196 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001197 warn!("Image in the secondary slot after revert is invalid at stop={}",
1198 stop);
1199 fails += 1;
1200 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001201
David Brown84b49f72019-03-01 10:58:22 -07001202 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1203 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001204 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001205 fails += 1;
1206 }
David Brown84b49f72019-03-01 10:58:22 -07001207 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1208 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001209 warn!("Mismatched trailer for the secondary slot after revert");
1210 fails += 1;
1211 }
1212
David Brownc423ac42021-06-04 13:47:34 -06001213 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001214 warn!("Should have finished 3rd boot");
1215 fails += 1;
1216 }
1217
1218 if !self.verify_images(&flash, 0, 0) {
1219 warn!("Image in the primary slot is invalid on 1st boot after revert");
1220 fails += 1;
1221 }
1222 if !self.verify_images(&flash, 1, 1) {
1223 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1224 fails += 1;
1225 }
1226
David Browndb505822019-03-01 10:04:20 -07001227 fails > 0
1228 }
1229
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001230
David Browndb505822019-03-01 10:04:20 -07001231 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1232 let mut flash = self.flash.clone();
1233
David Brown84b49f72019-03-01 10:58:22 -07001234 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001235
1236 let mut rng = rand::thread_rng();
1237 let mut resets = vec![0i32; count];
1238 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001239 for reset in &mut resets {
David Browncd842842020-07-09 15:46:53 -06001240 let reset_counter = rng.gen_range(1, remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001241 let mut counter = reset_counter;
1242 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001243 x if x.interrupted() => (),
1244 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001245 }
1246 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001247 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001248 }
1249
1250 match c::boot_go(&mut flash, &self.areadesc, None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001251 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1252 x if x.success() => (),
1253 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001254 }
David Brown5c9e0f12019-01-09 16:34:33 -07001255
David Browndb505822019-03-01 10:04:20 -07001256 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001257 }
David Brown84b49f72019-03-01 10:58:22 -07001258
1259 /// Verify the image in the given flash device, the specified slot
1260 /// against the expected image.
1261 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001262 self.images.iter().all(|image| {
1263 verify_image(flash, &image.slots[slot],
1264 match against {
1265 0 => &image.primaries,
1266 1 => &image.upgrades,
1267 _ => panic!("Invalid 'against'")
1268 })
1269 })
David Brown84b49f72019-03-01 10:58:22 -07001270 }
1271
David Brownc3898d62019-08-05 14:20:02 -06001272 /// Verify the images, according to the dependency test.
1273 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1274 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1275 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1276 if !verify_image(flash, &image.slots[0],
1277 match upgrade {
1278 UpgradeInfo::Upgraded => &image.upgrades,
1279 UpgradeInfo::Held => &image.primaries,
1280 }) {
1281 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1282 return true;
1283 }
1284 }
1285
1286 false
1287 }
1288
Fabio Utzig8af7f792019-07-30 12:40:01 -03001289 /// Verify that at least one of the trailers of the images have the
1290 /// specified values.
1291 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1292 magic: Option<u8>, image_ok: Option<u8>,
1293 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001294 self.images.iter().any(|image| {
1295 verify_trailer(flash, &image.slots[slot],
1296 magic, image_ok, copy_done)
1297 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001298 }
1299
David Brown84b49f72019-03-01 10:58:22 -07001300 /// Verify that the trailers of the images have the specified
1301 /// values.
1302 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1303 magic: Option<u8>, image_ok: Option<u8>,
1304 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001305 self.images.iter().all(|image| {
1306 verify_trailer(flash, &image.slots[slot],
1307 magic, image_ok, copy_done)
1308 })
David Brown84b49f72019-03-01 10:58:22 -07001309 }
1310
1311 /// Mark each of the images for permanent upgrade.
1312 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1313 for image in &self.images {
1314 mark_permanent_upgrade(flash, &image.slots[slot]);
1315 }
1316 }
1317
1318 /// Mark each of the images for permanent upgrade.
1319 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1320 for image in &self.images {
1321 mark_upgrade(flash, &image.slots[slot]);
1322 }
1323 }
David Brown297029a2019-08-13 14:29:51 -06001324
1325 /// Dump out the flash image(s) to one or more files for debugging
1326 /// purposes. The names will be written as either "{prefix}.mcubin" or
1327 /// "{prefix}-001.mcubin" depending on how many images there are.
1328 pub fn debug_dump(&self, prefix: &str) {
1329 for (id, fdev) in &self.flash {
1330 let name = if self.flash.len() == 1 {
1331 format!("{}.mcubin", prefix)
1332 } else {
1333 format!("{}-{:>0}.mcubin", prefix, id)
1334 };
1335 fdev.write_file(&name).unwrap();
1336 }
1337 }
David Brown5c9e0f12019-01-09 16:34:33 -07001338}
1339
1340/// Show the flash layout.
1341#[allow(dead_code)]
1342fn show_flash(flash: &dyn Flash) {
1343 println!("---- Flash configuration ----");
1344 for sector in flash.sector_iter() {
1345 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1346 sector.num, sector.base, sector.size);
1347 }
David Brown599b2db2021-03-10 05:23:26 -07001348 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001349}
1350
1351/// Install a "program" into the given image. This fakes the image header, or at least all of the
1352/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001353fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownc3898d62019-08-05 14:20:02 -06001354 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001355 let offset = slot.base_off;
1356 let slot_len = slot.len;
1357 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001358
David Brown43643dd2019-01-11 15:43:28 -07001359 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001360
David Brownc3898d62019-08-05 14:20:02 -06001361 // Add the dependencies early to the tlv.
1362 for dep in deps.my_deps(offset, slot.index) {
1363 tlv.add_dependency(deps.other_id(), &dep);
1364 }
1365
David Brown5c9e0f12019-01-09 16:34:33 -07001366 const HDR_SIZE: usize = 32;
1367
1368 // Generate a boot header. Note that the size doesn't include the header.
1369 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001370 magic: tlv.get_magic(),
David Brown8a4e23b2021-06-11 10:29:01 -06001371 load_addr: if Caps::RamLoad.present() { ram_load_addr() } else { 0 },
David Brown5c9e0f12019-01-09 16:34:33 -07001372 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001373 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001374 img_size: len as u32,
1375 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001376 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001377 _pad2: 0,
1378 };
1379
1380 let mut b_header = [0; HDR_SIZE];
1381 b_header[..32].clone_from_slice(header.as_raw());
1382 assert_eq!(b_header.len(), HDR_SIZE);
1383
1384 tlv.add_bytes(&b_header);
1385
1386 // The core of the image itself is just pseudorandom data.
1387 let mut b_img = vec![0; len];
1388 splat(&mut b_img, offset);
1389
David Browncb47dd72019-08-05 14:21:49 -06001390 // Add some information at the start of the payload to make it easier
1391 // to see what it is. This will fail if the image itself is too small.
1392 {
1393 let mut wr = Cursor::new(&mut b_img);
1394 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1395 offset, dev_id, slot).unwrap();
1396 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1397 }
1398
David Brown5c9e0f12019-01-09 16:34:33 -07001399 // TLV signatures work over plain image
1400 tlv.add_bytes(&b_img);
1401
1402 // Generate encrypted images
Salome Thirot6fdbf552021-05-14 16:46:14 +01001403 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1404 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001405 let mut b_encimg = vec![];
1406 if is_encrypted {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001407 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1408 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001409 tlv.generate_enc_key();
1410 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001411 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001412 b_encimg = b_img.clone();
Salome Thirot6fdbf552021-05-14 16:46:14 +01001413 if aes256 {
1414 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
1415 let mut cipher = Aes256Ctr::new(&key, &nonce);
1416 cipher.apply_keystream(&mut b_encimg);
1417 } else {
1418 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
1419 let mut cipher = Aes128Ctr::new(&key, &nonce);
1420 cipher.apply_keystream(&mut b_encimg);
1421 }
David Brown5c9e0f12019-01-09 16:34:33 -07001422 }
1423
1424 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001425 if bad_sig {
1426 tlv.corrupt_sig();
1427 }
1428 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001429
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001430 let dev = flash.get_mut(&dev_id).unwrap();
1431
David Brown5c9e0f12019-01-09 16:34:33 -07001432 let mut buf = vec![];
1433 buf.append(&mut b_header.to_vec());
1434 buf.append(&mut b_img);
1435 buf.append(&mut b_tlv.clone());
1436
David Brown95de4502019-11-15 12:01:34 -07001437 // Pad the buffer to a multiple of the flash alignment.
1438 let align = dev.align();
1439 while buf.len() % align != 0 {
1440 buf.push(dev.erased_val());
1441 }
1442
David Brown5c9e0f12019-01-09 16:34:33 -07001443 let mut encbuf = vec![];
1444 if is_encrypted {
1445 encbuf.append(&mut b_header.to_vec());
1446 encbuf.append(&mut b_encimg);
1447 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001448
1449 while encbuf.len() % align != 0 {
1450 encbuf.push(dev.erased_val());
1451 }
David Brown5c9e0f12019-01-09 16:34:33 -07001452 }
1453
David Vincze2d736ad2019-02-18 11:50:22 +01001454 // Since images are always non-encrypted in the primary slot, we first write
1455 // an encrypted image, re-read to use for verification, erase + flash
1456 // un-encrypted. In the secondary slot the image is written un-encrypted,
1457 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001458
David Brown3b090212019-07-30 15:59:28 -06001459 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001460 let enc_copy: Option<Vec<u8>>;
1461
1462 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001463 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001464
1465 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001466 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001467
1468 enc_copy = Some(enc);
1469
David Brown76101572019-02-28 11:29:03 -07001470 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001471 } else {
1472 enc_copy = None;
1473 }
1474
David Brown76101572019-02-28 11:29:03 -07001475 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001476
1477 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001478 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001479
David Brownca234692019-02-28 11:22:19 -07001480 ImageData {
1481 plain: copy,
1482 cipher: enc_copy,
1483 }
David Brown5c9e0f12019-01-09 16:34:33 -07001484 } else {
1485
David Brown76101572019-02-28 11:29:03 -07001486 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001487
1488 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001489 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001490
1491 let enc_copy: Option<Vec<u8>>;
1492
1493 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001494 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001495
David Brown76101572019-02-28 11:29:03 -07001496 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001497
1498 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001499 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001500
1501 enc_copy = Some(enc);
1502 } else {
1503 enc_copy = None;
1504 }
1505
David Brownca234692019-02-28 11:22:19 -07001506 ImageData {
1507 plain: copy,
1508 cipher: enc_copy,
1509 }
David Brown5c9e0f12019-01-09 16:34:33 -07001510 }
David Brown5c9e0f12019-01-09 16:34:33 -07001511}
1512
David Brown873be312019-09-03 12:22:32 -06001513/// Install no image. This is used when no upgrade happens.
1514fn install_no_image() -> ImageData {
1515 ImageData {
1516 plain: vec![],
1517 cipher: None,
1518 }
1519}
1520
David Brown5c9e0f12019-01-09 16:34:33 -07001521fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001522 if Caps::EcdsaP224.present() {
1523 panic!("Ecdsa P224 not supported in Simulator");
1524 }
Salome Thirot6fdbf552021-05-14 16:46:14 +01001525 let mut aes_key_size = 128;
1526 if Caps::Aes256.present() {
1527 aes_key_size = 256;
1528 }
David Brown5c9e0f12019-01-09 16:34:33 -07001529
David Brownb8882112019-01-11 14:04:11 -07001530 if Caps::EncKw.present() {
1531 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001532 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001533 } else if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001534 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001535 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001536 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001537 }
1538 } else if Caps::EncRsa.present() {
1539 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001540 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001541 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001542 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001543 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001544 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001545 if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001546 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001547 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001548 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001549 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001550 } else if Caps::EncX25519.present() {
1551 if Caps::Ed25519.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001552 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001553 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001554 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001555 }
David Brownb8882112019-01-11 14:04:11 -07001556 } else {
1557 // The non-encrypted configuration.
1558 if Caps::RSA2048.present() {
1559 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001560 } else if Caps::RSA3072.present() {
1561 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001562 } else if Caps::EcdsaP256.present() {
1563 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001564 } else if Caps::Ed25519.present() {
1565 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001566 } else {
1567 TlvGen::new_hash_only()
1568 }
1569 }
David Brown5c9e0f12019-01-09 16:34:33 -07001570}
1571
David Brownca234692019-02-28 11:22:19 -07001572impl ImageData {
1573 /// Find the image contents for the given slot. This assumes that slot 0
1574 /// is unencrypted, and slot 1 is encrypted.
1575 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001576 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001577 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001578 match (encrypted, slot) {
1579 (false, _) => &self.plain,
1580 (true, 0) => &self.plain,
1581 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1582 _ => panic!("Invalid slot requested"),
1583 }
David Brown5c9e0f12019-01-09 16:34:33 -07001584 }
1585}
1586
David Brown5c9e0f12019-01-09 16:34:33 -07001587/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001588fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1589 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001590 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001591 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001592
1593 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001594 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001595 let dev = flash.get(&dev_id).unwrap();
1596 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001597
1598 if buf != &copy[..] {
1599 for i in 0 .. buf.len() {
1600 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001601 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1602 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001603 break;
1604 }
1605 }
1606 false
1607 } else {
1608 true
1609 }
1610}
1611
David Brown3b090212019-07-30 15:59:28 -06001612fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001613 magic: Option<u8>, image_ok: Option<u8>,
1614 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001615 if Caps::OverwriteUpgrade.present() {
1616 return true;
1617 }
David Brown5c9e0f12019-01-09 16:34:33 -07001618
David Brown3b090212019-07-30 15:59:28 -06001619 let offset = slot.trailer_off + c::boot_max_align();
1620 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001621 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001622 let mut failed = false;
1623
David Brown76101572019-02-28 11:29:03 -07001624 let dev = flash.get(&dev_id).unwrap();
1625 let erased_val = dev.erased_val();
1626 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001627
1628 failed |= match magic {
1629 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001630 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001631 warn!("\"magic\" mismatch at {:#x}", offset);
1632 true
1633 } else if v == 3 {
1634 let expected = [erased_val; 16];
David Brownd36f6b12021-03-10 05:23:56 -07001635 if copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001636 warn!("\"magic\" mismatch at {:#x}", offset);
1637 true
1638 } else {
1639 false
1640 }
1641 } else {
1642 false
1643 }
1644 },
1645 None => false,
1646 };
1647
1648 failed |= match image_ok {
1649 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001650 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001651 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1652 true
1653 } else {
1654 false
1655 }
1656 },
1657 None => false,
1658 };
1659
1660 failed |= match copy_done {
1661 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001662 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001663 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1664 true
1665 } else {
1666 false
1667 }
1668 },
1669 None => false,
1670 };
1671
1672 !failed
1673}
1674
David Brown297029a2019-08-13 14:29:51 -06001675/// Install a partition table. This is a simplified partition table that
1676/// we write at the beginning of flash so make it easier for external tools
1677/// to analyze these images.
1678fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1679 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1680 for &id in &ids {
1681 // If there are any partitions in this device that start at 0, and
1682 // aren't marked as the BootLoader partition, avoid adding the
1683 // partition table. This makes it harder to view the image, but
1684 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07001685 let skip_ptable = areadesc
1686 .iter_areas()
1687 .any(|area| {
1688 area.device_id == id &&
1689 area.off == 0 &&
1690 area.flash_id != FlashId::BootLoader
1691 });
1692 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06001693 if log_enabled!(Info) {
1694 let special: Vec<FlashId> = areadesc.iter_areas()
1695 .filter(|area| area.device_id == id && area.off == 0)
1696 .map(|area| area.flash_id)
1697 .collect();
1698 info!("Skipping partition table: {:?}", special);
1699 }
1700 break;
1701 }
1702
1703 let mut buf: Vec<u8> = vec![];
1704 write!(&mut buf, "mcuboot\0").unwrap();
1705
1706 // Iterate through all of the partitions in that device, and encode
1707 // into the table.
1708 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1709 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1710
1711 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1712 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1713 buf.write_u32::<LittleEndian>(area.off).unwrap();
1714 buf.write_u32::<LittleEndian>(area.size).unwrap();
1715 buf.write_u32::<LittleEndian>(0).unwrap();
1716 }
1717
1718 let dev = flash.get_mut(&id).unwrap();
1719
1720 // Pad to alignment.
1721 while buf.len() % dev.align() != 0 {
1722 buf.push(0);
1723 }
1724
1725 dev.write(0, &buf).unwrap();
1726 }
1727}
1728
David Brown5c9e0f12019-01-09 16:34:33 -07001729/// The image header
1730#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001731#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001732pub struct ImageHeader {
1733 magic: u32,
1734 load_addr: u32,
1735 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001736 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001737 img_size: u32,
1738 flags: u32,
1739 ver: ImageVersion,
1740 _pad2: u32,
1741}
1742
1743impl AsRaw for ImageHeader {}
1744
1745#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001746#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001747pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001748 pub major: u8,
1749 pub minor: u8,
1750 pub revision: u16,
1751 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001752}
1753
David Brownc3898d62019-08-05 14:20:02 -06001754#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001755pub struct SlotInfo {
1756 pub base_off: usize,
1757 pub trailer_off: usize,
1758 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001759 // Which slot within this device.
1760 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001761 pub dev_id: u8,
1762}
1763
David Brown347dc572019-11-15 11:37:25 -07001764const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1765 0x60, 0xd2, 0xef, 0x7f,
1766 0x35, 0x52, 0x50, 0x0f,
1767 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001768
1769// Replicates defines found in bootutil.h
1770const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1771const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1772
1773const BOOT_FLAG_SET: Option<u8> = Some(1);
1774const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1775
1776/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001777pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1778 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001779 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001780 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001781 if offset % align != 0 || MAGIC.len() % align != 0 {
1782 // The write size is larger than the magic value. Fill a buffer
1783 // with the erased value, put the MAGIC in it, and write it in its
1784 // entirety.
1785 let mut buf = vec![dev.erased_val(); align];
1786 buf[(offset % align)..].copy_from_slice(MAGIC);
1787 dev.write(offset - (offset % align), &buf).unwrap();
1788 } else {
1789 dev.write(offset, MAGIC).unwrap();
1790 }
David Brown5c9e0f12019-01-09 16:34:33 -07001791}
1792
1793/// Writes the image_ok flag which, guess what, tells the bootloader
1794/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001795fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001796 // Overwrite mode always is permanent, and only the magic is used in
1797 // the trailer. To avoid problems with large write sizes, don't try to
1798 // set anything in this case.
1799 if Caps::OverwriteUpgrade.present() {
1800 return;
1801 }
1802
David Brown76101572019-02-28 11:29:03 -07001803 let dev = flash.get_mut(&slot.dev_id).unwrap();
1804 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001805 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001806 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001807 let align = dev.align();
1808 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001809}
1810
1811// Drop some pseudo-random gibberish onto the data.
1812fn splat(data: &mut [u8], seed: usize) {
David Browncd842842020-07-09 15:46:53 -06001813 let mut seed_block = [0u8; 16];
1814 let mut buf = Cursor::new(&mut seed_block[..]);
1815 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
1816 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
1817 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
1818 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
1819 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07001820 rng.fill_bytes(data);
1821}
1822
1823/// Return a read-only view into the raw bytes of this object
1824trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07001825 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07001826 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1827 mem::size_of::<Self>()) }
1828 }
1829}
1830
1831pub fn show_sizes() {
1832 // This isn't panic safe.
1833 for min in &[1, 2, 4, 8] {
1834 let msize = c::boot_trailer_sz(*min);
1835 println!("{:2}: {} (0x{:x})", min, msize, msize);
1836 }
1837}
David Brown95de4502019-11-15 12:01:34 -07001838
1839#[cfg(not(feature = "large-write"))]
1840fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001841 &[1, 2, 4, 8]
1842}
1843
1844#[cfg(feature = "large-write")]
1845fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001846 &[1, 2, 4, 8, 128, 512]
1847}