blob: e9865e4367f48c3c455eb9d09378e23fcb6f9ab8 [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 Brown76101572019-02-28 11:29:03 -0700152 flash: flash,
David Browne5133242019-02-28 11:05:19 -0700153 areadesc: areadesc,
David Brown06ef06e2019-03-05 12:28:10 -0700154 slots: 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 {
189 slots: slots,
190 primaries: primaries,
191 upgrades: upgrades,
192 }}).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 Brown76101572019-02-28 11:29:03 -0700195 flash: flash,
David Browne5133242019-02-28 11:05:19 -0700196 areadesc: self.areadesc,
David Brown84b49f72019-03-01 10:58:22 -0700197 images: 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 Browne5133242019-02-28 11:05:19 -0700210 Ok(v) => v,
Fabio Utzig7c1d1552019-08-28 10:59:22 -0300211 Err(_) =>
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 {
230 slots: slots,
231 primaries: primaries,
232 upgrades: upgrades,
233 }}).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 Brown84b49f72019-03-01 10:58:22 -0700237 images: 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 {
249 slots: slots,
250 primaries: primaries,
251 upgrades: upgrades,
252 }}).collect();
253 Images {
254 flash: flash,
255 areadesc: self.areadesc,
256 images: images,
257 total_count: None,
258 }
259 }
260
David Browne5133242019-02-28 11:05:19 -0700261 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300262 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700263 match device {
264 DeviceName::Stm32f4 => {
265 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700266 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
267 64 * 1024,
268 128 * 1024, 128 * 1024, 128 * 1024],
269 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700270 let dev_id = 0;
271 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700272 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700273 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
274 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
275 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
276
David Brown76101572019-02-28 11:29:03 -0700277 let mut flash = SimMultiFlash::new();
278 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300279 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700280 }
281 DeviceName::K64f => {
282 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700283 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700284
285 let dev_id = 0;
286 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700287 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700288 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
289 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
290 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
291
David Brown76101572019-02-28 11:29:03 -0700292 let mut flash = SimMultiFlash::new();
293 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300294 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700295 }
296 DeviceName::K64fBig => {
297 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
298 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700299 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700300
301 let dev_id = 0;
302 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700303 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700304 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
305 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
306 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
307
David Brown76101572019-02-28 11:29:03 -0700308 let mut flash = SimMultiFlash::new();
309 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300310 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700311 }
312 DeviceName::Nrf52840 => {
313 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
314 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700315 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700316
317 let dev_id = 0;
318 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700319 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700320 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
321 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
322 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
323
David Brown76101572019-02-28 11:29:03 -0700324 let mut flash = SimMultiFlash::new();
325 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300326 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700327 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300328 DeviceName::Nrf52840UnequalSlots => {
329 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
330
331 let dev_id = 0;
332 let mut areadesc = AreaDesc::new();
333 areadesc.add_flash_sectors(dev_id, &dev);
334 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
335 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
336
337 let mut flash = SimMultiFlash::new();
338 flash.insert(dev_id, dev);
339 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
340 }
David Browne5133242019-02-28 11:05:19 -0700341 DeviceName::Nrf52840SpiFlash => {
342 // Simulate nrf52840 with external SPI flash. The external SPI flash
343 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700344 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
345 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700346
347 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700348 areadesc.add_flash_sectors(0, &dev0);
349 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700350
351 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
352 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
353 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
354
David Brown76101572019-02-28 11:29:03 -0700355 let mut flash = SimMultiFlash::new();
356 flash.insert(0, dev0);
357 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300358 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700359 }
David Brown2bff6472019-03-05 13:58:35 -0700360 DeviceName::K64fMulti => {
361 // NXP style flash, but larger, to support multiple images.
362 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
363
364 let dev_id = 0;
365 let mut areadesc = AreaDesc::new();
366 areadesc.add_flash_sectors(dev_id, &dev);
367 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
368 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
369 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
370 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
371 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
372
373 let mut flash = SimMultiFlash::new();
374 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300375 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700376 }
David Browne5133242019-02-28 11:05:19 -0700377 }
378 }
David Brownc3898d62019-08-05 14:20:02 -0600379
380 pub fn num_images(&self) -> usize {
381 self.slots.len()
382 }
David Browne5133242019-02-28 11:05:19 -0700383}
384
David Brown5c9e0f12019-01-09 16:34:33 -0700385impl Images {
386 /// A simple upgrade without forced failures.
387 ///
388 /// Returns the number of flash operations which can later be used to
389 /// inject failures at chosen steps.
Fabio Utziged4a5362019-07-30 12:43:23 -0300390 pub fn run_basic_upgrade(&self, permanent: bool) -> Result<i32, ()> {
391 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700392 info!("Total flash operation count={}", total_count);
393
David Brown84b49f72019-03-01 10:58:22 -0700394 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700395 warn!("Image mismatch after first boot");
396 Err(())
397 } else {
398 Ok(total_count)
399 }
400 }
401
David Brownc3898d62019-08-05 14:20:02 -0600402 /// Test a simple upgrade, with dependencies given, and verify that the
403 /// image does as is described in the test.
404 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
405 let (flash, _) = self.try_upgrade(None, true);
406
407 self.verify_dep_images(&flash, deps)
408 }
409
Fabio Utzigf5480c72019-11-28 10:41:57 -0300410 fn is_swap_upgrade(&self) -> bool {
411 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
412 }
413
David Brown5c9e0f12019-01-09 16:34:33 -0700414 pub fn run_basic_revert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700415 if Caps::OverwriteUpgrade.present() {
416 return false;
417 }
David Brown5c9e0f12019-01-09 16:34:33 -0700418
David Brown5c9e0f12019-01-09 16:34:33 -0700419 let mut fails = 0;
420
421 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300422 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700423 for count in 2 .. 5 {
424 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700425 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700426 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700427 error!("Revert failure on count {}", count);
428 fails += 1;
429 }
430 }
431 }
432
433 fails > 0
434 }
435
436 pub fn run_perm_with_fails(&self) -> bool {
437 let mut fails = 0;
438 let total_flash_ops = self.total_count.unwrap();
439
440 // Let's try an image halfway through.
441 for i in 1 .. total_flash_ops {
442 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300443 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700444 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700445 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700446 warn!("FAIL at step {} of {}", i, total_flash_ops);
447 fails += 1;
448 }
449
David Brown84b49f72019-03-01 10:58:22 -0700450 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
451 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100452 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700453 fails += 1;
454 }
455
David Brown84b49f72019-03-01 10:58:22 -0700456 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
457 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100458 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700459 fails += 1;
460 }
461
Fabio Utzigf5480c72019-11-28 10:41:57 -0300462 if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700463 if !self.verify_images(&flash, 1, 0) {
David Vincze2d736ad2019-02-18 11:50:22 +0100464 warn!("Secondary slot FAIL at step {} of {}",
465 i, total_flash_ops);
David Brown5c9e0f12019-01-09 16:34:33 -0700466 fails += 1;
467 }
468 }
469 }
470
471 if fails > 0 {
472 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
473 fails as f32 * 100.0 / total_flash_ops as f32);
474 }
475
476 fails > 0
477 }
478
David Brown5c9e0f12019-01-09 16:34:33 -0700479 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
480 let mut fails = 0;
481 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700482 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700483 info!("Random interruptions at reset points={:?}", total_counts);
484
David Brown84b49f72019-03-01 10:58:22 -0700485 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300486 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700487 // TODO: This result is ignored.
488 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700489 } else {
490 true
491 };
David Vincze2d736ad2019-02-18 11:50:22 +0100492 if !primary_slot_ok || !secondary_slot_ok {
493 error!("Image mismatch after random interrupts: primary slot={} \
494 secondary slot={}",
495 if primary_slot_ok { "ok" } else { "fail" },
496 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700497 fails += 1;
498 }
David Brown84b49f72019-03-01 10:58:22 -0700499 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
500 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100501 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700502 fails += 1;
503 }
David Brown84b49f72019-03-01 10:58:22 -0700504 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
505 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100506 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700507 fails += 1;
508 }
509
510 if fails > 0 {
511 error!("Error testing perm upgrade with {} fails", total_fails);
512 }
513
514 fails > 0
515 }
516
David Brown5c9e0f12019-01-09 16:34:33 -0700517 pub fn run_revert_with_fails(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700518 if Caps::OverwriteUpgrade.present() {
519 return false;
520 }
David Brown5c9e0f12019-01-09 16:34:33 -0700521
David Brown5c9e0f12019-01-09 16:34:33 -0700522 let mut fails = 0;
523
Fabio Utzigf5480c72019-11-28 10:41:57 -0300524 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300525 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700526 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700527 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700528 error!("Revert failed at interruption {}", i);
529 fails += 1;
530 }
531 }
532 }
533
534 fails > 0
535 }
536
David Brown5c9e0f12019-01-09 16:34:33 -0700537 pub fn run_norevert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700538 if Caps::OverwriteUpgrade.present() {
539 return false;
540 }
David Brown5c9e0f12019-01-09 16:34:33 -0700541
David Brown76101572019-02-28 11:29:03 -0700542 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700543 let mut fails = 0;
544
545 info!("Try norevert");
546
547 // First do a normal upgrade...
David Brown76101572019-02-28 11:29:03 -0700548 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700549 if result != 0 {
550 warn!("Failed first boot");
551 fails += 1;
552 }
553
554 //FIXME: copy_done is written by boot_go, is it ok if no copy
555 // was ever done?
556
David Brown84b49f72019-03-01 10:58:22 -0700557 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100558 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700559 fails += 1;
560 }
David Brown84b49f72019-03-01 10:58:22 -0700561 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
562 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100563 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700564 fails += 1;
565 }
David Brown84b49f72019-03-01 10:58:22 -0700566 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
567 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100568 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700569 fails += 1;
570 }
571
David Vincze2d736ad2019-02-18 11:50:22 +0100572 // Marks image in the primary slot as permanent,
573 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700574 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700575
David Brown84b49f72019-03-01 10:58:22 -0700576 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
577 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100578 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700579 fails += 1;
580 }
581
David Brown76101572019-02-28 11:29:03 -0700582 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700583 if result != 0 {
584 warn!("Failed second boot");
585 fails += 1;
586 }
587
David Brown84b49f72019-03-01 10:58:22 -0700588 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
589 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100590 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700591 fails += 1;
592 }
David Brown84b49f72019-03-01 10:58:22 -0700593 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700594 warn!("Failed image verification");
595 fails += 1;
596 }
597
598 if fails > 0 {
599 error!("Error running upgrade without revert");
600 }
601
602 fails > 0
603 }
604
David Brown2ee5f7f2020-01-13 14:04:01 -0700605 // Test that an upgrade is rejected. Assumes that the image was build
606 // such that the upgrade is instead a downgrade.
607 pub fn run_nodowngrade(&self) -> bool {
608 if !Caps::DowngradePrevention.present() {
609 return false;
610 }
611
612 let mut flash = self.flash.clone();
613 let mut fails = 0;
614
615 info!("Try no downgrade");
616
617 // First, do a normal upgrade.
618 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
619 if result != 0 {
620 warn!("Failed first boot");
621 fails += 1;
622 }
623
624 if !self.verify_images(&flash, 0, 0) {
625 warn!("Failed verification after downgrade rejection");
626 fails += 1;
627 }
628
629 if fails > 0 {
630 error!("Error testing downgrade rejection");
631 }
632
633 fails > 0
634 }
635
David Vincze2d736ad2019-02-18 11:50:22 +0100636 // Tests a new image written to the primary slot that already has magic and
637 // image_ok set while there is no image on the secondary slot, so no revert
638 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700639 pub fn run_norevert_newimage(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700640 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700641 let mut fails = 0;
642
643 info!("Try non-revert on imgtool generated image");
644
David Brown84b49f72019-03-01 10:58:22 -0700645 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700646
David Vincze2d736ad2019-02-18 11:50:22 +0100647 // This simulates writing an image created by imgtool to
648 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700649 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
650 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100651 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700652 fails += 1;
653 }
654
655 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700656 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700657 if result != 0 {
658 warn!("Failed first boot");
659 fails += 1;
660 }
661
662 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700663 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700664 warn!("Failed image verification");
665 fails += 1;
666 }
David Brown84b49f72019-03-01 10:58:22 -0700667 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
668 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100669 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700670 fails += 1;
671 }
David Brown84b49f72019-03-01 10:58:22 -0700672 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
673 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100674 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700675 fails += 1;
676 }
677
678 if fails > 0 {
679 error!("Expected a non revert with new image");
680 }
681
682 fails > 0
683 }
684
David Vincze2d736ad2019-02-18 11:50:22 +0100685 // Tests a new image written to the primary slot that already has magic and
686 // image_ok set while there is no image on the secondary slot, so no revert
687 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700688 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700689 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700690 let mut fails = 0;
691
692 info!("Try upgrade image with bad signature");
693
David Brown84b49f72019-03-01 10:58:22 -0700694 self.mark_upgrades(&mut flash, 0);
695 self.mark_permanent_upgrades(&mut flash, 0);
696 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700697
David Brown84b49f72019-03-01 10:58:22 -0700698 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
699 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100700 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700701 fails += 1;
702 }
703
704 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700705 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700706 if result != 0 {
707 warn!("Failed first boot");
708 fails += 1;
709 }
710
711 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700712 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700713 warn!("Failed image verification");
714 fails += 1;
715 }
David Brown84b49f72019-03-01 10:58:22 -0700716 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
717 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100718 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700719 fails += 1;
720 }
721
722 if fails > 0 {
723 error!("Expected an upgrade failure when image has bad signature");
724 }
725
726 fails > 0
727 }
728
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300729 // Should detect there is a leftover trailer in an otherwise erased
730 // secondary slot and erase its trailer.
731 pub fn run_secondary_leftover_trailer(&self) -> bool {
732 let mut flash = self.flash.clone();
733 let mut fails = 0;
734
735 info!("Try with a leftover trailer in the secondary; must be erased");
736
737 // Add a trailer on the secondary slot
738 self.mark_permanent_upgrades(&mut flash, 1);
739 self.mark_upgrades(&mut flash, 1);
740
741 // Run the bootloader...
742 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
743 if result != 0 {
744 warn!("Failed first boot");
745 fails += 1;
746 }
747
748 // State should not have changed
749 if !self.verify_images(&flash, 0, 0) {
750 warn!("Failed image verification");
751 fails += 1;
752 }
753 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
754 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
755 warn!("Mismatched trailer for the secondary slot");
756 fails += 1;
757 }
758
759 if fails > 0 {
760 error!("Expected trailer on secondary slot to be erased");
761 }
762
763 fails > 0
764 }
765
David Brown5c9e0f12019-01-09 16:34:33 -0700766 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300767 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700768 }
769
David Brown5c9e0f12019-01-09 16:34:33 -0700770 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300771 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700772 }
773
774 /// This test runs a simple upgrade with no fails in the images, but
775 /// allowing for fails in the status area. This should run to the end
776 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700777 pub fn run_with_status_fails_complete(&self) -> bool {
David Vincze2d736ad2019-02-18 11:50:22 +0100778 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700779 return false;
780 }
781
David Brown76101572019-02-28 11:29:03 -0700782 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700783 let mut fails = 0;
784
785 info!("Try swap with status fails");
786
David Brown84b49f72019-03-01 10:58:22 -0700787 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700788 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700789
David Brown76101572019-02-28 11:29:03 -0700790 let (result, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown5c9e0f12019-01-09 16:34:33 -0700791 if result != 0 {
792 warn!("Failed!");
793 fails += 1;
794 }
795
796 // Failed writes to the marked "bad" region don't assert anymore.
797 // Any detected assert() is happening in another part of the code.
798 if asserts != 0 {
799 warn!("At least one assert() was called");
800 fails += 1;
801 }
802
David Brown84b49f72019-03-01 10:58:22 -0700803 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
804 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100805 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700806 fails += 1;
807 }
808
David Brown84b49f72019-03-01 10:58:22 -0700809 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700810 warn!("Failed image verification");
811 fails += 1;
812 }
813
David Vincze2d736ad2019-02-18 11:50:22 +0100814 info!("validate primary slot enabled; \
815 re-run of boot_go should just work");
David Brown76101572019-02-28 11:29:03 -0700816 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700817 if result != 0 {
818 warn!("Failed!");
819 fails += 1;
820 }
821
822 if fails > 0 {
823 error!("Error running upgrade with status write fails");
824 }
825
826 fails > 0
827 }
828
829 /// This test runs a simple upgrade with no fails in the images, but
830 /// allowing for fails in the status area. This should run to the end
831 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700832 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown85904a82019-01-11 13:45:12 -0700833 if Caps::OverwriteUpgrade.present() {
834 false
David Vincze2d736ad2019-02-18 11:50:22 +0100835 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700836
David Brown76101572019-02-28 11:29:03 -0700837 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700838 let mut fails = 0;
839 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700840
David Brown85904a82019-01-11 13:45:12 -0700841 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700842
David Brown85904a82019-01-11 13:45:12 -0700843 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700844
David Brown84b49f72019-03-01 10:58:22 -0700845 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700846 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700847
848 // Should not fail, writing to bad regions does not assert
David Brown76101572019-02-28 11:29:03 -0700849 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true);
David Brown85904a82019-01-11 13:45:12 -0700850 if asserts != 0 {
851 warn!("At least one assert() was called");
852 fails += 1;
853 }
854
David Brown76101572019-02-28 11:29:03 -0700855 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700856
857 info!("Resuming an interrupted swap operation");
David Brown76101572019-02-28 11:29:03 -0700858 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700859
860 // This might throw no asserts, for large sector devices, where
861 // a single failure writing is indistinguishable from no failure,
862 // or throw a single assert for small sector devices that fail
863 // multiple times...
864 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100865 warn!("Expected single assert validating the primary slot, \
866 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700867 fails += 1;
868 }
869
870 if fails > 0 {
871 error!("Error running upgrade with status write fails");
872 }
873
874 fails > 0
875 } else {
David Brown76101572019-02-28 11:29:03 -0700876 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700877 let mut fails = 0;
878
879 info!("Try interrupted swap with status fails");
880
David Brown84b49f72019-03-01 10:58:22 -0700881 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700882 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700883
884 // This is expected to fail while writing to bad regions...
David Brown76101572019-02-28 11:29:03 -0700885 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700886 if asserts == 0 {
887 warn!("No assert() detected");
888 fails += 1;
889 }
890
891 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700892 }
David Brown5c9e0f12019-01-09 16:34:33 -0700893 }
894
895 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -0700896 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -0700897 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -0700898 if Caps::OverwriteUpgrade.present() {
899 return;
900 }
901
David Brown84b49f72019-03-01 10:58:22 -0700902 // Set this for each image.
903 for image in &self.images {
904 let dev_id = &image.slots[slot].dev_id;
905 let dev = flash.get_mut(&dev_id).unwrap();
906 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -0700907 let off = &image.slots[slot].base_off;
908 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -0700909 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -0700910
David Brown84b49f72019-03-01 10:58:22 -0700911 // Mark the status area as a bad area
912 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
913 }
David Brown5c9e0f12019-01-09 16:34:33 -0700914 }
915
David Brown76101572019-02-28 11:29:03 -0700916 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +0100917 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700918 return;
919 }
920
David Brown84b49f72019-03-01 10:58:22 -0700921 for image in &self.images {
922 let dev_id = &image.slots[slot].dev_id;
923 let dev = flash.get_mut(&dev_id).unwrap();
924 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -0700925
David Brown84b49f72019-03-01 10:58:22 -0700926 // Disabling write verification the only assert triggered by
927 // boot_go should be checking for integrity of status bytes.
928 dev.set_verify_writes(false);
929 }
David Brown5c9e0f12019-01-09 16:34:33 -0700930 }
931
David Browndb505822019-03-01 10:04:20 -0700932 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
933 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -0300934 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -0700935 // Clone the flash to have a new copy.
936 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700937
Fabio Utziged4a5362019-07-30 12:43:23 -0300938 if permanent {
939 self.mark_permanent_upgrades(&mut flash, 1);
940 }
David Brown5c9e0f12019-01-09 16:34:33 -0700941
David Browndb505822019-03-01 10:04:20 -0700942 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -0700943
David Browndb505822019-03-01 10:04:20 -0700944 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
945 (-0x13579, _) => (true, stop.unwrap()),
946 (0, _) => (false, -counter),
947 (x, _) => panic!("Unknown return: {}", x),
948 };
David Brown5c9e0f12019-01-09 16:34:33 -0700949
David Browndb505822019-03-01 10:04:20 -0700950 counter = 0;
951 if first_interrupted {
952 // fl.dump();
953 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
954 (-0x13579, _) => panic!("Shouldn't stop again"),
955 (0, _) => (),
956 (x, _) => panic!("Unknown return: {}", x),
957 }
958 }
David Brown5c9e0f12019-01-09 16:34:33 -0700959
David Browndb505822019-03-01 10:04:20 -0700960 (flash, count - counter)
961 }
962
963 fn try_revert(&self, count: usize) -> SimMultiFlash {
964 let mut flash = self.flash.clone();
965
966 // fl.write_file("image0.bin").unwrap();
967 for i in 0 .. count {
968 info!("Running boot pass {}", i + 1);
969 assert_eq!(c::boot_go(&mut flash, &self.areadesc, None, false), (0, 0));
970 }
971 flash
972 }
973
974 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
975 let mut flash = self.flash.clone();
976 let mut fails = 0;
977
978 let mut counter = stop;
979 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
980 if x != -0x13579 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700981 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -0700982 fails += 1;
983 }
984
Fabio Utzig8af7f792019-07-30 12:40:01 -0300985 // In a multi-image setup, copy done might be set if any number of
986 // images was already successfully swapped.
987 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
988 warn!("copy_done should be unset");
989 fails += 1;
990 }
991
David Browndb505822019-03-01 10:04:20 -0700992 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
993 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700994 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -0700995 fails += 1;
996 }
997
David Brown84b49f72019-03-01 10:58:22 -0700998 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -0700999 warn!("Image in the primary slot before revert is invalid at stop={}",
1000 stop);
1001 fails += 1;
1002 }
David Brown84b49f72019-03-01 10:58:22 -07001003 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001004 warn!("Image in the secondary slot before revert is invalid at stop={}",
1005 stop);
1006 fails += 1;
1007 }
David Brown84b49f72019-03-01 10:58:22 -07001008 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1009 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001010 warn!("Mismatched trailer for the primary slot before revert");
1011 fails += 1;
1012 }
David Brown84b49f72019-03-01 10:58:22 -07001013 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1014 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001015 warn!("Mismatched trailer for the secondary slot before revert");
1016 fails += 1;
1017 }
1018
1019 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001020 let mut counter = stop;
1021 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
1022 if x != -0x13579 {
1023 warn!("Should have stopped revert at interruption point");
1024 fails += 1;
1025 }
1026
David Browndb505822019-03-01 10:04:20 -07001027 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
1028 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001029 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001030 fails += 1;
1031 }
1032
David Brown84b49f72019-03-01 10:58:22 -07001033 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001034 warn!("Image in the primary slot after revert is invalid at stop={}",
1035 stop);
1036 fails += 1;
1037 }
David Brown84b49f72019-03-01 10:58:22 -07001038 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001039 warn!("Image in the secondary slot after revert is invalid at stop={}",
1040 stop);
1041 fails += 1;
1042 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001043
David Brown84b49f72019-03-01 10:58:22 -07001044 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1045 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001046 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001047 fails += 1;
1048 }
David Brown84b49f72019-03-01 10:58:22 -07001049 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1050 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001051 warn!("Mismatched trailer for the secondary slot after revert");
1052 fails += 1;
1053 }
1054
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001055 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
1056 if x != 0 {
1057 warn!("Should have finished 3rd boot");
1058 fails += 1;
1059 }
1060
1061 if !self.verify_images(&flash, 0, 0) {
1062 warn!("Image in the primary slot is invalid on 1st boot after revert");
1063 fails += 1;
1064 }
1065 if !self.verify_images(&flash, 1, 1) {
1066 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1067 fails += 1;
1068 }
1069
David Browndb505822019-03-01 10:04:20 -07001070 fails > 0
1071 }
1072
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001073
David Browndb505822019-03-01 10:04:20 -07001074 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1075 let mut flash = self.flash.clone();
1076
David Brown84b49f72019-03-01 10:58:22 -07001077 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001078
1079 let mut rng = rand::thread_rng();
1080 let mut resets = vec![0i32; count];
1081 let mut remaining_ops = total_ops;
1082 for i in 0 .. count {
David Browncd842842020-07-09 15:46:53 -06001083 let reset_counter = rng.gen_range(1, remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001084 let mut counter = reset_counter;
1085 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
1086 (0, _) | (-0x13579, _) => (),
1087 (x, _) => panic!("Unknown return: {}", x),
1088 }
1089 remaining_ops -= reset_counter;
1090 resets[i] = reset_counter;
1091 }
1092
1093 match c::boot_go(&mut flash, &self.areadesc, None, false) {
1094 (-0x13579, _) => panic!("Should not be have been interrupted!"),
David Brown5c9e0f12019-01-09 16:34:33 -07001095 (0, _) => (),
1096 (x, _) => panic!("Unknown return: {}", x),
1097 }
David Brown5c9e0f12019-01-09 16:34:33 -07001098
David Browndb505822019-03-01 10:04:20 -07001099 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001100 }
David Brown84b49f72019-03-01 10:58:22 -07001101
1102 /// Verify the image in the given flash device, the specified slot
1103 /// against the expected image.
1104 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001105 self.images.iter().all(|image| {
1106 verify_image(flash, &image.slots[slot],
1107 match against {
1108 0 => &image.primaries,
1109 1 => &image.upgrades,
1110 _ => panic!("Invalid 'against'")
1111 })
1112 })
David Brown84b49f72019-03-01 10:58:22 -07001113 }
1114
David Brownc3898d62019-08-05 14:20:02 -06001115 /// Verify the images, according to the dependency test.
1116 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1117 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1118 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1119 if !verify_image(flash, &image.slots[0],
1120 match upgrade {
1121 UpgradeInfo::Upgraded => &image.upgrades,
1122 UpgradeInfo::Held => &image.primaries,
1123 }) {
1124 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1125 return true;
1126 }
1127 }
1128
1129 false
1130 }
1131
Fabio Utzig8af7f792019-07-30 12:40:01 -03001132 /// Verify that at least one of the trailers of the images have the
1133 /// specified values.
1134 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1135 magic: Option<u8>, image_ok: Option<u8>,
1136 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001137 self.images.iter().any(|image| {
1138 verify_trailer(flash, &image.slots[slot],
1139 magic, image_ok, copy_done)
1140 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001141 }
1142
David Brown84b49f72019-03-01 10:58:22 -07001143 /// Verify that the trailers of the images have the specified
1144 /// values.
1145 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1146 magic: Option<u8>, image_ok: Option<u8>,
1147 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001148 self.images.iter().all(|image| {
1149 verify_trailer(flash, &image.slots[slot],
1150 magic, image_ok, copy_done)
1151 })
David Brown84b49f72019-03-01 10:58:22 -07001152 }
1153
1154 /// Mark each of the images for permanent upgrade.
1155 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1156 for image in &self.images {
1157 mark_permanent_upgrade(flash, &image.slots[slot]);
1158 }
1159 }
1160
1161 /// Mark each of the images for permanent upgrade.
1162 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1163 for image in &self.images {
1164 mark_upgrade(flash, &image.slots[slot]);
1165 }
1166 }
David Brown297029a2019-08-13 14:29:51 -06001167
1168 /// Dump out the flash image(s) to one or more files for debugging
1169 /// purposes. The names will be written as either "{prefix}.mcubin" or
1170 /// "{prefix}-001.mcubin" depending on how many images there are.
1171 pub fn debug_dump(&self, prefix: &str) {
1172 for (id, fdev) in &self.flash {
1173 let name = if self.flash.len() == 1 {
1174 format!("{}.mcubin", prefix)
1175 } else {
1176 format!("{}-{:>0}.mcubin", prefix, id)
1177 };
1178 fdev.write_file(&name).unwrap();
1179 }
1180 }
David Brown5c9e0f12019-01-09 16:34:33 -07001181}
1182
1183/// Show the flash layout.
1184#[allow(dead_code)]
1185fn show_flash(flash: &dyn Flash) {
1186 println!("---- Flash configuration ----");
1187 for sector in flash.sector_iter() {
1188 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1189 sector.num, sector.base, sector.size);
1190 }
1191 println!("");
1192}
1193
1194/// Install a "program" into the given image. This fakes the image header, or at least all of the
1195/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001196fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownc3898d62019-08-05 14:20:02 -06001197 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001198 let offset = slot.base_off;
1199 let slot_len = slot.len;
1200 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001201
David Brown43643dd2019-01-11 15:43:28 -07001202 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001203
David Brownc3898d62019-08-05 14:20:02 -06001204 // Add the dependencies early to the tlv.
1205 for dep in deps.my_deps(offset, slot.index) {
1206 tlv.add_dependency(deps.other_id(), &dep);
1207 }
1208
David Brown5c9e0f12019-01-09 16:34:33 -07001209 const HDR_SIZE: usize = 32;
1210
1211 // Generate a boot header. Note that the size doesn't include the header.
1212 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001213 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -07001214 load_addr: 0,
1215 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001216 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001217 img_size: len as u32,
1218 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001219 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001220 _pad2: 0,
1221 };
1222
1223 let mut b_header = [0; HDR_SIZE];
1224 b_header[..32].clone_from_slice(header.as_raw());
1225 assert_eq!(b_header.len(), HDR_SIZE);
1226
1227 tlv.add_bytes(&b_header);
1228
1229 // The core of the image itself is just pseudorandom data.
1230 let mut b_img = vec![0; len];
1231 splat(&mut b_img, offset);
1232
David Browncb47dd72019-08-05 14:21:49 -06001233 // Add some information at the start of the payload to make it easier
1234 // to see what it is. This will fail if the image itself is too small.
1235 {
1236 let mut wr = Cursor::new(&mut b_img);
1237 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1238 offset, dev_id, slot).unwrap();
1239 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1240 }
1241
David Brown5c9e0f12019-01-09 16:34:33 -07001242 // TLV signatures work over plain image
1243 tlv.add_bytes(&b_img);
1244
1245 // Generate encrypted images
1246 let flag = TlvFlags::ENCRYPTED as u32;
1247 let is_encrypted = (tlv.get_flags() & flag) == flag;
1248 let mut b_encimg = vec![];
1249 if is_encrypted {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001250 tlv.generate_enc_key();
1251 let enc_key = tlv.get_enc_key();
1252 let key = GenericArray::from_slice(enc_key.as_slice());
David Brown5c9e0f12019-01-09 16:34:33 -07001253 let nonce = GenericArray::from_slice(&[0; 16]);
1254 let mut cipher = Aes128Ctr::new(&key, &nonce);
1255 b_encimg = b_img.clone();
1256 cipher.apply_keystream(&mut b_encimg);
1257 }
1258
1259 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001260 if bad_sig {
1261 tlv.corrupt_sig();
1262 }
1263 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001264
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001265 let dev = flash.get_mut(&dev_id).unwrap();
1266
David Brown5c9e0f12019-01-09 16:34:33 -07001267 let mut buf = vec![];
1268 buf.append(&mut b_header.to_vec());
1269 buf.append(&mut b_img);
1270 buf.append(&mut b_tlv.clone());
1271
David Brown95de4502019-11-15 12:01:34 -07001272 // Pad the buffer to a multiple of the flash alignment.
1273 let align = dev.align();
1274 while buf.len() % align != 0 {
1275 buf.push(dev.erased_val());
1276 }
1277
David Brown5c9e0f12019-01-09 16:34:33 -07001278 let mut encbuf = vec![];
1279 if is_encrypted {
1280 encbuf.append(&mut b_header.to_vec());
1281 encbuf.append(&mut b_encimg);
1282 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001283
1284 while encbuf.len() % align != 0 {
1285 encbuf.push(dev.erased_val());
1286 }
David Brown5c9e0f12019-01-09 16:34:33 -07001287 }
1288
David Vincze2d736ad2019-02-18 11:50:22 +01001289 // Since images are always non-encrypted in the primary slot, we first write
1290 // an encrypted image, re-read to use for verification, erase + flash
1291 // un-encrypted. In the secondary slot the image is written un-encrypted,
1292 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001293
David Brown3b090212019-07-30 15:59:28 -06001294 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001295 let enc_copy: Option<Vec<u8>>;
1296
1297 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001298 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001299
1300 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001301 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001302
1303 enc_copy = Some(enc);
1304
David Brown76101572019-02-28 11:29:03 -07001305 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001306 } else {
1307 enc_copy = None;
1308 }
1309
David Brown76101572019-02-28 11:29:03 -07001310 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001311
1312 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001313 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001314
David Brownca234692019-02-28 11:22:19 -07001315 ImageData {
1316 plain: copy,
1317 cipher: enc_copy,
1318 }
David Brown5c9e0f12019-01-09 16:34:33 -07001319 } else {
1320
David Brown76101572019-02-28 11:29:03 -07001321 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001322
1323 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001324 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001325
1326 let enc_copy: Option<Vec<u8>>;
1327
1328 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001329 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001330
David Brown76101572019-02-28 11:29:03 -07001331 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001332
1333 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001334 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001335
1336 enc_copy = Some(enc);
1337 } else {
1338 enc_copy = None;
1339 }
1340
David Brownca234692019-02-28 11:22:19 -07001341 ImageData {
1342 plain: copy,
1343 cipher: enc_copy,
1344 }
David Brown5c9e0f12019-01-09 16:34:33 -07001345 }
David Brown5c9e0f12019-01-09 16:34:33 -07001346}
1347
David Brown873be312019-09-03 12:22:32 -06001348/// Install no image. This is used when no upgrade happens.
1349fn install_no_image() -> ImageData {
1350 ImageData {
1351 plain: vec![],
1352 cipher: None,
1353 }
1354}
1355
David Brown5c9e0f12019-01-09 16:34:33 -07001356fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001357 if Caps::EcdsaP224.present() {
1358 panic!("Ecdsa P224 not supported in Simulator");
1359 }
David Brown5c9e0f12019-01-09 16:34:33 -07001360
David Brownb8882112019-01-11 14:04:11 -07001361 if Caps::EncKw.present() {
1362 if Caps::RSA2048.present() {
1363 TlvGen::new_rsa_kw()
1364 } else if Caps::EcdsaP256.present() {
1365 TlvGen::new_ecdsa_kw()
1366 } else {
1367 TlvGen::new_enc_kw()
1368 }
1369 } else if Caps::EncRsa.present() {
1370 if Caps::RSA2048.present() {
1371 TlvGen::new_sig_enc_rsa()
1372 } else {
1373 TlvGen::new_enc_rsa()
1374 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001375 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001376 if Caps::EcdsaP256.present() {
1377 TlvGen::new_ecdsa_ecies_p256()
1378 } else {
1379 TlvGen::new_ecies_p256()
1380 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001381 } else if Caps::EncX25519.present() {
1382 if Caps::Ed25519.present() {
1383 TlvGen::new_ed25519_ecies_x25519()
1384 } else {
1385 TlvGen::new_ecies_x25519()
1386 }
David Brownb8882112019-01-11 14:04:11 -07001387 } else {
1388 // The non-encrypted configuration.
1389 if Caps::RSA2048.present() {
1390 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001391 } else if Caps::RSA3072.present() {
1392 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001393 } else if Caps::EcdsaP256.present() {
1394 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001395 } else if Caps::Ed25519.present() {
1396 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001397 } else {
1398 TlvGen::new_hash_only()
1399 }
1400 }
David Brown5c9e0f12019-01-09 16:34:33 -07001401}
1402
David Brownca234692019-02-28 11:22:19 -07001403impl ImageData {
1404 /// Find the image contents for the given slot. This assumes that slot 0
1405 /// is unencrypted, and slot 1 is encrypted.
1406 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001407 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001408 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001409 match (encrypted, slot) {
1410 (false, _) => &self.plain,
1411 (true, 0) => &self.plain,
1412 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1413 _ => panic!("Invalid slot requested"),
1414 }
David Brown5c9e0f12019-01-09 16:34:33 -07001415 }
1416}
1417
David Brown5c9e0f12019-01-09 16:34:33 -07001418/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001419fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1420 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001421 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001422 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001423
1424 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001425 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001426 let dev = flash.get(&dev_id).unwrap();
1427 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001428
1429 if buf != &copy[..] {
1430 for i in 0 .. buf.len() {
1431 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001432 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1433 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001434 break;
1435 }
1436 }
1437 false
1438 } else {
1439 true
1440 }
1441}
1442
David Brown3b090212019-07-30 15:59:28 -06001443fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001444 magic: Option<u8>, image_ok: Option<u8>,
1445 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001446 if Caps::OverwriteUpgrade.present() {
1447 return true;
1448 }
David Brown5c9e0f12019-01-09 16:34:33 -07001449
David Brown3b090212019-07-30 15:59:28 -06001450 let offset = slot.trailer_off + c::boot_max_align();
1451 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001452 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001453 let mut failed = false;
1454
David Brown76101572019-02-28 11:29:03 -07001455 let dev = flash.get(&dev_id).unwrap();
1456 let erased_val = dev.erased_val();
1457 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001458
1459 failed |= match magic {
1460 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001461 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001462 warn!("\"magic\" mismatch at {:#x}", offset);
1463 true
1464 } else if v == 3 {
1465 let expected = [erased_val; 16];
Christopher Collinsa1c12042019-05-23 14:00:28 -07001466 if &copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001467 warn!("\"magic\" mismatch at {:#x}", offset);
1468 true
1469 } else {
1470 false
1471 }
1472 } else {
1473 false
1474 }
1475 },
1476 None => false,
1477 };
1478
1479 failed |= match image_ok {
1480 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001481 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001482 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1483 true
1484 } else {
1485 false
1486 }
1487 },
1488 None => false,
1489 };
1490
1491 failed |= match copy_done {
1492 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001493 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001494 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1495 true
1496 } else {
1497 false
1498 }
1499 },
1500 None => false,
1501 };
1502
1503 !failed
1504}
1505
David Brown297029a2019-08-13 14:29:51 -06001506/// Install a partition table. This is a simplified partition table that
1507/// we write at the beginning of flash so make it easier for external tools
1508/// to analyze these images.
1509fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1510 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1511 for &id in &ids {
1512 // If there are any partitions in this device that start at 0, and
1513 // aren't marked as the BootLoader partition, avoid adding the
1514 // partition table. This makes it harder to view the image, but
1515 // avoids messing up images already written.
1516 if areadesc.iter_areas().any(|area| {
1517 area.device_id == id &&
1518 area.off == 0 &&
1519 area.flash_id != FlashId::BootLoader
1520 }) {
1521 if log_enabled!(Info) {
1522 let special: Vec<FlashId> = areadesc.iter_areas()
1523 .filter(|area| area.device_id == id && area.off == 0)
1524 .map(|area| area.flash_id)
1525 .collect();
1526 info!("Skipping partition table: {:?}", special);
1527 }
1528 break;
1529 }
1530
1531 let mut buf: Vec<u8> = vec![];
1532 write!(&mut buf, "mcuboot\0").unwrap();
1533
1534 // Iterate through all of the partitions in that device, and encode
1535 // into the table.
1536 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1537 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1538
1539 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1540 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1541 buf.write_u32::<LittleEndian>(area.off).unwrap();
1542 buf.write_u32::<LittleEndian>(area.size).unwrap();
1543 buf.write_u32::<LittleEndian>(0).unwrap();
1544 }
1545
1546 let dev = flash.get_mut(&id).unwrap();
1547
1548 // Pad to alignment.
1549 while buf.len() % dev.align() != 0 {
1550 buf.push(0);
1551 }
1552
1553 dev.write(0, &buf).unwrap();
1554 }
1555}
1556
David Brown5c9e0f12019-01-09 16:34:33 -07001557/// The image header
1558#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001559#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001560pub struct ImageHeader {
1561 magic: u32,
1562 load_addr: u32,
1563 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001564 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001565 img_size: u32,
1566 flags: u32,
1567 ver: ImageVersion,
1568 _pad2: u32,
1569}
1570
1571impl AsRaw for ImageHeader {}
1572
1573#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001574#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001575pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001576 pub major: u8,
1577 pub minor: u8,
1578 pub revision: u16,
1579 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001580}
1581
David Brownc3898d62019-08-05 14:20:02 -06001582#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001583pub struct SlotInfo {
1584 pub base_off: usize,
1585 pub trailer_off: usize,
1586 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001587 // Which slot within this device.
1588 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001589 pub dev_id: u8,
1590}
1591
David Brown347dc572019-11-15 11:37:25 -07001592const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1593 0x60, 0xd2, 0xef, 0x7f,
1594 0x35, 0x52, 0x50, 0x0f,
1595 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001596
1597// Replicates defines found in bootutil.h
1598const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1599const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1600
1601const BOOT_FLAG_SET: Option<u8> = Some(1);
1602const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1603
1604/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001605pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1606 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001607 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001608 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001609 if offset % align != 0 || MAGIC.len() % align != 0 {
1610 // The write size is larger than the magic value. Fill a buffer
1611 // with the erased value, put the MAGIC in it, and write it in its
1612 // entirety.
1613 let mut buf = vec![dev.erased_val(); align];
1614 buf[(offset % align)..].copy_from_slice(MAGIC);
1615 dev.write(offset - (offset % align), &buf).unwrap();
1616 } else {
1617 dev.write(offset, MAGIC).unwrap();
1618 }
David Brown5c9e0f12019-01-09 16:34:33 -07001619}
1620
1621/// Writes the image_ok flag which, guess what, tells the bootloader
1622/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001623fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001624 // Overwrite mode always is permanent, and only the magic is used in
1625 // the trailer. To avoid problems with large write sizes, don't try to
1626 // set anything in this case.
1627 if Caps::OverwriteUpgrade.present() {
1628 return;
1629 }
1630
David Brown76101572019-02-28 11:29:03 -07001631 let dev = flash.get_mut(&slot.dev_id).unwrap();
1632 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001633 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001634 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001635 let align = dev.align();
1636 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001637}
1638
1639// Drop some pseudo-random gibberish onto the data.
1640fn splat(data: &mut [u8], seed: usize) {
David Browncd842842020-07-09 15:46:53 -06001641 let mut seed_block = [0u8; 16];
1642 let mut buf = Cursor::new(&mut seed_block[..]);
1643 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
1644 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
1645 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
1646 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
1647 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07001648 rng.fill_bytes(data);
1649}
1650
1651/// Return a read-only view into the raw bytes of this object
1652trait AsRaw : Sized {
1653 fn as_raw<'a>(&'a self) -> &'a [u8] {
1654 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1655 mem::size_of::<Self>()) }
1656 }
1657}
1658
1659pub fn show_sizes() {
1660 // This isn't panic safe.
1661 for min in &[1, 2, 4, 8] {
1662 let msize = c::boot_trailer_sz(*min);
1663 println!("{:2}: {} (0x{:x})", min, msize, msize);
1664 }
1665}
David Brown95de4502019-11-15 12:01:34 -07001666
1667#[cfg(not(feature = "large-write"))]
1668fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001669 &[1, 2, 4, 8]
1670}
1671
1672#[cfg(feature = "large-write")]
1673fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001674 &[1, 2, 4, 8, 128, 512]
1675}