blob: b7f8ed62535613ccb6c919837021f674e24f5bad [file] [log] [blame]
David Brown297029a2019-08-13 14:29:51 -06001use byteorder::{
2 LittleEndian, WriteBytesExt,
3};
4use log::{
5 Level::Info,
6 error,
7 info,
8 log_enabled,
9 warn,
10};
David Brown5c9e0f12019-01-09 16:34:33 -070011use rand::{
12 distributions::{IndependentSample, Range},
13 Rng, SeedableRng, XorShiftRng,
14};
15use std::{
David Brown297029a2019-08-13 14:29:51 -060016 collections::HashSet,
David Browncb47dd72019-08-05 14:21:49 -060017 io::{Cursor, Write},
David Brown5c9e0f12019-01-09 16:34:33 -070018 mem,
19 slice,
20};
21use aes_ctr::{
22 Aes128Ctr,
23 stream_cipher::{
24 generic_array::GenericArray,
25 NewFixStreamCipher,
26 StreamCipherCore,
27 },
28};
29
David Brown76101572019-02-28 11:29:03 -070030use simflash::{Flash, SimFlash, SimMultiFlash};
David Browne5133242019-02-28 11:05:19 -070031use mcuboot_sys::{c, AreaDesc, FlashId};
32use crate::{
33 ALL_DEVICES,
34 DeviceName,
35};
David Brown5c9e0f12019-01-09 16:34:33 -070036use crate::caps::Caps;
David Brownc3898d62019-08-05 14:20:02 -060037use crate::depends::{
38 BoringDep,
39 Depender,
40 DepTest,
David Brown873be312019-09-03 12:22:32 -060041 DepType,
David Brownc3898d62019-08-05 14:20:02 -060042 PairDep,
43 UpgradeInfo,
44};
Fabio Utzig90f449e2019-10-24 07:43:53 -030045use crate::tlv::{ManifestGen, TlvGen, TlvFlags};
David Brown5c9e0f12019-01-09 16:34:33 -070046
David Browne5133242019-02-28 11:05:19 -070047/// A builder for Images. This describes a single run of the simulator,
48/// capturing the configuration of a particular set of devices, including
49/// the flash simulator(s) and the information about the slots.
50#[derive(Clone)]
51pub struct ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -070052 flash: SimMultiFlash,
David Browne5133242019-02-28 11:05:19 -070053 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070054 slots: Vec<[SlotInfo; 2]>,
David Browne5133242019-02-28 11:05:19 -070055}
56
David Brown998aa8d2019-02-28 10:54:50 -070057/// Images represents the state of a simulation for a given set of images.
David Brown76101572019-02-28 11:29:03 -070058/// The flash holds the state of the simulated flash, whereas primaries
David Brown998aa8d2019-02-28 10:54:50 -070059/// and upgrades hold the expected contents of these images.
60pub struct Images {
David Brown76101572019-02-28 11:29:03 -070061 flash: SimMultiFlash,
David Brownca234692019-02-28 11:22:19 -070062 areadesc: AreaDesc,
David Brown84b49f72019-03-01 10:58:22 -070063 images: Vec<OneImage>,
64 total_count: Option<i32>,
65}
66
67/// When doing multi-image, there is an instance of this information for
68/// each of the images. Single image there will be one of these.
69struct OneImage {
David Brownca234692019-02-28 11:22:19 -070070 slots: [SlotInfo; 2],
71 primaries: ImageData,
72 upgrades: ImageData,
David Brownca234692019-02-28 11:22:19 -070073}
74
75/// The Rust-side representation of an image. For unencrypted images, this
76/// is just the unencrypted payload. For encrypted images, we store both
77/// the encrypted and the plaintext.
78struct ImageData {
79 plain: Vec<u8>,
80 cipher: Option<Vec<u8>>,
David Brown998aa8d2019-02-28 10:54:50 -070081}
82
David Browne5133242019-02-28 11:05:19 -070083impl ImagesBuilder {
David Brown5bc62c62019-03-05 12:11:48 -070084 /// Construct a new image builder for the given device. Returns
85 /// Some(builder) if is possible to test this configuration, or None if
86 /// not possible (for example, if there aren't enough image slots).
Fabio Utzig114a6472019-11-28 10:24:09 -030087 pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
88 let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
89
90 for cap in unsupported_caps {
91 if cap.present() {
92 return Err(format!("unsupported {:?}", cap));
93 }
94 }
David Browne5133242019-02-28 11:05:19 -070095
David Brown06ef06e2019-03-05 12:28:10 -070096 let num_images = Caps::get_num_images();
David Browne5133242019-02-28 11:05:19 -070097
David Brown06ef06e2019-03-05 12:28:10 -070098 let mut slots = Vec::with_capacity(num_images);
99 for image in 0..num_images {
100 // This mapping must match that defined in
101 // `boot/zephyr/include/sysflash/sysflash.h`.
102 let id0 = match image {
103 0 => FlashId::Image0,
104 1 => FlashId::Image2,
105 _ => panic!("More than 2 images not supported"),
106 };
107 let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
108 Some(info) => info,
Fabio Utzig114a6472019-11-28 10:24:09 -0300109 None => return Err("insufficient partitions".to_string()),
David Brown06ef06e2019-03-05 12:28:10 -0700110 };
111 let id1 = match image {
112 0 => FlashId::Image1,
113 1 => FlashId::Image3,
114 _ => panic!("More than 2 images not supported"),
115 };
116 let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
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 };
David Browne5133242019-02-28 11:05:19 -0700120
Christopher Collinsa1c12042019-05-23 14:00:28 -0700121 let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
David Browne5133242019-02-28 11:05:19 -0700122
David Brown06ef06e2019-03-05 12:28:10 -0700123 // Construct a primary image.
124 let primary = SlotInfo {
125 base_off: primary_base as usize,
126 trailer_off: primary_base + primary_len - offset_from_end,
127 len: primary_len as usize,
128 dev_id: primary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600129 index: 0,
David Brown06ef06e2019-03-05 12:28:10 -0700130 };
131
132 // And an upgrade image.
133 let secondary = SlotInfo {
134 base_off: secondary_base as usize,
135 trailer_off: secondary_base + secondary_len - offset_from_end,
136 len: secondary_len as usize,
137 dev_id: secondary_dev_id,
David Brown3b090212019-07-30 15:59:28 -0600138 index: 1,
David Brown06ef06e2019-03-05 12:28:10 -0700139 };
140
141 slots.push([primary, secondary]);
142 }
David Browne5133242019-02-28 11:05:19 -0700143
Fabio Utzig114a6472019-11-28 10:24:09 -0300144 Ok(ImagesBuilder {
David Brown76101572019-02-28 11:29:03 -0700145 flash: flash,
David Browne5133242019-02-28 11:05:19 -0700146 areadesc: areadesc,
David Brown06ef06e2019-03-05 12:28:10 -0700147 slots: slots,
David Brown5bc62c62019-03-05 12:11:48 -0700148 })
David Browne5133242019-02-28 11:05:19 -0700149 }
150
151 pub fn each_device<F>(f: F)
152 where F: Fn(Self)
153 {
154 for &dev in ALL_DEVICES {
David Brown95de4502019-11-15 12:01:34 -0700155 for &align in test_alignments() {
David Browne5133242019-02-28 11:05:19 -0700156 for &erased_val in &[0, 0xff] {
David Brown5bc62c62019-03-05 12:11:48 -0700157 match Self::new(dev, align, erased_val) {
Fabio Utzig114a6472019-11-28 10:24:09 -0300158 Ok(run) => f(run),
159 Err(msg) => warn!("Skipping {}: {}", dev, msg),
David Brown5bc62c62019-03-05 12:11:48 -0700160 }
David Browne5133242019-02-28 11:05:19 -0700161 }
162 }
163 }
164 }
165
166 /// Construct an `Images` that doesn't expect an upgrade to happen.
David Brownc3898d62019-08-05 14:20:02 -0600167 pub fn make_no_upgrade_image(self, deps: &DepTest) -> Images {
168 let num_images = self.num_images();
David Brown76101572019-02-28 11:29:03 -0700169 let mut flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600170 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
171 let dep: Box<dyn Depender> = if num_images > 1 {
172 Box::new(PairDep::new(num_images, image_num, deps))
173 } else {
174 Box::new(BoringDep(image_num))
175 };
176 let primaries = install_image(&mut flash, &slots[0], 42784, &*dep, false);
David Brown873be312019-09-03 12:22:32 -0600177 let upgrades = match deps.depends[image_num] {
178 DepType::NoUpgrade => install_no_image(),
179 _ => install_image(&mut flash, &slots[1], 46928, &*dep, false)
180 };
David Brown84b49f72019-03-01 10:58:22 -0700181 OneImage {
182 slots: slots,
183 primaries: primaries,
184 upgrades: upgrades,
185 }}).collect();
David Brown297029a2019-08-13 14:29:51 -0600186 install_ptable(&mut flash, &self.areadesc);
David Browne5133242019-02-28 11:05:19 -0700187 Images {
David Brown76101572019-02-28 11:29:03 -0700188 flash: flash,
David Browne5133242019-02-28 11:05:19 -0700189 areadesc: self.areadesc,
David Brown84b49f72019-03-01 10:58:22 -0700190 images: images,
David Browne5133242019-02-28 11:05:19 -0700191 total_count: None,
192 }
193 }
194
David Brownc3898d62019-08-05 14:20:02 -0600195 pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
196 let mut images = self.make_no_upgrade_image(deps);
David Brown84b49f72019-03-01 10:58:22 -0700197 for image in &images.images {
198 mark_upgrade(&mut images.flash, &image.slots[1]);
199 }
David Browne5133242019-02-28 11:05:19 -0700200
201 // upgrades without fails, counts number of flash operations
Fabio Utziged4a5362019-07-30 12:43:23 -0300202 let total_count = match images.run_basic_upgrade(permanent) {
David Browne5133242019-02-28 11:05:19 -0700203 Ok(v) => v,
Fabio Utzig7c1d1552019-08-28 10:59:22 -0300204 Err(_) =>
David Brown0e6bc7f2019-09-03 12:29:56 -0600205 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
206 0
207 } else {
208 panic!("Unable to perform basic upgrade");
209 }
David Browne5133242019-02-28 11:05:19 -0700210 };
211
212 images.total_count = Some(total_count);
213 images
214 }
215
216 pub fn make_bad_secondary_slot_image(self) -> Images {
David Brown76101572019-02-28 11:29:03 -0700217 let mut bad_flash = self.flash;
David Brownc3898d62019-08-05 14:20:02 -0600218 let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
219 let dep = BoringDep(image_num);
220 let primaries = install_image(&mut bad_flash, &slots[0], 32784, &dep, false);
221 let upgrades = install_image(&mut bad_flash, &slots[1], 41928, &dep, true);
David Brown84b49f72019-03-01 10:58:22 -0700222 OneImage {
223 slots: slots,
224 primaries: primaries,
225 upgrades: upgrades,
226 }}).collect();
David Browne5133242019-02-28 11:05:19 -0700227 Images {
David Brown76101572019-02-28 11:29:03 -0700228 flash: bad_flash,
David Browne5133242019-02-28 11:05:19 -0700229 areadesc: self.areadesc,
David Brown84b49f72019-03-01 10:58:22 -0700230 images: images,
David Browne5133242019-02-28 11:05:19 -0700231 total_count: None,
232 }
233 }
234
235 /// Build the Flash and area descriptor for a given device.
Fabio Utzig114a6472019-11-28 10:24:09 -0300236 pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, AreaDesc, &'static [Caps]) {
David Browne5133242019-02-28 11:05:19 -0700237 match device {
238 DeviceName::Stm32f4 => {
239 // STM style flash. Large sectors, with a large scratch area.
David Brown76101572019-02-28 11:29:03 -0700240 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024,
241 64 * 1024,
242 128 * 1024, 128 * 1024, 128 * 1024],
243 align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700244 let dev_id = 0;
245 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700246 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700247 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
248 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
249 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
250
David Brown76101572019-02-28 11:29:03 -0700251 let mut flash = SimMultiFlash::new();
252 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300253 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700254 }
255 DeviceName::K64f => {
256 // NXP style flash. Small sectors, one small sector for scratch.
David Brown76101572019-02-28 11:29:03 -0700257 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700258
259 let dev_id = 0;
260 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700261 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700262 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
263 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
264 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
265
David Brown76101572019-02-28 11:29:03 -0700266 let mut flash = SimMultiFlash::new();
267 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300268 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700269 }
270 DeviceName::K64fBig => {
271 // Simulating an STM style flash on top of an NXP style flash. Underlying flash device
272 // uses small sectors, but we tell the bootloader they are large.
David Brown76101572019-02-28 11:29:03 -0700273 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700274
275 let dev_id = 0;
276 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700277 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700278 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
279 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
280 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
281
David Brown76101572019-02-28 11:29:03 -0700282 let mut flash = SimMultiFlash::new();
283 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300284 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700285 }
286 DeviceName::Nrf52840 => {
287 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
288 // does not divide into the image size.
David Brown76101572019-02-28 11:29:03 -0700289 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700290
291 let dev_id = 0;
292 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700293 areadesc.add_flash_sectors(dev_id, &dev);
David Browne5133242019-02-28 11:05:19 -0700294 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
295 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
296 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
297
David Brown76101572019-02-28 11:29:03 -0700298 let mut flash = SimMultiFlash::new();
299 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300300 (flash, areadesc, &[])
David Browne5133242019-02-28 11:05:19 -0700301 }
302 DeviceName::Nrf52840SpiFlash => {
303 // Simulate nrf52840 with external SPI flash. The external SPI flash
304 // has a larger sector size so for now store scratch on that flash.
David Brown76101572019-02-28 11:29:03 -0700305 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
306 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
David Browne5133242019-02-28 11:05:19 -0700307
308 let mut areadesc = AreaDesc::new();
David Brown76101572019-02-28 11:29:03 -0700309 areadesc.add_flash_sectors(0, &dev0);
310 areadesc.add_flash_sectors(1, &dev1);
David Browne5133242019-02-28 11:05:19 -0700311
312 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
313 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
314 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
315
David Brown76101572019-02-28 11:29:03 -0700316 let mut flash = SimMultiFlash::new();
317 flash.insert(0, dev0);
318 flash.insert(1, dev1);
Fabio Utzig114a6472019-11-28 10:24:09 -0300319 (flash, areadesc, &[Caps::SwapUsingMove])
David Browne5133242019-02-28 11:05:19 -0700320 }
David Brown2bff6472019-03-05 13:58:35 -0700321 DeviceName::K64fMulti => {
322 // NXP style flash, but larger, to support multiple images.
323 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
324
325 let dev_id = 0;
326 let mut areadesc = AreaDesc::new();
327 areadesc.add_flash_sectors(dev_id, &dev);
328 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
329 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
330 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
331 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
332 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
333
334 let mut flash = SimMultiFlash::new();
335 flash.insert(dev_id, dev);
Fabio Utzig114a6472019-11-28 10:24:09 -0300336 (flash, areadesc, &[])
David Brown2bff6472019-03-05 13:58:35 -0700337 }
David Browne5133242019-02-28 11:05:19 -0700338 }
339 }
David Brownc3898d62019-08-05 14:20:02 -0600340
341 pub fn num_images(&self) -> usize {
342 self.slots.len()
343 }
David Browne5133242019-02-28 11:05:19 -0700344}
345
David Brown5c9e0f12019-01-09 16:34:33 -0700346impl Images {
347 /// A simple upgrade without forced failures.
348 ///
349 /// Returns the number of flash operations which can later be used to
350 /// inject failures at chosen steps.
Fabio Utziged4a5362019-07-30 12:43:23 -0300351 pub fn run_basic_upgrade(&self, permanent: bool) -> Result<i32, ()> {
352 let (flash, total_count) = self.try_upgrade(None, permanent);
David Brown5c9e0f12019-01-09 16:34:33 -0700353 info!("Total flash operation count={}", total_count);
354
David Brown84b49f72019-03-01 10:58:22 -0700355 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700356 warn!("Image mismatch after first boot");
357 Err(())
358 } else {
359 Ok(total_count)
360 }
361 }
362
David Brownc3898d62019-08-05 14:20:02 -0600363 /// Test a simple upgrade, with dependencies given, and verify that the
364 /// image does as is described in the test.
365 pub fn run_check_deps(&self, deps: &DepTest) -> bool {
366 let (flash, _) = self.try_upgrade(None, true);
367
368 self.verify_dep_images(&flash, deps)
369 }
370
Fabio Utzigf5480c72019-11-28 10:41:57 -0300371 fn is_swap_upgrade(&self) -> bool {
372 Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
373 }
374
David Brown5c9e0f12019-01-09 16:34:33 -0700375 pub fn run_basic_revert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700376 if Caps::OverwriteUpgrade.present() {
377 return false;
378 }
David Brown5c9e0f12019-01-09 16:34:33 -0700379
David Brown5c9e0f12019-01-09 16:34:33 -0700380 let mut fails = 0;
381
382 // FIXME: this test would also pass if no swap is ever performed???
Fabio Utzigf5480c72019-11-28 10:41:57 -0300383 if self.is_swap_upgrade() {
David Brown5c9e0f12019-01-09 16:34:33 -0700384 for count in 2 .. 5 {
385 info!("Try revert: {}", count);
David Browndb505822019-03-01 10:04:20 -0700386 let flash = self.try_revert(count);
David Brown84b49f72019-03-01 10:58:22 -0700387 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700388 error!("Revert failure on count {}", count);
389 fails += 1;
390 }
391 }
392 }
393
394 fails > 0
395 }
396
397 pub fn run_perm_with_fails(&self) -> bool {
398 let mut fails = 0;
399 let total_flash_ops = self.total_count.unwrap();
400
401 // Let's try an image halfway through.
402 for i in 1 .. total_flash_ops {
403 info!("Try interruption at {}", i);
Fabio Utziged4a5362019-07-30 12:43:23 -0300404 let (flash, count) = self.try_upgrade(Some(i), true);
David Brown5c9e0f12019-01-09 16:34:33 -0700405 info!("Second boot, count={}", count);
David Brown84b49f72019-03-01 10:58:22 -0700406 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700407 warn!("FAIL at step {} of {}", i, total_flash_ops);
408 fails += 1;
409 }
410
David Brown84b49f72019-03-01 10:58:22 -0700411 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
412 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100413 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700414 fails += 1;
415 }
416
David Brown84b49f72019-03-01 10:58:22 -0700417 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
418 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100419 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700420 fails += 1;
421 }
422
Fabio Utzigf5480c72019-11-28 10:41:57 -0300423 if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700424 if !self.verify_images(&flash, 1, 0) {
David Vincze2d736ad2019-02-18 11:50:22 +0100425 warn!("Secondary slot FAIL at step {} of {}",
426 i, total_flash_ops);
David Brown5c9e0f12019-01-09 16:34:33 -0700427 fails += 1;
428 }
429 }
430 }
431
432 if fails > 0 {
433 error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
434 fails as f32 * 100.0 / total_flash_ops as f32);
435 }
436
437 fails > 0
438 }
439
David Brown5c9e0f12019-01-09 16:34:33 -0700440 pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
441 let mut fails = 0;
442 let total_flash_ops = self.total_count.unwrap();
David Browndb505822019-03-01 10:04:20 -0700443 let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
David Brown5c9e0f12019-01-09 16:34:33 -0700444 info!("Random interruptions at reset points={:?}", total_counts);
445
David Brown84b49f72019-03-01 10:58:22 -0700446 let primary_slot_ok = self.verify_images(&flash, 0, 1);
Fabio Utzigf5480c72019-11-28 10:41:57 -0300447 let secondary_slot_ok = if self.is_swap_upgrade() {
David Brown84b49f72019-03-01 10:58:22 -0700448 // TODO: This result is ignored.
449 self.verify_images(&flash, 1, 0)
David Brown5c9e0f12019-01-09 16:34:33 -0700450 } else {
451 true
452 };
David Vincze2d736ad2019-02-18 11:50:22 +0100453 if !primary_slot_ok || !secondary_slot_ok {
454 error!("Image mismatch after random interrupts: primary slot={} \
455 secondary slot={}",
456 if primary_slot_ok { "ok" } else { "fail" },
457 if secondary_slot_ok { "ok" } else { "fail" });
David Brown5c9e0f12019-01-09 16:34:33 -0700458 fails += 1;
459 }
David Brown84b49f72019-03-01 10:58:22 -0700460 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
461 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100462 error!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700463 fails += 1;
464 }
David Brown84b49f72019-03-01 10:58:22 -0700465 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
466 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100467 error!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700468 fails += 1;
469 }
470
471 if fails > 0 {
472 error!("Error testing perm upgrade with {} fails", total_fails);
473 }
474
475 fails > 0
476 }
477
David Brown5c9e0f12019-01-09 16:34:33 -0700478 pub fn run_revert_with_fails(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700479 if Caps::OverwriteUpgrade.present() {
480 return false;
481 }
David Brown5c9e0f12019-01-09 16:34:33 -0700482
David Brown5c9e0f12019-01-09 16:34:33 -0700483 let mut fails = 0;
484
Fabio Utzigf5480c72019-11-28 10:41:57 -0300485 if self.is_swap_upgrade() {
Fabio Utziged4a5362019-07-30 12:43:23 -0300486 for i in 1 .. self.total_count.unwrap() {
David Brown5c9e0f12019-01-09 16:34:33 -0700487 info!("Try interruption at {}", i);
David Browndb505822019-03-01 10:04:20 -0700488 if self.try_revert_with_fail_at(i) {
David Brown5c9e0f12019-01-09 16:34:33 -0700489 error!("Revert failed at interruption {}", i);
490 fails += 1;
491 }
492 }
493 }
494
495 fails > 0
496 }
497
David Brown5c9e0f12019-01-09 16:34:33 -0700498 pub fn run_norevert(&self) -> bool {
David Brown3910ab12019-01-11 12:02:26 -0700499 if Caps::OverwriteUpgrade.present() {
500 return false;
501 }
David Brown5c9e0f12019-01-09 16:34:33 -0700502
David Brown76101572019-02-28 11:29:03 -0700503 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700504 let mut fails = 0;
505
506 info!("Try norevert");
507
508 // First do a normal upgrade...
David Brown76101572019-02-28 11:29:03 -0700509 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700510 if result != 0 {
511 warn!("Failed first boot");
512 fails += 1;
513 }
514
515 //FIXME: copy_done is written by boot_go, is it ok if no copy
516 // was ever done?
517
David Brown84b49f72019-03-01 10:58:22 -0700518 if !self.verify_images(&flash, 0, 1) {
David Vincze2d736ad2019-02-18 11:50:22 +0100519 warn!("Primary slot image verification FAIL");
David Brown5c9e0f12019-01-09 16:34:33 -0700520 fails += 1;
521 }
David Brown84b49f72019-03-01 10:58:22 -0700522 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
523 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100524 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700525 fails += 1;
526 }
David Brown84b49f72019-03-01 10:58:22 -0700527 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
528 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100529 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700530 fails += 1;
531 }
532
David Vincze2d736ad2019-02-18 11:50:22 +0100533 // Marks image in the primary slot as permanent,
534 // no revert should happen...
David Brown84b49f72019-03-01 10:58:22 -0700535 self.mark_permanent_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700536
David Brown84b49f72019-03-01 10:58:22 -0700537 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
538 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100539 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700540 fails += 1;
541 }
542
David Brown76101572019-02-28 11:29:03 -0700543 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700544 if result != 0 {
545 warn!("Failed second boot");
546 fails += 1;
547 }
548
David Brown84b49f72019-03-01 10:58:22 -0700549 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
550 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100551 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700552 fails += 1;
553 }
David Brown84b49f72019-03-01 10:58:22 -0700554 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700555 warn!("Failed image verification");
556 fails += 1;
557 }
558
559 if fails > 0 {
560 error!("Error running upgrade without revert");
561 }
562
563 fails > 0
564 }
565
David Vincze2d736ad2019-02-18 11:50:22 +0100566 // Tests a new image written to the primary slot that already has magic and
567 // image_ok set while there is no image on the secondary slot, so no revert
568 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700569 pub fn run_norevert_newimage(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700570 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700571 let mut fails = 0;
572
573 info!("Try non-revert on imgtool generated image");
574
David Brown84b49f72019-03-01 10:58:22 -0700575 self.mark_upgrades(&mut flash, 0);
David Brown5c9e0f12019-01-09 16:34:33 -0700576
David Vincze2d736ad2019-02-18 11:50:22 +0100577 // This simulates writing an image created by imgtool to
578 // the primary slot
David Brown84b49f72019-03-01 10:58:22 -0700579 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
580 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100581 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700582 fails += 1;
583 }
584
585 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700586 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700587 if result != 0 {
588 warn!("Failed first boot");
589 fails += 1;
590 }
591
592 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700593 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700594 warn!("Failed image verification");
595 fails += 1;
596 }
David Brown84b49f72019-03-01 10:58:22 -0700597 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
598 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100599 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700600 fails += 1;
601 }
David Brown84b49f72019-03-01 10:58:22 -0700602 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
603 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100604 warn!("Mismatched trailer for the secondary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700605 fails += 1;
606 }
607
608 if fails > 0 {
609 error!("Expected a non revert with new image");
610 }
611
612 fails > 0
613 }
614
David Vincze2d736ad2019-02-18 11:50:22 +0100615 // Tests a new image written to the primary slot that already has magic and
616 // image_ok set while there is no image on the secondary slot, so no revert
617 // should ever happen...
David Brown5c9e0f12019-01-09 16:34:33 -0700618 pub fn run_signfail_upgrade(&self) -> bool {
David Brown76101572019-02-28 11:29:03 -0700619 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700620 let mut fails = 0;
621
622 info!("Try upgrade image with bad signature");
623
David Brown84b49f72019-03-01 10:58:22 -0700624 self.mark_upgrades(&mut flash, 0);
625 self.mark_permanent_upgrades(&mut flash, 0);
626 self.mark_upgrades(&mut flash, 1);
David Brown5c9e0f12019-01-09 16:34:33 -0700627
David Brown84b49f72019-03-01 10:58:22 -0700628 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
629 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100630 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700631 fails += 1;
632 }
633
634 // Run the bootloader...
David Brown76101572019-02-28 11:29:03 -0700635 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700636 if result != 0 {
637 warn!("Failed first boot");
638 fails += 1;
639 }
640
641 // State should not have changed
David Brown84b49f72019-03-01 10:58:22 -0700642 if !self.verify_images(&flash, 0, 0) {
David Brown5c9e0f12019-01-09 16:34:33 -0700643 warn!("Failed image verification");
644 fails += 1;
645 }
David Brown84b49f72019-03-01 10:58:22 -0700646 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
647 BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100648 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700649 fails += 1;
650 }
651
652 if fails > 0 {
653 error!("Expected an upgrade failure when image has bad signature");
654 }
655
656 fails > 0
657 }
658
David Brown5c9e0f12019-01-09 16:34:33 -0700659 fn trailer_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300660 c::boot_trailer_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700661 }
662
David Brown5c9e0f12019-01-09 16:34:33 -0700663 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300664 c::boot_status_sz(align as u32) as usize
David Brown5c9e0f12019-01-09 16:34:33 -0700665 }
666
667 /// This test runs a simple upgrade with no fails in the images, but
668 /// allowing for fails in the status area. This should run to the end
669 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700670 pub fn run_with_status_fails_complete(&self) -> bool {
David Vincze2d736ad2019-02-18 11:50:22 +0100671 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700672 return false;
673 }
674
David Brown76101572019-02-28 11:29:03 -0700675 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700676 let mut fails = 0;
677
678 info!("Try swap with status fails");
679
David Brown84b49f72019-03-01 10:58:22 -0700680 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700681 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700682
David Brown76101572019-02-28 11:29:03 -0700683 let (result, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown5c9e0f12019-01-09 16:34:33 -0700684 if result != 0 {
685 warn!("Failed!");
686 fails += 1;
687 }
688
689 // Failed writes to the marked "bad" region don't assert anymore.
690 // Any detected assert() is happening in another part of the code.
691 if asserts != 0 {
692 warn!("At least one assert() was called");
693 fails += 1;
694 }
695
David Brown84b49f72019-03-01 10:58:22 -0700696 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
697 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100698 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700699 fails += 1;
700 }
701
David Brown84b49f72019-03-01 10:58:22 -0700702 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700703 warn!("Failed image verification");
704 fails += 1;
705 }
706
David Vincze2d736ad2019-02-18 11:50:22 +0100707 info!("validate primary slot enabled; \
708 re-run of boot_go should just work");
David Brown76101572019-02-28 11:29:03 -0700709 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700710 if result != 0 {
711 warn!("Failed!");
712 fails += 1;
713 }
714
715 if fails > 0 {
716 error!("Error running upgrade with status write fails");
717 }
718
719 fails > 0
720 }
721
722 /// This test runs a simple upgrade with no fails in the images, but
723 /// allowing for fails in the status area. This should run to the end
724 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700725 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown85904a82019-01-11 13:45:12 -0700726 if Caps::OverwriteUpgrade.present() {
727 false
David Vincze2d736ad2019-02-18 11:50:22 +0100728 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700729
David Brown76101572019-02-28 11:29:03 -0700730 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700731 let mut fails = 0;
732 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700733
David Brown85904a82019-01-11 13:45:12 -0700734 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700735
David Brown85904a82019-01-11 13:45:12 -0700736 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700737
David Brown84b49f72019-03-01 10:58:22 -0700738 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700739 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700740
741 // Should not fail, writing to bad regions does not assert
David Brown76101572019-02-28 11:29:03 -0700742 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true);
David Brown85904a82019-01-11 13:45:12 -0700743 if asserts != 0 {
744 warn!("At least one assert() was called");
745 fails += 1;
746 }
747
David Brown76101572019-02-28 11:29:03 -0700748 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700749
750 info!("Resuming an interrupted swap operation");
David Brown76101572019-02-28 11:29:03 -0700751 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700752
753 // This might throw no asserts, for large sector devices, where
754 // a single failure writing is indistinguishable from no failure,
755 // or throw a single assert for small sector devices that fail
756 // multiple times...
757 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100758 warn!("Expected single assert validating the primary slot, \
759 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700760 fails += 1;
761 }
762
763 if fails > 0 {
764 error!("Error running upgrade with status write fails");
765 }
766
767 fails > 0
768 } else {
David Brown76101572019-02-28 11:29:03 -0700769 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700770 let mut fails = 0;
771
772 info!("Try interrupted swap with status fails");
773
David Brown84b49f72019-03-01 10:58:22 -0700774 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700775 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700776
777 // This is expected to fail while writing to bad regions...
David Brown76101572019-02-28 11:29:03 -0700778 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700779 if asserts == 0 {
780 warn!("No assert() detected");
781 fails += 1;
782 }
783
784 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700785 }
David Brown5c9e0f12019-01-09 16:34:33 -0700786 }
787
788 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -0700789 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -0700790 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -0700791 if Caps::OverwriteUpgrade.present() {
792 return;
793 }
794
David Brown84b49f72019-03-01 10:58:22 -0700795 // Set this for each image.
796 for image in &self.images {
797 let dev_id = &image.slots[slot].dev_id;
798 let dev = flash.get_mut(&dev_id).unwrap();
799 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -0700800 let off = &image.slots[slot].base_off;
801 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -0700802 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -0700803
David Brown84b49f72019-03-01 10:58:22 -0700804 // Mark the status area as a bad area
805 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
806 }
David Brown5c9e0f12019-01-09 16:34:33 -0700807 }
808
David Brown76101572019-02-28 11:29:03 -0700809 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +0100810 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700811 return;
812 }
813
David Brown84b49f72019-03-01 10:58:22 -0700814 for image in &self.images {
815 let dev_id = &image.slots[slot].dev_id;
816 let dev = flash.get_mut(&dev_id).unwrap();
817 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -0700818
David Brown84b49f72019-03-01 10:58:22 -0700819 // Disabling write verification the only assert triggered by
820 // boot_go should be checking for integrity of status bytes.
821 dev.set_verify_writes(false);
822 }
David Brown5c9e0f12019-01-09 16:34:33 -0700823 }
824
David Browndb505822019-03-01 10:04:20 -0700825 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
826 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -0300827 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -0700828 // Clone the flash to have a new copy.
829 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700830
Fabio Utziged4a5362019-07-30 12:43:23 -0300831 if permanent {
832 self.mark_permanent_upgrades(&mut flash, 1);
833 }
David Brown5c9e0f12019-01-09 16:34:33 -0700834
David Browndb505822019-03-01 10:04:20 -0700835 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -0700836
David Browndb505822019-03-01 10:04:20 -0700837 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
838 (-0x13579, _) => (true, stop.unwrap()),
839 (0, _) => (false, -counter),
840 (x, _) => panic!("Unknown return: {}", x),
841 };
David Brown5c9e0f12019-01-09 16:34:33 -0700842
David Browndb505822019-03-01 10:04:20 -0700843 counter = 0;
844 if first_interrupted {
845 // fl.dump();
846 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
847 (-0x13579, _) => panic!("Shouldn't stop again"),
848 (0, _) => (),
849 (x, _) => panic!("Unknown return: {}", x),
850 }
851 }
David Brown5c9e0f12019-01-09 16:34:33 -0700852
David Browndb505822019-03-01 10:04:20 -0700853 (flash, count - counter)
854 }
855
856 fn try_revert(&self, count: usize) -> SimMultiFlash {
857 let mut flash = self.flash.clone();
858
859 // fl.write_file("image0.bin").unwrap();
860 for i in 0 .. count {
861 info!("Running boot pass {}", i + 1);
862 assert_eq!(c::boot_go(&mut flash, &self.areadesc, None, false), (0, 0));
863 }
864 flash
865 }
866
867 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
868 let mut flash = self.flash.clone();
869 let mut fails = 0;
870
871 let mut counter = stop;
872 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
873 if x != -0x13579 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700874 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -0700875 fails += 1;
876 }
877
Fabio Utzig8af7f792019-07-30 12:40:01 -0300878 // In a multi-image setup, copy done might be set if any number of
879 // images was already successfully swapped.
880 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
881 warn!("copy_done should be unset");
882 fails += 1;
883 }
884
David Browndb505822019-03-01 10:04:20 -0700885 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
886 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700887 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -0700888 fails += 1;
889 }
890
David Brown84b49f72019-03-01 10:58:22 -0700891 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -0700892 warn!("Image in the primary slot before revert is invalid at stop={}",
893 stop);
894 fails += 1;
895 }
David Brown84b49f72019-03-01 10:58:22 -0700896 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -0700897 warn!("Image in the secondary slot before revert is invalid at stop={}",
898 stop);
899 fails += 1;
900 }
David Brown84b49f72019-03-01 10:58:22 -0700901 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
902 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -0700903 warn!("Mismatched trailer for the primary slot before revert");
904 fails += 1;
905 }
David Brown84b49f72019-03-01 10:58:22 -0700906 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
907 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -0700908 warn!("Mismatched trailer for the secondary slot before revert");
909 fails += 1;
910 }
911
912 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700913 let mut counter = stop;
914 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
915 if x != -0x13579 {
916 warn!("Should have stopped revert at interruption point");
917 fails += 1;
918 }
919
David Browndb505822019-03-01 10:04:20 -0700920 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
921 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700922 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -0700923 fails += 1;
924 }
925
David Brown84b49f72019-03-01 10:58:22 -0700926 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -0700927 warn!("Image in the primary slot after revert is invalid at stop={}",
928 stop);
929 fails += 1;
930 }
David Brown84b49f72019-03-01 10:58:22 -0700931 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -0700932 warn!("Image in the secondary slot after revert is invalid at stop={}",
933 stop);
934 fails += 1;
935 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700936
David Brown84b49f72019-03-01 10:58:22 -0700937 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
938 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700939 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -0700940 fails += 1;
941 }
David Brown84b49f72019-03-01 10:58:22 -0700942 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
943 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -0700944 warn!("Mismatched trailer for the secondary slot after revert");
945 fails += 1;
946 }
947
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700948 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
949 if x != 0 {
950 warn!("Should have finished 3rd boot");
951 fails += 1;
952 }
953
954 if !self.verify_images(&flash, 0, 0) {
955 warn!("Image in the primary slot is invalid on 1st boot after revert");
956 fails += 1;
957 }
958 if !self.verify_images(&flash, 1, 1) {
959 warn!("Image in the secondary slot is invalid on 1st boot after revert");
960 fails += 1;
961 }
962
David Browndb505822019-03-01 10:04:20 -0700963 fails > 0
964 }
965
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700966
David Browndb505822019-03-01 10:04:20 -0700967 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
968 let mut flash = self.flash.clone();
969
David Brown84b49f72019-03-01 10:58:22 -0700970 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -0700971
972 let mut rng = rand::thread_rng();
973 let mut resets = vec![0i32; count];
974 let mut remaining_ops = total_ops;
975 for i in 0 .. count {
976 let ops = Range::new(1, remaining_ops / 2);
977 let reset_counter = ops.ind_sample(&mut rng);
978 let mut counter = reset_counter;
979 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
980 (0, _) | (-0x13579, _) => (),
981 (x, _) => panic!("Unknown return: {}", x),
982 }
983 remaining_ops -= reset_counter;
984 resets[i] = reset_counter;
985 }
986
987 match c::boot_go(&mut flash, &self.areadesc, None, false) {
988 (-0x13579, _) => panic!("Should not be have been interrupted!"),
David Brown5c9e0f12019-01-09 16:34:33 -0700989 (0, _) => (),
990 (x, _) => panic!("Unknown return: {}", x),
991 }
David Brown5c9e0f12019-01-09 16:34:33 -0700992
David Browndb505822019-03-01 10:04:20 -0700993 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -0700994 }
David Brown84b49f72019-03-01 10:58:22 -0700995
996 /// Verify the image in the given flash device, the specified slot
997 /// against the expected image.
998 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -0600999 self.images.iter().all(|image| {
1000 verify_image(flash, &image.slots[slot],
1001 match against {
1002 0 => &image.primaries,
1003 1 => &image.upgrades,
1004 _ => panic!("Invalid 'against'")
1005 })
1006 })
David Brown84b49f72019-03-01 10:58:22 -07001007 }
1008
David Brownc3898d62019-08-05 14:20:02 -06001009 /// Verify the images, according to the dependency test.
1010 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1011 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1012 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1013 if !verify_image(flash, &image.slots[0],
1014 match upgrade {
1015 UpgradeInfo::Upgraded => &image.upgrades,
1016 UpgradeInfo::Held => &image.primaries,
1017 }) {
1018 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1019 return true;
1020 }
1021 }
1022
1023 false
1024 }
1025
Fabio Utzig8af7f792019-07-30 12:40:01 -03001026 /// Verify that at least one of the trailers of the images have the
1027 /// specified values.
1028 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1029 magic: Option<u8>, image_ok: Option<u8>,
1030 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001031 self.images.iter().any(|image| {
1032 verify_trailer(flash, &image.slots[slot],
1033 magic, image_ok, copy_done)
1034 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001035 }
1036
David Brown84b49f72019-03-01 10:58:22 -07001037 /// Verify that the trailers of the images have the specified
1038 /// values.
1039 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1040 magic: Option<u8>, image_ok: Option<u8>,
1041 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001042 self.images.iter().all(|image| {
1043 verify_trailer(flash, &image.slots[slot],
1044 magic, image_ok, copy_done)
1045 })
David Brown84b49f72019-03-01 10:58:22 -07001046 }
1047
1048 /// Mark each of the images for permanent upgrade.
1049 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1050 for image in &self.images {
1051 mark_permanent_upgrade(flash, &image.slots[slot]);
1052 }
1053 }
1054
1055 /// Mark each of the images for permanent upgrade.
1056 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1057 for image in &self.images {
1058 mark_upgrade(flash, &image.slots[slot]);
1059 }
1060 }
David Brown297029a2019-08-13 14:29:51 -06001061
1062 /// Dump out the flash image(s) to one or more files for debugging
1063 /// purposes. The names will be written as either "{prefix}.mcubin" or
1064 /// "{prefix}-001.mcubin" depending on how many images there are.
1065 pub fn debug_dump(&self, prefix: &str) {
1066 for (id, fdev) in &self.flash {
1067 let name = if self.flash.len() == 1 {
1068 format!("{}.mcubin", prefix)
1069 } else {
1070 format!("{}-{:>0}.mcubin", prefix, id)
1071 };
1072 fdev.write_file(&name).unwrap();
1073 }
1074 }
David Brown5c9e0f12019-01-09 16:34:33 -07001075}
1076
1077/// Show the flash layout.
1078#[allow(dead_code)]
1079fn show_flash(flash: &dyn Flash) {
1080 println!("---- Flash configuration ----");
1081 for sector in flash.sector_iter() {
1082 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1083 sector.num, sector.base, sector.size);
1084 }
1085 println!("");
1086}
1087
1088/// Install a "program" into the given image. This fakes the image header, or at least all of the
1089/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001090fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownc3898d62019-08-05 14:20:02 -06001091 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001092 let offset = slot.base_off;
1093 let slot_len = slot.len;
1094 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001095
David Brown43643dd2019-01-11 15:43:28 -07001096 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001097
David Brownc3898d62019-08-05 14:20:02 -06001098 // Add the dependencies early to the tlv.
1099 for dep in deps.my_deps(offset, slot.index) {
1100 tlv.add_dependency(deps.other_id(), &dep);
1101 }
1102
David Brown5c9e0f12019-01-09 16:34:33 -07001103 const HDR_SIZE: usize = 32;
1104
1105 // Generate a boot header. Note that the size doesn't include the header.
1106 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001107 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -07001108 load_addr: 0,
1109 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001110 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001111 img_size: len as u32,
1112 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001113 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001114 _pad2: 0,
1115 };
1116
1117 let mut b_header = [0; HDR_SIZE];
1118 b_header[..32].clone_from_slice(header.as_raw());
1119 assert_eq!(b_header.len(), HDR_SIZE);
1120
1121 tlv.add_bytes(&b_header);
1122
1123 // The core of the image itself is just pseudorandom data.
1124 let mut b_img = vec![0; len];
1125 splat(&mut b_img, offset);
1126
David Browncb47dd72019-08-05 14:21:49 -06001127 // Add some information at the start of the payload to make it easier
1128 // to see what it is. This will fail if the image itself is too small.
1129 {
1130 let mut wr = Cursor::new(&mut b_img);
1131 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1132 offset, dev_id, slot).unwrap();
1133 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1134 }
1135
David Brown5c9e0f12019-01-09 16:34:33 -07001136 // TLV signatures work over plain image
1137 tlv.add_bytes(&b_img);
1138
1139 // Generate encrypted images
1140 let flag = TlvFlags::ENCRYPTED as u32;
1141 let is_encrypted = (tlv.get_flags() & flag) == flag;
1142 let mut b_encimg = vec![];
1143 if is_encrypted {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001144 tlv.generate_enc_key();
1145 let enc_key = tlv.get_enc_key();
1146 let key = GenericArray::from_slice(enc_key.as_slice());
David Brown5c9e0f12019-01-09 16:34:33 -07001147 let nonce = GenericArray::from_slice(&[0; 16]);
1148 let mut cipher = Aes128Ctr::new(&key, &nonce);
1149 b_encimg = b_img.clone();
1150 cipher.apply_keystream(&mut b_encimg);
1151 }
1152
1153 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001154 if bad_sig {
1155 tlv.corrupt_sig();
1156 }
1157 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001158
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001159 let dev = flash.get_mut(&dev_id).unwrap();
1160
David Brown5c9e0f12019-01-09 16:34:33 -07001161 let mut buf = vec![];
1162 buf.append(&mut b_header.to_vec());
1163 buf.append(&mut b_img);
1164 buf.append(&mut b_tlv.clone());
1165
David Brown95de4502019-11-15 12:01:34 -07001166 // Pad the buffer to a multiple of the flash alignment.
1167 let align = dev.align();
1168 while buf.len() % align != 0 {
1169 buf.push(dev.erased_val());
1170 }
1171
David Brown5c9e0f12019-01-09 16:34:33 -07001172 let mut encbuf = vec![];
1173 if is_encrypted {
1174 encbuf.append(&mut b_header.to_vec());
1175 encbuf.append(&mut b_encimg);
1176 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001177
1178 while encbuf.len() % align != 0 {
1179 encbuf.push(dev.erased_val());
1180 }
David Brown5c9e0f12019-01-09 16:34:33 -07001181 }
1182
David Vincze2d736ad2019-02-18 11:50:22 +01001183 // Since images are always non-encrypted in the primary slot, we first write
1184 // an encrypted image, re-read to use for verification, erase + flash
1185 // un-encrypted. In the secondary slot the image is written un-encrypted,
1186 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001187
David Brown3b090212019-07-30 15:59:28 -06001188 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001189 let enc_copy: Option<Vec<u8>>;
1190
1191 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001192 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001193
1194 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001195 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001196
1197 enc_copy = Some(enc);
1198
David Brown76101572019-02-28 11:29:03 -07001199 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001200 } else {
1201 enc_copy = None;
1202 }
1203
David Brown76101572019-02-28 11:29:03 -07001204 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001205
1206 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001207 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001208
David Brownca234692019-02-28 11:22:19 -07001209 ImageData {
1210 plain: copy,
1211 cipher: enc_copy,
1212 }
David Brown5c9e0f12019-01-09 16:34:33 -07001213 } else {
1214
David Brown76101572019-02-28 11:29:03 -07001215 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001216
1217 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001218 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001219
1220 let enc_copy: Option<Vec<u8>>;
1221
1222 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001223 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001224
David Brown76101572019-02-28 11:29:03 -07001225 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001226
1227 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001228 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001229
1230 enc_copy = Some(enc);
1231 } else {
1232 enc_copy = None;
1233 }
1234
David Brownca234692019-02-28 11:22:19 -07001235 ImageData {
1236 plain: copy,
1237 cipher: enc_copy,
1238 }
David Brown5c9e0f12019-01-09 16:34:33 -07001239 }
David Brown5c9e0f12019-01-09 16:34:33 -07001240}
1241
David Brown873be312019-09-03 12:22:32 -06001242/// Install no image. This is used when no upgrade happens.
1243fn install_no_image() -> ImageData {
1244 ImageData {
1245 plain: vec![],
1246 cipher: None,
1247 }
1248}
1249
David Brown5c9e0f12019-01-09 16:34:33 -07001250fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001251 if Caps::EcdsaP224.present() {
1252 panic!("Ecdsa P224 not supported in Simulator");
1253 }
David Brown5c9e0f12019-01-09 16:34:33 -07001254
David Brownb8882112019-01-11 14:04:11 -07001255 if Caps::EncKw.present() {
1256 if Caps::RSA2048.present() {
1257 TlvGen::new_rsa_kw()
1258 } else if Caps::EcdsaP256.present() {
1259 TlvGen::new_ecdsa_kw()
1260 } else {
1261 TlvGen::new_enc_kw()
1262 }
1263 } else if Caps::EncRsa.present() {
1264 if Caps::RSA2048.present() {
1265 TlvGen::new_sig_enc_rsa()
1266 } else {
1267 TlvGen::new_enc_rsa()
1268 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001269 } else if Caps::EncEc256.present() {
1270 //FIXME: should fail with RSA signature?
1271 TlvGen::new_ecdsa_ecies_p256()
David Brownb8882112019-01-11 14:04:11 -07001272 } else {
1273 // The non-encrypted configuration.
1274 if Caps::RSA2048.present() {
1275 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001276 } else if Caps::RSA3072.present() {
1277 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001278 } else if Caps::EcdsaP256.present() {
1279 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001280 } else if Caps::Ed25519.present() {
1281 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001282 } else {
1283 TlvGen::new_hash_only()
1284 }
1285 }
David Brown5c9e0f12019-01-09 16:34:33 -07001286}
1287
David Brownca234692019-02-28 11:22:19 -07001288impl ImageData {
1289 /// Find the image contents for the given slot. This assumes that slot 0
1290 /// is unencrypted, and slot 1 is encrypted.
1291 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001292 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
1293 Caps::EncEc256.present();
David Brownca234692019-02-28 11:22:19 -07001294 match (encrypted, slot) {
1295 (false, _) => &self.plain,
1296 (true, 0) => &self.plain,
1297 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1298 _ => panic!("Invalid slot requested"),
1299 }
David Brown5c9e0f12019-01-09 16:34:33 -07001300 }
1301}
1302
David Brown5c9e0f12019-01-09 16:34:33 -07001303/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001304fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1305 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001306 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001307 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001308
1309 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001310 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001311 let dev = flash.get(&dev_id).unwrap();
1312 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001313
1314 if buf != &copy[..] {
1315 for i in 0 .. buf.len() {
1316 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001317 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1318 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001319 break;
1320 }
1321 }
1322 false
1323 } else {
1324 true
1325 }
1326}
1327
David Brown3b090212019-07-30 15:59:28 -06001328fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001329 magic: Option<u8>, image_ok: Option<u8>,
1330 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001331 if Caps::OverwriteUpgrade.present() {
1332 return true;
1333 }
David Brown5c9e0f12019-01-09 16:34:33 -07001334
David Brown3b090212019-07-30 15:59:28 -06001335 let offset = slot.trailer_off + c::boot_max_align();
1336 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001337 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001338 let mut failed = false;
1339
David Brown76101572019-02-28 11:29:03 -07001340 let dev = flash.get(&dev_id).unwrap();
1341 let erased_val = dev.erased_val();
1342 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001343
1344 failed |= match magic {
1345 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001346 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001347 warn!("\"magic\" mismatch at {:#x}", offset);
1348 true
1349 } else if v == 3 {
1350 let expected = [erased_val; 16];
Christopher Collinsa1c12042019-05-23 14:00:28 -07001351 if &copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001352 warn!("\"magic\" mismatch at {:#x}", offset);
1353 true
1354 } else {
1355 false
1356 }
1357 } else {
1358 false
1359 }
1360 },
1361 None => false,
1362 };
1363
1364 failed |= match image_ok {
1365 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001366 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001367 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1368 true
1369 } else {
1370 false
1371 }
1372 },
1373 None => false,
1374 };
1375
1376 failed |= match copy_done {
1377 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001378 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001379 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1380 true
1381 } else {
1382 false
1383 }
1384 },
1385 None => false,
1386 };
1387
1388 !failed
1389}
1390
David Brown297029a2019-08-13 14:29:51 -06001391/// Install a partition table. This is a simplified partition table that
1392/// we write at the beginning of flash so make it easier for external tools
1393/// to analyze these images.
1394fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1395 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1396 for &id in &ids {
1397 // If there are any partitions in this device that start at 0, and
1398 // aren't marked as the BootLoader partition, avoid adding the
1399 // partition table. This makes it harder to view the image, but
1400 // avoids messing up images already written.
1401 if areadesc.iter_areas().any(|area| {
1402 area.device_id == id &&
1403 area.off == 0 &&
1404 area.flash_id != FlashId::BootLoader
1405 }) {
1406 if log_enabled!(Info) {
1407 let special: Vec<FlashId> = areadesc.iter_areas()
1408 .filter(|area| area.device_id == id && area.off == 0)
1409 .map(|area| area.flash_id)
1410 .collect();
1411 info!("Skipping partition table: {:?}", special);
1412 }
1413 break;
1414 }
1415
1416 let mut buf: Vec<u8> = vec![];
1417 write!(&mut buf, "mcuboot\0").unwrap();
1418
1419 // Iterate through all of the partitions in that device, and encode
1420 // into the table.
1421 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1422 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1423
1424 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1425 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1426 buf.write_u32::<LittleEndian>(area.off).unwrap();
1427 buf.write_u32::<LittleEndian>(area.size).unwrap();
1428 buf.write_u32::<LittleEndian>(0).unwrap();
1429 }
1430
1431 let dev = flash.get_mut(&id).unwrap();
1432
1433 // Pad to alignment.
1434 while buf.len() % dev.align() != 0 {
1435 buf.push(0);
1436 }
1437
1438 dev.write(0, &buf).unwrap();
1439 }
1440}
1441
David Brown5c9e0f12019-01-09 16:34:33 -07001442/// The image header
1443#[repr(C)]
1444pub struct ImageHeader {
1445 magic: u32,
1446 load_addr: u32,
1447 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001448 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001449 img_size: u32,
1450 flags: u32,
1451 ver: ImageVersion,
1452 _pad2: u32,
1453}
1454
1455impl AsRaw for ImageHeader {}
1456
1457#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001458#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001459pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001460 pub major: u8,
1461 pub minor: u8,
1462 pub revision: u16,
1463 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001464}
1465
David Brownc3898d62019-08-05 14:20:02 -06001466#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001467pub struct SlotInfo {
1468 pub base_off: usize,
1469 pub trailer_off: usize,
1470 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001471 // Which slot within this device.
1472 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001473 pub dev_id: u8,
1474}
1475
David Brown347dc572019-11-15 11:37:25 -07001476const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1477 0x60, 0xd2, 0xef, 0x7f,
1478 0x35, 0x52, 0x50, 0x0f,
1479 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001480
1481// Replicates defines found in bootutil.h
1482const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1483const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1484
1485const BOOT_FLAG_SET: Option<u8> = Some(1);
1486const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1487
1488/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001489pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1490 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001491 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001492 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001493 if offset % align != 0 || MAGIC.len() % align != 0 {
1494 // The write size is larger than the magic value. Fill a buffer
1495 // with the erased value, put the MAGIC in it, and write it in its
1496 // entirety.
1497 let mut buf = vec![dev.erased_val(); align];
1498 buf[(offset % align)..].copy_from_slice(MAGIC);
1499 dev.write(offset - (offset % align), &buf).unwrap();
1500 } else {
1501 dev.write(offset, MAGIC).unwrap();
1502 }
David Brown5c9e0f12019-01-09 16:34:33 -07001503}
1504
1505/// Writes the image_ok flag which, guess what, tells the bootloader
1506/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001507fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001508 // Overwrite mode always is permanent, and only the magic is used in
1509 // the trailer. To avoid problems with large write sizes, don't try to
1510 // set anything in this case.
1511 if Caps::OverwriteUpgrade.present() {
1512 return;
1513 }
1514
David Brown76101572019-02-28 11:29:03 -07001515 let dev = flash.get_mut(&slot.dev_id).unwrap();
1516 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001517 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001518 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001519 let align = dev.align();
1520 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001521}
1522
1523// Drop some pseudo-random gibberish onto the data.
1524fn splat(data: &mut [u8], seed: usize) {
1525 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
1526 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
1527 rng.fill_bytes(data);
1528}
1529
1530/// Return a read-only view into the raw bytes of this object
1531trait AsRaw : Sized {
1532 fn as_raw<'a>(&'a self) -> &'a [u8] {
1533 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1534 mem::size_of::<Self>()) }
1535 }
1536}
1537
1538pub fn show_sizes() {
1539 // This isn't panic safe.
1540 for min in &[1, 2, 4, 8] {
1541 let msize = c::boot_trailer_sz(*min);
1542 println!("{:2}: {} (0x{:x})", min, msize, msize);
1543 }
1544}
David Brown95de4502019-11-15 12:01:34 -07001545
1546#[cfg(not(feature = "large-write"))]
1547fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001548 &[1, 2, 4, 8]
1549}
1550
1551#[cfg(feature = "large-write")]
1552fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001553 &[1, 2, 4, 8, 128, 512]
1554}