blob: 5898560ca0b137f17c4a1a7d4d56b31bbbaa3e47 [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
210 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300211 let total_count = match images.run_basic_upgrade(permanent) {
David Brown8973f552021-03-10 05:21:11 -0700212 Some(v) => v,
213 None =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600214 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
215 0
216 } else {
217 panic!("Unable to perform basic upgrade");
218 }
David Browne5133242019-02-28 11:05:19 -0700219 };
220
221 images.total_count = Some(total_count);
222 images
223 }
224
225 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700226 let mut bad_flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600227 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
David Brown2ee5f7f2020-01-13 14:04:01 -0700228 let dep = BoringDep::new(image_num, &NO_DEPS);
David Brownc3898d62019-08-05 14:20:02 -0600229 let primaries = install_image(&mut bad_flash, &slots[0], 32784, &dep, false);
230 let upgrades = install_image(&mut bad_flash, &slots[1], 41928, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700231 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700232 slots,
233 primaries,
234 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700235 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700236 Images {
David Brown76101572019-02-28 11:29:03 -0700237 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700238 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700239 images,
David Browne5133242019-02-28 11:05:19 -0700240 total_count: None,
241 }
242 }
243
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300244 pub fn make_erased_secondary_image(self) -> Images {
245 let mut flash = self.flash;
246 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
247 let dep = BoringDep::new(image_num, &NO_DEPS);
248 let primaries = install_image(&mut flash, &slots[0], 32784, &dep, false);
249 let upgrades = install_no_image();
250 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700251 slots,
252 primaries,
253 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300254 }}).collect();
255 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700256 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300257 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700258 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300259 total_count: None,
260 }
261 }
262
Fabio Utzigd0157342020-10-02 15:22:11 -0300263 pub fn make_bootstrap_image(self) -> Images {
264 let mut flash = self.flash;
265 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
266 let dep = BoringDep::new(image_num, &NO_DEPS);
267 let primaries = install_no_image();
268 let upgrades = install_image(&mut flash, &slots[1], 32784, &dep, false);
269 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700270 slots,
271 primaries,
272 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300273 }}).collect();
274 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700275 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300276 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700277 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300278 total_count: None,
279 }
280 }
281
David Browne5133242019-02-28 11:05:19 -0700282 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300283 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700284 match device {
285 DeviceName::Stm32f4 => {
286 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700287 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
288 64 * 1024,
289 128 * 1024, 128 * 1024, 128 * 1024],
290 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700291 let dev_id = 0;
292 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700293 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700294 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
295 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
296 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
297
David Brown76101572019-02-28 11:29:03 -0700298 let mut flash = SimMultiFlash::new();
299 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300300 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700301 }
302 DeviceName::K64f => {
303 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700304 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700305
306 let dev_id = 0;
307 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700308 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700309 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
310 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
311 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
312
David Brown76101572019-02-28 11:29:03 -0700313 let mut flash = SimMultiFlash::new();
314 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300315 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700316 }
317 DeviceName::K64fBig => {
318 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
319 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700320 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700321
322 let dev_id = 0;
323 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700324 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700325 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
326 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
327 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
328
David Brown76101572019-02-28 11:29:03 -0700329 let mut flash = SimMultiFlash::new();
330 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300331 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700332 }
333 DeviceName::Nrf52840 => {
334 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
335 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700336 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700337
338 let dev_id = 0;
339 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700340 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700341 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
342 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
343 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
344
David Brown76101572019-02-28 11:29:03 -0700345 let mut flash = SimMultiFlash::new();
346 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300347 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700348 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300349 DeviceName::Nrf52840UnequalSlots => {
350 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
351
352 let dev_id = 0;
353 let mut areadesc = AreaDesc::new();
354 areadesc.add_flash_sectors(dev_id, &dev);
355 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
356 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
357
358 let mut flash = SimMultiFlash::new();
359 flash.insert(dev_id, dev);
360 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
361 }
David Browne5133242019-02-28 11:05:19 -0700362 DeviceName::Nrf52840SpiFlash => {
363 // Simulate nrf52840 with external SPI flash. The external SPI flash
364 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700365 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
366 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700367
368 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700369 areadesc.add_flash_sectors(0, &dev0);
370 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700371
372 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
373 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
374 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
375
David Brown76101572019-02-28 11:29:03 -0700376 let mut flash = SimMultiFlash::new();
377 flash.insert(0, dev0);
378 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300379 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700380 }
David Brown2bff6472019-03-05 13:58:35 -0700381 DeviceName::K64fMulti => {
382 // NXP style flash, but larger, to support multiple images.
383 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
384
385 let dev_id = 0;
386 let mut areadesc = AreaDesc::new();
387 areadesc.add_flash_sectors(dev_id, &dev);
388 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
389 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
390 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
391 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
392 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
393
394 let mut flash = SimMultiFlash::new();
395 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300396 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700397 }
David Browne5133242019-02-28 11:05:19 -0700398 }
399 }
David Brownc3898d62019-08-05 14:20:02 -0600400
401 pub fn num_images(&self) -> usize {
402 self.slots.len()
403 }
David Browne5133242019-02-28 11:05:19 -0700404}
405
David Brown5c9e0f12019-01-09 16:34:33 -0700406impl Images {
407 /// A simple upgrade without forced failures.
408 ///
409 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700410 /// inject failures at chosen steps. Returns None if it was unable to
411 /// count the operations in a basic upgrade.
412 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300413 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700414 info!("Total flash operation count={}", total_count);
415
David Brown84b49f72019-03-01 10:58:22 -0700416 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700417 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700418 None
David Brown5c9e0f12019-01-09 16:34:33 -0700419 } else {
David Brown8973f552021-03-10 05:21:11 -0700420 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700421 }
422 }
423
Fabio Utzigd0157342020-10-02 15:22:11 -0300424 pub fn run_bootstrap(&self) -> bool {
425 let mut flash = self.flash.clone();
426 let mut fails = 0;
427
428 if Caps::Bootstrap.present() {
429 info!("Try bootstraping image in the primary");
430
David Brownc423ac42021-06-04 13:47:34 -0600431 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigd0157342020-10-02 15:22:11 -0300432 warn!("Failed first boot");
433 fails += 1;
434 }
435
436 if !self.verify_images(&flash, 0, 1) {
437 warn!("Image in the first slot was not bootstrapped");
438 fails += 1;
439 }
440
441 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
442 BOOT_FLAG_SET, BOOT_FLAG_SET) {
443 warn!("Mismatched trailer for the primary slot");
444 fails += 1;
445 }
446 }
447
448 if fails > 0 {
449 error!("Expected trailer on secondary slot to be erased");
450 }
451
452 fails > 0
453 }
454
455
David Brownc3898d62019-08-05 14:20:02 -0600456 /// Test a simple upgrade, with dependencies given, and verify that the
457 /// image does as is described in the test.
458 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
459 let (flash, _) = self.try_upgrade(None, true);
460
461 self.verify_dep_images(&flash, deps)
462 }
463
Fabio Utzigf5480c72019-11-28 10:41:57 -0300464 fn is_swap_upgrade(&self) -> bool {
465 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
466 }
467
David Brown5c9e0f12019-01-09 16:34:33 -0700468 pub fn run_basic_revert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700469 if Caps::OverwriteUpgrade.present() {
470 return false;
471 }
David Brown5c9e0f12019-01-09 16:34:33 -0700472
David Brown5c9e0f12019-01-09 16:34:33 -0700473 let mut fails = 0;
474
475 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300476 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700477 for count in 2 .. 5 {
478 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700479 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700480 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700481 error!("Revert failure on count {}", count);
482 fails += 1;
483 }
484 }
485 }
486
487 fails > 0
488 }
489
490 pub fn run_perm_with_fails(&self) -> bool {
491 let mut fails = 0;
492 let total_flash_ops = self.total_count.unwrap();
493
494 // Let's try an image halfway through.
495 for i in 1 .. total_flash_ops {
496 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300497 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700498 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700499 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700500 warn!("FAIL at step {} of {}", i, total_flash_ops);
501 fails += 1;
502 }
503
David Brown84b49f72019-03-01 10:58:22 -0700504 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
505 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100506 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700507 fails += 1;
508 }
509
David Brown84b49f72019-03-01 10:58:22 -0700510 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
511 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100512 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700513 fails += 1;
514 }
515
David Brownaec56b22021-03-10 05:22:07 -0700516 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
517 warn!("Secondary slot FAIL at step {} of {}",
518 i, total_flash_ops);
519 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700520 }
521 }
522
523 if fails > 0 {
524 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
525 fails as f32 * 100.0 / total_flash_ops as f32);
526 }
527
528 fails > 0
529 }
530
David Brown5c9e0f12019-01-09 16:34:33 -0700531 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
532 let mut fails = 0;
533 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700534 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700535 info!("Random interruptions at reset points={:?}", total_counts);
536
David Brown84b49f72019-03-01 10:58:22 -0700537 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300538 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700539 // TODO: This result is ignored.
540 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700541 } else {
542 true
543 };
David Vincze2d736ad2019-02-18 11:50:22 +0100544 if !primary_slot_ok || !secondary_slot_ok {
545 error!("Image mismatch after random interrupts: primary slot={} \
546 secondary slot={}",
547 if primary_slot_ok { "ok" } else { "fail" },
548 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700549 fails += 1;
550 }
David Brown84b49f72019-03-01 10:58:22 -0700551 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
552 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100553 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700554 fails += 1;
555 }
David Brown84b49f72019-03-01 10:58:22 -0700556 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
557 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100558 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700559 fails += 1;
560 }
561
562 if fails > 0 {
563 error!("Error testing perm upgrade with {} fails", total_fails);
564 }
565
566 fails > 0
567 }
568
David Brown5c9e0f12019-01-09 16:34:33 -0700569 pub fn run_revert_with_fails(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700570 if Caps::OverwriteUpgrade.present() {
571 return false;
572 }
David Brown5c9e0f12019-01-09 16:34:33 -0700573
David Brown5c9e0f12019-01-09 16:34:33 -0700574 let mut fails = 0;
575
Fabio Utzigf5480c72019-11-28 10:41:57 -0300576 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300577 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700578 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700579 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700580 error!("Revert failed at interruption {}", i);
581 fails += 1;
582 }
583 }
584 }
585
586 fails > 0
587 }
588
David Brown5c9e0f12019-01-09 16:34:33 -0700589 pub fn run_norevert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700590 if Caps::OverwriteUpgrade.present() {
591 return false;
592 }
David Brown5c9e0f12019-01-09 16:34:33 -0700593
David Brown76101572019-02-28 11:29:03 -0700594 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700595 let mut fails = 0;
596
597 info!("Try norevert");
598
599 // First do a normal upgrade...
David Brownc423ac42021-06-04 13:47:34 -0600600 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700601 warn!("Failed first boot");
602 fails += 1;
603 }
604
605 //FIXME: copy_done is written by boot_go, is it ok if no copy
606 // was ever done?
607
David Brown84b49f72019-03-01 10:58:22 -0700608 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100609 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700610 fails += 1;
611 }
David Brown84b49f72019-03-01 10:58:22 -0700612 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
613 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100614 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700615 fails += 1;
616 }
David Brown84b49f72019-03-01 10:58:22 -0700617 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
618 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100619 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700620 fails += 1;
621 }
622
David Vincze2d736ad2019-02-18 11:50:22 +0100623 // Marks image in the primary slot as permanent,
624 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700625 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700626
David Brown84b49f72019-03-01 10:58:22 -0700627 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
628 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100629 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700630 fails += 1;
631 }
632
David Brownc423ac42021-06-04 13:47:34 -0600633 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700634 warn!("Failed second boot");
635 fails += 1;
636 }
637
David Brown84b49f72019-03-01 10:58:22 -0700638 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
639 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100640 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700641 fails += 1;
642 }
David Brown84b49f72019-03-01 10:58:22 -0700643 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700644 warn!("Failed image verification");
645 fails += 1;
646 }
647
648 if fails > 0 {
649 error!("Error running upgrade without revert");
650 }
651
652 fails > 0
653 }
654
David Brown2ee5f7f2020-01-13 14:04:01 -0700655 // Test that an upgrade is rejected. Assumes that the image was build
656 // such that the upgrade is instead a downgrade.
657 pub fn run_nodowngrade(&self) -> bool {
658 if !Caps::DowngradePrevention.present() {
659 return false;
660 }
661
662 let mut flash = self.flash.clone();
663 let mut fails = 0;
664
665 info!("Try no downgrade");
666
667 // First, do a normal upgrade.
David Brownc423ac42021-06-04 13:47:34 -0600668 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700669 warn!("Failed first boot");
670 fails += 1;
671 }
672
673 if !self.verify_images(&flash, 0, 0) {
674 warn!("Failed verification after downgrade rejection");
675 fails += 1;
676 }
677
678 if fails > 0 {
679 error!("Error testing downgrade rejection");
680 }
681
682 fails > 0
683 }
684
David Vincze2d736ad2019-02-18 11:50:22 +0100685 // Tests a new image written to the primary slot that already has magic and
686 // image_ok set while there is no image on the secondary slot, so no revert
687 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700688 pub fn run_norevert_newimage(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700689 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700690 let mut fails = 0;
691
692 info!("Try non-revert on imgtool generated image");
693
David Brown84b49f72019-03-01 10:58:22 -0700694 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700695
David Vincze2d736ad2019-02-18 11:50:22 +0100696 // This simulates writing an image created by imgtool to
697 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700698 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
699 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100700 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700701 fails += 1;
702 }
703
704 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600705 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700706 warn!("Failed first boot");
707 fails += 1;
708 }
709
710 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700711 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700712 warn!("Failed image verification");
713 fails += 1;
714 }
David Brown84b49f72019-03-01 10:58:22 -0700715 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
716 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100717 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700718 fails += 1;
719 }
David Brown84b49f72019-03-01 10:58:22 -0700720 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
721 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100722 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700723 fails += 1;
724 }
725
726 if fails > 0 {
727 error!("Expected a non revert with new image");
728 }
729
730 fails > 0
731 }
732
David Vincze2d736ad2019-02-18 11:50:22 +0100733 // Tests a new image written to the primary slot that already has magic and
734 // image_ok set while there is no image on the secondary slot, so no revert
735 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700736 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700737 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700738 let mut fails = 0;
739
740 info!("Try upgrade image with bad signature");
741
David Brown84b49f72019-03-01 10:58:22 -0700742 self.mark_upgrades(&mut flash, 0);
743 self.mark_permanent_upgrades(&mut flash, 0);
744 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700745
David Brown84b49f72019-03-01 10:58:22 -0700746 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
747 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100748 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700749 fails += 1;
750 }
751
752 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600753 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700754 warn!("Failed first boot");
755 fails += 1;
756 }
757
758 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700759 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700760 warn!("Failed image verification");
761 fails += 1;
762 }
David Brown84b49f72019-03-01 10:58:22 -0700763 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
764 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100765 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700766 fails += 1;
767 }
768
769 if fails > 0 {
770 error!("Expected an upgrade failure when image has bad signature");
771 }
772
773 fails > 0
774 }
775
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300776 // Should detect there is a leftover trailer in an otherwise erased
777 // secondary slot and erase its trailer.
778 pub fn run_secondary_leftover_trailer(&self) -> bool {
779 let mut flash = self.flash.clone();
780 let mut fails = 0;
781
782 info!("Try with a leftover trailer in the secondary; must be erased");
783
784 // Add a trailer on the secondary slot
785 self.mark_permanent_upgrades(&mut flash, 1);
786 self.mark_upgrades(&mut flash, 1);
787
788 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600789 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300790 warn!("Failed first boot");
791 fails += 1;
792 }
793
794 // State should not have changed
795 if !self.verify_images(&flash, 0, 0) {
796 warn!("Failed image verification");
797 fails += 1;
798 }
799 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
800 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
801 warn!("Mismatched trailer for the secondary slot");
802 fails += 1;
803 }
804
805 if fails > 0 {
806 error!("Expected trailer on secondary slot to be erased");
807 }
808
809 fails > 0
810 }
811
David Brown5c9e0f12019-01-09 16:34:33 -0700812 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300813 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700814 }
815
David Brown5c9e0f12019-01-09 16:34:33 -0700816 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300817 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700818 }
819
820 /// This test runs a simple upgrade with no fails in the images, but
821 /// allowing for fails in the status area. This should run to the end
822 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700823 pub fn run_with_status_fails_complete(&self) -> bool {
David Vincze2d736ad2019-02-18 11:50:22 +0100824 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700825 return false;
826 }
827
David Brown76101572019-02-28 11:29:03 -0700828 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700829 let mut fails = 0;
830
831 info!("Try swap with status fails");
832
David Brown84b49f72019-03-01 10:58:22 -0700833 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700834 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700835
David Brownc423ac42021-06-04 13:47:34 -0600836 let result = c::boot_go(&mut flash, &self.areadesc, None, true);
837 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700838 warn!("Failed!");
839 fails += 1;
840 }
841
842 // Failed writes to the marked "bad" region don't assert anymore.
843 // Any detected assert() is happening in another part of the code.
David Brownc423ac42021-06-04 13:47:34 -0600844 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -0700845 warn!("At least one assert() was called");
846 fails += 1;
847 }
848
David Brown84b49f72019-03-01 10:58:22 -0700849 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
850 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100851 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700852 fails += 1;
853 }
854
David Brown84b49f72019-03-01 10:58:22 -0700855 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700856 warn!("Failed image verification");
857 fails += 1;
858 }
859
David Vincze2d736ad2019-02-18 11:50:22 +0100860 info!("validate primary slot enabled; \
861 re-run of boot_go should just work");
David Brownc423ac42021-06-04 13:47:34 -0600862 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700863 warn!("Failed!");
864 fails += 1;
865 }
866
867 if fails > 0 {
868 error!("Error running upgrade with status write fails");
869 }
870
871 fails > 0
872 }
873
874 /// This test runs a simple upgrade with no fails in the images, but
875 /// allowing for fails in the status area. This should run to the end
876 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700877 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown85904a82019-01-11 13:45:12 -0700878 if Caps::OverwriteUpgrade.present() {
879 false
David Vincze2d736ad2019-02-18 11:50:22 +0100880 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700881
David Brown76101572019-02-28 11:29:03 -0700882 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700883 let mut fails = 0;
884 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700885
David Brown85904a82019-01-11 13:45:12 -0700886 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700887
David Brown85904a82019-01-11 13:45:12 -0700888 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700889
David Brown84b49f72019-03-01 10:58:22 -0700890 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700891 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700892
893 // Should not fail, writing to bad regions does not assert
David Brownc423ac42021-06-04 13:47:34 -0600894 let asserts = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700895 if asserts != 0 {
896 warn!("At least one assert() was called");
897 fails += 1;
898 }
899
David Brown76101572019-02-28 11:29:03 -0700900 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700901
902 info!("Resuming an interrupted swap operation");
David Brownc423ac42021-06-04 13:47:34 -0600903 let asserts = c::boot_go(&mut flash, &self.areadesc, None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700904
905 // This might throw no asserts, for large sector devices, where
906 // a single failure writing is indistinguishable from no failure,
907 // or throw a single assert for small sector devices that fail
908 // multiple times...
909 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100910 warn!("Expected single assert validating the primary slot, \
911 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700912 fails += 1;
913 }
914
915 if fails > 0 {
916 error!("Error running upgrade with status write fails");
917 }
918
919 fails > 0
920 } else {
David Brown76101572019-02-28 11:29:03 -0700921 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700922 let mut fails = 0;
923
924 info!("Try interrupted swap with status fails");
925
David Brown84b49f72019-03-01 10:58:22 -0700926 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700927 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700928
929 // This is expected to fail while writing to bad regions...
David Brownc423ac42021-06-04 13:47:34 -0600930 let asserts = c::boot_go(&mut flash, &self.areadesc, None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700931 if asserts == 0 {
932 warn!("No assert() detected");
933 fails += 1;
934 }
935
936 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700937 }
David Brown5c9e0f12019-01-09 16:34:33 -0700938 }
939
940 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -0700941 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -0700942 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -0700943 if Caps::OverwriteUpgrade.present() {
944 return;
945 }
946
David Brown84b49f72019-03-01 10:58:22 -0700947 // Set this for each image.
948 for image in &self.images {
949 let dev_id = &image.slots[slot].dev_id;
950 let dev = flash.get_mut(&dev_id).unwrap();
951 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -0700952 let off = &image.slots[slot].base_off;
953 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -0700954 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -0700955
David Brown84b49f72019-03-01 10:58:22 -0700956 // Mark the status area as a bad area
957 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
958 }
David Brown5c9e0f12019-01-09 16:34:33 -0700959 }
960
David Brown76101572019-02-28 11:29:03 -0700961 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +0100962 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700963 return;
964 }
965
David Brown84b49f72019-03-01 10:58:22 -0700966 for image in &self.images {
967 let dev_id = &image.slots[slot].dev_id;
968 let dev = flash.get_mut(&dev_id).unwrap();
969 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -0700970
David Brown84b49f72019-03-01 10:58:22 -0700971 // Disabling write verification the only assert triggered by
972 // boot_go should be checking for integrity of status bytes.
973 dev.set_verify_writes(false);
974 }
David Brown5c9e0f12019-01-09 16:34:33 -0700975 }
976
David Browndb505822019-03-01 10:04:20 -0700977 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
978 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -0300979 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -0700980 // Clone the flash to have a new copy.
981 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700982
Fabio Utziged4a5362019-07-30 12:43:23 -0300983 if permanent {
984 self.mark_permanent_upgrades(&mut flash, 1);
985 }
David Brown5c9e0f12019-01-09 16:34:33 -0700986
David Browndb505822019-03-01 10:04:20 -0700987 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -0700988
David Browndb505822019-03-01 10:04:20 -0700989 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -0600990 x if x.interrupted() => (true, stop.unwrap()),
991 x if x.success() => (false, -counter),
992 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -0700993 };
David Brown5c9e0f12019-01-09 16:34:33 -0700994
David Browndb505822019-03-01 10:04:20 -0700995 counter = 0;
996 if first_interrupted {
997 // fl.dump();
998 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -0600999 x if x.interrupted() => panic!("Shouldn't stop again"),
1000 x if x.success() => (),
1001 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001002 }
1003 }
David Brown5c9e0f12019-01-09 16:34:33 -07001004
David Browndb505822019-03-01 10:04:20 -07001005 (flash, count - counter)
1006 }
1007
1008 fn try_revert(&self, count: usize) -> SimMultiFlash {
1009 let mut flash = self.flash.clone();
1010
1011 // fl.write_file("image0.bin").unwrap();
1012 for i in 0 .. count {
1013 info!("Running boot pass {}", i + 1);
David Brownc423ac42021-06-04 13:47:34 -06001014 assert!(c::boot_go(&mut flash, &self.areadesc, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001015 }
1016 flash
1017 }
1018
1019 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1020 let mut flash = self.flash.clone();
1021 let mut fails = 0;
1022
1023 let mut counter = stop;
David Brownc423ac42021-06-04 13:47:34 -06001024 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001025 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001026 fails += 1;
1027 }
1028
Fabio Utzig8af7f792019-07-30 12:40:01 -03001029 // In a multi-image setup, copy done might be set if any number of
1030 // images was already successfully swapped.
1031 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1032 warn!("copy_done should be unset");
1033 fails += 1;
1034 }
1035
David Brownc423ac42021-06-04 13:47:34 -06001036 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001037 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001038 fails += 1;
1039 }
1040
David Brown84b49f72019-03-01 10:58:22 -07001041 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001042 warn!("Image in the primary slot before revert is invalid at stop={}",
1043 stop);
1044 fails += 1;
1045 }
David Brown84b49f72019-03-01 10:58:22 -07001046 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001047 warn!("Image in the secondary slot before revert is invalid at stop={}",
1048 stop);
1049 fails += 1;
1050 }
David Brown84b49f72019-03-01 10:58:22 -07001051 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1052 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001053 warn!("Mismatched trailer for the primary slot before revert");
1054 fails += 1;
1055 }
David Brown84b49f72019-03-01 10:58:22 -07001056 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1057 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001058 warn!("Mismatched trailer for the secondary slot before revert");
1059 fails += 1;
1060 }
1061
1062 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001063 let mut counter = stop;
David Brownc423ac42021-06-04 13:47:34 -06001064 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001065 warn!("Should have stopped revert at interruption point");
1066 fails += 1;
1067 }
1068
David Brownc423ac42021-06-04 13:47:34 -06001069 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001070 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001071 fails += 1;
1072 }
1073
David Brown84b49f72019-03-01 10:58:22 -07001074 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001075 warn!("Image in the primary slot after revert is invalid at stop={}",
1076 stop);
1077 fails += 1;
1078 }
David Brown84b49f72019-03-01 10:58:22 -07001079 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001080 warn!("Image in the secondary slot after revert is invalid at stop={}",
1081 stop);
1082 fails += 1;
1083 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001084
David Brown84b49f72019-03-01 10:58:22 -07001085 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1086 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001087 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001088 fails += 1;
1089 }
David Brown84b49f72019-03-01 10:58:22 -07001090 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1091 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001092 warn!("Mismatched trailer for the secondary slot after revert");
1093 fails += 1;
1094 }
1095
David Brownc423ac42021-06-04 13:47:34 -06001096 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001097 warn!("Should have finished 3rd boot");
1098 fails += 1;
1099 }
1100
1101 if !self.verify_images(&flash, 0, 0) {
1102 warn!("Image in the primary slot is invalid on 1st boot after revert");
1103 fails += 1;
1104 }
1105 if !self.verify_images(&flash, 1, 1) {
1106 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1107 fails += 1;
1108 }
1109
David Browndb505822019-03-01 10:04:20 -07001110 fails > 0
1111 }
1112
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001113
David Browndb505822019-03-01 10:04:20 -07001114 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1115 let mut flash = self.flash.clone();
1116
David Brown84b49f72019-03-01 10:58:22 -07001117 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001118
1119 let mut rng = rand::thread_rng();
1120 let mut resets = vec![0i32; count];
1121 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001122 for reset in &mut resets {
David Browncd842842020-07-09 15:46:53 -06001123 let reset_counter = rng.gen_range(1, remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001124 let mut counter = reset_counter;
1125 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001126 x if x.interrupted() => (),
1127 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001128 }
1129 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001130 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001131 }
1132
1133 match c::boot_go(&mut flash, &self.areadesc, None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001134 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1135 x if x.success() => (),
1136 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001137 }
David Brown5c9e0f12019-01-09 16:34:33 -07001138
David Browndb505822019-03-01 10:04:20 -07001139 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001140 }
David Brown84b49f72019-03-01 10:58:22 -07001141
1142 /// Verify the image in the given flash device, the specified slot
1143 /// against the expected image.
1144 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001145 self.images.iter().all(|image| {
1146 verify_image(flash, &image.slots[slot],
1147 match against {
1148 0 => &image.primaries,
1149 1 => &image.upgrades,
1150 _ => panic!("Invalid 'against'")
1151 })
1152 })
David Brown84b49f72019-03-01 10:58:22 -07001153 }
1154
David Brownc3898d62019-08-05 14:20:02 -06001155 /// Verify the images, according to the dependency test.
1156 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1157 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1158 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1159 if !verify_image(flash, &image.slots[0],
1160 match upgrade {
1161 UpgradeInfo::Upgraded => &image.upgrades,
1162 UpgradeInfo::Held => &image.primaries,
1163 }) {
1164 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1165 return true;
1166 }
1167 }
1168
1169 false
1170 }
1171
Fabio Utzig8af7f792019-07-30 12:40:01 -03001172 /// Verify that at least one of the trailers of the images have the
1173 /// specified values.
1174 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1175 magic: Option<u8>, image_ok: Option<u8>,
1176 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001177 self.images.iter().any(|image| {
1178 verify_trailer(flash, &image.slots[slot],
1179 magic, image_ok, copy_done)
1180 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001181 }
1182
David Brown84b49f72019-03-01 10:58:22 -07001183 /// Verify that the trailers of the images have the specified
1184 /// values.
1185 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1186 magic: Option<u8>, image_ok: Option<u8>,
1187 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001188 self.images.iter().all(|image| {
1189 verify_trailer(flash, &image.slots[slot],
1190 magic, image_ok, copy_done)
1191 })
David Brown84b49f72019-03-01 10:58:22 -07001192 }
1193
1194 /// Mark each of the images for permanent upgrade.
1195 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1196 for image in &self.images {
1197 mark_permanent_upgrade(flash, &image.slots[slot]);
1198 }
1199 }
1200
1201 /// Mark each of the images for permanent upgrade.
1202 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1203 for image in &self.images {
1204 mark_upgrade(flash, &image.slots[slot]);
1205 }
1206 }
David Brown297029a2019-08-13 14:29:51 -06001207
1208 /// Dump out the flash image(s) to one or more files for debugging
1209 /// purposes. The names will be written as either "{prefix}.mcubin" or
1210 /// "{prefix}-001.mcubin" depending on how many images there are.
1211 pub fn debug_dump(&self, prefix: &str) {
1212 for (id, fdev) in &self.flash {
1213 let name = if self.flash.len() == 1 {
1214 format!("{}.mcubin", prefix)
1215 } else {
1216 format!("{}-{:>0}.mcubin", prefix, id)
1217 };
1218 fdev.write_file(&name).unwrap();
1219 }
1220 }
David Brown5c9e0f12019-01-09 16:34:33 -07001221}
1222
1223/// Show the flash layout.
1224#[allow(dead_code)]
1225fn show_flash(flash: &dyn Flash) {
1226 println!("---- Flash configuration ----");
1227 for sector in flash.sector_iter() {
1228 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1229 sector.num, sector.base, sector.size);
1230 }
David Brown599b2db2021-03-10 05:23:26 -07001231 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001232}
1233
1234/// Install a "program" into the given image. This fakes the image header, or at least all of the
1235/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001236fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownc3898d62019-08-05 14:20:02 -06001237 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001238 let offset = slot.base_off;
1239 let slot_len = slot.len;
1240 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001241
David Brown43643dd2019-01-11 15:43:28 -07001242 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001243
David Brownc3898d62019-08-05 14:20:02 -06001244 // Add the dependencies early to the tlv.
1245 for dep in deps.my_deps(offset, slot.index) {
1246 tlv.add_dependency(deps.other_id(), &dep);
1247 }
1248
David Brown5c9e0f12019-01-09 16:34:33 -07001249 const HDR_SIZE: usize = 32;
1250
1251 // Generate a boot header. Note that the size doesn't include the header.
1252 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001253 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -07001254 load_addr: 0,
1255 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001256 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001257 img_size: len as u32,
1258 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001259 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001260 _pad2: 0,
1261 };
1262
1263 let mut b_header = [0; HDR_SIZE];
1264 b_header[..32].clone_from_slice(header.as_raw());
1265 assert_eq!(b_header.len(), HDR_SIZE);
1266
1267 tlv.add_bytes(&b_header);
1268
1269 // The core of the image itself is just pseudorandom data.
1270 let mut b_img = vec![0; len];
1271 splat(&mut b_img, offset);
1272
David Browncb47dd72019-08-05 14:21:49 -06001273 // Add some information at the start of the payload to make it easier
1274 // to see what it is. This will fail if the image itself is too small.
1275 {
1276 let mut wr = Cursor::new(&mut b_img);
1277 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1278 offset, dev_id, slot).unwrap();
1279 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1280 }
1281
David Brown5c9e0f12019-01-09 16:34:33 -07001282 // TLV signatures work over plain image
1283 tlv.add_bytes(&b_img);
1284
1285 // Generate encrypted images
Salome Thirot6fdbf552021-05-14 16:46:14 +01001286 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1287 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001288 let mut b_encimg = vec![];
1289 if is_encrypted {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001290 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1291 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001292 tlv.generate_enc_key();
1293 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001294 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001295 b_encimg = b_img.clone();
Salome Thirot6fdbf552021-05-14 16:46:14 +01001296 if aes256 {
1297 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
1298 let mut cipher = Aes256Ctr::new(&key, &nonce);
1299 cipher.apply_keystream(&mut b_encimg);
1300 } else {
1301 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
1302 let mut cipher = Aes128Ctr::new(&key, &nonce);
1303 cipher.apply_keystream(&mut b_encimg);
1304 }
David Brown5c9e0f12019-01-09 16:34:33 -07001305 }
1306
1307 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001308 if bad_sig {
1309 tlv.corrupt_sig();
1310 }
1311 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001312
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001313 let dev = flash.get_mut(&dev_id).unwrap();
1314
David Brown5c9e0f12019-01-09 16:34:33 -07001315 let mut buf = vec![];
1316 buf.append(&mut b_header.to_vec());
1317 buf.append(&mut b_img);
1318 buf.append(&mut b_tlv.clone());
1319
David Brown95de4502019-11-15 12:01:34 -07001320 // Pad the buffer to a multiple of the flash alignment.
1321 let align = dev.align();
1322 while buf.len() % align != 0 {
1323 buf.push(dev.erased_val());
1324 }
1325
David Brown5c9e0f12019-01-09 16:34:33 -07001326 let mut encbuf = vec![];
1327 if is_encrypted {
1328 encbuf.append(&mut b_header.to_vec());
1329 encbuf.append(&mut b_encimg);
1330 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001331
1332 while encbuf.len() % align != 0 {
1333 encbuf.push(dev.erased_val());
1334 }
David Brown5c9e0f12019-01-09 16:34:33 -07001335 }
1336
David Vincze2d736ad2019-02-18 11:50:22 +01001337 // Since images are always non-encrypted in the primary slot, we first write
1338 // an encrypted image, re-read to use for verification, erase + flash
1339 // un-encrypted. In the secondary slot the image is written un-encrypted,
1340 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001341
David Brown3b090212019-07-30 15:59:28 -06001342 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001343 let enc_copy: Option<Vec<u8>>;
1344
1345 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001346 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001347
1348 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001349 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001350
1351 enc_copy = Some(enc);
1352
David Brown76101572019-02-28 11:29:03 -07001353 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001354 } else {
1355 enc_copy = None;
1356 }
1357
David Brown76101572019-02-28 11:29:03 -07001358 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001359
1360 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001361 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001362
David Brownca234692019-02-28 11:22:19 -07001363 ImageData {
1364 plain: copy,
1365 cipher: enc_copy,
1366 }
David Brown5c9e0f12019-01-09 16:34:33 -07001367 } else {
1368
David Brown76101572019-02-28 11:29:03 -07001369 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001370
1371 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001372 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001373
1374 let enc_copy: Option<Vec<u8>>;
1375
1376 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001377 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001378
David Brown76101572019-02-28 11:29:03 -07001379 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001380
1381 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001382 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001383
1384 enc_copy = Some(enc);
1385 } else {
1386 enc_copy = None;
1387 }
1388
David Brownca234692019-02-28 11:22:19 -07001389 ImageData {
1390 plain: copy,
1391 cipher: enc_copy,
1392 }
David Brown5c9e0f12019-01-09 16:34:33 -07001393 }
David Brown5c9e0f12019-01-09 16:34:33 -07001394}
1395
David Brown873be312019-09-03 12:22:32 -06001396/// Install no image. This is used when no upgrade happens.
1397fn install_no_image() -> ImageData {
1398 ImageData {
1399 plain: vec![],
1400 cipher: None,
1401 }
1402}
1403
David Brown5c9e0f12019-01-09 16:34:33 -07001404fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001405 if Caps::EcdsaP224.present() {
1406 panic!("Ecdsa P224 not supported in Simulator");
1407 }
Salome Thirot6fdbf552021-05-14 16:46:14 +01001408 let mut aes_key_size = 128;
1409 if Caps::Aes256.present() {
1410 aes_key_size = 256;
1411 }
David Brown5c9e0f12019-01-09 16:34:33 -07001412
David Brownb8882112019-01-11 14:04:11 -07001413 if Caps::EncKw.present() {
1414 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001415 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001416 } else if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001417 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001418 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001419 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001420 }
1421 } else if Caps::EncRsa.present() {
1422 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001423 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001424 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001425 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001426 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001427 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001428 if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001429 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001430 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001431 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001432 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001433 } else if Caps::EncX25519.present() {
1434 if Caps::Ed25519.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001435 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001436 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001437 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001438 }
David Brownb8882112019-01-11 14:04:11 -07001439 } else {
1440 // The non-encrypted configuration.
1441 if Caps::RSA2048.present() {
1442 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001443 } else if Caps::RSA3072.present() {
1444 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001445 } else if Caps::EcdsaP256.present() {
1446 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001447 } else if Caps::Ed25519.present() {
1448 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001449 } else {
1450 TlvGen::new_hash_only()
1451 }
1452 }
David Brown5c9e0f12019-01-09 16:34:33 -07001453}
1454
David Brownca234692019-02-28 11:22:19 -07001455impl ImageData {
1456 /// Find the image contents for the given slot. This assumes that slot 0
1457 /// is unencrypted, and slot 1 is encrypted.
1458 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001459 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001460 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001461 match (encrypted, slot) {
1462 (false, _) => &self.plain,
1463 (true, 0) => &self.plain,
1464 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1465 _ => panic!("Invalid slot requested"),
1466 }
David Brown5c9e0f12019-01-09 16:34:33 -07001467 }
1468}
1469
David Brown5c9e0f12019-01-09 16:34:33 -07001470/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001471fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1472 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001473 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001474 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001475
1476 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001477 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001478 let dev = flash.get(&dev_id).unwrap();
1479 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001480
1481 if buf != &copy[..] {
1482 for i in 0 .. buf.len() {
1483 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001484 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1485 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001486 break;
1487 }
1488 }
1489 false
1490 } else {
1491 true
1492 }
1493}
1494
David Brown3b090212019-07-30 15:59:28 -06001495fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001496 magic: Option<u8>, image_ok: Option<u8>,
1497 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001498 if Caps::OverwriteUpgrade.present() {
1499 return true;
1500 }
David Brown5c9e0f12019-01-09 16:34:33 -07001501
David Brown3b090212019-07-30 15:59:28 -06001502 let offset = slot.trailer_off + c::boot_max_align();
1503 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001504 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001505 let mut failed = false;
1506
David Brown76101572019-02-28 11:29:03 -07001507 let dev = flash.get(&dev_id).unwrap();
1508 let erased_val = dev.erased_val();
1509 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001510
1511 failed |= match magic {
1512 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001513 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001514 warn!("\"magic\" mismatch at {:#x}", offset);
1515 true
1516 } else if v == 3 {
1517 let expected = [erased_val; 16];
David Brownd36f6b12021-03-10 05:23:56 -07001518 if copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001519 warn!("\"magic\" mismatch at {:#x}", offset);
1520 true
1521 } else {
1522 false
1523 }
1524 } else {
1525 false
1526 }
1527 },
1528 None => false,
1529 };
1530
1531 failed |= match image_ok {
1532 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001533 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001534 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1535 true
1536 } else {
1537 false
1538 }
1539 },
1540 None => false,
1541 };
1542
1543 failed |= match copy_done {
1544 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001545 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001546 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1547 true
1548 } else {
1549 false
1550 }
1551 },
1552 None => false,
1553 };
1554
1555 !failed
1556}
1557
David Brown297029a2019-08-13 14:29:51 -06001558/// Install a partition table. This is a simplified partition table that
1559/// we write at the beginning of flash so make it easier for external tools
1560/// to analyze these images.
1561fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1562 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1563 for &id in &ids {
1564 // If there are any partitions in this device that start at 0, and
1565 // aren't marked as the BootLoader partition, avoid adding the
1566 // partition table. This makes it harder to view the image, but
1567 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07001568 let skip_ptable = areadesc
1569 .iter_areas()
1570 .any(|area| {
1571 area.device_id == id &&
1572 area.off == 0 &&
1573 area.flash_id != FlashId::BootLoader
1574 });
1575 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06001576 if log_enabled!(Info) {
1577 let special: Vec<FlashId> = areadesc.iter_areas()
1578 .filter(|area| area.device_id == id && area.off == 0)
1579 .map(|area| area.flash_id)
1580 .collect();
1581 info!("Skipping partition table: {:?}", special);
1582 }
1583 break;
1584 }
1585
1586 let mut buf: Vec<u8> = vec![];
1587 write!(&mut buf, "mcuboot\0").unwrap();
1588
1589 // Iterate through all of the partitions in that device, and encode
1590 // into the table.
1591 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1592 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1593
1594 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1595 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1596 buf.write_u32::<LittleEndian>(area.off).unwrap();
1597 buf.write_u32::<LittleEndian>(area.size).unwrap();
1598 buf.write_u32::<LittleEndian>(0).unwrap();
1599 }
1600
1601 let dev = flash.get_mut(&id).unwrap();
1602
1603 // Pad to alignment.
1604 while buf.len() % dev.align() != 0 {
1605 buf.push(0);
1606 }
1607
1608 dev.write(0, &buf).unwrap();
1609 }
1610}
1611
David Brown5c9e0f12019-01-09 16:34:33 -07001612/// The image header
1613#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001614#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001615pub struct ImageHeader {
1616 magic: u32,
1617 load_addr: u32,
1618 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001619 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001620 img_size: u32,
1621 flags: u32,
1622 ver: ImageVersion,
1623 _pad2: u32,
1624}
1625
1626impl AsRaw for ImageHeader {}
1627
1628#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001629#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001630pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001631 pub major: u8,
1632 pub minor: u8,
1633 pub revision: u16,
1634 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001635}
1636
David Brownc3898d62019-08-05 14:20:02 -06001637#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001638pub struct SlotInfo {
1639 pub base_off: usize,
1640 pub trailer_off: usize,
1641 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001642 // Which slot within this device.
1643 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001644 pub dev_id: u8,
1645}
1646
David Brown347dc572019-11-15 11:37:25 -07001647const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1648 0x60, 0xd2, 0xef, 0x7f,
1649 0x35, 0x52, 0x50, 0x0f,
1650 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001651
1652// Replicates defines found in bootutil.h
1653const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1654const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1655
1656const BOOT_FLAG_SET: Option<u8> = Some(1);
1657const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1658
1659/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001660pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1661 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001662 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001663 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001664 if offset % align != 0 || MAGIC.len() % align != 0 {
1665 // The write size is larger than the magic value. Fill a buffer
1666 // with the erased value, put the MAGIC in it, and write it in its
1667 // entirety.
1668 let mut buf = vec![dev.erased_val(); align];
1669 buf[(offset % align)..].copy_from_slice(MAGIC);
1670 dev.write(offset - (offset % align), &buf).unwrap();
1671 } else {
1672 dev.write(offset, MAGIC).unwrap();
1673 }
David Brown5c9e0f12019-01-09 16:34:33 -07001674}
1675
1676/// Writes the image_ok flag which, guess what, tells the bootloader
1677/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001678fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001679 // Overwrite mode always is permanent, and only the magic is used in
1680 // the trailer. To avoid problems with large write sizes, don't try to
1681 // set anything in this case.
1682 if Caps::OverwriteUpgrade.present() {
1683 return;
1684 }
1685
David Brown76101572019-02-28 11:29:03 -07001686 let dev = flash.get_mut(&slot.dev_id).unwrap();
1687 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001688 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001689 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001690 let align = dev.align();
1691 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001692}
1693
1694// Drop some pseudo-random gibberish onto the data.
1695fn splat(data: &mut [u8], seed: usize) {
David Browncd842842020-07-09 15:46:53 -06001696 let mut seed_block = [0u8; 16];
1697 let mut buf = Cursor::new(&mut seed_block[..]);
1698 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
1699 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
1700 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
1701 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
1702 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07001703 rng.fill_bytes(data);
1704}
1705
1706/// Return a read-only view into the raw bytes of this object
1707trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07001708 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07001709 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1710 mem::size_of::<Self>()) }
1711 }
1712}
1713
1714pub fn show_sizes() {
1715 // This isn't panic safe.
1716 for min in &[1, 2, 4, 8] {
1717 let msize = c::boot_trailer_sz(*min);
1718 println!("{:2}: {} (0x{:x})", min, msize, msize);
1719 }
1720}
David Brown95de4502019-11-15 12:01:34 -07001721
1722#[cfg(not(feature = "large-write"))]
1723fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001724 &[1, 2, 4, 8]
1725}
1726
1727#[cfg(feature = "large-write")]
1728fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001729 &[1, 2, 4, 8, 128, 512]
1730}