blob: 8d6fb911604e11d448f6eb65a9edd84f05188ab2 [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 {
660 c::boot_trailer_sz(align as u8) as usize
661 }
662
663 // FIXME: could get status sz from bootloader
David Brown5c9e0f12019-01-09 16:34:33 -0700664 fn status_sz(&self, align: usize) -> usize {
Fabio Utzig90f449e2019-10-24 07:43:53 -0300665 let bias = if Caps::EncRsa.present() || Caps::EncKw.present() ||
666 Caps::EncEc256.present() {
David Brown9930a3e2019-01-11 12:28:26 -0700667 32
668 } else {
669 0
670 };
David Brown5c9e0f12019-01-09 16:34:33 -0700671
Christopher Collinsa1c12042019-05-23 14:00:28 -0700672 self.trailer_sz(align) - (16 + 32 + bias)
David Brown5c9e0f12019-01-09 16:34:33 -0700673 }
674
675 /// This test runs a simple upgrade with no fails in the images, but
676 /// allowing for fails in the status area. This should run to the end
677 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700678 pub fn run_with_status_fails_complete(&self) -> bool {
David Vincze2d736ad2019-02-18 11:50:22 +0100679 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700680 return false;
681 }
682
David Brown76101572019-02-28 11:29:03 -0700683 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700684 let mut fails = 0;
685
686 info!("Try swap with status fails");
687
David Brown84b49f72019-03-01 10:58:22 -0700688 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700689 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown5c9e0f12019-01-09 16:34:33 -0700690
David Brown76101572019-02-28 11:29:03 -0700691 let (result, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown5c9e0f12019-01-09 16:34:33 -0700692 if result != 0 {
693 warn!("Failed!");
694 fails += 1;
695 }
696
697 // Failed writes to the marked "bad" region don't assert anymore.
698 // Any detected assert() is happening in another part of the code.
699 if asserts != 0 {
700 warn!("At least one assert() was called");
701 fails += 1;
702 }
703
David Brown84b49f72019-03-01 10:58:22 -0700704 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
705 BOOT_FLAG_SET, BOOT_FLAG_SET) {
David Vincze2d736ad2019-02-18 11:50:22 +0100706 warn!("Mismatched trailer for the primary slot");
David Brown5c9e0f12019-01-09 16:34:33 -0700707 fails += 1;
708 }
709
David Brown84b49f72019-03-01 10:58:22 -0700710 if !self.verify_images(&flash, 0, 1) {
David Brown5c9e0f12019-01-09 16:34:33 -0700711 warn!("Failed image verification");
712 fails += 1;
713 }
714
David Vincze2d736ad2019-02-18 11:50:22 +0100715 info!("validate primary slot enabled; \
716 re-run of boot_go should just work");
David Brown76101572019-02-28 11:29:03 -0700717 let (result, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
David Brown5c9e0f12019-01-09 16:34:33 -0700718 if result != 0 {
719 warn!("Failed!");
720 fails += 1;
721 }
722
723 if fails > 0 {
724 error!("Error running upgrade with status write fails");
725 }
726
727 fails > 0
728 }
729
730 /// This test runs a simple upgrade with no fails in the images, but
731 /// allowing for fails in the status area. This should run to the end
732 /// and warn that write fails were detected...
David Brown5c9e0f12019-01-09 16:34:33 -0700733 pub fn run_with_status_fails_with_reset(&self) -> bool {
David Brown85904a82019-01-11 13:45:12 -0700734 if Caps::OverwriteUpgrade.present() {
735 false
David Vincze2d736ad2019-02-18 11:50:22 +0100736 } else if Caps::ValidatePrimarySlot.present() {
David Brown5c9e0f12019-01-09 16:34:33 -0700737
David Brown76101572019-02-28 11:29:03 -0700738 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700739 let mut fails = 0;
740 let mut count = self.total_count.unwrap() / 2;
David Brown5c9e0f12019-01-09 16:34:33 -0700741
David Brown85904a82019-01-11 13:45:12 -0700742 //info!("count={}\n", count);
David Brown5c9e0f12019-01-09 16:34:33 -0700743
David Brown85904a82019-01-11 13:45:12 -0700744 info!("Try interrupted swap with status fails");
David Brown5c9e0f12019-01-09 16:34:33 -0700745
David Brown84b49f72019-03-01 10:58:22 -0700746 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700747 self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
David Brown85904a82019-01-11 13:45:12 -0700748
749 // Should not fail, writing to bad regions does not assert
David Brown76101572019-02-28 11:29:03 -0700750 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, Some(&mut count), true);
David Brown85904a82019-01-11 13:45:12 -0700751 if asserts != 0 {
752 warn!("At least one assert() was called");
753 fails += 1;
754 }
755
David Brown76101572019-02-28 11:29:03 -0700756 self.reset_bad_status(&mut flash, 0);
David Brown85904a82019-01-11 13:45:12 -0700757
758 info!("Resuming an interrupted swap operation");
David Brown76101572019-02-28 11:29:03 -0700759 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700760
761 // This might throw no asserts, for large sector devices, where
762 // a single failure writing is indistinguishable from no failure,
763 // or throw a single assert for small sector devices that fail
764 // multiple times...
765 if asserts > 1 {
David Vincze2d736ad2019-02-18 11:50:22 +0100766 warn!("Expected single assert validating the primary slot, \
767 more detected {}", asserts);
David Brown85904a82019-01-11 13:45:12 -0700768 fails += 1;
769 }
770
771 if fails > 0 {
772 error!("Error running upgrade with status write fails");
773 }
774
775 fails > 0
776 } else {
David Brown76101572019-02-28 11:29:03 -0700777 let mut flash = self.flash.clone();
David Brown85904a82019-01-11 13:45:12 -0700778 let mut fails = 0;
779
780 info!("Try interrupted swap with status fails");
781
David Brown84b49f72019-03-01 10:58:22 -0700782 self.mark_permanent_upgrades(&mut flash, 1);
David Brown76101572019-02-28 11:29:03 -0700783 self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
David Brown85904a82019-01-11 13:45:12 -0700784
785 // This is expected to fail while writing to bad regions...
David Brown76101572019-02-28 11:29:03 -0700786 let (_, asserts) = c::boot_go(&mut flash, &self.areadesc, None, true);
David Brown85904a82019-01-11 13:45:12 -0700787 if asserts == 0 {
788 warn!("No assert() detected");
789 fails += 1;
790 }
791
792 fails > 0
David Brown5c9e0f12019-01-09 16:34:33 -0700793 }
David Brown5c9e0f12019-01-09 16:34:33 -0700794 }
795
796 /// Adds a new flash area that fails statistically
David Brown76101572019-02-28 11:29:03 -0700797 fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
David Brown5c9e0f12019-01-09 16:34:33 -0700798 rate: f32) {
David Brown85904a82019-01-11 13:45:12 -0700799 if Caps::OverwriteUpgrade.present() {
800 return;
801 }
802
David Brown84b49f72019-03-01 10:58:22 -0700803 // Set this for each image.
804 for image in &self.images {
805 let dev_id = &image.slots[slot].dev_id;
806 let dev = flash.get_mut(&dev_id).unwrap();
807 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -0700808 let off = &image.slots[slot].base_off;
809 let len = &image.slots[slot].len;
David Brown84b49f72019-03-01 10:58:22 -0700810 let status_off = off + len - self.trailer_sz(align);
David Brown5c9e0f12019-01-09 16:34:33 -0700811
David Brown84b49f72019-03-01 10:58:22 -0700812 // Mark the status area as a bad area
813 let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
814 }
David Brown5c9e0f12019-01-09 16:34:33 -0700815 }
816
David Brown76101572019-02-28 11:29:03 -0700817 fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
David Vincze2d736ad2019-02-18 11:50:22 +0100818 if !Caps::ValidatePrimarySlot.present() {
David Brown85904a82019-01-11 13:45:12 -0700819 return;
820 }
821
David Brown84b49f72019-03-01 10:58:22 -0700822 for image in &self.images {
823 let dev_id = &image.slots[slot].dev_id;
824 let dev = flash.get_mut(&dev_id).unwrap();
825 dev.reset_bad_regions();
David Brown5c9e0f12019-01-09 16:34:33 -0700826
David Brown84b49f72019-03-01 10:58:22 -0700827 // Disabling write verification the only assert triggered by
828 // boot_go should be checking for integrity of status bytes.
829 dev.set_verify_writes(false);
830 }
David Brown5c9e0f12019-01-09 16:34:33 -0700831 }
832
David Browndb505822019-03-01 10:04:20 -0700833 /// Test a boot, optionally stopping after 'n' flash options. Returns a count
834 /// of the number of flash operations done total.
Fabio Utziged4a5362019-07-30 12:43:23 -0300835 fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
David Browndb505822019-03-01 10:04:20 -0700836 // Clone the flash to have a new copy.
837 let mut flash = self.flash.clone();
David Brown5c9e0f12019-01-09 16:34:33 -0700838
Fabio Utziged4a5362019-07-30 12:43:23 -0300839 if permanent {
840 self.mark_permanent_upgrades(&mut flash, 1);
841 }
David Brown5c9e0f12019-01-09 16:34:33 -0700842
David Browndb505822019-03-01 10:04:20 -0700843 let mut counter = stop.unwrap_or(0);
David Brown5c9e0f12019-01-09 16:34:33 -0700844
David Browndb505822019-03-01 10:04:20 -0700845 let (first_interrupted, count) = match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
846 (-0x13579, _) => (true, stop.unwrap()),
847 (0, _) => (false, -counter),
848 (x, _) => panic!("Unknown return: {}", x),
849 };
David Brown5c9e0f12019-01-09 16:34:33 -0700850
David Browndb505822019-03-01 10:04:20 -0700851 counter = 0;
852 if first_interrupted {
853 // fl.dump();
854 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
855 (-0x13579, _) => panic!("Shouldn't stop again"),
856 (0, _) => (),
857 (x, _) => panic!("Unknown return: {}", x),
858 }
859 }
David Brown5c9e0f12019-01-09 16:34:33 -0700860
David Browndb505822019-03-01 10:04:20 -0700861 (flash, count - counter)
862 }
863
864 fn try_revert(&self, count: usize) -> SimMultiFlash {
865 let mut flash = self.flash.clone();
866
867 // fl.write_file("image0.bin").unwrap();
868 for i in 0 .. count {
869 info!("Running boot pass {}", i + 1);
870 assert_eq!(c::boot_go(&mut flash, &self.areadesc, None, false), (0, 0));
871 }
872 flash
873 }
874
875 fn try_revert_with_fail_at(&self, stop: i32) -> bool {
876 let mut flash = self.flash.clone();
877 let mut fails = 0;
878
879 let mut counter = stop;
880 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
881 if x != -0x13579 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700882 warn!("Should have stopped test at interruption point");
David Browndb505822019-03-01 10:04:20 -0700883 fails += 1;
884 }
885
Fabio Utzig8af7f792019-07-30 12:40:01 -0300886 // In a multi-image setup, copy done might be set if any number of
887 // images was already successfully swapped.
888 if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
889 warn!("copy_done should be unset");
890 fails += 1;
891 }
892
David Browndb505822019-03-01 10:04:20 -0700893 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
894 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700895 warn!("Should have finished test upgrade");
David Browndb505822019-03-01 10:04:20 -0700896 fails += 1;
897 }
898
David Brown84b49f72019-03-01 10:58:22 -0700899 if !self.verify_images(&flash, 0, 1) {
David Browndb505822019-03-01 10:04:20 -0700900 warn!("Image in the primary slot before revert is invalid at stop={}",
901 stop);
902 fails += 1;
903 }
David Brown84b49f72019-03-01 10:58:22 -0700904 if !self.verify_images(&flash, 1, 0) {
David Browndb505822019-03-01 10:04:20 -0700905 warn!("Image in the secondary slot before revert is invalid at stop={}",
906 stop);
907 fails += 1;
908 }
David Brown84b49f72019-03-01 10:58:22 -0700909 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
910 BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
David Browndb505822019-03-01 10:04:20 -0700911 warn!("Mismatched trailer for the primary slot before revert");
912 fails += 1;
913 }
David Brown84b49f72019-03-01 10:58:22 -0700914 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
915 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -0700916 warn!("Mismatched trailer for the secondary slot before revert");
917 fails += 1;
918 }
919
920 // Do Revert
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700921 let mut counter = stop;
922 let (x, _) = c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false);
923 if x != -0x13579 {
924 warn!("Should have stopped revert at interruption point");
925 fails += 1;
926 }
927
David Browndb505822019-03-01 10:04:20 -0700928 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
929 if x != 0 {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700930 warn!("Should have finished revert upgrade");
David Browndb505822019-03-01 10:04:20 -0700931 fails += 1;
932 }
933
David Brown84b49f72019-03-01 10:58:22 -0700934 if !self.verify_images(&flash, 0, 0) {
David Browndb505822019-03-01 10:04:20 -0700935 warn!("Image in the primary slot after revert is invalid at stop={}",
936 stop);
937 fails += 1;
938 }
David Brown84b49f72019-03-01 10:58:22 -0700939 if !self.verify_images(&flash, 1, 1) {
David Browndb505822019-03-01 10:04:20 -0700940 warn!("Image in the secondary slot after revert is invalid at stop={}",
941 stop);
942 fails += 1;
943 }
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700944
David Brown84b49f72019-03-01 10:58:22 -0700945 if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
946 BOOT_FLAG_SET, BOOT_FLAG_SET) {
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700947 warn!("Mismatched trailer for the primary slot after revert");
David Browndb505822019-03-01 10:04:20 -0700948 fails += 1;
949 }
David Brown84b49f72019-03-01 10:58:22 -0700950 if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
951 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
David Browndb505822019-03-01 10:04:20 -0700952 warn!("Mismatched trailer for the secondary slot after revert");
953 fails += 1;
954 }
955
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700956 let (x, _) = c::boot_go(&mut flash, &self.areadesc, None, false);
957 if x != 0 {
958 warn!("Should have finished 3rd boot");
959 fails += 1;
960 }
961
962 if !self.verify_images(&flash, 0, 0) {
963 warn!("Image in the primary slot is invalid on 1st boot after revert");
964 fails += 1;
965 }
966 if !self.verify_images(&flash, 1, 1) {
967 warn!("Image in the secondary slot is invalid on 1st boot after revert");
968 fails += 1;
969 }
970
David Browndb505822019-03-01 10:04:20 -0700971 fails > 0
972 }
973
Fabio Utzigfc07eab2019-05-17 10:23:38 -0700974
David Browndb505822019-03-01 10:04:20 -0700975 fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
976 let mut flash = self.flash.clone();
977
David Brown84b49f72019-03-01 10:58:22 -0700978 self.mark_permanent_upgrades(&mut flash, 1);
David Browndb505822019-03-01 10:04:20 -0700979
980 let mut rng = rand::thread_rng();
981 let mut resets = vec![0i32; count];
982 let mut remaining_ops = total_ops;
983 for i in 0 .. count {
984 let ops = Range::new(1, remaining_ops / 2);
985 let reset_counter = ops.ind_sample(&mut rng);
986 let mut counter = reset_counter;
987 match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), false) {
988 (0, _) | (-0x13579, _) => (),
989 (x, _) => panic!("Unknown return: {}", x),
990 }
991 remaining_ops -= reset_counter;
992 resets[i] = reset_counter;
993 }
994
995 match c::boot_go(&mut flash, &self.areadesc, None, false) {
996 (-0x13579, _) => panic!("Should not be have been interrupted!"),
David Brown5c9e0f12019-01-09 16:34:33 -0700997 (0, _) => (),
998 (x, _) => panic!("Unknown return: {}", x),
999 }
David Brown5c9e0f12019-01-09 16:34:33 -07001000
David Browndb505822019-03-01 10:04:20 -07001001 (flash, resets)
David Brown5c9e0f12019-01-09 16:34:33 -07001002 }
David Brown84b49f72019-03-01 10:58:22 -07001003
1004 /// Verify the image in the given flash device, the specified slot
1005 /// against the expected image.
1006 fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001007 self.images.iter().all(|image| {
1008 verify_image(flash, &image.slots[slot],
1009 match against {
1010 0 => &image.primaries,
1011 1 => &image.upgrades,
1012 _ => panic!("Invalid 'against'")
1013 })
1014 })
David Brown84b49f72019-03-01 10:58:22 -07001015 }
1016
David Brownc3898d62019-08-05 14:20:02 -06001017 /// Verify the images, according to the dependency test.
1018 fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1019 for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1020 info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1021 if !verify_image(flash, &image.slots[0],
1022 match upgrade {
1023 UpgradeInfo::Upgraded => &image.upgrades,
1024 UpgradeInfo::Held => &image.primaries,
1025 }) {
1026 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1027 return true;
1028 }
1029 }
1030
1031 false
1032 }
1033
Fabio Utzig8af7f792019-07-30 12:40:01 -03001034 /// Verify that at least one of the trailers of the images have the
1035 /// specified values.
1036 fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1037 magic: Option<u8>, image_ok: Option<u8>,
1038 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001039 self.images.iter().any(|image| {
1040 verify_trailer(flash, &image.slots[slot],
1041 magic, image_ok, copy_done)
1042 })
Fabio Utzig8af7f792019-07-30 12:40:01 -03001043 }
1044
David Brown84b49f72019-03-01 10:58:22 -07001045 /// Verify that the trailers of the images have the specified
1046 /// values.
1047 fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1048 magic: Option<u8>, image_ok: Option<u8>,
1049 copy_done: Option<u8>) -> bool {
David Brownf9aec952019-08-06 10:23:58 -06001050 self.images.iter().all(|image| {
1051 verify_trailer(flash, &image.slots[slot],
1052 magic, image_ok, copy_done)
1053 })
David Brown84b49f72019-03-01 10:58:22 -07001054 }
1055
1056 /// Mark each of the images for permanent upgrade.
1057 fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1058 for image in &self.images {
1059 mark_permanent_upgrade(flash, &image.slots[slot]);
1060 }
1061 }
1062
1063 /// Mark each of the images for permanent upgrade.
1064 fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1065 for image in &self.images {
1066 mark_upgrade(flash, &image.slots[slot]);
1067 }
1068 }
David Brown297029a2019-08-13 14:29:51 -06001069
1070 /// Dump out the flash image(s) to one or more files for debugging
1071 /// purposes. The names will be written as either "{prefix}.mcubin" or
1072 /// "{prefix}-001.mcubin" depending on how many images there are.
1073 pub fn debug_dump(&self, prefix: &str) {
1074 for (id, fdev) in &self.flash {
1075 let name = if self.flash.len() == 1 {
1076 format!("{}.mcubin", prefix)
1077 } else {
1078 format!("{}-{:>0}.mcubin", prefix, id)
1079 };
1080 fdev.write_file(&name).unwrap();
1081 }
1082 }
David Brown5c9e0f12019-01-09 16:34:33 -07001083}
1084
1085/// Show the flash layout.
1086#[allow(dead_code)]
1087fn show_flash(flash: &dyn Flash) {
1088 println!("---- Flash configuration ----");
1089 for sector in flash.sector_iter() {
1090 println!(" {:3}: 0x{:08x}, 0x{:08x}",
1091 sector.num, sector.base, sector.size);
1092 }
1093 println!("");
1094}
1095
1096/// Install a "program" into the given image. This fakes the image header, or at least all of the
1097/// fields used by the given code. Returns a copy of the image that was written.
David Brown3b090212019-07-30 15:59:28 -06001098fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: usize,
David Brownc3898d62019-08-05 14:20:02 -06001099 deps: &dyn Depender, bad_sig: bool) -> ImageData {
David Brown3b090212019-07-30 15:59:28 -06001100 let offset = slot.base_off;
1101 let slot_len = slot.len;
1102 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001103
David Brown43643dd2019-01-11 15:43:28 -07001104 let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
David Brown5c9e0f12019-01-09 16:34:33 -07001105
David Brownc3898d62019-08-05 14:20:02 -06001106 // Add the dependencies early to the tlv.
1107 for dep in deps.my_deps(offset, slot.index) {
1108 tlv.add_dependency(deps.other_id(), &dep);
1109 }
1110
David Brown5c9e0f12019-01-09 16:34:33 -07001111 const HDR_SIZE: usize = 32;
1112
1113 // Generate a boot header. Note that the size doesn't include the header.
1114 let header = ImageHeader {
David Brownac46e262019-01-11 15:46:18 -07001115 magic: tlv.get_magic(),
David Brown5c9e0f12019-01-09 16:34:33 -07001116 load_addr: 0,
1117 hdr_size: HDR_SIZE as u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001118 protect_tlv_size: tlv.protect_size(),
David Brown5c9e0f12019-01-09 16:34:33 -07001119 img_size: len as u32,
1120 flags: tlv.get_flags(),
David Brownc3898d62019-08-05 14:20:02 -06001121 ver: deps.my_version(offset, slot.index),
David Brown5c9e0f12019-01-09 16:34:33 -07001122 _pad2: 0,
1123 };
1124
1125 let mut b_header = [0; HDR_SIZE];
1126 b_header[..32].clone_from_slice(header.as_raw());
1127 assert_eq!(b_header.len(), HDR_SIZE);
1128
1129 tlv.add_bytes(&b_header);
1130
1131 // The core of the image itself is just pseudorandom data.
1132 let mut b_img = vec![0; len];
1133 splat(&mut b_img, offset);
1134
David Browncb47dd72019-08-05 14:21:49 -06001135 // Add some information at the start of the payload to make it easier
1136 // to see what it is. This will fail if the image itself is too small.
1137 {
1138 let mut wr = Cursor::new(&mut b_img);
1139 writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1140 offset, dev_id, slot).unwrap();
1141 writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1142 }
1143
David Brown5c9e0f12019-01-09 16:34:33 -07001144 // TLV signatures work over plain image
1145 tlv.add_bytes(&b_img);
1146
1147 // Generate encrypted images
1148 let flag = TlvFlags::ENCRYPTED as u32;
1149 let is_encrypted = (tlv.get_flags() & flag) == flag;
1150 let mut b_encimg = vec![];
1151 if is_encrypted {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001152 tlv.generate_enc_key();
1153 let enc_key = tlv.get_enc_key();
1154 let key = GenericArray::from_slice(enc_key.as_slice());
David Brown5c9e0f12019-01-09 16:34:33 -07001155 let nonce = GenericArray::from_slice(&[0; 16]);
1156 let mut cipher = Aes128Ctr::new(&key, &nonce);
1157 b_encimg = b_img.clone();
1158 cipher.apply_keystream(&mut b_encimg);
1159 }
1160
1161 // Build the TLV itself.
David Browne90b13f2019-12-06 15:04:00 -07001162 if bad_sig {
1163 tlv.corrupt_sig();
1164 }
1165 let mut b_tlv = tlv.make_tlv();
David Brown5c9e0f12019-01-09 16:34:33 -07001166
Fabio Utzig2f6c1642019-09-11 19:36:30 -03001167 let dev = flash.get_mut(&dev_id).unwrap();
1168
David Brown5c9e0f12019-01-09 16:34:33 -07001169 let mut buf = vec![];
1170 buf.append(&mut b_header.to_vec());
1171 buf.append(&mut b_img);
1172 buf.append(&mut b_tlv.clone());
1173
David Brown95de4502019-11-15 12:01:34 -07001174 // Pad the buffer to a multiple of the flash alignment.
1175 let align = dev.align();
1176 while buf.len() % align != 0 {
1177 buf.push(dev.erased_val());
1178 }
1179
David Brown5c9e0f12019-01-09 16:34:33 -07001180 let mut encbuf = vec![];
1181 if is_encrypted {
1182 encbuf.append(&mut b_header.to_vec());
1183 encbuf.append(&mut b_encimg);
1184 encbuf.append(&mut b_tlv);
David Brown95de4502019-11-15 12:01:34 -07001185
1186 while encbuf.len() % align != 0 {
1187 encbuf.push(dev.erased_val());
1188 }
David Brown5c9e0f12019-01-09 16:34:33 -07001189 }
1190
David Vincze2d736ad2019-02-18 11:50:22 +01001191 // Since images are always non-encrypted in the primary slot, we first write
1192 // an encrypted image, re-read to use for verification, erase + flash
1193 // un-encrypted. In the secondary slot the image is written un-encrypted,
1194 // and if encryption is requested, it follows an erase + flash encrypted.
David Brown5c9e0f12019-01-09 16:34:33 -07001195
David Brown3b090212019-07-30 15:59:28 -06001196 if slot.index == 0 {
David Brown5c9e0f12019-01-09 16:34:33 -07001197 let enc_copy: Option<Vec<u8>>;
1198
1199 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001200 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001201
1202 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001203 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001204
1205 enc_copy = Some(enc);
1206
David Brown76101572019-02-28 11:29:03 -07001207 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001208 } else {
1209 enc_copy = None;
1210 }
1211
David Brown76101572019-02-28 11:29:03 -07001212 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001213
1214 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001215 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001216
David Brownca234692019-02-28 11:22:19 -07001217 ImageData {
1218 plain: copy,
1219 cipher: enc_copy,
1220 }
David Brown5c9e0f12019-01-09 16:34:33 -07001221 } else {
1222
David Brown76101572019-02-28 11:29:03 -07001223 dev.write(offset, &buf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001224
1225 let mut copy = vec![0u8; buf.len()];
David Brown76101572019-02-28 11:29:03 -07001226 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001227
1228 let enc_copy: Option<Vec<u8>>;
1229
1230 if is_encrypted {
David Brown76101572019-02-28 11:29:03 -07001231 dev.erase(offset, slot_len).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001232
David Brown76101572019-02-28 11:29:03 -07001233 dev.write(offset, &encbuf).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001234
1235 let mut enc = vec![0u8; encbuf.len()];
David Brown76101572019-02-28 11:29:03 -07001236 dev.read(offset, &mut enc).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001237
1238 enc_copy = Some(enc);
1239 } else {
1240 enc_copy = None;
1241 }
1242
David Brownca234692019-02-28 11:22:19 -07001243 ImageData {
1244 plain: copy,
1245 cipher: enc_copy,
1246 }
David Brown5c9e0f12019-01-09 16:34:33 -07001247 }
David Brown5c9e0f12019-01-09 16:34:33 -07001248}
1249
David Brown873be312019-09-03 12:22:32 -06001250/// Install no image. This is used when no upgrade happens.
1251fn install_no_image() -> ImageData {
1252 ImageData {
1253 plain: vec![],
1254 cipher: None,
1255 }
1256}
1257
David Brown5c9e0f12019-01-09 16:34:33 -07001258fn make_tlv() -> TlvGen {
David Brownb8882112019-01-11 14:04:11 -07001259 if Caps::EcdsaP224.present() {
1260 panic!("Ecdsa P224 not supported in Simulator");
1261 }
David Brown5c9e0f12019-01-09 16:34:33 -07001262
David Brownb8882112019-01-11 14:04:11 -07001263 if Caps::EncKw.present() {
1264 if Caps::RSA2048.present() {
1265 TlvGen::new_rsa_kw()
1266 } else if Caps::EcdsaP256.present() {
1267 TlvGen::new_ecdsa_kw()
1268 } else {
1269 TlvGen::new_enc_kw()
1270 }
1271 } else if Caps::EncRsa.present() {
1272 if Caps::RSA2048.present() {
1273 TlvGen::new_sig_enc_rsa()
1274 } else {
1275 TlvGen::new_enc_rsa()
1276 }
Fabio Utzig90f449e2019-10-24 07:43:53 -03001277 } else if Caps::EncEc256.present() {
1278 //FIXME: should fail with RSA signature?
1279 TlvGen::new_ecdsa_ecies_p256()
David Brownb8882112019-01-11 14:04:11 -07001280 } else {
1281 // The non-encrypted configuration.
1282 if Caps::RSA2048.present() {
1283 TlvGen::new_rsa_pss()
Fabio Utzig39297432019-05-08 18:51:10 -03001284 } else if Caps::RSA3072.present() {
1285 TlvGen::new_rsa3072_pss()
David Brownb8882112019-01-11 14:04:11 -07001286 } else if Caps::EcdsaP256.present() {
1287 TlvGen::new_ecdsa()
Fabio Utzig97710282019-05-24 17:44:49 -03001288 } else if Caps::Ed25519.present() {
1289 TlvGen::new_ed25519()
David Brownb8882112019-01-11 14:04:11 -07001290 } else {
1291 TlvGen::new_hash_only()
1292 }
1293 }
David Brown5c9e0f12019-01-09 16:34:33 -07001294}
1295
David Brownca234692019-02-28 11:22:19 -07001296impl ImageData {
1297 /// Find the image contents for the given slot. This assumes that slot 0
1298 /// is unencrypted, and slot 1 is encrypted.
1299 fn find(&self, slot: usize) -> &Vec<u8> {
Fabio Utzig90f449e2019-10-24 07:43:53 -03001300 let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
1301 Caps::EncEc256.present();
David Brownca234692019-02-28 11:22:19 -07001302 match (encrypted, slot) {
1303 (false, _) => &self.plain,
1304 (true, 0) => &self.plain,
1305 (true, 1) => self.cipher.as_ref().expect("Invalid image"),
1306 _ => panic!("Invalid slot requested"),
1307 }
David Brown5c9e0f12019-01-09 16:34:33 -07001308 }
1309}
1310
David Brown5c9e0f12019-01-09 16:34:33 -07001311/// Verify that given image is present in the flash at the given offset.
David Brown3b090212019-07-30 15:59:28 -06001312fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
1313 let image = images.find(slot.index);
David Brown5c9e0f12019-01-09 16:34:33 -07001314 let buf = image.as_slice();
David Brown3b090212019-07-30 15:59:28 -06001315 let dev_id = slot.dev_id;
David Brown5c9e0f12019-01-09 16:34:33 -07001316
1317 let mut copy = vec![0u8; buf.len()];
David Brown3b090212019-07-30 15:59:28 -06001318 let offset = slot.base_off;
David Brown76101572019-02-28 11:29:03 -07001319 let dev = flash.get(&dev_id).unwrap();
1320 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001321
1322 if buf != &copy[..] {
1323 for i in 0 .. buf.len() {
1324 if buf[i] != copy[i] {
David Brownc3898d62019-08-05 14:20:02 -06001325 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
1326 slot.index, offset + i, i, buf[i], copy[i]);
David Brown5c9e0f12019-01-09 16:34:33 -07001327 break;
1328 }
1329 }
1330 false
1331 } else {
1332 true
1333 }
1334}
1335
David Brown3b090212019-07-30 15:59:28 -06001336fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
David Brown5c9e0f12019-01-09 16:34:33 -07001337 magic: Option<u8>, image_ok: Option<u8>,
1338 copy_done: Option<u8>) -> bool {
David Brown61a540d2019-01-11 14:29:14 -07001339 if Caps::OverwriteUpgrade.present() {
1340 return true;
1341 }
David Brown5c9e0f12019-01-09 16:34:33 -07001342
David Brown3b090212019-07-30 15:59:28 -06001343 let offset = slot.trailer_off + c::boot_max_align();
1344 let dev_id = slot.dev_id;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001345 let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
David Brown5c9e0f12019-01-09 16:34:33 -07001346 let mut failed = false;
1347
David Brown76101572019-02-28 11:29:03 -07001348 let dev = flash.get(&dev_id).unwrap();
1349 let erased_val = dev.erased_val();
1350 dev.read(offset, &mut copy).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001351
1352 failed |= match magic {
1353 Some(v) => {
David Brown347dc572019-11-15 11:37:25 -07001354 if v == 1 && &copy[24..] != MAGIC {
David Brown5c9e0f12019-01-09 16:34:33 -07001355 warn!("\"magic\" mismatch at {:#x}", offset);
1356 true
1357 } else if v == 3 {
1358 let expected = [erased_val; 16];
Christopher Collinsa1c12042019-05-23 14:00:28 -07001359 if &copy[24..] != expected {
David Brown5c9e0f12019-01-09 16:34:33 -07001360 warn!("\"magic\" mismatch at {:#x}", offset);
1361 true
1362 } else {
1363 false
1364 }
1365 } else {
1366 false
1367 }
1368 },
1369 None => false,
1370 };
1371
1372 failed |= match image_ok {
1373 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001374 if (v == 1 && copy[16] != v) || (v == 3 && copy[16] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001375 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[8]);
1376 true
1377 } else {
1378 false
1379 }
1380 },
1381 None => false,
1382 };
1383
1384 failed |= match copy_done {
1385 Some(v) => {
Christopher Collinsa1c12042019-05-23 14:00:28 -07001386 if (v == 1 && copy[8] != v) || (v == 3 && copy[8] != erased_val) {
David Brown5c9e0f12019-01-09 16:34:33 -07001387 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[0]);
1388 true
1389 } else {
1390 false
1391 }
1392 },
1393 None => false,
1394 };
1395
1396 !failed
1397}
1398
David Brown297029a2019-08-13 14:29:51 -06001399/// Install a partition table. This is a simplified partition table that
1400/// we write at the beginning of flash so make it easier for external tools
1401/// to analyze these images.
1402fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
1403 let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
1404 for &id in &ids {
1405 // If there are any partitions in this device that start at 0, and
1406 // aren't marked as the BootLoader partition, avoid adding the
1407 // partition table. This makes it harder to view the image, but
1408 // avoids messing up images already written.
1409 if areadesc.iter_areas().any(|area| {
1410 area.device_id == id &&
1411 area.off == 0 &&
1412 area.flash_id != FlashId::BootLoader
1413 }) {
1414 if log_enabled!(Info) {
1415 let special: Vec<FlashId> = areadesc.iter_areas()
1416 .filter(|area| area.device_id == id && area.off == 0)
1417 .map(|area| area.flash_id)
1418 .collect();
1419 info!("Skipping partition table: {:?}", special);
1420 }
1421 break;
1422 }
1423
1424 let mut buf: Vec<u8> = vec![];
1425 write!(&mut buf, "mcuboot\0").unwrap();
1426
1427 // Iterate through all of the partitions in that device, and encode
1428 // into the table.
1429 let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
1430 buf.write_u32::<LittleEndian>(count as u32).unwrap();
1431
1432 for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
1433 buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
1434 buf.write_u32::<LittleEndian>(area.off).unwrap();
1435 buf.write_u32::<LittleEndian>(area.size).unwrap();
1436 buf.write_u32::<LittleEndian>(0).unwrap();
1437 }
1438
1439 let dev = flash.get_mut(&id).unwrap();
1440
1441 // Pad to alignment.
1442 while buf.len() % dev.align() != 0 {
1443 buf.push(0);
1444 }
1445
1446 dev.write(0, &buf).unwrap();
1447 }
1448}
1449
David Brown5c9e0f12019-01-09 16:34:33 -07001450/// The image header
1451#[repr(C)]
1452pub struct ImageHeader {
1453 magic: u32,
1454 load_addr: u32,
1455 hdr_size: u16,
David Brown7a81c4b2019-07-29 15:20:21 -06001456 protect_tlv_size: u16,
David Brown5c9e0f12019-01-09 16:34:33 -07001457 img_size: u32,
1458 flags: u32,
1459 ver: ImageVersion,
1460 _pad2: u32,
1461}
1462
1463impl AsRaw for ImageHeader {}
1464
1465#[repr(C)]
David Brownc3898d62019-08-05 14:20:02 -06001466#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001467pub struct ImageVersion {
David Brown7a81c4b2019-07-29 15:20:21 -06001468 pub major: u8,
1469 pub minor: u8,
1470 pub revision: u16,
1471 pub build_num: u32,
David Brown5c9e0f12019-01-09 16:34:33 -07001472}
1473
David Brownc3898d62019-08-05 14:20:02 -06001474#[derive(Clone, Debug)]
David Brown5c9e0f12019-01-09 16:34:33 -07001475pub struct SlotInfo {
1476 pub base_off: usize,
1477 pub trailer_off: usize,
1478 pub len: usize,
David Brown3b090212019-07-30 15:59:28 -06001479 // Which slot within this device.
1480 pub index: usize,
David Brown5c9e0f12019-01-09 16:34:33 -07001481 pub dev_id: u8,
1482}
1483
David Brown347dc572019-11-15 11:37:25 -07001484const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
1485 0x60, 0xd2, 0xef, 0x7f,
1486 0x35, 0x52, 0x50, 0x0f,
1487 0x2c, 0xb6, 0x79, 0x80];
David Brown5c9e0f12019-01-09 16:34:33 -07001488
1489// Replicates defines found in bootutil.h
1490const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
1491const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
1492
1493const BOOT_FLAG_SET: Option<u8> = Some(1);
1494const BOOT_FLAG_UNSET: Option<u8> = Some(3);
1495
1496/// Write out the magic so that the loader tries doing an upgrade.
David Brown76101572019-02-28 11:29:03 -07001497pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
1498 let dev = flash.get_mut(&slot.dev_id).unwrap();
David Brown95de4502019-11-15 12:01:34 -07001499 let align = dev.align();
Christopher Collinsa1c12042019-05-23 14:00:28 -07001500 let offset = slot.trailer_off + c::boot_max_align() * 4;
David Brown95de4502019-11-15 12:01:34 -07001501 if offset % align != 0 || MAGIC.len() % align != 0 {
1502 // The write size is larger than the magic value. Fill a buffer
1503 // with the erased value, put the MAGIC in it, and write it in its
1504 // entirety.
1505 let mut buf = vec![dev.erased_val(); align];
1506 buf[(offset % align)..].copy_from_slice(MAGIC);
1507 dev.write(offset - (offset % align), &buf).unwrap();
1508 } else {
1509 dev.write(offset, MAGIC).unwrap();
1510 }
David Brown5c9e0f12019-01-09 16:34:33 -07001511}
1512
1513/// Writes the image_ok flag which, guess what, tells the bootloader
1514/// the this image is ok (not a test, and no revert is to be performed).
David Brown76101572019-02-28 11:29:03 -07001515fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
David Browneecae522019-11-15 12:00:20 -07001516 // Overwrite mode always is permanent, and only the magic is used in
1517 // the trailer. To avoid problems with large write sizes, don't try to
1518 // set anything in this case.
1519 if Caps::OverwriteUpgrade.present() {
1520 return;
1521 }
1522
David Brown76101572019-02-28 11:29:03 -07001523 let dev = flash.get_mut(&slot.dev_id).unwrap();
1524 let mut ok = [dev.erased_val(); 8];
David Brown5c9e0f12019-01-09 16:34:33 -07001525 ok[0] = 1u8;
Christopher Collinsa1c12042019-05-23 14:00:28 -07001526 let off = slot.trailer_off + c::boot_max_align() * 3;
David Brown76101572019-02-28 11:29:03 -07001527 let align = dev.align();
1528 dev.write(off, &ok[..align]).unwrap();
David Brown5c9e0f12019-01-09 16:34:33 -07001529}
1530
1531// Drop some pseudo-random gibberish onto the data.
1532fn splat(data: &mut [u8], seed: usize) {
1533 let seed_block = [0x135782ea, 0x92184728, data.len() as u32, seed as u32];
1534 let mut rng: XorShiftRng = SeedableRng::from_seed(seed_block);
1535 rng.fill_bytes(data);
1536}
1537
1538/// Return a read-only view into the raw bytes of this object
1539trait AsRaw : Sized {
1540 fn as_raw<'a>(&'a self) -> &'a [u8] {
1541 unsafe { slice::from_raw_parts(self as *const _ as *const u8,
1542 mem::size_of::<Self>()) }
1543 }
1544}
1545
1546pub fn show_sizes() {
1547 // This isn't panic safe.
1548 for min in &[1, 2, 4, 8] {
1549 let msize = c::boot_trailer_sz(*min);
1550 println!("{:2}: {} (0x{:x})", min, msize, msize);
1551 }
1552}
David Brown95de4502019-11-15 12:01:34 -07001553
1554#[cfg(not(feature = "large-write"))]
1555fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001556 &[1, 2, 4, 8]
1557}
1558
1559#[cfg(feature = "large-write")]
1560fn test_alignments() -> &'static [usize] {
David Brown95de4502019-11-15 12:01:34 -07001561 &[1, 2, 4, 8, 128, 512]
1562}