blob: 37c59ad1018087521883f5ce5a316bdef73f091b [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
Fabio Utzigf5480c72019-11-28 10:41:57 -0300515 if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700516 if !self.verify_images(&flash, 1, 0) {
David Vincze2d736ad2019-02-18 11:50:22 +0100517 warn!("Secondary slot FAIL at step {} of {}",
518 i, total_flash_ops);
David Brown5c9e0f12019-01-09 16:34:33 -0700519 fails += 1;
520 }
521 }
522 }
523
524 if fails > 0 {
525 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
526 fails as f32 * 100.0 / total_flash_ops as f32);
527 }
528
529 fails > 0
530 }
531
David Brown5c9e0f12019-01-09 16:34:33 -0700532 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
533 let mut fails = 0;
534 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700535 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700536 info!("Random interruptions at reset points={:?}", total_counts);
537
David Brown84b49f72019-03-01 10:58:22 -0700538 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300539 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700540 // TODO: This result is ignored.
541 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700542 } else {
543 true
544 };
David Vincze2d736ad2019-02-18 11:50:22 +0100545 if !primary_slot_ok || !secondary_slot_ok {
546 error!("Image mismatch after random interrupts: primary slot={} \
547 secondary slot={}",
548 if primary_slot_ok { "ok" } else { "fail" },
549 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700550 fails += 1;
551 }
David Brown84b49f72019-03-01 10:58:22 -0700552 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
553 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100554 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700555 fails += 1;
556 }
David Brown84b49f72019-03-01 10:58:22 -0700557 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
558 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100559 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700560 fails += 1;
561 }
562
563 if fails > 0 {
564 error!("Error testing perm upgrade with {} fails", total_fails);
565 }
566
567 fails > 0
568 }
569
David Brown5c9e0f12019-01-09 16:34:33 -0700570 pub fn run_revert_with_fails(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700571 if Caps::OverwriteUpgrade.present() {
572 return false;
573 }
David Brown5c9e0f12019-01-09 16:34:33 -0700574
David Brown5c9e0f12019-01-09 16:34:33 -0700575 let mut fails = 0;
576
Fabio Utzigf5480c72019-11-28 10:41:57 -0300577 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300578 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700579 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700580 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700581 error!("Revert failed at interruption {}", i);
582 fails += 1;
583 }
584 }
585 }
586
587 fails > 0
588 }
589
David Brown5c9e0f12019-01-09 16:34:33 -0700590 pub fn run_norevert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700591 if Caps::OverwriteUpgrade.present() {
592 return false;
593 }
David Brown5c9e0f12019-01-09 16:34:33 -0700594
David Brown76101572019-02-28 11:29:03 -0700595 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700596 let mut fails = 0;
597
598 info!("Try norevert");
599
600 // First do a normal upgrade...
David Brown76101572019-02-28 11:29:03 -0700601 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700602 if result != 0 {
603 warn!("Failed first boot");
604 fails += 1;
605 }
606
607 //FIXME: copy_done is written by boot_go, is it ok if no copy
608 // was ever done?
609
David Brown84b49f72019-03-01 10:58:22 -0700610 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100611 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700612 fails += 1;
613 }
David Brown84b49f72019-03-01 10:58:22 -0700614 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
615 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100616 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700617 fails += 1;
618 }
David Brown84b49f72019-03-01 10:58:22 -0700619 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
620 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100621 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700622 fails += 1;
623 }
624
David Vincze2d736ad2019-02-18 11:50:22 +0100625 // Marks image in the primary slot as permanent,
626 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700627 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700628
David Brown84b49f72019-03-01 10:58:22 -0700629 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
630 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100631 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700632 fails += 1;
633 }
634
David Brown76101572019-02-28 11:29:03 -0700635 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700636 if result != 0 {
637 warn!("Failed second boot");
638 fails += 1;
639 }
640
David Brown84b49f72019-03-01 10:58:22 -0700641 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
642 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100643 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700644 fails += 1;
645 }
David Brown84b49f72019-03-01 10:58:22 -0700646 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700647 warn!("Failed image verification");
648 fails += 1;
649 }
650
651 if fails > 0 {
652 error!("Error running upgrade without revert");
653 }
654
655 fails > 0
656 }
657
David Brown2ee5f7f2020-01-13 14:04:01 -0700658 // Test that an upgrade is rejected. Assumes that the image was build
659 // such that the upgrade is instead a downgrade.
660 pub fn run_nodowngrade(&self) -> bool {
661 if !Caps::DowngradePrevention.present() {
662 return false;
663 }
664
665 let mut flash = self.flash.clone();
666 let mut fails = 0;
667
668 info!("Try no downgrade");
669
670 // First, do a normal upgrade.
671 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
672 if result != 0 {
673 warn!("Failed first boot");
674 fails += 1;
675 }
676
677 if !self.verify_images(&flash, 0, 0) {
678 warn!("Failed verification after downgrade rejection");
679 fails += 1;
680 }
681
682 if fails > 0 {
683 error!("Error testing downgrade rejection");
684 }
685
686 fails > 0
687 }
688
David Vincze2d736ad2019-02-18 11:50:22 +0100689 // Tests a new image written to the primary slot that already has magic and
690 // image_ok set while there is no image on the secondary slot, so no revert
691 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700692 pub fn run_norevert_newimage(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700693 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700694 let mut fails = 0;
695
696 info!("Try non-revert on imgtool generated image");
697
David Brown84b49f72019-03-01 10:58:22 -0700698 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700699
David Vincze2d736ad2019-02-18 11:50:22 +0100700 // This simulates writing an image created by imgtool to
701 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700702 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
703 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100704 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700705 fails += 1;
706 }
707
708 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700709 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700710 if result != 0 {
711 warn!("Failed first boot");
712 fails += 1;
713 }
714
715 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700716 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700717 warn!("Failed image verification");
718 fails += 1;
719 }
David Brown84b49f72019-03-01 10:58:22 -0700720 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
721 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100722 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700723 fails += 1;
724 }
David Brown84b49f72019-03-01 10:58:22 -0700725 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
726 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100727 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700728 fails += 1;
729 }
730
731 if fails > 0 {
732 error!("Expected a non revert with new image");
733 }
734
735 fails > 0
736 }
737
David Vincze2d736ad2019-02-18 11:50:22 +0100738 // Tests a new image written to the primary slot that already has magic and
739 // image_ok set while there is no image on the secondary slot, so no revert
740 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700741 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700742 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700743 let mut fails = 0;
744
745 info!("Try upgrade image with bad signature");
746
David Brown84b49f72019-03-01 10:58:22 -0700747 self.mark_upgrades(&mut flash, 0);
748 self.mark_permanent_upgrades(&mut flash, 0);
749 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700750
David Brown84b49f72019-03-01 10:58:22 -0700751 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
752 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100753 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700754 fails += 1;
755 }
756
757 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700758 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700759 if result != 0 {
760 warn!("Failed first boot");
761 fails += 1;
762 }
763
764 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700765 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700766 warn!("Failed image verification");
767 fails += 1;
768 }
David Brown84b49f72019-03-01 10:58:22 -0700769 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
770 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100771 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700772 fails += 1;
773 }
774
775 if fails > 0 {
776 error!("Expected an upgrade failure when image has bad signature");
777 }
778
779 fails > 0
780 }
781
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300782 // Should detect there is a leftover trailer in an otherwise erased
783 // secondary slot and erase its trailer.
784 pub fn run_secondary_leftover_trailer(&self) -> bool {
785 let mut flash = self.flash.clone();
786 let mut fails = 0;
787
788 info!("Try with a leftover trailer in the secondary; must be erased");
789
790 // Add a trailer on the secondary slot
791 self.mark_permanent_upgrades(&mut flash, 1);
792 self.mark_upgrades(&mut flash, 1);
793
794 // Run the bootloader...
795 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
796 if result != 0 {
797 warn!("Failed first boot");
798 fails += 1;
799 }
800
801 // State should not have changed
802 if !self.verify_images(&flash, 0, 0) {
803 warn!("Failed image verification");
804 fails += 1;
805 }
806 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
807 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
808 warn!("Mismatched trailer for the secondary slot");
809 fails += 1;
810 }
811
812 if fails > 0 {
813 error!("Expected trailer on secondary slot to be erased");
814 }
815
816 fails > 0
817 }
818
David Brown5c9e0f12019-01-09 16:34:33 -0700819 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300820 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700821 }
822
David Brown5c9e0f12019-01-09 16:34:33 -0700823 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300824 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700825 }
826
827 /// This test runs a simple upgrade with no fails in the images, but
828 /// allowing for fails in the status area. This should run to the end
829 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700830 pub fn run_with_status_fails_complete(&self) -> bool {
David Vincze2d736ad2019-02-18 11:50:22 +0100831 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700832 return false;
833 }
834
David Brown76101572019-02-28 11:29:03 -0700835 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700836 let mut fails = 0;
837
838 info!("Try swap with status fails");
839
David Brown84b49f72019-03-01 10:58:22 -0700840 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700841 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700842
David Brown76101572019-02-28 11:29:03 -0700843 let (result, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown5c9e0f12019-01-09 16:34:33 -0700844 if result != 0 {
845 warn!("Failed!");
846 fails += 1;
847 }
848
849 // Failed writes to the marked "bad" region don't assert anymore.
850 // Any detected assert() is happening in another part of the code.
851 if asserts != 0 {
852 warn!("At least one assert() was called");
853 fails += 1;
854 }
855
David Brown84b49f72019-03-01 10:58:22 -0700856 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
857 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100858 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700859 fails += 1;
860 }
861
David Brown84b49f72019-03-01 10:58:22 -0700862 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700863 warn!("Failed image verification");
864 fails += 1;
865 }
866
David Vincze2d736ad2019-02-18 11:50:22 +0100867 info!("validate primary slot enabled; \
868 re-run of boot_go should just work");
David Brown76101572019-02-28 11:29:03 -0700869 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700870 if result != 0 {
871 warn!("Failed!");
872 fails += 1;
873 }
874
875 if fails > 0 {
876 error!("Error running upgrade with status write fails");
877 }
878
879 fails > 0
880 }
881
882 /// This test runs a simple upgrade with no fails in the images, but
883 /// allowing for fails in the status area. This should run to the end
884 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700885 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown85904a82019-01-11 13:45:12 -0700886 if Caps::OverwriteUpgrade.present() {
887 false
David Vincze2d736ad2019-02-18 11:50:22 +0100888 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700889
David Brown76101572019-02-28 11:29:03 -0700890 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700891 let mut fails = 0;
892 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700893
David Brown85904a82019-01-11 13:45:12 -0700894 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700895
David Brown85904a82019-01-11 13:45:12 -0700896 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700897
David Brown84b49f72019-03-01 10:58:22 -0700898 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700899 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700900
901 // Should not fail, writing to bad regions does not assert
David Brown76101572019-02-28 11:29:03 -0700902 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true);
David Brown85904a82019-01-11 13:45:12 -0700903 if asserts != 0 {
904 warn!("At least one assert() was called");
905 fails += 1;
906 }
907
David Brown76101572019-02-28 11:29:03 -0700908 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700909
910 info!("Resuming an interrupted swap operation");
David Brown76101572019-02-28 11:29:03 -0700911 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700912
913 // This might throw no asserts, for large sector devices, where
914 // a single failure writing is indistinguishable from no failure,
915 // or throw a single assert for small sector devices that fail
916 // multiple times...
917 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100918 warn!("Expected single assert validating the primary slot, \
919 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700920 fails += 1;
921 }
922
923 if fails > 0 {
924 error!("Error running upgrade with status write fails");
925 }
926
927 fails > 0
928 } else {
David Brown76101572019-02-28 11:29:03 -0700929 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700930 let mut fails = 0;
931
932 info!("Try interrupted swap with status fails");
933
David Brown84b49f72019-03-01 10:58:22 -0700934 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700935 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700936
937 // This is expected to fail while writing to bad regions...
David Brown76101572019-02-28 11:29:03 -0700938 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700939 if asserts == 0 {
940 warn!("No assert() detected");
941 fails += 1;
942 }
943
944 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700945 }
David Brown5c9e0f12019-01-09 16:34:33 -0700946 }
947
948 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -0700949 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -0700950 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -0700951 if Caps::OverwriteUpgrade.present() {
952 return;
953 }
954
David Brown84b49f72019-03-01 10:58:22 -0700955 // Set this for each image.
956 for image in &self.images {
957 let dev_id = &image.slots[slot].dev_id;
958 let dev = flash.get_mut(&dev_id).unwrap();
959 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -0700960 let off = &image.slots[slot].base_off;
961 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -0700962 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -0700963
David Brown84b49f72019-03-01 10:58:22 -0700964 // Mark the status area as a bad area
965 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
966 }
David Brown5c9e0f12019-01-09 16:34:33 -0700967 }
968
David Brown76101572019-02-28 11:29:03 -0700969 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +0100970 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700971 return;
972 }
973
David Brown84b49f72019-03-01 10:58:22 -0700974 for image in &self.images {
975 let dev_id = &image.slots[slot].dev_id;
976 let dev = flash.get_mut(&dev_id).unwrap();
977 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -0700978
David Brown84b49f72019-03-01 10:58:22 -0700979 // Disabling write verification the only assert triggered by
980 // boot_go should be checking for integrity of status bytes.
981 dev.set_verify_writes(false);
982 }
David Brown5c9e0f12019-01-09 16:34:33 -0700983 }
984
David Browndb505822019-03-01 10:04:20 -0700985 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
986 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -0300987 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -0700988 // Clone the flash to have a new copy.
989 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700990
Fabio Utziged4a5362019-07-30 12:43:23 -0300991 if permanent {
992 self.mark_permanent_upgrades(&mut flash, 1);
993 }
David Brown5c9e0f12019-01-09 16:34:33 -0700994
David Browndb505822019-03-01 10:04:20 -0700995 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -0700996
David Browndb505822019-03-01 10:04:20 -0700997 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
998 (-0x13579, _) => (true, stop.unwrap()),
999 (0, _) => (false, -counter),
1000 (x, _) => panic!("Unknown return: {}", x),
1001 };
David Brown5c9e0f12019-01-09 16:34:33 -07001002
David Browndb505822019-03-01 10:04:20 -07001003 counter = 0;
1004 if first_interrupted {
1005 // fl.dump();
1006 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
1007 (-0x13579, _) => panic!("Shouldn't stop again"),
1008 (0, _) => (),
1009 (x, _) => panic!("Unknown return: {}", x),
1010 }
1011 }
David Brown5c9e0f12019-01-09 16:34:33 -07001012
David Browndb505822019-03-01 10:04:20 -07001013 (flash, count - counter)
1014 }
1015
1016 fn try_revert(&self, count: usize) -> SimMultiFlash {
1017 let mut flash = self.flash.clone();
1018
1019 // fl.write_file("image0.bin").unwrap();
1020 for i in 0 .. count {
1021 info!("Running boot pass {}", i + 1);
1022 assert_eq!(c::boot_go(&mut flash, &self.areadesc, None, false), (0, 0));
1023 }
1024 flash
1025 }
1026
1027 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1028 let mut flash = self.flash.clone();
1029 let mut fails = 0;
1030
1031 let mut counter = stop;
1032 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
1033 if x != -0x13579 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001034 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001035 fails += 1;
1036 }
1037
Fabio Utzig8af7f792019-07-30 12:40:01 -03001038 // In a multi-image setup, copy done might be set if any number of
1039 // images was already successfully swapped.
1040 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1041 warn!("copy_done should be unset");
1042 fails += 1;
1043 }
1044
David Browndb505822019-03-01 10:04:20 -07001045 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
1046 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001047 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001048 fails += 1;
1049 }
1050
David Brown84b49f72019-03-01 10:58:22 -07001051 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001052 warn!("Image in the primary slot before revert is invalid at stop={}",
1053 stop);
1054 fails += 1;
1055 }
David Brown84b49f72019-03-01 10:58:22 -07001056 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001057 warn!("Image in the secondary slot before revert is invalid at stop={}",
1058 stop);
1059 fails += 1;
1060 }
David Brown84b49f72019-03-01 10:58:22 -07001061 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1062 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001063 warn!("Mismatched trailer for the primary slot before revert");
1064 fails += 1;
1065 }
David Brown84b49f72019-03-01 10:58:22 -07001066 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1067 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001068 warn!("Mismatched trailer for the secondary slot before revert");
1069 fails += 1;
1070 }
1071
1072 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001073 let mut counter = stop;
1074 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
1075 if x != -0x13579 {
1076 warn!("Should have stopped revert at interruption point");
1077 fails += 1;
1078 }
1079
David Browndb505822019-03-01 10:04:20 -07001080 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
1081 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001082 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001083 fails += 1;
1084 }
1085
David Brown84b49f72019-03-01 10:58:22 -07001086 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001087 warn!("Image in the primary slot after revert is invalid at stop={}",
1088 stop);
1089 fails += 1;
1090 }
David Brown84b49f72019-03-01 10:58:22 -07001091 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001092 warn!("Image in the secondary slot after revert is invalid at stop={}",
1093 stop);
1094 fails += 1;
1095 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001096
David Brown84b49f72019-03-01 10:58:22 -07001097 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1098 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001099 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001100 fails += 1;
1101 }
David Brown84b49f72019-03-01 10:58:22 -07001102 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1103 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001104 warn!("Mismatched trailer for the secondary slot after revert");
1105 fails += 1;
1106 }
1107
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001108 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
1109 if x != 0 {
1110 warn!("Should have finished 3rd boot");
1111 fails += 1;
1112 }
1113
1114 if !self.verify_images(&flash, 0, 0) {
1115 warn!("Image in the primary slot is invalid on 1st boot after revert");
1116 fails += 1;
1117 }
1118 if !self.verify_images(&flash, 1, 1) {
1119 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1120 fails += 1;
1121 }
1122
David Browndb505822019-03-01 10:04:20 -07001123 fails > 0
1124 }
1125
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001126
David Browndb505822019-03-01 10:04:20 -07001127 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1128 let mut flash = self.flash.clone();
1129
David Brown84b49f72019-03-01 10:58:22 -07001130 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001131
1132 let mut rng = rand::thread_rng();
1133 let mut resets = vec![0i32; count];
1134 let mut remaining_ops = total_ops;
1135 for i in 0 .. count {
David Browncd842842020-07-09 15:46:53 -06001136 let reset_counter = rng.gen_range(1, remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001137 let mut counter = reset_counter;
1138 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
1139 (0, _) | (-0x13579, _) => (),
1140 (x, _) => panic!("Unknown return: {}", x),
1141 }
1142 remaining_ops -= reset_counter;
1143 resets[i] = reset_counter;
1144 }
1145
1146 match c::boot_go(&mut flash, &self.areadesc, None, false) {
1147 (-0x13579, _) => panic!("Should not be have been interrupted!"),
David Brown5c9e0f12019-01-09 16:34:33 -07001148 (0, _) => (),
1149 (x, _) => panic!("Unknown return: {}", x),
1150 }
David Brown5c9e0f12019-01-09 16:34:33 -07001151
David Browndb505822019-03-01 10:04:20 -07001152 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001153 }
David Brown84b49f72019-03-01 10:58:22 -07001154
1155 /// Verify the image in the given flash device, the specified slot
1156 /// against the expected image.
1157 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001158 self.images.iter().all(|image| {
1159 verify_image(flash, &image.slots[slot],
1160 match against {
1161 0 => &image.primaries,
1162 1 => &image.upgrades,
1163 _ => panic!("Invalid 'against'")
1164 })
1165 })
David Brown84b49f72019-03-01 10:58:22 -07001166 }
1167
David Brownc3898d62019-08-05 14:20:02 -06001168 /// Verify the images, according to the dependency test.
1169 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1170 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1171 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1172 if !verify_image(flash, &image.slots[0],
1173 match upgrade {
1174 UpgradeInfo::Upgraded => &image.upgrades,
1175 UpgradeInfo::Held => &image.primaries,
1176 }) {
1177 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1178 return true;
1179 }
1180 }
1181
1182 false
1183 }
1184
Fabio Utzig8af7f792019-07-30 12:40:01 -03001185 /// Verify that at least one of the trailers of the images have the
1186 /// specified values.
1187 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1188 magic: Option<u8>, image_ok: Option<u8>,
1189 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001190 self.images.iter().any(|image| {
1191 verify_trailer(flash, &image.slots[slot],
1192 magic, image_ok, copy_done)
1193 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001194 }
1195
David Brown84b49f72019-03-01 10:58:22 -07001196 /// Verify that the trailers of the images have the specified
1197 /// values.
1198 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1199 magic: Option<u8>, image_ok: Option<u8>,
1200 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001201 self.images.iter().all(|image| {
1202 verify_trailer(flash, &image.slots[slot],
1203 magic, image_ok, copy_done)
1204 })
David Brown84b49f72019-03-01 10:58:22 -07001205 }
1206
1207 /// Mark each of the images for permanent upgrade.
1208 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1209 for image in &self.images {
1210 mark_permanent_upgrade(flash, &image.slots[slot]);
1211 }
1212 }
1213
1214 /// Mark each of the images for permanent upgrade.
1215 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1216 for image in &self.images {
1217 mark_upgrade(flash, &image.slots[slot]);
1218 }
1219 }
David Brown297029a2019-08-13 14:29:51 -06001220
1221 /// Dump out the flash image(s) to one or more files for debugging
1222 /// purposes. The names will be written as either "{prefix}.mcubin" or
1223 /// "{prefix}-001.mcubin" depending on how many images there are.
1224 pub fn debug_dump(&self, prefix: &str) {
1225 for (id, fdev) in &self.flash {
1226 let name = if self.flash.len() == 1 {
1227 format!("{}.mcubin", prefix)
1228 } else {
1229 format!("{}-{:>0}.mcubin", prefix, id)
1230 };
1231 fdev.write_file(&name).unwrap();
1232 }
1233 }
David Brown5c9e0f12019-01-09 16:34:33 -07001234}
1235
1236/// Show the flash layout.
1237#[allow(dead_code)]
1238fn show_flash(flash: &dyn Flash) {
1239 println!("---- Flash configuration ----");
1240 for sector in flash.sector_iter() {
1241 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1242 sector.num, sector.base, sector.size);
1243 }
1244 println!("");
1245}
1246
1247/// Install a "program" into the given image. This fakes the image header, or at least all of the
1248/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001249fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownc3898d62019-08-05 14:20:02 -06001250 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001251 let offset = slot.base_off;
1252 let slot_len = slot.len;
1253 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001254
David Brown43643dd2019-01-11 15:43:28 -07001255 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001256
David Brownc3898d62019-08-05 14:20:02 -06001257 // Add the dependencies early to the tlv.
1258 for dep in deps.my_deps(offset, slot.index) {
1259 tlv.add_dependency(deps.other_id(), &dep);
1260 }
1261
David Brown5c9e0f12019-01-09 16:34:33 -07001262 const HDR_SIZE: usize = 32;
1263
1264 // Generate a boot header. Note that the size doesn't include the header.
1265 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001266 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -07001267 load_addr: 0,
1268 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001269 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001270 img_size: len as u32,
1271 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001272 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001273 _pad2: 0,
1274 };
1275
1276 let mut b_header = [0; HDR_SIZE];
1277 b_header[..32].clone_from_slice(header.as_raw());
1278 assert_eq!(b_header.len(), HDR_SIZE);
1279
1280 tlv.add_bytes(&b_header);
1281
1282 // The core of the image itself is just pseudorandom data.
1283 let mut b_img = vec![0; len];
1284 splat(&mut b_img, offset);
1285
David Browncb47dd72019-08-05 14:21:49 -06001286 // Add some information at the start of the payload to make it easier
1287 // to see what it is. This will fail if the image itself is too small.
1288 {
1289 let mut wr = Cursor::new(&mut b_img);
1290 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1291 offset, dev_id, slot).unwrap();
1292 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1293 }
1294
David Brown5c9e0f12019-01-09 16:34:33 -07001295 // TLV signatures work over plain image
1296 tlv.add_bytes(&b_img);
1297
1298 // Generate encrypted images
1299 let flag = TlvFlags::ENCRYPTED as u32;
1300 let is_encrypted = (tlv.get_flags() & flag) == flag;
1301 let mut b_encimg = vec![];
1302 if is_encrypted {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001303 tlv.generate_enc_key();
1304 let enc_key = tlv.get_enc_key();
1305 let key = GenericArray::from_slice(enc_key.as_slice());
David Brown5c9e0f12019-01-09 16:34:33 -07001306 let nonce = GenericArray::from_slice(&[0; 16]);
1307 let mut cipher = Aes128Ctr::new(&key, &nonce);
1308 b_encimg = b_img.clone();
1309 cipher.apply_keystream(&mut b_encimg);
1310 }
1311
1312 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001313 if bad_sig {
1314 tlv.corrupt_sig();
1315 }
1316 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001317
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001318 let dev = flash.get_mut(&dev_id).unwrap();
1319
David Brown5c9e0f12019-01-09 16:34:33 -07001320 let mut buf = vec![];
1321 buf.append(&mut b_header.to_vec());
1322 buf.append(&mut b_img);
1323 buf.append(&mut b_tlv.clone());
1324
David Brown95de4502019-11-15 12:01:34 -07001325 // Pad the buffer to a multiple of the flash alignment.
1326 let align = dev.align();
1327 while buf.len() % align != 0 {
1328 buf.push(dev.erased_val());
1329 }
1330
David Brown5c9e0f12019-01-09 16:34:33 -07001331 let mut encbuf = vec![];
1332 if is_encrypted {
1333 encbuf.append(&mut b_header.to_vec());
1334 encbuf.append(&mut b_encimg);
1335 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001336
1337 while encbuf.len() % align != 0 {
1338 encbuf.push(dev.erased_val());
1339 }
David Brown5c9e0f12019-01-09 16:34:33 -07001340 }
1341
David Vincze2d736ad2019-02-18 11:50:22 +01001342 // Since images are always non-encrypted in the primary slot, we first write
1343 // an encrypted image, re-read to use for verification, erase + flash
1344 // un-encrypted. In the secondary slot the image is written un-encrypted,
1345 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001346
David Brown3b090212019-07-30 15:59:28 -06001347 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001348 let enc_copy: Option<Vec<u8>>;
1349
1350 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001351 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001352
1353 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001354 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001355
1356 enc_copy = Some(enc);
1357
David Brown76101572019-02-28 11:29:03 -07001358 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001359 } else {
1360 enc_copy = None;
1361 }
1362
David Brown76101572019-02-28 11:29:03 -07001363 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001364
1365 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001366 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001367
David Brownca234692019-02-28 11:22:19 -07001368 ImageData {
1369 plain: copy,
1370 cipher: enc_copy,
1371 }
David Brown5c9e0f12019-01-09 16:34:33 -07001372 } else {
1373
David Brown76101572019-02-28 11:29:03 -07001374 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001375
1376 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001377 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001378
1379 let enc_copy: Option<Vec<u8>>;
1380
1381 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001382 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001383
David Brown76101572019-02-28 11:29:03 -07001384 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001385
1386 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001387 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001388
1389 enc_copy = Some(enc);
1390 } else {
1391 enc_copy = None;
1392 }
1393
David Brownca234692019-02-28 11:22:19 -07001394 ImageData {
1395 plain: copy,
1396 cipher: enc_copy,
1397 }
David Brown5c9e0f12019-01-09 16:34:33 -07001398 }
David Brown5c9e0f12019-01-09 16:34:33 -07001399}
1400
David Brown873be312019-09-03 12:22:32 -06001401/// Install no image. This is used when no upgrade happens.
1402fn install_no_image() -> ImageData {
1403 ImageData {
1404 plain: vec![],
1405 cipher: None,
1406 }
1407}
1408
David Brown5c9e0f12019-01-09 16:34:33 -07001409fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001410 if Caps::EcdsaP224.present() {
1411 panic!("Ecdsa P224 not supported in Simulator");
1412 }
David Brown5c9e0f12019-01-09 16:34:33 -07001413
David Brownb8882112019-01-11 14:04:11 -07001414 if Caps::EncKw.present() {
1415 if Caps::RSA2048.present() {
1416 TlvGen::new_rsa_kw()
1417 } else if Caps::EcdsaP256.present() {
1418 TlvGen::new_ecdsa_kw()
1419 } else {
1420 TlvGen::new_enc_kw()
1421 }
1422 } else if Caps::EncRsa.present() {
1423 if Caps::RSA2048.present() {
1424 TlvGen::new_sig_enc_rsa()
1425 } else {
1426 TlvGen::new_enc_rsa()
1427 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001428 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001429 if Caps::EcdsaP256.present() {
1430 TlvGen::new_ecdsa_ecies_p256()
1431 } else {
1432 TlvGen::new_ecies_p256()
1433 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001434 } else if Caps::EncX25519.present() {
1435 if Caps::Ed25519.present() {
1436 TlvGen::new_ed25519_ecies_x25519()
1437 } else {
1438 TlvGen::new_ecies_x25519()
1439 }
David Brownb8882112019-01-11 14:04:11 -07001440 } else {
1441 // The non-encrypted configuration.
1442 if Caps::RSA2048.present() {
1443 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001444 } else if Caps::RSA3072.present() {
1445 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001446 } else if Caps::EcdsaP256.present() {
1447 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001448 } else if Caps::Ed25519.present() {
1449 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001450 } else {
1451 TlvGen::new_hash_only()
1452 }
1453 }
David Brown5c9e0f12019-01-09 16:34:33 -07001454}
1455
David Brownca234692019-02-28 11:22:19 -07001456impl ImageData {
1457 /// Find the image contents for the given slot. This assumes that slot 0
1458 /// is unencrypted, and slot 1 is encrypted.
1459 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001460 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001461 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001462 match (encrypted, slot) {
1463 (false, _) => &self.plain,
1464 (true, 0) => &self.plain,
1465 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1466 _ => panic!("Invalid slot requested"),
1467 }
David Brown5c9e0f12019-01-09 16:34:33 -07001468 }
1469}
1470
David Brown5c9e0f12019-01-09 16:34:33 -07001471/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001472fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1473 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001474 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001475 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001476
1477 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001478 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001479 let dev = flash.get(&dev_id).unwrap();
1480 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001481
1482 if buf != &copy[..] {
1483 for i in 0 .. buf.len() {
1484 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001485 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1486 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001487 break;
1488 }
1489 }
1490 false
1491 } else {
1492 true
1493 }
1494}
1495
David Brown3b090212019-07-30 15:59:28 -06001496fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001497 magic: Option<u8>, image_ok: Option<u8>,
1498 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001499 if Caps::OverwriteUpgrade.present() {
1500 return true;
1501 }
David Brown5c9e0f12019-01-09 16:34:33 -07001502
David Brown3b090212019-07-30 15:59:28 -06001503 let offset = slot.trailer_off + c::boot_max_align();
1504 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001505 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001506 let mut failed = false;
1507
David Brown76101572019-02-28 11:29:03 -07001508 let dev = flash.get(&dev_id).unwrap();
1509 let erased_val = dev.erased_val();
1510 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001511
1512 failed |= match magic {
1513 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001514 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001515 warn!("\"magic\" mismatch at {:#x}", offset);
1516 true
1517 } else if v == 3 {
1518 let expected = [erased_val; 16];
Christopher Collinsa1c12042019-05-23 14:00:28 -07001519 if &copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001520 warn!("\"magic\" mismatch at {:#x}", offset);
1521 true
1522 } else {
1523 false
1524 }
1525 } else {
1526 false
1527 }
1528 },
1529 None => false,
1530 };
1531
1532 failed |= match image_ok {
1533 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001534 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001535 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1536 true
1537 } else {
1538 false
1539 }
1540 },
1541 None => false,
1542 };
1543
1544 failed |= match copy_done {
1545 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001546 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001547 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1548 true
1549 } else {
1550 false
1551 }
1552 },
1553 None => false,
1554 };
1555
1556 !failed
1557}
1558
David Brown297029a2019-08-13 14:29:51 -06001559/// Install a partition table. This is a simplified partition table that
1560/// we write at the beginning of flash so make it easier for external tools
1561/// to analyze these images.
1562fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1563 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1564 for &id in &ids {
1565 // If there are any partitions in this device that start at 0, and
1566 // aren't marked as the BootLoader partition, avoid adding the
1567 // partition table. This makes it harder to view the image, but
1568 // avoids messing up images already written.
1569 if areadesc.iter_areas().any(|area| {
1570 area.device_id == id &&
1571 area.off == 0 &&
1572 area.flash_id != FlashId::BootLoader
1573 }) {
1574 if log_enabled!(Info) {
1575 let special: Vec<FlashId> = areadesc.iter_areas()
1576 .filter(|area| area.device_id == id && area.off == 0)
1577 .map(|area| area.flash_id)
1578 .collect();
1579 info!("Skipping partition table: {:?}", special);
1580 }
1581 break;
1582 }
1583
1584 let mut buf: Vec<u8> = vec![];
1585 write!(&mut buf, "mcuboot\0").unwrap();
1586
1587 // Iterate through all of the partitions in that device, and encode
1588 // into the table.
1589 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1590 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1591
1592 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1593 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1594 buf.write_u32::<LittleEndian>(area.off).unwrap();
1595 buf.write_u32::<LittleEndian>(area.size).unwrap();
1596 buf.write_u32::<LittleEndian>(0).unwrap();
1597 }
1598
1599 let dev = flash.get_mut(&id).unwrap();
1600
1601 // Pad to alignment.
1602 while buf.len() % dev.align() != 0 {
1603 buf.push(0);
1604 }
1605
1606 dev.write(0, &buf).unwrap();
1607 }
1608}
1609
David Brown5c9e0f12019-01-09 16:34:33 -07001610/// The image header
1611#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001612#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001613pub struct ImageHeader {
1614 magic: u32,
1615 load_addr: u32,
1616 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001617 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001618 img_size: u32,
1619 flags: u32,
1620 ver: ImageVersion,
1621 _pad2: u32,
1622}
1623
1624impl AsRaw for ImageHeader {}
1625
1626#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001627#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001628pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001629 pub major: u8,
1630 pub minor: u8,
1631 pub revision: u16,
1632 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001633}
1634
David Brownc3898d62019-08-05 14:20:02 -06001635#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001636pub struct SlotInfo {
1637 pub base_off: usize,
1638 pub trailer_off: usize,
1639 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001640 // Which slot within this device.
1641 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001642 pub dev_id: u8,
1643}
1644
David Brown347dc572019-11-15 11:37:25 -07001645const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1646 0x60, 0xd2, 0xef, 0x7f,
1647 0x35, 0x52, 0x50, 0x0f,
1648 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001649
1650// Replicates defines found in bootutil.h
1651const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1652const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1653
1654const BOOT_FLAG_SET: Option<u8> = Some(1);
1655const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1656
1657/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001658pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1659 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001660 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001661 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001662 if offset % align != 0 || MAGIC.len() % align != 0 {
1663 // The write size is larger than the magic value. Fill a buffer
1664 // with the erased value, put the MAGIC in it, and write it in its
1665 // entirety.
1666 let mut buf = vec![dev.erased_val(); align];
1667 buf[(offset % align)..].copy_from_slice(MAGIC);
1668 dev.write(offset - (offset % align), &buf).unwrap();
1669 } else {
1670 dev.write(offset, MAGIC).unwrap();
1671 }
David Brown5c9e0f12019-01-09 16:34:33 -07001672}
1673
1674/// Writes the image_ok flag which, guess what, tells the bootloader
1675/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001676fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001677 // Overwrite mode always is permanent, and only the magic is used in
1678 // the trailer. To avoid problems with large write sizes, don't try to
1679 // set anything in this case.
1680 if Caps::OverwriteUpgrade.present() {
1681 return;
1682 }
1683
David Brown76101572019-02-28 11:29:03 -07001684 let dev = flash.get_mut(&slot.dev_id).unwrap();
1685 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001686 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001687 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001688 let align = dev.align();
1689 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001690}
1691
1692// Drop some pseudo-random gibberish onto the data.
1693fn splat(data: &mut [u8], seed: usize) {
David Browncd842842020-07-09 15:46:53 -06001694 let mut seed_block = [0u8; 16];
1695 let mut buf = Cursor::new(&mut seed_block[..]);
1696 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
1697 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
1698 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
1699 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
1700 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07001701 rng.fill_bytes(data);
1702}
1703
1704/// Return a read-only view into the raw bytes of this object
1705trait AsRaw : Sized {
1706 fn as_raw<'a>(&'a self) -> &'a [u8] {
1707 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1708 mem::size_of::<Self>()) }
1709 }
1710}
1711
1712pub fn show_sizes() {
1713 // This isn't panic safe.
1714 for min in &[1, 2, 4, 8] {
1715 let msize = c::boot_trailer_sz(*min);
1716 println!("{:2}: {} (0x{:x})", min, msize, msize);
1717 }
1718}
David Brown95de4502019-11-15 12:01:34 -07001719
1720#[cfg(not(feature = "large-write"))]
1721fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001722 &[1, 2, 4, 8]
1723}
1724
1725#[cfg(feature = "large-write")]
1726fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001727 &[1, 2, 4, 8, 128, 512]
1728}