blob: 8251a6a18ed824484380504019d8c1267ad13c01 [file] [log] [blame]
David Browne2acfae2020-01-21 16:45:01 -07001// Copyright (c) 2019 Linaro LTD
2// Copyright (c) 2019-2020 JUUL Labs
3// Copyright (c) 2019 Arm Limited
4//
5// SPDX-License-Identifier: Apache-2.0
6
David Brown297029a2019-08-13 14:29:51 -06007use byteorder::{
8 LittleEndian, WriteBytesExt,
9};
10use log::{
11 Level::Info,
12 error,
13 info,
14 log_enabled,
15 warn,
16};
David Brown5c9e0f12019-01-09 16:34:33 -070017use rand::{
David Browncd842842020-07-09 15:46:53 -060018 Rng, RngCore, SeedableRng,
19 rngs::SmallRng,
David Brown5c9e0f12019-01-09 16:34:33 -070020};
21use std::{
David Brown297029a2019-08-13 14:29:51 -060022 collections::HashSet,
David Browncb47dd72019-08-05 14:21:49 -060023 io::{Cursor, Write},
David Brown5c9e0f12019-01-09 16:34:33 -070024 mem,
25 slice,
26};
27use aes_ctr::{
28 Aes128Ctr,
29 stream_cipher::{
30 generic_array::GenericArray,
David Brown8a99adf2020-07-09 16:52:38 -060031 NewStreamCipher,
32 SyncStreamCipher,
David Brown5c9e0f12019-01-09 16:34:33 -070033 },
34};
35
David Brown76101572019-02-28 11:29:03 -070036use simflash::{Flash, SimFlash, SimMultiFlash};
David Browne5133242019-02-28 11:05:19 -070037use mcuboot_sys::{c, AreaDesc, FlashId};
38use crate::{
39 ALL_DEVICES,
40 DeviceName,
41};
David Brown5c9e0f12019-01-09 16:34:33 -070042use crate::caps::Caps;
David Brownc3898d62019-08-05 14:20:02 -060043use crate::depends::{
44 BoringDep,
45 Depender,
46 DepTest,
David Brown873be312019-09-03 12:22:32 -060047 DepType,
David Brown2ee5f7f2020-01-13 14:04:01 -070048 NO_DEPS,
David Brownc3898d62019-08-05 14:20:02 -060049 PairDep,
50 UpgradeInfo,
51};
Fabio Utzig90f449e2019-10-24 07:43:53 -030052use crate::tlv::{ManifestGen, TlvGen, TlvFlags};
David Brown5c9e0f12019-01-09 16:34:33 -070053
David Browne5133242019-02-28 11:05:19 -070054/// A builder for Images. This describes a single run of the simulator,
55/// capturing the configuration of a particular set of devices, including
56/// the flash simulator(s) and the information about the slots.
57#[derive(Clone)]
58pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070059 flash: SimMultiFlash,
David Browne5133242019-02-28 11:05:19 -070060 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070061 slots: Vec<[SlotInfo; 2]>,
David Browne5133242019-02-28 11:05:19 -070062}
63
David Brown998aa8d2019-02-28 10:54:50 -070064/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070065/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070066/// and upgrades hold the expected contents of these images.
67pub struct Images {
David Brown76101572019-02-28 11:29:03 -070068 flash: SimMultiFlash,
David Brownca234692019-02-28 11:22:19 -070069 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070070 images: Vec<OneImage>,
71 total_count: Option<i32>,
72}
73
74/// When doing multi-image, there is an instance of this information for
75/// each of the images. Single image there will be one of these.
76struct OneImage {
David Brownca234692019-02-28 11:22:19 -070077 slots: [SlotInfo; 2],
78 primaries: ImageData,
79 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070080}
81
82/// The Rust-side representation of an image. For unencrypted images, this
83/// is just the unencrypted payload. For encrypted images, we store both
84/// the encrypted and the plaintext.
85struct ImageData {
86 plain: Vec<u8>,
87 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -070088}
89
David Browne5133242019-02-28 11:05:19 -070090impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -070091 /// Construct a new image builder for the given device. Returns
92 /// Some(builder) if is possible to test this configuration, or None if
93 /// not possible (for example, if there aren't enough image slots).
Fabio Utzig114a6472019-11-28 10:24:09 -030094 pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
95 let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
96
97 for cap in unsupported_caps {
98 if cap.present() {
99 return Err(format!("unsupported {:?}", cap));
100 }
101 }
David Browne5133242019-02-28 11:05:19 -0700102
David Brown06ef06e2019-03-05 12:28:10 -0700103 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -0700104
David Brown06ef06e2019-03-05 12:28:10 -0700105 let mut slots = Vec::with_capacity(num_images);
106 for image in 0..num_images {
107 // This mapping must match that defined in
108 // `boot/zephyr/include/sysflash/sysflash.h`.
109 let id0 = match image {
110 0 => FlashId::Image0,
111 1 => FlashId::Image2,
112 _ => panic!("More than 2 images not supported"),
113 };
114 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
115 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300116 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700117 };
118 let id1 = match image {
119 0 => FlashId::Image1,
120 1 => FlashId::Image3,
121 _ => panic!("More than 2 images not supported"),
122 };
123 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
124 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300125 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700126 };
David Browne5133242019-02-28 11:05:19 -0700127
Christopher Collinsa1c12042019-05-23 14:00:28 -0700128 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700129
David Brown06ef06e2019-03-05 12:28:10 -0700130 // Construct a primary image.
131 let primary = SlotInfo {
132 base_off: primary_base as usize,
133 trailer_off: primary_base + primary_len - offset_from_end,
134 len: primary_len as usize,
135 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600136 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700137 };
138
139 // And an upgrade image.
140 let secondary = SlotInfo {
141 base_off: secondary_base as usize,
142 trailer_off: secondary_base + secondary_len - offset_from_end,
143 len: secondary_len as usize,
144 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600145 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700146 };
147
148 slots.push([primary, secondary]);
149 }
David Browne5133242019-02-28 11:05:19 -0700150
Fabio Utzig114a6472019-11-28 10:24:09 -0300151 Ok(ImagesBuilder {
David Brown4dfb33c2021-03-10 05:15:45 -0700152 flash,
153 areadesc,
154 slots,
David Brown5bc62c62019-03-05 12:11:48 -0700155 })
David Browne5133242019-02-28 11:05:19 -0700156 }
157
158 pub fn each_device<F>(f: F)
159 where F: Fn(Self)
160 {
161 for &dev in ALL_DEVICES {
David Brown95de4502019-11-15 12:01:34 -0700162 for &align in test_alignments() {
David Browne5133242019-02-28 11:05:19 -0700163 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700164 match Self::new(dev, align, erased_val) {
Fabio Utzig114a6472019-11-28 10:24:09 -0300165 Ok(run) => f(run),
166 Err(msg) => warn!("Skipping {}: {}", dev, msg),
David Brown5bc62c62019-03-05 12:11:48 -0700167 }
David Browne5133242019-02-28 11:05:19 -0700168 }
169 }
170 }
171 }
172
173 /// Construct an `Images` that doesn't expect an upgrade to happen.
David Brownc3898d62019-08-05 14:20:02 -0600174 pub fn make_no_upgrade_image(self, deps: &DepTest) -> Images {
175 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700176 let mut flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600177 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
178 let dep: Box<dyn Depender> = if num_images > 1 {
179 Box::new(PairDep::new(num_images, image_num, deps))
180 } else {
David Brown2ee5f7f2020-01-13 14:04:01 -0700181 Box::new(BoringDep::new(image_num, deps))
David Brownc3898d62019-08-05 14:20:02 -0600182 };
183 let primaries = install_image(&mut flash, &slots[0], 42784, &*dep, false);
David Brown873be312019-09-03 12:22:32 -0600184 let upgrades = match deps.depends[image_num] {
185 DepType::NoUpgrade => install_no_image(),
186 _ => install_image(&mut flash, &slots[1], 46928, &*dep, false)
187 };
David Brown84b49f72019-03-01 10:58:22 -0700188 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700189 slots,
190 primaries,
191 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700192 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600193 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700194 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700195 flash,
David Browne5133242019-02-28 11:05:19 -0700196 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700197 images,
David Browne5133242019-02-28 11:05:19 -0700198 total_count: None,
199 }
200 }
201
David Brownc3898d62019-08-05 14:20:02 -0600202 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
203 let mut images = self.make_no_upgrade_image(deps);
David Brown84b49f72019-03-01 10:58:22 -0700204 for image in &images.images {
205 mark_upgrade(&mut images.flash, &image.slots[1]);
206 }
David Browne5133242019-02-28 11:05:19 -0700207
208 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300209 let total_count = match images.run_basic_upgrade(permanent) {
David Brown8973f552021-03-10 05:21:11 -0700210 Some(v) => v,
211 None =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600212 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
213 0
214 } else {
215 panic!("Unable to perform basic upgrade");
216 }
David Browne5133242019-02-28 11:05:19 -0700217 };
218
219 images.total_count = Some(total_count);
220 images
221 }
222
223 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700224 let mut bad_flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600225 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
David Brown2ee5f7f2020-01-13 14:04:01 -0700226 let dep = BoringDep::new(image_num, &NO_DEPS);
David Brownc3898d62019-08-05 14:20:02 -0600227 let primaries = install_image(&mut bad_flash, &slots[0], 32784, &dep, false);
228 let upgrades = install_image(&mut bad_flash, &slots[1], 41928, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700229 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700230 slots,
231 primaries,
232 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700233 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700234 Images {
David Brown76101572019-02-28 11:29:03 -0700235 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700236 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700237 images,
David Browne5133242019-02-28 11:05:19 -0700238 total_count: None,
239 }
240 }
241
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300242 pub fn make_erased_secondary_image(self) -> Images {
243 let mut flash = self.flash;
244 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
245 let dep = BoringDep::new(image_num, &NO_DEPS);
246 let primaries = install_image(&mut flash, &slots[0], 32784, &dep, false);
247 let upgrades = install_no_image();
248 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700249 slots,
250 primaries,
251 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300252 }}).collect();
253 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700254 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300255 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700256 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300257 total_count: None,
258 }
259 }
260
Fabio Utzigd0157342020-10-02 15:22:11 -0300261 pub fn make_bootstrap_image(self) -> Images {
262 let mut flash = self.flash;
263 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
264 let dep = BoringDep::new(image_num, &NO_DEPS);
265 let primaries = install_no_image();
266 let upgrades = install_image(&mut flash, &slots[1], 32784, &dep, false);
267 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700268 slots,
269 primaries,
270 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300271 }}).collect();
272 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700273 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300274 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700275 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300276 total_count: None,
277 }
278 }
279
David Browne5133242019-02-28 11:05:19 -0700280 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300281 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700282 match device {
283 DeviceName::Stm32f4 => {
284 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700285 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
286 64 * 1024,
287 128 * 1024, 128 * 1024, 128 * 1024],
288 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700289 let dev_id = 0;
290 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700291 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700292 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
293 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
294 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
295
David Brown76101572019-02-28 11:29:03 -0700296 let mut flash = SimMultiFlash::new();
297 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300298 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700299 }
300 DeviceName::K64f => {
301 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700302 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700303
304 let dev_id = 0;
305 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700306 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700307 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
308 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
309 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
310
David Brown76101572019-02-28 11:29:03 -0700311 let mut flash = SimMultiFlash::new();
312 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300313 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700314 }
315 DeviceName::K64fBig => {
316 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
317 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700318 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700319
320 let dev_id = 0;
321 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700322 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700323 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
324 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
325 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
326
David Brown76101572019-02-28 11:29:03 -0700327 let mut flash = SimMultiFlash::new();
328 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300329 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700330 }
331 DeviceName::Nrf52840 => {
332 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
333 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700334 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700335
336 let dev_id = 0;
337 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700338 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700339 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
340 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
341 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
342
David Brown76101572019-02-28 11:29:03 -0700343 let mut flash = SimMultiFlash::new();
344 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300345 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700346 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300347 DeviceName::Nrf52840UnequalSlots => {
348 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
349
350 let dev_id = 0;
351 let mut areadesc = AreaDesc::new();
352 areadesc.add_flash_sectors(dev_id, &dev);
353 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
354 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
355
356 let mut flash = SimMultiFlash::new();
357 flash.insert(dev_id, dev);
358 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
359 }
David Browne5133242019-02-28 11:05:19 -0700360 DeviceName::Nrf52840SpiFlash => {
361 // Simulate nrf52840 with external SPI flash. The external SPI flash
362 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700363 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
364 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700365
366 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700367 areadesc.add_flash_sectors(0, &dev0);
368 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700369
370 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
371 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
372 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
373
David Brown76101572019-02-28 11:29:03 -0700374 let mut flash = SimMultiFlash::new();
375 flash.insert(0, dev0);
376 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300377 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700378 }
David Brown2bff6472019-03-05 13:58:35 -0700379 DeviceName::K64fMulti => {
380 // NXP style flash, but larger, to support multiple images.
381 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
382
383 let dev_id = 0;
384 let mut areadesc = AreaDesc::new();
385 areadesc.add_flash_sectors(dev_id, &dev);
386 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
387 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
388 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
389 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
390 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
391
392 let mut flash = SimMultiFlash::new();
393 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300394 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700395 }
David Browne5133242019-02-28 11:05:19 -0700396 }
397 }
David Brownc3898d62019-08-05 14:20:02 -0600398
399 pub fn num_images(&self) -> usize {
400 self.slots.len()
401 }
David Browne5133242019-02-28 11:05:19 -0700402}
403
David Brown5c9e0f12019-01-09 16:34:33 -0700404impl Images {
405 /// A simple upgrade without forced failures.
406 ///
407 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700408 /// inject failures at chosen steps. Returns None if it was unable to
409 /// count the operations in a basic upgrade.
410 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300411 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700412 info!("Total flash operation count={}", total_count);
413
David Brown84b49f72019-03-01 10:58:22 -0700414 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700415 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700416 None
David Brown5c9e0f12019-01-09 16:34:33 -0700417 } else {
David Brown8973f552021-03-10 05:21:11 -0700418 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700419 }
420 }
421
Fabio Utzigd0157342020-10-02 15:22:11 -0300422 pub fn run_bootstrap(&self) -> bool {
423 let mut flash = self.flash.clone();
424 let mut fails = 0;
425
426 if Caps::Bootstrap.present() {
427 info!("Try bootstraping image in the primary");
428
429 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
430 if result != 0 {
431 warn!("Failed first boot");
432 fails += 1;
433 }
434
435 if !self.verify_images(&flash, 0, 1) {
436 warn!("Image in the first slot was not bootstrapped");
437 fails += 1;
438 }
439
440 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
441 BOOT_FLAG_SET, BOOT_FLAG_SET) {
442 warn!("Mismatched trailer for the primary slot");
443 fails += 1;
444 }
445 }
446
447 if fails > 0 {
448 error!("Expected trailer on secondary slot to be erased");
449 }
450
451 fails > 0
452 }
453
454
David Brownc3898d62019-08-05 14:20:02 -0600455 /// Test a simple upgrade, with dependencies given, and verify that the
456 /// image does as is described in the test.
457 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
458 let (flash, _) = self.try_upgrade(None, true);
459
460 self.verify_dep_images(&flash, deps)
461 }
462
Fabio Utzigf5480c72019-11-28 10:41:57 -0300463 fn is_swap_upgrade(&self) -> bool {
464 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
465 }
466
David Brown5c9e0f12019-01-09 16:34:33 -0700467 pub fn run_basic_revert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700468 if Caps::OverwriteUpgrade.present() {
469 return false;
470 }
David Brown5c9e0f12019-01-09 16:34:33 -0700471
David Brown5c9e0f12019-01-09 16:34:33 -0700472 let mut fails = 0;
473
474 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300475 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700476 for count in 2 .. 5 {
477 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700478 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700479 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700480 error!("Revert failure on count {}", count);
481 fails += 1;
482 }
483 }
484 }
485
486 fails > 0
487 }
488
489 pub fn run_perm_with_fails(&self) -> bool {
490 let mut fails = 0;
491 let total_flash_ops = self.total_count.unwrap();
492
493 // Let's try an image halfway through.
494 for i in 1 .. total_flash_ops {
495 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300496 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700497 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700498 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700499 warn!("FAIL at step {} of {}", i, total_flash_ops);
500 fails += 1;
501 }
502
David Brown84b49f72019-03-01 10:58:22 -0700503 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
504 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100505 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700506 fails += 1;
507 }
508
David Brown84b49f72019-03-01 10:58:22 -0700509 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
510 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100511 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700512 fails += 1;
513 }
514
David Brownaec56b22021-03-10 05:22:07 -0700515 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
516 warn!("Secondary slot FAIL at step {} of {}",
517 i, total_flash_ops);
518 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700519 }
520 }
521
522 if fails > 0 {
523 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
524 fails as f32 * 100.0 / total_flash_ops as f32);
525 }
526
527 fails > 0
528 }
529
David Brown5c9e0f12019-01-09 16:34:33 -0700530 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
531 let mut fails = 0;
532 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700533 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700534 info!("Random interruptions at reset points={:?}", total_counts);
535
David Brown84b49f72019-03-01 10:58:22 -0700536 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300537 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700538 // TODO: This result is ignored.
539 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700540 } else {
541 true
542 };
David Vincze2d736ad2019-02-18 11:50:22 +0100543 if !primary_slot_ok || !secondary_slot_ok {
544 error!("Image mismatch after random interrupts: primary slot={} \
545 secondary slot={}",
546 if primary_slot_ok { "ok" } else { "fail" },
547 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700548 fails += 1;
549 }
David Brown84b49f72019-03-01 10:58:22 -0700550 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
551 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100552 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700553 fails += 1;
554 }
David Brown84b49f72019-03-01 10:58:22 -0700555 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
556 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100557 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700558 fails += 1;
559 }
560
561 if fails > 0 {
562 error!("Error testing perm upgrade with {} fails", total_fails);
563 }
564
565 fails > 0
566 }
567
David Brown5c9e0f12019-01-09 16:34:33 -0700568 pub fn run_revert_with_fails(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700569 if Caps::OverwriteUpgrade.present() {
570 return false;
571 }
David Brown5c9e0f12019-01-09 16:34:33 -0700572
David Brown5c9e0f12019-01-09 16:34:33 -0700573 let mut fails = 0;
574
Fabio Utzigf5480c72019-11-28 10:41:57 -0300575 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300576 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700577 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700578 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700579 error!("Revert failed at interruption {}", i);
580 fails += 1;
581 }
582 }
583 }
584
585 fails > 0
586 }
587
David Brown5c9e0f12019-01-09 16:34:33 -0700588 pub fn run_norevert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700589 if Caps::OverwriteUpgrade.present() {
590 return false;
591 }
David Brown5c9e0f12019-01-09 16:34:33 -0700592
David Brown76101572019-02-28 11:29:03 -0700593 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700594 let mut fails = 0;
595
596 info!("Try norevert");
597
598 // First do a normal upgrade...
David Brown76101572019-02-28 11:29:03 -0700599 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700600 if result != 0 {
601 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 Brown76101572019-02-28 11:29:03 -0700633 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700634 if result != 0 {
635 warn!("Failed second boot");
636 fails += 1;
637 }
638
David Brown84b49f72019-03-01 10:58:22 -0700639 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
640 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100641 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700642 fails += 1;
643 }
David Brown84b49f72019-03-01 10:58:22 -0700644 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700645 warn!("Failed image verification");
646 fails += 1;
647 }
648
649 if fails > 0 {
650 error!("Error running upgrade without revert");
651 }
652
653 fails > 0
654 }
655
David Brown2ee5f7f2020-01-13 14:04:01 -0700656 // Test that an upgrade is rejected. Assumes that the image was build
657 // such that the upgrade is instead a downgrade.
658 pub fn run_nodowngrade(&self) -> bool {
659 if !Caps::DowngradePrevention.present() {
660 return false;
661 }
662
663 let mut flash = self.flash.clone();
664 let mut fails = 0;
665
666 info!("Try no downgrade");
667
668 // First, do a normal upgrade.
669 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
670 if result != 0 {
671 warn!("Failed first boot");
672 fails += 1;
673 }
674
675 if !self.verify_images(&flash, 0, 0) {
676 warn!("Failed verification after downgrade rejection");
677 fails += 1;
678 }
679
680 if fails > 0 {
681 error!("Error testing downgrade rejection");
682 }
683
684 fails > 0
685 }
686
David Vincze2d736ad2019-02-18 11:50:22 +0100687 // Tests a new image written to the primary slot that already has magic and
688 // image_ok set while there is no image on the secondary slot, so no revert
689 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700690 pub fn run_norevert_newimage(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700691 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700692 let mut fails = 0;
693
694 info!("Try non-revert on imgtool generated image");
695
David Brown84b49f72019-03-01 10:58:22 -0700696 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700697
David Vincze2d736ad2019-02-18 11:50:22 +0100698 // This simulates writing an image created by imgtool to
699 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700700 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
701 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100702 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700703 fails += 1;
704 }
705
706 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700707 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700708 if result != 0 {
709 warn!("Failed first boot");
710 fails += 1;
711 }
712
713 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700714 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700715 warn!("Failed image verification");
716 fails += 1;
717 }
David Brown84b49f72019-03-01 10:58:22 -0700718 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
719 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100720 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700721 fails += 1;
722 }
David Brown84b49f72019-03-01 10:58:22 -0700723 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
724 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100725 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700726 fails += 1;
727 }
728
729 if fails > 0 {
730 error!("Expected a non revert with new image");
731 }
732
733 fails > 0
734 }
735
David Vincze2d736ad2019-02-18 11:50:22 +0100736 // Tests a new image written to the primary slot that already has magic and
737 // image_ok set while there is no image on the secondary slot, so no revert
738 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700739 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700740 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700741 let mut fails = 0;
742
743 info!("Try upgrade image with bad signature");
744
David Brown84b49f72019-03-01 10:58:22 -0700745 self.mark_upgrades(&mut flash, 0);
746 self.mark_permanent_upgrades(&mut flash, 0);
747 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700748
David Brown84b49f72019-03-01 10:58:22 -0700749 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
750 BOOT_FLAG_SET, 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 }
754
755 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700756 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700757 if result != 0 {
758 warn!("Failed first boot");
759 fails += 1;
760 }
761
762 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700763 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700764 warn!("Failed image verification");
765 fails += 1;
766 }
David Brown84b49f72019-03-01 10:58:22 -0700767 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
768 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100769 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700770 fails += 1;
771 }
772
773 if fails > 0 {
774 error!("Expected an upgrade failure when image has bad signature");
775 }
776
777 fails > 0
778 }
779
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300780 // Should detect there is a leftover trailer in an otherwise erased
781 // secondary slot and erase its trailer.
782 pub fn run_secondary_leftover_trailer(&self) -> bool {
783 let mut flash = self.flash.clone();
784 let mut fails = 0;
785
786 info!("Try with a leftover trailer in the secondary; must be erased");
787
788 // Add a trailer on the secondary slot
789 self.mark_permanent_upgrades(&mut flash, 1);
790 self.mark_upgrades(&mut flash, 1);
791
792 // Run the bootloader...
793 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
794 if result != 0 {
795 warn!("Failed first boot");
796 fails += 1;
797 }
798
799 // State should not have changed
800 if !self.verify_images(&flash, 0, 0) {
801 warn!("Failed image verification");
802 fails += 1;
803 }
804 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
805 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
806 warn!("Mismatched trailer for the secondary slot");
807 fails += 1;
808 }
809
810 if fails > 0 {
811 error!("Expected trailer on secondary slot to be erased");
812 }
813
814 fails > 0
815 }
816
David Brown5c9e0f12019-01-09 16:34:33 -0700817 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300818 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700819 }
820
David Brown5c9e0f12019-01-09 16:34:33 -0700821 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300822 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700823 }
824
825 /// This test runs a simple upgrade with no fails in the images, but
826 /// allowing for fails in the status area. This should run to the end
827 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700828 pub fn run_with_status_fails_complete(&self) -> bool {
David Vincze2d736ad2019-02-18 11:50:22 +0100829 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700830 return false;
831 }
832
David Brown76101572019-02-28 11:29:03 -0700833 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700834 let mut fails = 0;
835
836 info!("Try swap with status fails");
837
David Brown84b49f72019-03-01 10:58:22 -0700838 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700839 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700840
David Brown76101572019-02-28 11:29:03 -0700841 let (result, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown5c9e0f12019-01-09 16:34:33 -0700842 if result != 0 {
843 warn!("Failed!");
844 fails += 1;
845 }
846
847 // Failed writes to the marked "bad" region don't assert anymore.
848 // Any detected assert() is happening in another part of the code.
849 if asserts != 0 {
850 warn!("At least one assert() was called");
851 fails += 1;
852 }
853
David Brown84b49f72019-03-01 10:58:22 -0700854 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
855 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100856 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700857 fails += 1;
858 }
859
David Brown84b49f72019-03-01 10:58:22 -0700860 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700861 warn!("Failed image verification");
862 fails += 1;
863 }
864
David Vincze2d736ad2019-02-18 11:50:22 +0100865 info!("validate primary slot enabled; \
866 re-run of boot_go should just work");
David Brown76101572019-02-28 11:29:03 -0700867 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700868 if result != 0 {
869 warn!("Failed!");
870 fails += 1;
871 }
872
873 if fails > 0 {
874 error!("Error running upgrade with status write fails");
875 }
876
877 fails > 0
878 }
879
880 /// This test runs a simple upgrade with no fails in the images, but
881 /// allowing for fails in the status area. This should run to the end
882 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700883 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown85904a82019-01-11 13:45:12 -0700884 if Caps::OverwriteUpgrade.present() {
885 false
David Vincze2d736ad2019-02-18 11:50:22 +0100886 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700887
David Brown76101572019-02-28 11:29:03 -0700888 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700889 let mut fails = 0;
890 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700891
David Brown85904a82019-01-11 13:45:12 -0700892 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700893
David Brown85904a82019-01-11 13:45:12 -0700894 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700895
David Brown84b49f72019-03-01 10:58:22 -0700896 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700897 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700898
899 // Should not fail, writing to bad regions does not assert
David Brown76101572019-02-28 11:29:03 -0700900 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true);
David Brown85904a82019-01-11 13:45:12 -0700901 if asserts != 0 {
902 warn!("At least one assert() was called");
903 fails += 1;
904 }
905
David Brown76101572019-02-28 11:29:03 -0700906 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700907
908 info!("Resuming an interrupted swap operation");
David Brown76101572019-02-28 11:29:03 -0700909 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700910
911 // This might throw no asserts, for large sector devices, where
912 // a single failure writing is indistinguishable from no failure,
913 // or throw a single assert for small sector devices that fail
914 // multiple times...
915 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100916 warn!("Expected single assert validating the primary slot, \
917 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700918 fails += 1;
919 }
920
921 if fails > 0 {
922 error!("Error running upgrade with status write fails");
923 }
924
925 fails > 0
926 } else {
David Brown76101572019-02-28 11:29:03 -0700927 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700928 let mut fails = 0;
929
930 info!("Try interrupted swap with status fails");
931
David Brown84b49f72019-03-01 10:58:22 -0700932 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700933 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700934
935 // This is expected to fail while writing to bad regions...
David Brown76101572019-02-28 11:29:03 -0700936 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700937 if asserts == 0 {
938 warn!("No assert() detected");
939 fails += 1;
940 }
941
942 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700943 }
David Brown5c9e0f12019-01-09 16:34:33 -0700944 }
945
946 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -0700947 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -0700948 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -0700949 if Caps::OverwriteUpgrade.present() {
950 return;
951 }
952
David Brown84b49f72019-03-01 10:58:22 -0700953 // Set this for each image.
954 for image in &self.images {
955 let dev_id = &image.slots[slot].dev_id;
956 let dev = flash.get_mut(&dev_id).unwrap();
957 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -0700958 let off = &image.slots[slot].base_off;
959 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -0700960 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -0700961
David Brown84b49f72019-03-01 10:58:22 -0700962 // Mark the status area as a bad area
963 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
964 }
David Brown5c9e0f12019-01-09 16:34:33 -0700965 }
966
David Brown76101572019-02-28 11:29:03 -0700967 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +0100968 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700969 return;
970 }
971
David Brown84b49f72019-03-01 10:58:22 -0700972 for image in &self.images {
973 let dev_id = &image.slots[slot].dev_id;
974 let dev = flash.get_mut(&dev_id).unwrap();
975 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -0700976
David Brown84b49f72019-03-01 10:58:22 -0700977 // Disabling write verification the only assert triggered by
978 // boot_go should be checking for integrity of status bytes.
979 dev.set_verify_writes(false);
980 }
David Brown5c9e0f12019-01-09 16:34:33 -0700981 }
982
David Browndb505822019-03-01 10:04:20 -0700983 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
984 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -0300985 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -0700986 // Clone the flash to have a new copy.
987 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700988
Fabio Utziged4a5362019-07-30 12:43:23 -0300989 if permanent {
990 self.mark_permanent_upgrades(&mut flash, 1);
991 }
David Brown5c9e0f12019-01-09 16:34:33 -0700992
David Browndb505822019-03-01 10:04:20 -0700993 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -0700994
David Browndb505822019-03-01 10:04:20 -0700995 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
996 (-0x13579, _) => (true, stop.unwrap()),
997 (0, _) => (false, -counter),
998 (x, _) => panic!("Unknown return: {}", x),
999 };
David Brown5c9e0f12019-01-09 16:34:33 -07001000
David Browndb505822019-03-01 10:04:20 -07001001 counter = 0;
1002 if first_interrupted {
1003 // fl.dump();
1004 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
1005 (-0x13579, _) => panic!("Shouldn't stop again"),
1006 (0, _) => (),
1007 (x, _) => panic!("Unknown return: {}", x),
1008 }
1009 }
David Brown5c9e0f12019-01-09 16:34:33 -07001010
David Browndb505822019-03-01 10:04:20 -07001011 (flash, count - counter)
1012 }
1013
1014 fn try_revert(&self, count: usize) -> SimMultiFlash {
1015 let mut flash = self.flash.clone();
1016
1017 // fl.write_file("image0.bin").unwrap();
1018 for i in 0 .. count {
1019 info!("Running boot pass {}", i + 1);
1020 assert_eq!(c::boot_go(&mut flash, &self.areadesc, None, false), (0, 0));
1021 }
1022 flash
1023 }
1024
1025 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1026 let mut flash = self.flash.clone();
1027 let mut fails = 0;
1028
1029 let mut counter = stop;
1030 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
1031 if x != -0x13579 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001032 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001033 fails += 1;
1034 }
1035
Fabio Utzig8af7f792019-07-30 12:40:01 -03001036 // In a multi-image setup, copy done might be set if any number of
1037 // images was already successfully swapped.
1038 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1039 warn!("copy_done should be unset");
1040 fails += 1;
1041 }
1042
David Browndb505822019-03-01 10:04:20 -07001043 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
1044 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001045 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001046 fails += 1;
1047 }
1048
David Brown84b49f72019-03-01 10:58:22 -07001049 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001050 warn!("Image in the primary slot before revert is invalid at stop={}",
1051 stop);
1052 fails += 1;
1053 }
David Brown84b49f72019-03-01 10:58:22 -07001054 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001055 warn!("Image in the secondary slot before revert is invalid at stop={}",
1056 stop);
1057 fails += 1;
1058 }
David Brown84b49f72019-03-01 10:58:22 -07001059 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1060 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001061 warn!("Mismatched trailer for the primary slot before revert");
1062 fails += 1;
1063 }
David Brown84b49f72019-03-01 10:58:22 -07001064 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1065 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001066 warn!("Mismatched trailer for the secondary slot before revert");
1067 fails += 1;
1068 }
1069
1070 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001071 let mut counter = stop;
1072 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
1073 if x != -0x13579 {
1074 warn!("Should have stopped revert at interruption point");
1075 fails += 1;
1076 }
1077
David Browndb505822019-03-01 10:04:20 -07001078 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
1079 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001080 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001081 fails += 1;
1082 }
1083
David Brown84b49f72019-03-01 10:58:22 -07001084 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001085 warn!("Image in the primary slot after revert is invalid at stop={}",
1086 stop);
1087 fails += 1;
1088 }
David Brown84b49f72019-03-01 10:58:22 -07001089 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001090 warn!("Image in the secondary slot after revert is invalid at stop={}",
1091 stop);
1092 fails += 1;
1093 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001094
David Brown84b49f72019-03-01 10:58:22 -07001095 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1096 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001097 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001098 fails += 1;
1099 }
David Brown84b49f72019-03-01 10:58:22 -07001100 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1101 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001102 warn!("Mismatched trailer for the secondary slot after revert");
1103 fails += 1;
1104 }
1105
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001106 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
1107 if x != 0 {
1108 warn!("Should have finished 3rd boot");
1109 fails += 1;
1110 }
1111
1112 if !self.verify_images(&flash, 0, 0) {
1113 warn!("Image in the primary slot is invalid on 1st boot after revert");
1114 fails += 1;
1115 }
1116 if !self.verify_images(&flash, 1, 1) {
1117 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1118 fails += 1;
1119 }
1120
David Browndb505822019-03-01 10:04:20 -07001121 fails > 0
1122 }
1123
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001124
David Browndb505822019-03-01 10:04:20 -07001125 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1126 let mut flash = self.flash.clone();
1127
David Brown84b49f72019-03-01 10:58:22 -07001128 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001129
1130 let mut rng = rand::thread_rng();
1131 let mut resets = vec![0i32; count];
1132 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001133 for reset in &mut resets {
David Browncd842842020-07-09 15:46:53 -06001134 let reset_counter = rng.gen_range(1, remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001135 let mut counter = reset_counter;
1136 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
1137 (0, _) | (-0x13579, _) => (),
1138 (x, _) => panic!("Unknown return: {}", x),
1139 }
1140 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001141 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001142 }
1143
1144 match c::boot_go(&mut flash, &self.areadesc, None, false) {
1145 (-0x13579, _) => panic!("Should not be have been interrupted!"),
David Brown5c9e0f12019-01-09 16:34:33 -07001146 (0, _) => (),
1147 (x, _) => panic!("Unknown return: {}", x),
1148 }
David Brown5c9e0f12019-01-09 16:34:33 -07001149
David Browndb505822019-03-01 10:04:20 -07001150 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001151 }
David Brown84b49f72019-03-01 10:58:22 -07001152
1153 /// Verify the image in the given flash device, the specified slot
1154 /// against the expected image.
1155 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001156 self.images.iter().all(|image| {
1157 verify_image(flash, &image.slots[slot],
1158 match against {
1159 0 => &image.primaries,
1160 1 => &image.upgrades,
1161 _ => panic!("Invalid 'against'")
1162 })
1163 })
David Brown84b49f72019-03-01 10:58:22 -07001164 }
1165
David Brownc3898d62019-08-05 14:20:02 -06001166 /// Verify the images, according to the dependency test.
1167 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1168 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1169 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1170 if !verify_image(flash, &image.slots[0],
1171 match upgrade {
1172 UpgradeInfo::Upgraded => &image.upgrades,
1173 UpgradeInfo::Held => &image.primaries,
1174 }) {
1175 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1176 return true;
1177 }
1178 }
1179
1180 false
1181 }
1182
Fabio Utzig8af7f792019-07-30 12:40:01 -03001183 /// Verify that at least one of the trailers of the images have the
1184 /// specified values.
1185 fn verify_trailers_loose(&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().any(|image| {
1189 verify_trailer(flash, &image.slots[slot],
1190 magic, image_ok, copy_done)
1191 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001192 }
1193
David Brown84b49f72019-03-01 10:58:22 -07001194 /// Verify that the trailers of the images have the specified
1195 /// values.
1196 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1197 magic: Option<u8>, image_ok: Option<u8>,
1198 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001199 self.images.iter().all(|image| {
1200 verify_trailer(flash, &image.slots[slot],
1201 magic, image_ok, copy_done)
1202 })
David Brown84b49f72019-03-01 10:58:22 -07001203 }
1204
1205 /// Mark each of the images for permanent upgrade.
1206 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1207 for image in &self.images {
1208 mark_permanent_upgrade(flash, &image.slots[slot]);
1209 }
1210 }
1211
1212 /// Mark each of the images for permanent upgrade.
1213 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1214 for image in &self.images {
1215 mark_upgrade(flash, &image.slots[slot]);
1216 }
1217 }
David Brown297029a2019-08-13 14:29:51 -06001218
1219 /// Dump out the flash image(s) to one or more files for debugging
1220 /// purposes. The names will be written as either "{prefix}.mcubin" or
1221 /// "{prefix}-001.mcubin" depending on how many images there are.
1222 pub fn debug_dump(&self, prefix: &str) {
1223 for (id, fdev) in &self.flash {
1224 let name = if self.flash.len() == 1 {
1225 format!("{}.mcubin", prefix)
1226 } else {
1227 format!("{}-{:>0}.mcubin", prefix, id)
1228 };
1229 fdev.write_file(&name).unwrap();
1230 }
1231 }
David Brown5c9e0f12019-01-09 16:34:33 -07001232}
1233
1234/// Show the flash layout.
1235#[allow(dead_code)]
1236fn show_flash(flash: &dyn Flash) {
1237 println!("---- Flash configuration ----");
1238 for sector in flash.sector_iter() {
1239 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1240 sector.num, sector.base, sector.size);
1241 }
1242 println!("");
1243}
1244
1245/// Install a "program" into the given image. This fakes the image header, or at least all of the
1246/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001247fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownc3898d62019-08-05 14:20:02 -06001248 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001249 let offset = slot.base_off;
1250 let slot_len = slot.len;
1251 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001252
David Brown43643dd2019-01-11 15:43:28 -07001253 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001254
David Brownc3898d62019-08-05 14:20:02 -06001255 // Add the dependencies early to the tlv.
1256 for dep in deps.my_deps(offset, slot.index) {
1257 tlv.add_dependency(deps.other_id(), &dep);
1258 }
1259
David Brown5c9e0f12019-01-09 16:34:33 -07001260 const HDR_SIZE: usize = 32;
1261
1262 // Generate a boot header. Note that the size doesn't include the header.
1263 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001264 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -07001265 load_addr: 0,
1266 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001267 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001268 img_size: len as u32,
1269 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001270 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001271 _pad2: 0,
1272 };
1273
1274 let mut b_header = [0; HDR_SIZE];
1275 b_header[..32].clone_from_slice(header.as_raw());
1276 assert_eq!(b_header.len(), HDR_SIZE);
1277
1278 tlv.add_bytes(&b_header);
1279
1280 // The core of the image itself is just pseudorandom data.
1281 let mut b_img = vec![0; len];
1282 splat(&mut b_img, offset);
1283
David Browncb47dd72019-08-05 14:21:49 -06001284 // Add some information at the start of the payload to make it easier
1285 // to see what it is. This will fail if the image itself is too small.
1286 {
1287 let mut wr = Cursor::new(&mut b_img);
1288 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1289 offset, dev_id, slot).unwrap();
1290 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1291 }
1292
David Brown5c9e0f12019-01-09 16:34:33 -07001293 // TLV signatures work over plain image
1294 tlv.add_bytes(&b_img);
1295
1296 // Generate encrypted images
1297 let flag = TlvFlags::ENCRYPTED as u32;
1298 let is_encrypted = (tlv.get_flags() & flag) == flag;
1299 let mut b_encimg = vec![];
1300 if is_encrypted {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001301 tlv.generate_enc_key();
1302 let enc_key = tlv.get_enc_key();
1303 let key = GenericArray::from_slice(enc_key.as_slice());
David Brown5c9e0f12019-01-09 16:34:33 -07001304 let nonce = GenericArray::from_slice(&[0; 16]);
1305 let mut cipher = Aes128Ctr::new(&key, &nonce);
1306 b_encimg = b_img.clone();
1307 cipher.apply_keystream(&mut b_encimg);
1308 }
1309
1310 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001311 if bad_sig {
1312 tlv.corrupt_sig();
1313 }
1314 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001315
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001316 let dev = flash.get_mut(&dev_id).unwrap();
1317
David Brown5c9e0f12019-01-09 16:34:33 -07001318 let mut buf = vec![];
1319 buf.append(&mut b_header.to_vec());
1320 buf.append(&mut b_img);
1321 buf.append(&mut b_tlv.clone());
1322
David Brown95de4502019-11-15 12:01:34 -07001323 // Pad the buffer to a multiple of the flash alignment.
1324 let align = dev.align();
1325 while buf.len() % align != 0 {
1326 buf.push(dev.erased_val());
1327 }
1328
David Brown5c9e0f12019-01-09 16:34:33 -07001329 let mut encbuf = vec![];
1330 if is_encrypted {
1331 encbuf.append(&mut b_header.to_vec());
1332 encbuf.append(&mut b_encimg);
1333 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001334
1335 while encbuf.len() % align != 0 {
1336 encbuf.push(dev.erased_val());
1337 }
David Brown5c9e0f12019-01-09 16:34:33 -07001338 }
1339
David Vincze2d736ad2019-02-18 11:50:22 +01001340 // Since images are always non-encrypted in the primary slot, we first write
1341 // an encrypted image, re-read to use for verification, erase + flash
1342 // un-encrypted. In the secondary slot the image is written un-encrypted,
1343 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001344
David Brown3b090212019-07-30 15:59:28 -06001345 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001346 let enc_copy: Option<Vec<u8>>;
1347
1348 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001349 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001350
1351 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001352 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001353
1354 enc_copy = Some(enc);
1355
David Brown76101572019-02-28 11:29:03 -07001356 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001357 } else {
1358 enc_copy = None;
1359 }
1360
David Brown76101572019-02-28 11:29:03 -07001361 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001362
1363 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001364 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001365
David Brownca234692019-02-28 11:22:19 -07001366 ImageData {
1367 plain: copy,
1368 cipher: enc_copy,
1369 }
David Brown5c9e0f12019-01-09 16:34:33 -07001370 } else {
1371
David Brown76101572019-02-28 11:29:03 -07001372 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001373
1374 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001375 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001376
1377 let enc_copy: Option<Vec<u8>>;
1378
1379 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001380 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001381
David Brown76101572019-02-28 11:29:03 -07001382 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001383
1384 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001385 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001386
1387 enc_copy = Some(enc);
1388 } else {
1389 enc_copy = None;
1390 }
1391
David Brownca234692019-02-28 11:22:19 -07001392 ImageData {
1393 plain: copy,
1394 cipher: enc_copy,
1395 }
David Brown5c9e0f12019-01-09 16:34:33 -07001396 }
David Brown5c9e0f12019-01-09 16:34:33 -07001397}
1398
David Brown873be312019-09-03 12:22:32 -06001399/// Install no image. This is used when no upgrade happens.
1400fn install_no_image() -> ImageData {
1401 ImageData {
1402 plain: vec![],
1403 cipher: None,
1404 }
1405}
1406
David Brown5c9e0f12019-01-09 16:34:33 -07001407fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001408 if Caps::EcdsaP224.present() {
1409 panic!("Ecdsa P224 not supported in Simulator");
1410 }
David Brown5c9e0f12019-01-09 16:34:33 -07001411
David Brownb8882112019-01-11 14:04:11 -07001412 if Caps::EncKw.present() {
1413 if Caps::RSA2048.present() {
1414 TlvGen::new_rsa_kw()
1415 } else if Caps::EcdsaP256.present() {
1416 TlvGen::new_ecdsa_kw()
1417 } else {
1418 TlvGen::new_enc_kw()
1419 }
1420 } else if Caps::EncRsa.present() {
1421 if Caps::RSA2048.present() {
1422 TlvGen::new_sig_enc_rsa()
1423 } else {
1424 TlvGen::new_enc_rsa()
1425 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001426 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001427 if Caps::EcdsaP256.present() {
1428 TlvGen::new_ecdsa_ecies_p256()
1429 } else {
1430 TlvGen::new_ecies_p256()
1431 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001432 } else if Caps::EncX25519.present() {
1433 if Caps::Ed25519.present() {
1434 TlvGen::new_ed25519_ecies_x25519()
1435 } else {
1436 TlvGen::new_ecies_x25519()
1437 }
David Brownb8882112019-01-11 14:04:11 -07001438 } else {
1439 // The non-encrypted configuration.
1440 if Caps::RSA2048.present() {
1441 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001442 } else if Caps::RSA3072.present() {
1443 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001444 } else if Caps::EcdsaP256.present() {
1445 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001446 } else if Caps::Ed25519.present() {
1447 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001448 } else {
1449 TlvGen::new_hash_only()
1450 }
1451 }
David Brown5c9e0f12019-01-09 16:34:33 -07001452}
1453
David Brownca234692019-02-28 11:22:19 -07001454impl ImageData {
1455 /// Find the image contents for the given slot. This assumes that slot 0
1456 /// is unencrypted, and slot 1 is encrypted.
1457 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001458 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001459 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001460 match (encrypted, slot) {
1461 (false, _) => &self.plain,
1462 (true, 0) => &self.plain,
1463 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1464 _ => panic!("Invalid slot requested"),
1465 }
David Brown5c9e0f12019-01-09 16:34:33 -07001466 }
1467}
1468
David Brown5c9e0f12019-01-09 16:34:33 -07001469/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001470fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1471 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001472 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001473 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001474
1475 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001476 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001477 let dev = flash.get(&dev_id).unwrap();
1478 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001479
1480 if buf != &copy[..] {
1481 for i in 0 .. buf.len() {
1482 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001483 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1484 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001485 break;
1486 }
1487 }
1488 false
1489 } else {
1490 true
1491 }
1492}
1493
David Brown3b090212019-07-30 15:59:28 -06001494fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001495 magic: Option<u8>, image_ok: Option<u8>,
1496 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001497 if Caps::OverwriteUpgrade.present() {
1498 return true;
1499 }
David Brown5c9e0f12019-01-09 16:34:33 -07001500
David Brown3b090212019-07-30 15:59:28 -06001501 let offset = slot.trailer_off + c::boot_max_align();
1502 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001503 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001504 let mut failed = false;
1505
David Brown76101572019-02-28 11:29:03 -07001506 let dev = flash.get(&dev_id).unwrap();
1507 let erased_val = dev.erased_val();
1508 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001509
1510 failed |= match magic {
1511 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001512 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001513 warn!("\"magic\" mismatch at {:#x}", offset);
1514 true
1515 } else if v == 3 {
1516 let expected = [erased_val; 16];
Christopher Collinsa1c12042019-05-23 14:00:28 -07001517 if &copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001518 warn!("\"magic\" mismatch at {:#x}", offset);
1519 true
1520 } else {
1521 false
1522 }
1523 } else {
1524 false
1525 }
1526 },
1527 None => false,
1528 };
1529
1530 failed |= match image_ok {
1531 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001532 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001533 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1534 true
1535 } else {
1536 false
1537 }
1538 },
1539 None => false,
1540 };
1541
1542 failed |= match copy_done {
1543 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001544 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001545 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1546 true
1547 } else {
1548 false
1549 }
1550 },
1551 None => false,
1552 };
1553
1554 !failed
1555}
1556
David Brown297029a2019-08-13 14:29:51 -06001557/// Install a partition table. This is a simplified partition table that
1558/// we write at the beginning of flash so make it easier for external tools
1559/// to analyze these images.
1560fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1561 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1562 for &id in &ids {
1563 // If there are any partitions in this device that start at 0, and
1564 // aren't marked as the BootLoader partition, avoid adding the
1565 // partition table. This makes it harder to view the image, but
1566 // avoids messing up images already written.
1567 if areadesc.iter_areas().any(|area| {
1568 area.device_id == id &&
1569 area.off == 0 &&
1570 area.flash_id != FlashId::BootLoader
1571 }) {
1572 if log_enabled!(Info) {
1573 let special: Vec<FlashId> = areadesc.iter_areas()
1574 .filter(|area| area.device_id == id && area.off == 0)
1575 .map(|area| area.flash_id)
1576 .collect();
1577 info!("Skipping partition table: {:?}", special);
1578 }
1579 break;
1580 }
1581
1582 let mut buf: Vec<u8> = vec![];
1583 write!(&mut buf, "mcuboot\0").unwrap();
1584
1585 // Iterate through all of the partitions in that device, and encode
1586 // into the table.
1587 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1588 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1589
1590 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1591 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1592 buf.write_u32::<LittleEndian>(area.off).unwrap();
1593 buf.write_u32::<LittleEndian>(area.size).unwrap();
1594 buf.write_u32::<LittleEndian>(0).unwrap();
1595 }
1596
1597 let dev = flash.get_mut(&id).unwrap();
1598
1599 // Pad to alignment.
1600 while buf.len() % dev.align() != 0 {
1601 buf.push(0);
1602 }
1603
1604 dev.write(0, &buf).unwrap();
1605 }
1606}
1607
David Brown5c9e0f12019-01-09 16:34:33 -07001608/// The image header
1609#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001610#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001611pub struct ImageHeader {
1612 magic: u32,
1613 load_addr: u32,
1614 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001615 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001616 img_size: u32,
1617 flags: u32,
1618 ver: ImageVersion,
1619 _pad2: u32,
1620}
1621
1622impl AsRaw for ImageHeader {}
1623
1624#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001625#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001626pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001627 pub major: u8,
1628 pub minor: u8,
1629 pub revision: u16,
1630 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001631}
1632
David Brownc3898d62019-08-05 14:20:02 -06001633#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001634pub struct SlotInfo {
1635 pub base_off: usize,
1636 pub trailer_off: usize,
1637 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001638 // Which slot within this device.
1639 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001640 pub dev_id: u8,
1641}
1642
David Brown347dc572019-11-15 11:37:25 -07001643const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1644 0x60, 0xd2, 0xef, 0x7f,
1645 0x35, 0x52, 0x50, 0x0f,
1646 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001647
1648// Replicates defines found in bootutil.h
1649const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1650const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1651
1652const BOOT_FLAG_SET: Option<u8> = Some(1);
1653const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1654
1655/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001656pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1657 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001658 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001659 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001660 if offset % align != 0 || MAGIC.len() % align != 0 {
1661 // The write size is larger than the magic value. Fill a buffer
1662 // with the erased value, put the MAGIC in it, and write it in its
1663 // entirety.
1664 let mut buf = vec![dev.erased_val(); align];
1665 buf[(offset % align)..].copy_from_slice(MAGIC);
1666 dev.write(offset - (offset % align), &buf).unwrap();
1667 } else {
1668 dev.write(offset, MAGIC).unwrap();
1669 }
David Brown5c9e0f12019-01-09 16:34:33 -07001670}
1671
1672/// Writes the image_ok flag which, guess what, tells the bootloader
1673/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001674fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001675 // Overwrite mode always is permanent, and only the magic is used in
1676 // the trailer. To avoid problems with large write sizes, don't try to
1677 // set anything in this case.
1678 if Caps::OverwriteUpgrade.present() {
1679 return;
1680 }
1681
David Brown76101572019-02-28 11:29:03 -07001682 let dev = flash.get_mut(&slot.dev_id).unwrap();
1683 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001684 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001685 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001686 let align = dev.align();
1687 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001688}
1689
1690// Drop some pseudo-random gibberish onto the data.
1691fn splat(data: &mut [u8], seed: usize) {
David Browncd842842020-07-09 15:46:53 -06001692 let mut seed_block = [0u8; 16];
1693 let mut buf = Cursor::new(&mut seed_block[..]);
1694 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
1695 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
1696 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
1697 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
1698 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07001699 rng.fill_bytes(data);
1700}
1701
1702/// Return a read-only view into the raw bytes of this object
1703trait AsRaw : Sized {
1704 fn as_raw<'a>(&'a self) -> &'a [u8] {
1705 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1706 mem::size_of::<Self>()) }
1707 }
1708}
1709
1710pub fn show_sizes() {
1711 // This isn't panic safe.
1712 for min in &[1, 2, 4, 8] {
1713 let msize = c::boot_trailer_sz(*min);
1714 println!("{:2}: {} (0x{:x})", min, msize, msize);
1715 }
1716}
David Brown95de4502019-11-15 12:01:34 -07001717
1718#[cfg(not(feature = "large-write"))]
1719fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001720 &[1, 2, 4, 8]
1721}
1722
1723#[cfg(feature = "large-write")]
1724fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001725 &[1, 2, 4, 8, 128, 512]
1726}