blob: d5355eb4ce1374d802b7248291ded311eecbe892 [file] [log] [blame]
David Browne2acfae2020-01-21 16:45:01 -07001// Copyright (c) 2019 Linaro LTD
2// Copyright (c) 2019-2020 JUUL Labs
Salome Thirot6fdbf552021-05-14 16:46:14 +01003// Copyright (c) 2019-2021 Arm Limited
David Browne2acfae2020-01-21 16:45:01 -07004//
5// SPDX-License-Identifier: Apache-2.0
6
David Brown297029a2019-08-13 14:29:51 -06007use byteorder::{
8 LittleEndian, WriteBytesExt,
9};
10use log::{
11 Level::Info,
12 error,
13 info,
14 log_enabled,
15 warn,
16};
David Brown5c9e0f12019-01-09 16:34:33 -070017use rand::{
David Browncd842842020-07-09 15:46:53 -060018 Rng, RngCore, SeedableRng,
19 rngs::SmallRng,
David Brown5c9e0f12019-01-09 16:34:33 -070020};
21use std::{
David Brown297029a2019-08-13 14:29:51 -060022 collections::HashSet,
David Browncb47dd72019-08-05 14:21:49 -060023 io::{Cursor, Write},
David Brown5c9e0f12019-01-09 16:34:33 -070024 mem,
25 slice,
26};
27use aes_ctr::{
28 Aes128Ctr,
Salome Thirot6fdbf552021-05-14 16:46:14 +010029 Aes256Ctr,
David Brown5c9e0f12019-01-09 16:34:33 -070030 stream_cipher::{
31 generic_array::GenericArray,
David Brown8a99adf2020-07-09 16:52:38 -060032 NewStreamCipher,
33 SyncStreamCipher,
David Brown5c9e0f12019-01-09 16:34:33 -070034 },
35};
36
David Brown76101572019-02-28 11:29:03 -070037use simflash::{Flash, SimFlash, SimMultiFlash};
David Browne5133242019-02-28 11:05:19 -070038use mcuboot_sys::{c, AreaDesc, FlashId};
39use crate::{
40 ALL_DEVICES,
41 DeviceName,
42};
David Brown5c9e0f12019-01-09 16:34:33 -070043use crate::caps::Caps;
David Brownc3898d62019-08-05 14:20:02 -060044use crate::depends::{
45 BoringDep,
46 Depender,
47 DepTest,
David Brown873be312019-09-03 12:22:32 -060048 DepType,
David Brown2ee5f7f2020-01-13 14:04:01 -070049 NO_DEPS,
David Brownc3898d62019-08-05 14:20:02 -060050 PairDep,
51 UpgradeInfo,
52};
Fabio Utzig90f449e2019-10-24 07:43:53 -030053use crate::tlv::{ManifestGen, TlvGen, TlvFlags};
Salome Thirot6fdbf552021-05-14 16:46:14 +010054use typenum::{U32, U16};
David Brown5c9e0f12019-01-09 16:34:33 -070055
David Browne5133242019-02-28 11:05:19 -070056/// A builder for Images. This describes a single run of the simulator,
57/// capturing the configuration of a particular set of devices, including
58/// the flash simulator(s) and the information about the slots.
59#[derive(Clone)]
60pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070061 flash: SimMultiFlash,
David Browne5133242019-02-28 11:05:19 -070062 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070063 slots: Vec<[SlotInfo; 2]>,
David Browne5133242019-02-28 11:05:19 -070064}
65
David Brown998aa8d2019-02-28 10:54:50 -070066/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070067/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070068/// and upgrades hold the expected contents of these images.
69pub struct Images {
David Brown76101572019-02-28 11:29:03 -070070 flash: SimMultiFlash,
David Brownca234692019-02-28 11:22:19 -070071 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070072 images: Vec<OneImage>,
73 total_count: Option<i32>,
74}
75
76/// When doing multi-image, there is an instance of this information for
77/// each of the images. Single image there will be one of these.
78struct OneImage {
David Brownca234692019-02-28 11:22:19 -070079 slots: [SlotInfo; 2],
80 primaries: ImageData,
81 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070082}
83
84/// The Rust-side representation of an image. For unencrypted images, this
85/// is just the unencrypted payload. For encrypted images, we store both
86/// the encrypted and the plaintext.
87struct ImageData {
88 plain: Vec<u8>,
89 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -070090}
91
David Browne5133242019-02-28 11:05:19 -070092impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -070093 /// Construct a new image builder for the given device. Returns
94 /// Some(builder) if is possible to test this configuration, or None if
95 /// not possible (for example, if there aren't enough image slots).
Fabio Utzig114a6472019-11-28 10:24:09 -030096 pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
97 let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
98
99 for cap in unsupported_caps {
100 if cap.present() {
101 return Err(format!("unsupported {:?}", cap));
102 }
103 }
David Browne5133242019-02-28 11:05:19 -0700104
David Brown06ef06e2019-03-05 12:28:10 -0700105 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -0700106
David Brown06ef06e2019-03-05 12:28:10 -0700107 let mut slots = Vec::with_capacity(num_images);
108 for image in 0..num_images {
109 // This mapping must match that defined in
110 // `boot/zephyr/include/sysflash/sysflash.h`.
111 let id0 = match image {
112 0 => FlashId::Image0,
113 1 => FlashId::Image2,
114 _ => panic!("More than 2 images not supported"),
115 };
116 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
117 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300118 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700119 };
120 let id1 = match image {
121 0 => FlashId::Image1,
122 1 => FlashId::Image3,
123 _ => panic!("More than 2 images not supported"),
124 };
125 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
126 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300127 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700128 };
David Browne5133242019-02-28 11:05:19 -0700129
Christopher Collinsa1c12042019-05-23 14:00:28 -0700130 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700131
David Brown06ef06e2019-03-05 12:28:10 -0700132 // Construct a primary image.
133 let primary = SlotInfo {
134 base_off: primary_base as usize,
135 trailer_off: primary_base + primary_len - offset_from_end,
136 len: primary_len as usize,
137 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600138 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700139 };
140
141 // And an upgrade image.
142 let secondary = SlotInfo {
143 base_off: secondary_base as usize,
144 trailer_off: secondary_base + secondary_len - offset_from_end,
145 len: secondary_len as usize,
146 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600147 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700148 };
149
150 slots.push([primary, secondary]);
151 }
David Browne5133242019-02-28 11:05:19 -0700152
Fabio Utzig114a6472019-11-28 10:24:09 -0300153 Ok(ImagesBuilder {
David Brown4dfb33c2021-03-10 05:15:45 -0700154 flash,
155 areadesc,
156 slots,
David Brown5bc62c62019-03-05 12:11:48 -0700157 })
David Browne5133242019-02-28 11:05:19 -0700158 }
159
160 pub fn each_device<F>(f: F)
161 where F: Fn(Self)
162 {
163 for &dev in ALL_DEVICES {
David Brown95de4502019-11-15 12:01:34 -0700164 for &align in test_alignments() {
David Browne5133242019-02-28 11:05:19 -0700165 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700166 match Self::new(dev, align, erased_val) {
Fabio Utzig114a6472019-11-28 10:24:09 -0300167 Ok(run) => f(run),
168 Err(msg) => warn!("Skipping {}: {}", dev, msg),
David Brown5bc62c62019-03-05 12:11:48 -0700169 }
David Browne5133242019-02-28 11:05:19 -0700170 }
171 }
172 }
173 }
174
175 /// Construct an `Images` that doesn't expect an upgrade to happen.
David Brownc3898d62019-08-05 14:20:02 -0600176 pub fn make_no_upgrade_image(self, deps: &DepTest) -> Images {
177 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700178 let mut flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600179 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
180 let dep: Box<dyn Depender> = if num_images > 1 {
181 Box::new(PairDep::new(num_images, image_num, deps))
182 } else {
David Brown2ee5f7f2020-01-13 14:04:01 -0700183 Box::new(BoringDep::new(image_num, deps))
David Brownc3898d62019-08-05 14:20:02 -0600184 };
185 let primaries = install_image(&mut flash, &slots[0], 42784, &*dep, false);
David Brown873be312019-09-03 12:22:32 -0600186 let upgrades = match deps.depends[image_num] {
187 DepType::NoUpgrade => install_no_image(),
188 _ => install_image(&mut flash, &slots[1], 46928, &*dep, false)
189 };
David Brown84b49f72019-03-01 10:58:22 -0700190 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700191 slots,
192 primaries,
193 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700194 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600195 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700196 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700197 flash,
David Browne5133242019-02-28 11:05:19 -0700198 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700199 images,
David Browne5133242019-02-28 11:05:19 -0700200 total_count: None,
201 }
202 }
203
David Brownc3898d62019-08-05 14:20:02 -0600204 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
205 let mut images = self.make_no_upgrade_image(deps);
David Brown84b49f72019-03-01 10:58:22 -0700206 for image in &images.images {
207 mark_upgrade(&mut images.flash, &image.slots[1]);
208 }
David Browne5133242019-02-28 11:05:19 -0700209
David Brown6db44d72021-05-26 16:22:58 -0600210 // The count is meaningless if no flash operations are performed.
211 if !Caps::modifies_flash() {
212 return images;
213 }
214
David Browne5133242019-02-28 11:05:19 -0700215 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300216 let total_count = match images.run_basic_upgrade(permanent) {
David Brown8973f552021-03-10 05:21:11 -0700217 Some(v) => v,
218 None =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600219 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
220 0
221 } else {
222 panic!("Unable to perform basic upgrade");
223 }
David Browne5133242019-02-28 11:05:19 -0700224 };
225
226 images.total_count = Some(total_count);
227 images
228 }
229
230 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700231 let mut bad_flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600232 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
David Brown2ee5f7f2020-01-13 14:04:01 -0700233 let dep = BoringDep::new(image_num, &NO_DEPS);
David Brownc3898d62019-08-05 14:20:02 -0600234 let primaries = install_image(&mut bad_flash, &slots[0], 32784, &dep, false);
235 let upgrades = install_image(&mut bad_flash, &slots[1], 41928, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700236 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700237 slots,
238 primaries,
239 upgrades,
David Brown84b49f72019-03-01 10:58:22 -0700240 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700241 Images {
David Brown76101572019-02-28 11:29:03 -0700242 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700243 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700244 images,
David Browne5133242019-02-28 11:05:19 -0700245 total_count: None,
246 }
247 }
248
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300249 pub fn make_erased_secondary_image(self) -> Images {
250 let mut flash = self.flash;
251 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
252 let dep = BoringDep::new(image_num, &NO_DEPS);
253 let primaries = install_image(&mut flash, &slots[0], 32784, &dep, false);
254 let upgrades = install_no_image();
255 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700256 slots,
257 primaries,
258 upgrades,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300259 }}).collect();
260 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700261 flash,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300262 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700263 images,
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300264 total_count: None,
265 }
266 }
267
Fabio Utzigd0157342020-10-02 15:22:11 -0300268 pub fn make_bootstrap_image(self) -> Images {
269 let mut flash = self.flash;
270 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
271 let dep = BoringDep::new(image_num, &NO_DEPS);
272 let primaries = install_no_image();
273 let upgrades = install_image(&mut flash, &slots[1], 32784, &dep, false);
274 OneImage {
David Brown4dfb33c2021-03-10 05:15:45 -0700275 slots,
276 primaries,
277 upgrades,
Fabio Utzigd0157342020-10-02 15:22:11 -0300278 }}).collect();
279 Images {
David Brown4dfb33c2021-03-10 05:15:45 -0700280 flash,
Fabio Utzigd0157342020-10-02 15:22:11 -0300281 areadesc: self.areadesc,
David Brown4dfb33c2021-03-10 05:15:45 -0700282 images,
Fabio Utzigd0157342020-10-02 15:22:11 -0300283 total_count: None,
284 }
285 }
286
David Browne5133242019-02-28 11:05:19 -0700287 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300288 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700289 match device {
290 DeviceName::Stm32f4 => {
291 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700292 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
293 64 * 1024,
294 128 * 1024, 128 * 1024, 128 * 1024],
295 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700296 let dev_id = 0;
297 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700298 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700299 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
300 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
301 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
302
David Brown76101572019-02-28 11:29:03 -0700303 let mut flash = SimMultiFlash::new();
304 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300305 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700306 }
307 DeviceName::K64f => {
308 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700309 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700310
311 let dev_id = 0;
312 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700313 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700314 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
315 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
316 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
317
David Brown76101572019-02-28 11:29:03 -0700318 let mut flash = SimMultiFlash::new();
319 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300320 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700321 }
322 DeviceName::K64fBig => {
323 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
324 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700325 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700326
327 let dev_id = 0;
328 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700329 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700330 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
331 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
332 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
333
David Brown76101572019-02-28 11:29:03 -0700334 let mut flash = SimMultiFlash::new();
335 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300336 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700337 }
338 DeviceName::Nrf52840 => {
339 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
340 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700341 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700342
343 let dev_id = 0;
344 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700345 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700346 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
347 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
348 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
349
David Brown76101572019-02-28 11:29:03 -0700350 let mut flash = SimMultiFlash::new();
351 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300352 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700353 }
Fabio Utzigc659ec52020-07-13 21:18:48 -0300354 DeviceName::Nrf52840UnequalSlots => {
355 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
356
357 let dev_id = 0;
358 let mut areadesc = AreaDesc::new();
359 areadesc.add_flash_sectors(dev_id, &dev);
360 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
361 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
362
363 let mut flash = SimMultiFlash::new();
364 flash.insert(dev_id, dev);
365 (flash, areadesc, &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
366 }
David Browne5133242019-02-28 11:05:19 -0700367 DeviceName::Nrf52840SpiFlash => {
368 // Simulate nrf52840 with external SPI flash. The external SPI flash
369 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700370 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
371 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700372
373 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700374 areadesc.add_flash_sectors(0, &dev0);
375 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700376
377 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
378 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
379 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
380
David Brown76101572019-02-28 11:29:03 -0700381 let mut flash = SimMultiFlash::new();
382 flash.insert(0, dev0);
383 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300384 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700385 }
David Brown2bff6472019-03-05 13:58:35 -0700386 DeviceName::K64fMulti => {
387 // NXP style flash, but larger, to support multiple images.
388 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
389
390 let dev_id = 0;
391 let mut areadesc = AreaDesc::new();
392 areadesc.add_flash_sectors(dev_id, &dev);
393 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
394 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
395 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
396 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
397 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
398
399 let mut flash = SimMultiFlash::new();
400 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300401 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700402 }
David Browne5133242019-02-28 11:05:19 -0700403 }
404 }
David Brownc3898d62019-08-05 14:20:02 -0600405
406 pub fn num_images(&self) -> usize {
407 self.slots.len()
408 }
David Browne5133242019-02-28 11:05:19 -0700409}
410
David Brown5c9e0f12019-01-09 16:34:33 -0700411impl Images {
412 /// A simple upgrade without forced failures.
413 ///
414 /// Returns the number of flash operations which can later be used to
David Brown8973f552021-03-10 05:21:11 -0700415 /// inject failures at chosen steps. Returns None if it was unable to
416 /// count the operations in a basic upgrade.
417 pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
Fabio Utziged4a5362019-07-30 12:43:23 -0300418 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700419 info!("Total flash operation count={}", total_count);
420
David Brown84b49f72019-03-01 10:58:22 -0700421 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700422 warn!("Image mismatch after first boot");
David Brown8973f552021-03-10 05:21:11 -0700423 None
David Brown5c9e0f12019-01-09 16:34:33 -0700424 } else {
David Brown8973f552021-03-10 05:21:11 -0700425 Some(total_count)
David Brown5c9e0f12019-01-09 16:34:33 -0700426 }
427 }
428
Fabio Utzigd0157342020-10-02 15:22:11 -0300429 pub fn run_bootstrap(&self) -> bool {
430 let mut flash = self.flash.clone();
431 let mut fails = 0;
432
433 if Caps::Bootstrap.present() {
434 info!("Try bootstraping image in the primary");
435
David Brownc423ac42021-06-04 13:47:34 -0600436 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigd0157342020-10-02 15:22:11 -0300437 warn!("Failed first boot");
438 fails += 1;
439 }
440
441 if !self.verify_images(&flash, 0, 1) {
442 warn!("Image in the first slot was not bootstrapped");
443 fails += 1;
444 }
445
446 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
447 BOOT_FLAG_SET, BOOT_FLAG_SET) {
448 warn!("Mismatched trailer for the primary slot");
449 fails += 1;
450 }
451 }
452
453 if fails > 0 {
454 error!("Expected trailer on secondary slot to be erased");
455 }
456
457 fails > 0
458 }
459
460
David Brownc3898d62019-08-05 14:20:02 -0600461 /// Test a simple upgrade, with dependencies given, and verify that the
462 /// image does as is described in the test.
463 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600464 if !Caps::modifies_flash() {
465 return false;
466 }
467
David Brownc3898d62019-08-05 14:20:02 -0600468 let (flash, _) = self.try_upgrade(None, true);
469
470 self.verify_dep_images(&flash, deps)
471 }
472
Fabio Utzigf5480c72019-11-28 10:41:57 -0300473 fn is_swap_upgrade(&self) -> bool {
474 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
475 }
476
David Brown5c9e0f12019-01-09 16:34:33 -0700477 pub fn run_basic_revert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600478 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700479 return false;
480 }
David Brown5c9e0f12019-01-09 16:34:33 -0700481
David Brown5c9e0f12019-01-09 16:34:33 -0700482 let mut fails = 0;
483
484 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300485 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700486 for count in 2 .. 5 {
487 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700488 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700489 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700490 error!("Revert failure on count {}", count);
491 fails += 1;
492 }
493 }
494 }
495
496 fails > 0
497 }
498
499 pub fn run_perm_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600500 if !Caps::modifies_flash() {
501 return false;
502 }
503
David Brown5c9e0f12019-01-09 16:34:33 -0700504 let mut fails = 0;
505 let total_flash_ops = self.total_count.unwrap();
506
507 // Let's try an image halfway through.
508 for i in 1 .. total_flash_ops {
509 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300510 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700511 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700512 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700513 warn!("FAIL at step {} of {}", i, total_flash_ops);
514 fails += 1;
515 }
516
David Brown84b49f72019-03-01 10:58:22 -0700517 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
518 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100519 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700520 fails += 1;
521 }
522
David Brown84b49f72019-03-01 10:58:22 -0700523 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
524 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100525 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700526 fails += 1;
527 }
528
David Brownaec56b22021-03-10 05:22:07 -0700529 if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
530 warn!("Secondary slot FAIL at step {} of {}",
531 i, total_flash_ops);
532 fails += 1;
David Brown5c9e0f12019-01-09 16:34:33 -0700533 }
534 }
535
536 if fails > 0 {
537 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
538 fails as f32 * 100.0 / total_flash_ops as f32);
539 }
540
541 fails > 0
542 }
543
David Brown5c9e0f12019-01-09 16:34:33 -0700544 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600545 if !Caps::modifies_flash() {
546 return false;
547 }
548
David Brown5c9e0f12019-01-09 16:34:33 -0700549 let mut fails = 0;
550 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700551 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700552 info!("Random interruptions at reset points={:?}", total_counts);
553
David Brown84b49f72019-03-01 10:58:22 -0700554 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300555 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700556 // TODO: This result is ignored.
557 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700558 } else {
559 true
560 };
David Vincze2d736ad2019-02-18 11:50:22 +0100561 if !primary_slot_ok || !secondary_slot_ok {
562 error!("Image mismatch after random interrupts: primary slot={} \
563 secondary slot={}",
564 if primary_slot_ok { "ok" } else { "fail" },
565 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700566 fails += 1;
567 }
David Brown84b49f72019-03-01 10:58:22 -0700568 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
569 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100570 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700571 fails += 1;
572 }
David Brown84b49f72019-03-01 10:58:22 -0700573 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
574 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100575 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700576 fails += 1;
577 }
578
579 if fails > 0 {
580 error!("Error testing perm upgrade with {} fails", total_fails);
581 }
582
583 fails > 0
584 }
585
David Brown5c9e0f12019-01-09 16:34:33 -0700586 pub fn run_revert_with_fails(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600587 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700588 return false;
589 }
David Brown5c9e0f12019-01-09 16:34:33 -0700590
David Brown5c9e0f12019-01-09 16:34:33 -0700591 let mut fails = 0;
592
Fabio Utzigf5480c72019-11-28 10:41:57 -0300593 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300594 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700595 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700596 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700597 error!("Revert failed at interruption {}", i);
598 fails += 1;
599 }
600 }
601 }
602
603 fails > 0
604 }
605
David Brown5c9e0f12019-01-09 16:34:33 -0700606 pub fn run_norevert(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600607 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown3910ab12019-01-11 12:02:26 -0700608 return false;
609 }
David Brown5c9e0f12019-01-09 16:34:33 -0700610
David Brown76101572019-02-28 11:29:03 -0700611 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700612 let mut fails = 0;
613
614 info!("Try norevert");
615
616 // First do a normal upgrade...
David Brownc423ac42021-06-04 13:47:34 -0600617 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700618 warn!("Failed first boot");
619 fails += 1;
620 }
621
622 //FIXME: copy_done is written by boot_go, is it ok if no copy
623 // was ever done?
624
David Brown84b49f72019-03-01 10:58:22 -0700625 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100626 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700627 fails += 1;
628 }
David Brown84b49f72019-03-01 10:58:22 -0700629 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
630 BOOT_FLAG_UNSET, 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 }
David Brown84b49f72019-03-01 10:58:22 -0700634 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
635 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100636 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700637 fails += 1;
638 }
639
David Vincze2d736ad2019-02-18 11:50:22 +0100640 // Marks image in the primary slot as permanent,
641 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700642 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700643
David Brown84b49f72019-03-01 10:58:22 -0700644 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
645 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100646 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700647 fails += 1;
648 }
649
David Brownc423ac42021-06-04 13:47:34 -0600650 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700651 warn!("Failed second boot");
652 fails += 1;
653 }
654
David Brown84b49f72019-03-01 10:58:22 -0700655 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
656 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100657 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700658 fails += 1;
659 }
David Brown84b49f72019-03-01 10:58:22 -0700660 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700661 warn!("Failed image verification");
662 fails += 1;
663 }
664
665 if fails > 0 {
666 error!("Error running upgrade without revert");
667 }
668
669 fails > 0
670 }
671
David Brown2ee5f7f2020-01-13 14:04:01 -0700672 // Test that an upgrade is rejected. Assumes that the image was build
673 // such that the upgrade is instead a downgrade.
674 pub fn run_nodowngrade(&self) -> bool {
675 if !Caps::DowngradePrevention.present() {
676 return false;
677 }
678
679 let mut flash = self.flash.clone();
680 let mut fails = 0;
681
682 info!("Try no downgrade");
683
684 // First, do a normal upgrade.
David Brownc423ac42021-06-04 13:47:34 -0600685 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown2ee5f7f2020-01-13 14:04:01 -0700686 warn!("Failed first boot");
687 fails += 1;
688 }
689
690 if !self.verify_images(&flash, 0, 0) {
691 warn!("Failed verification after downgrade rejection");
692 fails += 1;
693 }
694
695 if fails > 0 {
696 error!("Error testing downgrade rejection");
697 }
698
699 fails > 0
700 }
701
David Vincze2d736ad2019-02-18 11:50:22 +0100702 // Tests a new image written to the primary slot that already has magic and
703 // image_ok set while there is no image on the secondary slot, so no revert
704 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700705 pub fn run_norevert_newimage(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600706 if !Caps::modifies_flash() {
707 info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
708 return false;
709 }
710
David Brown76101572019-02-28 11:29:03 -0700711 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700712 let mut fails = 0;
713
714 info!("Try non-revert on imgtool generated image");
715
David Brown84b49f72019-03-01 10:58:22 -0700716 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700717
David Vincze2d736ad2019-02-18 11:50:22 +0100718 // This simulates writing an image created by imgtool to
719 // the primary slot
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 }
725
726 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600727 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700728 warn!("Failed first boot");
729 fails += 1;
730 }
731
732 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700733 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700734 warn!("Failed image verification");
735 fails += 1;
736 }
David Brown84b49f72019-03-01 10:58:22 -0700737 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
738 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100739 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700740 fails += 1;
741 }
David Brown84b49f72019-03-01 10:58:22 -0700742 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
743 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100744 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700745 fails += 1;
746 }
747
748 if fails > 0 {
749 error!("Expected a non revert with new image");
750 }
751
752 fails > 0
753 }
754
David Vincze2d736ad2019-02-18 11:50:22 +0100755 // Tests a new image written to the primary slot that already has magic and
756 // image_ok set while there is no image on the secondary slot, so no revert
757 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700758 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700759 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700760 let mut fails = 0;
761
762 info!("Try upgrade image with bad signature");
763
David Brown6db44d72021-05-26 16:22:58 -0600764 // Only perform this test if an upgrade is expected to happen.
765 if !Caps::modifies_flash() {
766 info!("Skipping upgrade image with bad signature");
767 return false;
768 }
769
David Brown84b49f72019-03-01 10:58:22 -0700770 self.mark_upgrades(&mut flash, 0);
771 self.mark_permanent_upgrades(&mut flash, 0);
772 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700773
David Brown84b49f72019-03-01 10:58:22 -0700774 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
775 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100776 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700777 fails += 1;
778 }
779
780 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600781 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700782 warn!("Failed first boot");
783 fails += 1;
784 }
785
786 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700787 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700788 warn!("Failed image verification");
789 fails += 1;
790 }
David Brown84b49f72019-03-01 10:58:22 -0700791 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
792 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100793 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700794 fails += 1;
795 }
796
797 if fails > 0 {
798 error!("Expected an upgrade failure when image has bad signature");
799 }
800
801 fails > 0
802 }
803
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300804 // Should detect there is a leftover trailer in an otherwise erased
805 // secondary slot and erase its trailer.
806 pub fn run_secondary_leftover_trailer(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600807 if !Caps::modifies_flash() {
808 return false;
809 }
810
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300811 let mut flash = self.flash.clone();
812 let mut fails = 0;
813
814 info!("Try with a leftover trailer in the secondary; must be erased");
815
816 // Add a trailer on the secondary slot
817 self.mark_permanent_upgrades(&mut flash, 1);
818 self.mark_upgrades(&mut flash, 1);
819
820 // Run the bootloader...
David Brownc423ac42021-06-04 13:47:34 -0600821 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzig2c3be5c2020-07-09 19:54:45 -0300822 warn!("Failed first boot");
823 fails += 1;
824 }
825
826 // State should not have changed
827 if !self.verify_images(&flash, 0, 0) {
828 warn!("Failed image verification");
829 fails += 1;
830 }
831 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
832 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
833 warn!("Mismatched trailer for the secondary slot");
834 fails += 1;
835 }
836
837 if fails > 0 {
838 error!("Expected trailer on secondary slot to be erased");
839 }
840
841 fails > 0
842 }
843
David Brown5c9e0f12019-01-09 16:34:33 -0700844 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300845 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700846 }
847
David Brown5c9e0f12019-01-09 16:34:33 -0700848 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300849 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700850 }
851
852 /// This test runs a simple upgrade with no fails in the images, but
853 /// allowing for fails in the status area. This should run to the end
854 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700855 pub fn run_with_status_fails_complete(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600856 if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700857 return false;
858 }
859
David Brown76101572019-02-28 11:29:03 -0700860 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700861 let mut fails = 0;
862
863 info!("Try swap with status fails");
864
David Brown84b49f72019-03-01 10:58:22 -0700865 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700866 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700867
David Brownc423ac42021-06-04 13:47:34 -0600868 let result = c::boot_go(&mut flash, &self.areadesc, None, true);
869 if !result.success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700870 warn!("Failed!");
871 fails += 1;
872 }
873
874 // Failed writes to the marked "bad" region don't assert anymore.
875 // Any detected assert() is happening in another part of the code.
David Brownc423ac42021-06-04 13:47:34 -0600876 if result.asserts() != 0 {
David Brown5c9e0f12019-01-09 16:34:33 -0700877 warn!("At least one assert() was called");
878 fails += 1;
879 }
880
David Brown84b49f72019-03-01 10:58:22 -0700881 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
882 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100883 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700884 fails += 1;
885 }
886
David Brown84b49f72019-03-01 10:58:22 -0700887 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700888 warn!("Failed image verification");
889 fails += 1;
890 }
891
David Vincze2d736ad2019-02-18 11:50:22 +0100892 info!("validate primary slot enabled; \
893 re-run of boot_go should just work");
David Brownc423ac42021-06-04 13:47:34 -0600894 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
David Brown5c9e0f12019-01-09 16:34:33 -0700895 warn!("Failed!");
896 fails += 1;
897 }
898
899 if fails > 0 {
900 error!("Error running upgrade with status write fails");
901 }
902
903 fails > 0
904 }
905
906 /// This test runs a simple upgrade with no fails in the images, but
907 /// allowing for fails in the status area. This should run to the end
908 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700909 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown6db44d72021-05-26 16:22:58 -0600910 if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
David Brown85904a82019-01-11 13:45:12 -0700911 false
David Vincze2d736ad2019-02-18 11:50:22 +0100912 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700913
David Brown76101572019-02-28 11:29:03 -0700914 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700915 let mut fails = 0;
916 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700917
David Brown85904a82019-01-11 13:45:12 -0700918 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700919
David Brown85904a82019-01-11 13:45:12 -0700920 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700921
David Brown84b49f72019-03-01 10:58:22 -0700922 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700923 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700924
925 // Should not fail, writing to bad regions does not assert
David Brownc423ac42021-06-04 13:47:34 -0600926 let asserts = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700927 if asserts != 0 {
928 warn!("At least one assert() was called");
929 fails += 1;
930 }
931
David Brown76101572019-02-28 11:29:03 -0700932 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700933
934 info!("Resuming an interrupted swap operation");
David Brownc423ac42021-06-04 13:47:34 -0600935 let asserts = c::boot_go(&mut flash, &self.areadesc, None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700936
937 // This might throw no asserts, for large sector devices, where
938 // a single failure writing is indistinguishable from no failure,
939 // or throw a single assert for small sector devices that fail
940 // multiple times...
941 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100942 warn!("Expected single assert validating the primary slot, \
943 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700944 fails += 1;
945 }
946
947 if fails > 0 {
948 error!("Error running upgrade with status write fails");
949 }
950
951 fails > 0
952 } else {
David Brown76101572019-02-28 11:29:03 -0700953 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700954 let mut fails = 0;
955
956 info!("Try interrupted swap with status fails");
957
David Brown84b49f72019-03-01 10:58:22 -0700958 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700959 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700960
961 // This is expected to fail while writing to bad regions...
David Brownc423ac42021-06-04 13:47:34 -0600962 let asserts = c::boot_go(&mut flash, &self.areadesc, None, true).asserts();
David Brown85904a82019-01-11 13:45:12 -0700963 if asserts == 0 {
964 warn!("No assert() detected");
965 fails += 1;
966 }
967
968 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700969 }
David Brown5c9e0f12019-01-09 16:34:33 -0700970 }
971
972 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -0700973 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -0700974 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -0700975 if Caps::OverwriteUpgrade.present() {
976 return;
977 }
978
David Brown84b49f72019-03-01 10:58:22 -0700979 // Set this for each image.
980 for image in &self.images {
981 let dev_id = &image.slots[slot].dev_id;
982 let dev = flash.get_mut(&dev_id).unwrap();
983 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -0700984 let off = &image.slots[slot].base_off;
985 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -0700986 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -0700987
David Brown84b49f72019-03-01 10:58:22 -0700988 // Mark the status area as a bad area
989 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
990 }
David Brown5c9e0f12019-01-09 16:34:33 -0700991 }
992
David Brown76101572019-02-28 11:29:03 -0700993 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +0100994 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700995 return;
996 }
997
David Brown84b49f72019-03-01 10:58:22 -0700998 for image in &self.images {
999 let dev_id = &image.slots[slot].dev_id;
1000 let dev = flash.get_mut(&dev_id).unwrap();
1001 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -07001002
David Brown84b49f72019-03-01 10:58:22 -07001003 // Disabling write verification the only assert triggered by
1004 // boot_go should be checking for integrity of status bytes.
1005 dev.set_verify_writes(false);
1006 }
David Brown5c9e0f12019-01-09 16:34:33 -07001007 }
1008
David Browndb505822019-03-01 10:04:20 -07001009 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
1010 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -03001011 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -07001012 // Clone the flash to have a new copy.
1013 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -07001014
Fabio Utziged4a5362019-07-30 12:43:23 -03001015 if permanent {
1016 self.mark_permanent_upgrades(&mut flash, 1);
1017 }
David Brown5c9e0f12019-01-09 16:34:33 -07001018
David Browndb505822019-03-01 10:04:20 -07001019 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -07001020
David Browndb505822019-03-01 10:04:20 -07001021 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001022 x if x.interrupted() => (true, stop.unwrap()),
1023 x if x.success() => (false, -counter),
1024 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001025 };
David Brown5c9e0f12019-01-09 16:34:33 -07001026
David Browndb505822019-03-01 10:04:20 -07001027 counter = 0;
1028 if first_interrupted {
1029 // fl.dump();
1030 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001031 x if x.interrupted() => panic!("Shouldn't stop again"),
1032 x if x.success() => (),
1033 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001034 }
1035 }
David Brown5c9e0f12019-01-09 16:34:33 -07001036
David Browndb505822019-03-01 10:04:20 -07001037 (flash, count - counter)
1038 }
1039
1040 fn try_revert(&self, count: usize) -> SimMultiFlash {
1041 let mut flash = self.flash.clone();
1042
1043 // fl.write_file("image0.bin").unwrap();
1044 for i in 0 .. count {
1045 info!("Running boot pass {}", i + 1);
David Brownc423ac42021-06-04 13:47:34 -06001046 assert!(c::boot_go(&mut flash, &self.areadesc, None, false).success_no_asserts());
David Browndb505822019-03-01 10:04:20 -07001047 }
1048 flash
1049 }
1050
1051 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1052 let mut flash = self.flash.clone();
1053 let mut fails = 0;
1054
1055 let mut counter = stop;
David Brownc423ac42021-06-04 13:47:34 -06001056 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001057 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -07001058 fails += 1;
1059 }
1060
Fabio Utzig8af7f792019-07-30 12:40:01 -03001061 // In a multi-image setup, copy done might be set if any number of
1062 // images was already successfully swapped.
1063 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1064 warn!("copy_done should be unset");
1065 fails += 1;
1066 }
1067
David Brownc423ac42021-06-04 13:47:34 -06001068 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001069 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -07001070 fails += 1;
1071 }
1072
David Brown84b49f72019-03-01 10:58:22 -07001073 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -07001074 warn!("Image in the primary slot before revert is invalid at stop={}",
1075 stop);
1076 fails += 1;
1077 }
David Brown84b49f72019-03-01 10:58:22 -07001078 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -07001079 warn!("Image in the secondary slot before revert is invalid at stop={}",
1080 stop);
1081 fails += 1;
1082 }
David Brown84b49f72019-03-01 10:58:22 -07001083 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1084 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -07001085 warn!("Mismatched trailer for the primary slot before revert");
1086 fails += 1;
1087 }
David Brown84b49f72019-03-01 10:58:22 -07001088 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1089 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001090 warn!("Mismatched trailer for the secondary slot before revert");
1091 fails += 1;
1092 }
1093
1094 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001095 let mut counter = stop;
David Brownc423ac42021-06-04 13:47:34 -06001096 if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false).interrupted() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001097 warn!("Should have stopped revert at interruption point");
1098 fails += 1;
1099 }
1100
David Brownc423ac42021-06-04 13:47:34 -06001101 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001102 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -07001103 fails += 1;
1104 }
1105
David Brown84b49f72019-03-01 10:58:22 -07001106 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -07001107 warn!("Image in the primary slot after revert is invalid at stop={}",
1108 stop);
1109 fails += 1;
1110 }
David Brown84b49f72019-03-01 10:58:22 -07001111 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -07001112 warn!("Image in the secondary slot after revert is invalid at stop={}",
1113 stop);
1114 fails += 1;
1115 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001116
David Brown84b49f72019-03-01 10:58:22 -07001117 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1118 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001119 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -07001120 fails += 1;
1121 }
David Brown84b49f72019-03-01 10:58:22 -07001122 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1123 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -07001124 warn!("Mismatched trailer for the secondary slot after revert");
1125 fails += 1;
1126 }
1127
David Brownc423ac42021-06-04 13:47:34 -06001128 if !c::boot_go(&mut flash, &self.areadesc, None, false).success() {
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001129 warn!("Should have finished 3rd boot");
1130 fails += 1;
1131 }
1132
1133 if !self.verify_images(&flash, 0, 0) {
1134 warn!("Image in the primary slot is invalid on 1st boot after revert");
1135 fails += 1;
1136 }
1137 if !self.verify_images(&flash, 1, 1) {
1138 warn!("Image in the secondary slot is invalid on 1st boot after revert");
1139 fails += 1;
1140 }
1141
David Browndb505822019-03-01 10:04:20 -07001142 fails > 0
1143 }
1144
Fabio Utzigfc07eab2019-05-17 10:23:38 -07001145
David Browndb505822019-03-01 10:04:20 -07001146 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1147 let mut flash = self.flash.clone();
1148
David Brown84b49f72019-03-01 10:58:22 -07001149 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -07001150
1151 let mut rng = rand::thread_rng();
1152 let mut resets = vec![0i32; count];
1153 let mut remaining_ops = total_ops;
David Brownfbc8f7c2021-03-10 05:22:39 -07001154 for reset in &mut resets {
David Browncd842842020-07-09 15:46:53 -06001155 let reset_counter = rng.gen_range(1, remaining_ops / 2);
David Browndb505822019-03-01 10:04:20 -07001156 let mut counter = reset_counter;
1157 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
David Brownc423ac42021-06-04 13:47:34 -06001158 x if x.interrupted() => (),
1159 x => panic!("Unknown return: {:?}", x),
David Browndb505822019-03-01 10:04:20 -07001160 }
1161 remaining_ops -= reset_counter;
David Brownfbc8f7c2021-03-10 05:22:39 -07001162 *reset = reset_counter;
David Browndb505822019-03-01 10:04:20 -07001163 }
1164
1165 match c::boot_go(&mut flash, &self.areadesc, None, false) {
David Brownc423ac42021-06-04 13:47:34 -06001166 x if x.interrupted() => panic!("Should not be have been interrupted!"),
1167 x if x.success() => (),
1168 x => panic!("Unknown return: {:?}", x),
David Brown5c9e0f12019-01-09 16:34:33 -07001169 }
David Brown5c9e0f12019-01-09 16:34:33 -07001170
David Browndb505822019-03-01 10:04:20 -07001171 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001172 }
David Brown84b49f72019-03-01 10:58:22 -07001173
1174 /// Verify the image in the given flash device, the specified slot
1175 /// against the expected image.
1176 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001177 self.images.iter().all(|image| {
1178 verify_image(flash, &image.slots[slot],
1179 match against {
1180 0 => &image.primaries,
1181 1 => &image.upgrades,
1182 _ => panic!("Invalid 'against'")
1183 })
1184 })
David Brown84b49f72019-03-01 10:58:22 -07001185 }
1186
David Brownc3898d62019-08-05 14:20:02 -06001187 /// Verify the images, according to the dependency test.
1188 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1189 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1190 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1191 if !verify_image(flash, &image.slots[0],
1192 match upgrade {
1193 UpgradeInfo::Upgraded => &image.upgrades,
1194 UpgradeInfo::Held => &image.primaries,
1195 }) {
1196 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1197 return true;
1198 }
1199 }
1200
1201 false
1202 }
1203
Fabio Utzig8af7f792019-07-30 12:40:01 -03001204 /// Verify that at least one of the trailers of the images have the
1205 /// specified values.
1206 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1207 magic: Option<u8>, image_ok: Option<u8>,
1208 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001209 self.images.iter().any(|image| {
1210 verify_trailer(flash, &image.slots[slot],
1211 magic, image_ok, copy_done)
1212 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001213 }
1214
David Brown84b49f72019-03-01 10:58:22 -07001215 /// Verify that the trailers of the images have the specified
1216 /// values.
1217 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1218 magic: Option<u8>, image_ok: Option<u8>,
1219 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001220 self.images.iter().all(|image| {
1221 verify_trailer(flash, &image.slots[slot],
1222 magic, image_ok, copy_done)
1223 })
David Brown84b49f72019-03-01 10:58:22 -07001224 }
1225
1226 /// Mark each of the images for permanent upgrade.
1227 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1228 for image in &self.images {
1229 mark_permanent_upgrade(flash, &image.slots[slot]);
1230 }
1231 }
1232
1233 /// Mark each of the images for permanent upgrade.
1234 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1235 for image in &self.images {
1236 mark_upgrade(flash, &image.slots[slot]);
1237 }
1238 }
David Brown297029a2019-08-13 14:29:51 -06001239
1240 /// Dump out the flash image(s) to one or more files for debugging
1241 /// purposes. The names will be written as either "{prefix}.mcubin" or
1242 /// "{prefix}-001.mcubin" depending on how many images there are.
1243 pub fn debug_dump(&self, prefix: &str) {
1244 for (id, fdev) in &self.flash {
1245 let name = if self.flash.len() == 1 {
1246 format!("{}.mcubin", prefix)
1247 } else {
1248 format!("{}-{:>0}.mcubin", prefix, id)
1249 };
1250 fdev.write_file(&name).unwrap();
1251 }
1252 }
David Brown5c9e0f12019-01-09 16:34:33 -07001253}
1254
1255/// Show the flash layout.
1256#[allow(dead_code)]
1257fn show_flash(flash: &dyn Flash) {
1258 println!("---- Flash configuration ----");
1259 for sector in flash.sector_iter() {
1260 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1261 sector.num, sector.base, sector.size);
1262 }
David Brown599b2db2021-03-10 05:23:26 -07001263 println!();
David Brown5c9e0f12019-01-09 16:34:33 -07001264}
1265
1266/// Install a "program" into the given image. This fakes the image header, or at least all of the
1267/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001268fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownc3898d62019-08-05 14:20:02 -06001269 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001270 let offset = slot.base_off;
1271 let slot_len = slot.len;
1272 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001273
David Brown43643dd2019-01-11 15:43:28 -07001274 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001275
David Brownc3898d62019-08-05 14:20:02 -06001276 // Add the dependencies early to the tlv.
1277 for dep in deps.my_deps(offset, slot.index) {
1278 tlv.add_dependency(deps.other_id(), &dep);
1279 }
1280
David Brown5c9e0f12019-01-09 16:34:33 -07001281 const HDR_SIZE: usize = 32;
1282
1283 // Generate a boot header. Note that the size doesn't include the header.
1284 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001285 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -07001286 load_addr: 0,
1287 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001288 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001289 img_size: len as u32,
1290 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001291 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001292 _pad2: 0,
1293 };
1294
1295 let mut b_header = [0; HDR_SIZE];
1296 b_header[..32].clone_from_slice(header.as_raw());
1297 assert_eq!(b_header.len(), HDR_SIZE);
1298
1299 tlv.add_bytes(&b_header);
1300
1301 // The core of the image itself is just pseudorandom data.
1302 let mut b_img = vec![0; len];
1303 splat(&mut b_img, offset);
1304
David Browncb47dd72019-08-05 14:21:49 -06001305 // Add some information at the start of the payload to make it easier
1306 // to see what it is. This will fail if the image itself is too small.
1307 {
1308 let mut wr = Cursor::new(&mut b_img);
1309 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1310 offset, dev_id, slot).unwrap();
1311 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1312 }
1313
David Brown5c9e0f12019-01-09 16:34:33 -07001314 // TLV signatures work over plain image
1315 tlv.add_bytes(&b_img);
1316
1317 // Generate encrypted images
Salome Thirot6fdbf552021-05-14 16:46:14 +01001318 let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1319 let is_encrypted = (tlv.get_flags() & flag) != 0;
David Brown5c9e0f12019-01-09 16:34:33 -07001320 let mut b_encimg = vec![];
1321 if is_encrypted {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001322 let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1323 let aes256 = (tlv.get_flags() & flag) == flag;
Fabio Utzig90f449e2019-10-24 07:43:53 -03001324 tlv.generate_enc_key();
1325 let enc_key = tlv.get_enc_key();
David Brown5c9e0f12019-01-09 16:34:33 -07001326 let nonce = GenericArray::from_slice(&[0; 16]);
David Brown5c9e0f12019-01-09 16:34:33 -07001327 b_encimg = b_img.clone();
Salome Thirot6fdbf552021-05-14 16:46:14 +01001328 if aes256 {
1329 let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
1330 let mut cipher = Aes256Ctr::new(&key, &nonce);
1331 cipher.apply_keystream(&mut b_encimg);
1332 } else {
1333 let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
1334 let mut cipher = Aes128Ctr::new(&key, &nonce);
1335 cipher.apply_keystream(&mut b_encimg);
1336 }
David Brown5c9e0f12019-01-09 16:34:33 -07001337 }
1338
1339 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001340 if bad_sig {
1341 tlv.corrupt_sig();
1342 }
1343 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001344
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001345 let dev = flash.get_mut(&dev_id).unwrap();
1346
David Brown5c9e0f12019-01-09 16:34:33 -07001347 let mut buf = vec![];
1348 buf.append(&mut b_header.to_vec());
1349 buf.append(&mut b_img);
1350 buf.append(&mut b_tlv.clone());
1351
David Brown95de4502019-11-15 12:01:34 -07001352 // Pad the buffer to a multiple of the flash alignment.
1353 let align = dev.align();
1354 while buf.len() % align != 0 {
1355 buf.push(dev.erased_val());
1356 }
1357
David Brown5c9e0f12019-01-09 16:34:33 -07001358 let mut encbuf = vec![];
1359 if is_encrypted {
1360 encbuf.append(&mut b_header.to_vec());
1361 encbuf.append(&mut b_encimg);
1362 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001363
1364 while encbuf.len() % align != 0 {
1365 encbuf.push(dev.erased_val());
1366 }
David Brown5c9e0f12019-01-09 16:34:33 -07001367 }
1368
David Vincze2d736ad2019-02-18 11:50:22 +01001369 // Since images are always non-encrypted in the primary slot, we first write
1370 // an encrypted image, re-read to use for verification, erase + flash
1371 // un-encrypted. In the secondary slot the image is written un-encrypted,
1372 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001373
David Brown3b090212019-07-30 15:59:28 -06001374 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001375 let enc_copy: Option<Vec<u8>>;
1376
1377 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001378 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001379
1380 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001381 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001382
1383 enc_copy = Some(enc);
1384
David Brown76101572019-02-28 11:29:03 -07001385 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001386 } else {
1387 enc_copy = None;
1388 }
1389
David Brown76101572019-02-28 11:29:03 -07001390 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001391
1392 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001393 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001394
David Brownca234692019-02-28 11:22:19 -07001395 ImageData {
1396 plain: copy,
1397 cipher: enc_copy,
1398 }
David Brown5c9e0f12019-01-09 16:34:33 -07001399 } else {
1400
David Brown76101572019-02-28 11:29:03 -07001401 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001402
1403 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001404 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001405
1406 let enc_copy: Option<Vec<u8>>;
1407
1408 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001409 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001410
David Brown76101572019-02-28 11:29:03 -07001411 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001412
1413 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001414 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001415
1416 enc_copy = Some(enc);
1417 } else {
1418 enc_copy = None;
1419 }
1420
David Brownca234692019-02-28 11:22:19 -07001421 ImageData {
1422 plain: copy,
1423 cipher: enc_copy,
1424 }
David Brown5c9e0f12019-01-09 16:34:33 -07001425 }
David Brown5c9e0f12019-01-09 16:34:33 -07001426}
1427
David Brown873be312019-09-03 12:22:32 -06001428/// Install no image. This is used when no upgrade happens.
1429fn install_no_image() -> ImageData {
1430 ImageData {
1431 plain: vec![],
1432 cipher: None,
1433 }
1434}
1435
David Brown5c9e0f12019-01-09 16:34:33 -07001436fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001437 if Caps::EcdsaP224.present() {
1438 panic!("Ecdsa P224 not supported in Simulator");
1439 }
Salome Thirot6fdbf552021-05-14 16:46:14 +01001440 let mut aes_key_size = 128;
1441 if Caps::Aes256.present() {
1442 aes_key_size = 256;
1443 }
David Brown5c9e0f12019-01-09 16:34:33 -07001444
David Brownb8882112019-01-11 14:04:11 -07001445 if Caps::EncKw.present() {
1446 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001447 TlvGen::new_rsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001448 } else if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001449 TlvGen::new_ecdsa_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001450 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001451 TlvGen::new_enc_kw(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001452 }
1453 } else if Caps::EncRsa.present() {
1454 if Caps::RSA2048.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001455 TlvGen::new_sig_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001456 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001457 TlvGen::new_enc_rsa(aes_key_size)
David Brownb8882112019-01-11 14:04:11 -07001458 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001459 } else if Caps::EncEc256.present() {
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001460 if Caps::EcdsaP256.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001461 TlvGen::new_ecdsa_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001462 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001463 TlvGen::new_ecies_p256(aes_key_size)
Fabio Utzig66b4caa2020-01-04 20:19:28 -03001464 }
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001465 } else if Caps::EncX25519.present() {
1466 if Caps::Ed25519.present() {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001467 TlvGen::new_ed25519_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001468 } else {
Salome Thirot6fdbf552021-05-14 16:46:14 +01001469 TlvGen::new_ecies_x25519(aes_key_size)
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001470 }
David Brownb8882112019-01-11 14:04:11 -07001471 } else {
1472 // The non-encrypted configuration.
1473 if Caps::RSA2048.present() {
1474 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001475 } else if Caps::RSA3072.present() {
1476 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001477 } else if Caps::EcdsaP256.present() {
1478 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001479 } else if Caps::Ed25519.present() {
1480 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001481 } else {
1482 TlvGen::new_hash_only()
1483 }
1484 }
David Brown5c9e0f12019-01-09 16:34:33 -07001485}
1486
David Brownca234692019-02-28 11:22:19 -07001487impl ImageData {
1488 /// Find the image contents for the given slot. This assumes that slot 0
1489 /// is unencrypted, and slot 1 is encrypted.
1490 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001491 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
Fabio Utzig3fa72ca2020-04-02 11:20:37 -03001492 Caps::EncEc256.present() || Caps::EncX25519.present();
David Brownca234692019-02-28 11:22:19 -07001493 match (encrypted, slot) {
1494 (false, _) => &self.plain,
1495 (true, 0) => &self.plain,
1496 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1497 _ => panic!("Invalid slot requested"),
1498 }
David Brown5c9e0f12019-01-09 16:34:33 -07001499 }
1500}
1501
David Brown5c9e0f12019-01-09 16:34:33 -07001502/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001503fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1504 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001505 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001506 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001507
1508 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001509 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001510 let dev = flash.get(&dev_id).unwrap();
1511 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001512
1513 if buf != &copy[..] {
1514 for i in 0 .. buf.len() {
1515 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001516 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1517 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001518 break;
1519 }
1520 }
1521 false
1522 } else {
1523 true
1524 }
1525}
1526
David Brown3b090212019-07-30 15:59:28 -06001527fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001528 magic: Option<u8>, image_ok: Option<u8>,
1529 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001530 if Caps::OverwriteUpgrade.present() {
1531 return true;
1532 }
David Brown5c9e0f12019-01-09 16:34:33 -07001533
David Brown3b090212019-07-30 15:59:28 -06001534 let offset = slot.trailer_off + c::boot_max_align();
1535 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001536 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001537 let mut failed = false;
1538
David Brown76101572019-02-28 11:29:03 -07001539 let dev = flash.get(&dev_id).unwrap();
1540 let erased_val = dev.erased_val();
1541 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001542
1543 failed |= match magic {
1544 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001545 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001546 warn!("\"magic\" mismatch at {:#x}", offset);
1547 true
1548 } else if v == 3 {
1549 let expected = [erased_val; 16];
David Brownd36f6b12021-03-10 05:23:56 -07001550 if copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001551 warn!("\"magic\" mismatch at {:#x}", offset);
1552 true
1553 } else {
1554 false
1555 }
1556 } else {
1557 false
1558 }
1559 },
1560 None => false,
1561 };
1562
1563 failed |= match image_ok {
1564 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001565 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001566 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1567 true
1568 } else {
1569 false
1570 }
1571 },
1572 None => false,
1573 };
1574
1575 failed |= match copy_done {
1576 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001577 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001578 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1579 true
1580 } else {
1581 false
1582 }
1583 },
1584 None => false,
1585 };
1586
1587 !failed
1588}
1589
David Brown297029a2019-08-13 14:29:51 -06001590/// Install a partition table. This is a simplified partition table that
1591/// we write at the beginning of flash so make it easier for external tools
1592/// to analyze these images.
1593fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1594 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1595 for &id in &ids {
1596 // If there are any partitions in this device that start at 0, and
1597 // aren't marked as the BootLoader partition, avoid adding the
1598 // partition table. This makes it harder to view the image, but
1599 // avoids messing up images already written.
David Brown80f836d2021-03-10 05:24:33 -07001600 let skip_ptable = areadesc
1601 .iter_areas()
1602 .any(|area| {
1603 area.device_id == id &&
1604 area.off == 0 &&
1605 area.flash_id != FlashId::BootLoader
1606 });
1607 if skip_ptable {
David Brown297029a2019-08-13 14:29:51 -06001608 if log_enabled!(Info) {
1609 let special: Vec<FlashId> = areadesc.iter_areas()
1610 .filter(|area| area.device_id == id && area.off == 0)
1611 .map(|area| area.flash_id)
1612 .collect();
1613 info!("Skipping partition table: {:?}", special);
1614 }
1615 break;
1616 }
1617
1618 let mut buf: Vec<u8> = vec![];
1619 write!(&mut buf, "mcuboot\0").unwrap();
1620
1621 // Iterate through all of the partitions in that device, and encode
1622 // into the table.
1623 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1624 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1625
1626 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1627 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1628 buf.write_u32::<LittleEndian>(area.off).unwrap();
1629 buf.write_u32::<LittleEndian>(area.size).unwrap();
1630 buf.write_u32::<LittleEndian>(0).unwrap();
1631 }
1632
1633 let dev = flash.get_mut(&id).unwrap();
1634
1635 // Pad to alignment.
1636 while buf.len() % dev.align() != 0 {
1637 buf.push(0);
1638 }
1639
1640 dev.write(0, &buf).unwrap();
1641 }
1642}
1643
David Brown5c9e0f12019-01-09 16:34:33 -07001644/// The image header
1645#[repr(C)]
David Brown2ee5f7f2020-01-13 14:04:01 -07001646#[derive(Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001647pub struct ImageHeader {
1648 magic: u32,
1649 load_addr: u32,
1650 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001651 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001652 img_size: u32,
1653 flags: u32,
1654 ver: ImageVersion,
1655 _pad2: u32,
1656}
1657
1658impl AsRaw for ImageHeader {}
1659
1660#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001661#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001662pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001663 pub major: u8,
1664 pub minor: u8,
1665 pub revision: u16,
1666 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001667}
1668
David Brownc3898d62019-08-05 14:20:02 -06001669#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001670pub struct SlotInfo {
1671 pub base_off: usize,
1672 pub trailer_off: usize,
1673 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001674 // Which slot within this device.
1675 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001676 pub dev_id: u8,
1677}
1678
David Brown347dc572019-11-15 11:37:25 -07001679const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1680 0x60, 0xd2, 0xef, 0x7f,
1681 0x35, 0x52, 0x50, 0x0f,
1682 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001683
1684// Replicates defines found in bootutil.h
1685const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1686const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1687
1688const BOOT_FLAG_SET: Option<u8> = Some(1);
1689const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1690
1691/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001692pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1693 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001694 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001695 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001696 if offset % align != 0 || MAGIC.len() % align != 0 {
1697 // The write size is larger than the magic value. Fill a buffer
1698 // with the erased value, put the MAGIC in it, and write it in its
1699 // entirety.
1700 let mut buf = vec![dev.erased_val(); align];
1701 buf[(offset % align)..].copy_from_slice(MAGIC);
1702 dev.write(offset - (offset % align), &buf).unwrap();
1703 } else {
1704 dev.write(offset, MAGIC).unwrap();
1705 }
David Brown5c9e0f12019-01-09 16:34:33 -07001706}
1707
1708/// Writes the image_ok flag which, guess what, tells the bootloader
1709/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001710fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001711 // Overwrite mode always is permanent, and only the magic is used in
1712 // the trailer. To avoid problems with large write sizes, don't try to
1713 // set anything in this case.
1714 if Caps::OverwriteUpgrade.present() {
1715 return;
1716 }
1717
David Brown76101572019-02-28 11:29:03 -07001718 let dev = flash.get_mut(&slot.dev_id).unwrap();
1719 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001720 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001721 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001722 let align = dev.align();
1723 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001724}
1725
1726// Drop some pseudo-random gibberish onto the data.
1727fn splat(data: &mut [u8], seed: usize) {
David Browncd842842020-07-09 15:46:53 -06001728 let mut seed_block = [0u8; 16];
1729 let mut buf = Cursor::new(&mut seed_block[..]);
1730 buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
1731 buf.write_u32::<LittleEndian>(0x92184728).unwrap();
1732 buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
1733 buf.write_u32::<LittleEndian>(seed as u32).unwrap();
1734 let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
David Brown5c9e0f12019-01-09 16:34:33 -07001735 rng.fill_bytes(data);
1736}
1737
1738/// Return a read-only view into the raw bytes of this object
1739trait AsRaw : Sized {
David Brown173e6ca2021-03-10 05:25:36 -07001740 fn as_raw(&self) -> &[u8] {
David Brown5c9e0f12019-01-09 16:34:33 -07001741 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1742 mem::size_of::<Self>()) }
1743 }
1744}
1745
1746pub fn show_sizes() {
1747 // This isn't panic safe.
1748 for min in &[1, 2, 4, 8] {
1749 let msize = c::boot_trailer_sz(*min);
1750 println!("{:2}: {} (0x{:x})", min, msize, msize);
1751 }
1752}
David Brown95de4502019-11-15 12:01:34 -07001753
1754#[cfg(not(feature = "large-write"))]
1755fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001756 &[1, 2, 4, 8]
1757}
1758
1759#[cfg(feature = "large-write")]
1760fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001761 &[1, 2, 4, 8, 128, 512]
1762}