1 // Copyright (c) 2019-2021 Linaro LTD
2 // Copyright (c) 2019-2020 JUUL Labs
3 // Copyright (c) 2019-2023 Arm Limited
4 //
5 // SPDX-License-Identifier: Apache-2.0
6 
7 use byteorder::{
8     LittleEndian, WriteBytesExt,
9 };
10 use log::{
11     Level::Info,
12     error,
13     info,
14     log_enabled,
15     warn,
16 };
17 use rand::{
18     Rng, RngCore, SeedableRng,
19     rngs::SmallRng,
20 };
21 use std::{
22     collections::{BTreeMap, HashSet}, io::{Cursor, Write}, mem, rc::Rc, slice
23 };
24 use aes::{
25     Aes128,
26     Aes128Ctr,
27     Aes256,
28     Aes256Ctr,
29     NewBlockCipher,
30 };
31 use cipher::{
32     FromBlockCipher,
33     generic_array::GenericArray,
34     StreamCipher,
35     };
36 
37 use simflash::{Flash, SimFlash, SimMultiFlash};
38 use mcuboot_sys::{c, AreaDesc, FlashId, RamBlock};
39 use crate::{
40     ALL_DEVICES,
41     DeviceName,
42 };
43 use crate::caps::Caps;
44 use crate::depends::{
45     BoringDep,
46     Depender,
47     DepTest,
48     DepType,
49     NO_DEPS,
50     PairDep,
51     UpgradeInfo,
52 };
53 use crate::tlv::{ManifestGen, TlvGen, TlvFlags};
54 use crate::utils::align_up;
55 use typenum::{U32, U16};
56 
57 /// For testing, use a non-zero offset for the ram-load, to make sure the offset is getting used
58 /// properly, but the value is not really that important.
59 const RAM_LOAD_ADDR: u32 = 1024;
60 
61 /// A builder for Images.  This describes a single run of the simulator,
62 /// capturing the configuration of a particular set of devices, including
63 /// the flash simulator(s) and the information about the slots.
64 #[derive(Clone)]
65 pub struct ImagesBuilder {
66     flash: SimMultiFlash,
67     areadesc: Rc<AreaDesc>,
68     slots: Vec<[SlotInfo; 2]>,
69     ram: RamData,
70 }
71 
72 /// Images represents the state of a simulation for a given set of images.
73 /// The flash holds the state of the simulated flash, whereas primaries
74 /// and upgrades hold the expected contents of these images.
75 pub struct Images {
76     flash: SimMultiFlash,
77     areadesc: Rc<AreaDesc>,
78     images: Vec<OneImage>,
79     total_count: Option<i32>,
80     ram: RamData,
81 }
82 
83 /// When doing multi-image, there is an instance of this information for
84 /// each of the images.  Single image there will be one of these.
85 struct OneImage {
86     slots: [SlotInfo; 2],
87     primaries: ImageData,
88     upgrades: ImageData,
89 }
90 
91 /// The Rust-side representation of an image.  For unencrypted images, this
92 /// is just the unencrypted payload.  For encrypted images, we store both
93 /// the encrypted and the plaintext.
94 struct ImageData {
95     size: usize,
96     plain: Vec<u8>,
97     cipher: Option<Vec<u8>>,
98 }
99 
100 /// For the RamLoad test cases, we need a contiguous area of RAM to load these images into.  For
101 /// multi-image builds, these may not correspond with the offsets.  This has to be computed early,
102 /// before images are built, because each image contains the offset where the image is to be loaded
103 /// in the header, which is contained within the signature.
104 #[derive(Clone, Debug)]
105 struct RamData {
106     places: BTreeMap<SlotKey, SlotPlace>,
107     total: u32,
108 }
109 
110 /// Every slot is indexed by this key.
111 #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
112 struct SlotKey {
113     dev_id: u8,
114     base_off: usize,
115 }
116 
117 #[derive(Clone, Debug)]
118 struct SlotPlace {
119     offset: u32,
120     size: u32,
121 }
122 
123 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
124 pub enum ImageManipulation {
125     None,
126     BadSignature,
127     WrongOffset,
128     IgnoreRamLoadFlag,
129     /// True to use same address,
130     /// false to overlap by 1 byte
131     OverlapImages(bool),
132     CorruptHigherVersionImage,
133 }
134 
135 
136 impl ImagesBuilder {
137     /// Construct a new image builder for the given device.  Returns
138     /// Some(builder) if is possible to test this configuration, or None if
139     /// not possible (for example, if there aren't enough image slots).
new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String>140     pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
141         let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
142 
143         for cap in unsupported_caps {
144             if cap.present() {
145                 return Err(format!("unsupported {:?}", cap));
146             }
147         }
148 
149         let num_images = Caps::get_num_images();
150 
151         let mut slots = Vec::with_capacity(num_images);
152         for image in 0..num_images {
153             // This mapping must match that defined in
154             // `boot/zephyr/include/sysflash/sysflash.h`.
155             let id0 = match image {
156                 0 => FlashId::Image0,
157                 1 => FlashId::Image2,
158                 _ => panic!("More than 2 images not supported"),
159             };
160             let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
161                 Some(info) => info,
162                 None => return Err("insufficient partitions".to_string()),
163             };
164             let id1 = match image {
165                 0 => FlashId::Image1,
166                 1 => FlashId::Image3,
167                 _ => panic!("More than 2 images not supported"),
168             };
169             let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
170                 Some(info) => info,
171                 None => return Err("insufficient partitions".to_string()),
172             };
173 
174             let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
175 
176             // Construct a primary image.
177             let primary = SlotInfo {
178                 base_off: primary_base as usize,
179                 trailer_off: primary_base + primary_len - offset_from_end,
180                 len: primary_len as usize,
181                 dev_id: primary_dev_id,
182                 index: 0,
183             };
184 
185             // And an upgrade image.
186             let secondary = SlotInfo {
187                 base_off: secondary_base as usize,
188                 trailer_off: secondary_base + secondary_len - offset_from_end,
189                 len: secondary_len as usize,
190                 dev_id: secondary_dev_id,
191                 index: 1,
192             };
193 
194             slots.push([primary, secondary]);
195         }
196 
197         let ram = RamData::new(&slots);
198 
199         Ok(ImagesBuilder {
200             flash,
201             areadesc,
202             slots,
203             ram,
204         })
205     }
206 
each_device<F>(f: F) where F: Fn(Self)207     pub fn each_device<F>(f: F)
208         where F: Fn(Self)
209     {
210         for &dev in ALL_DEVICES {
211             for &align in test_alignments() {
212                 for &erased_val in &[0, 0xff] {
213                     match Self::new(dev, align, erased_val) {
214                         Ok(run) => f(run),
215                         Err(msg) => warn!("Skipping {}: {}", dev, msg),
216                     }
217                 }
218             }
219         }
220     }
221 
222     /// Construct an `Images` that doesn't expect an upgrade to happen.
make_no_upgrade_image(self, deps: &DepTest, img_manipulation: ImageManipulation) -> Images223     pub fn make_no_upgrade_image(self, deps: &DepTest, img_manipulation: ImageManipulation) -> Images {
224         let num_images = self.num_images();
225         let mut flash = self.flash;
226         let ram = self.ram.clone();  // TODO: Avoid this clone.
227         let mut higher_version_corrupted = false;
228         let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
229             let dep: Box<dyn Depender> = if num_images > 1 {
230                 Box::new(PairDep::new(num_images, image_num, deps))
231             } else {
232                 Box::new(BoringDep::new(image_num, deps))
233             };
234 
235             let (primaries,upgrades) =  if img_manipulation == ImageManipulation::CorruptHigherVersionImage && !higher_version_corrupted {
236                 higher_version_corrupted = true;
237                let prim =  install_image(&mut flash, &slots[0],
238                     maximal(42784), &ram, &*dep, ImageManipulation::None, Some(0));
239                 let upgr   = match deps.depends[image_num] {
240                     DepType::NoUpgrade => install_no_image(),
241                     _ => install_image(&mut flash, &slots[1],
242                         maximal(46928), &ram, &*dep, ImageManipulation::BadSignature, Some(0))
243                 };
244                 (prim, upgr)
245             } else {
246                 let prim = install_image(&mut flash, &slots[0],
247                     maximal(42784), &ram, &*dep, img_manipulation, Some(0));
248                 let upgr = match deps.depends[image_num] {
249                         DepType::NoUpgrade => install_no_image(),
250                         _ => install_image(&mut flash, &slots[1],
251                             maximal(46928), &ram, &*dep, img_manipulation, Some(0))
252                     };
253                 (prim, upgr)
254             };
255             OneImage {
256                 slots,
257                 primaries,
258                 upgrades,
259             }}).collect();
260         install_ptable(&mut flash, &self.areadesc);
261         Images {
262             flash,
263             areadesc: self.areadesc,
264             images,
265             total_count: None,
266             ram: self.ram,
267         }
268     }
269 
make_image(self, deps: &DepTest, permanent: bool) -> Images270     pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
271         let mut images = self.make_no_upgrade_image(deps, ImageManipulation::None);
272         for image in &images.images {
273             mark_upgrade(&mut images.flash, &image.slots[1]);
274         }
275 
276         // The count is meaningless if no flash operations are performed.
277         if !Caps::modifies_flash() {
278             return images;
279         }
280 
281         // upgrades without fails, counts number of flash operations
282         let total_count = match images.run_basic_upgrade(permanent) {
283             Some(v)  => v,
284             None =>
285                 if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
286                     0
287                 } else {
288                     panic!("Unable to perform basic upgrade");
289                 }
290         };
291 
292         images.total_count = Some(total_count);
293         images
294     }
295 
make_bad_secondary_slot_image(self) -> Images296     pub fn make_bad_secondary_slot_image(self) -> Images {
297         let mut bad_flash = self.flash;
298         let ram = self.ram.clone(); // TODO: Avoid this clone.
299         let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
300             let dep = BoringDep::new(image_num, &NO_DEPS);
301             let primaries = install_image(&mut bad_flash, &slots[0],
302                 maximal(32784), &ram, &dep, ImageManipulation::None, Some(0));
303             let upgrades = install_image(&mut bad_flash, &slots[1],
304                 maximal(41928), &ram, &dep, ImageManipulation::BadSignature, Some(0));
305             OneImage {
306                 slots,
307                 primaries,
308                 upgrades,
309             }}).collect();
310         Images {
311             flash: bad_flash,
312             areadesc: self.areadesc,
313             images,
314             total_count: None,
315             ram: self.ram,
316         }
317     }
318 
make_oversized_secondary_slot_image(self) -> Images319     pub fn make_oversized_secondary_slot_image(self) -> Images {
320         let mut bad_flash = self.flash;
321         let ram = self.ram.clone(); // TODO: Avoid this clone.
322         let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
323             let dep = BoringDep::new(image_num, &NO_DEPS);
324             let primaries = install_image(&mut bad_flash, &slots[0],
325                 maximal(32784), &ram, &dep, ImageManipulation::None, Some(0));
326             let upgrades = install_image(&mut bad_flash, &slots[1],
327                 ImageSize::Oversized, &ram, &dep, ImageManipulation::None, Some(0));
328             OneImage {
329                 slots,
330                 primaries,
331                 upgrades,
332             }}).collect();
333         Images {
334             flash: bad_flash,
335             areadesc: self.areadesc,
336             images,
337             total_count: None,
338             ram: self.ram,
339         }
340     }
341 
make_erased_secondary_image(self) -> Images342     pub fn make_erased_secondary_image(self) -> Images {
343         let mut flash = self.flash;
344         let ram = self.ram.clone(); // TODO: Avoid this clone.
345         let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
346             let dep = BoringDep::new(image_num, &NO_DEPS);
347             let primaries = install_image(&mut flash, &slots[0],
348                 maximal(32784), &ram, &dep,ImageManipulation::None, Some(0));
349             let upgrades = install_no_image();
350             OneImage {
351                 slots,
352                 primaries,
353                 upgrades,
354             }}).collect();
355         Images {
356             flash,
357             areadesc: self.areadesc,
358             images,
359             total_count: None,
360             ram: self.ram,
361         }
362     }
363 
make_bootstrap_image(self) -> Images364     pub fn make_bootstrap_image(self) -> Images {
365         let mut flash = self.flash;
366         let ram = self.ram.clone(); // TODO: Avoid this clone.
367         let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
368             let dep = BoringDep::new(image_num, &NO_DEPS);
369             let primaries = install_no_image();
370             let upgrades = install_image(&mut flash, &slots[1],
371                 maximal(32784), &ram, &dep, ImageManipulation::None, Some(0));
372             OneImage {
373                 slots,
374                 primaries,
375                 upgrades,
376             }}).collect();
377         Images {
378             flash,
379             areadesc: self.areadesc,
380             images,
381             total_count: None,
382             ram: self.ram,
383         }
384     }
385 
make_oversized_bootstrap_image(self) -> Images386     pub fn make_oversized_bootstrap_image(self) -> Images {
387         let mut flash = self.flash;
388         let ram = self.ram.clone(); // TODO: Avoid this clone.
389         let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
390             let dep = BoringDep::new(image_num, &NO_DEPS);
391             let primaries = install_no_image();
392             let upgrades = install_image(&mut flash, &slots[1],
393                 ImageSize::Oversized, &ram, &dep, ImageManipulation::None, Some(0));
394             OneImage {
395                 slots,
396                 primaries,
397                 upgrades,
398             }}).collect();
399         Images {
400             flash,
401             areadesc: self.areadesc,
402             images,
403             total_count: None,
404             ram: self.ram,
405         }
406     }
407 
408     /// If security_cnt is None then do not add a security counter TLV, otherwise add the specified value.
make_image_with_security_counter(self, security_cnt: Option<u32>) -> Images409     pub fn make_image_with_security_counter(self, security_cnt: Option<u32>) -> Images {
410         let mut flash = self.flash;
411         let ram = self.ram.clone(); // TODO: Avoid this clone.
412         let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
413             let dep = BoringDep::new(image_num, &NO_DEPS);
414             let primaries = install_image(&mut flash, &slots[0],
415                 maximal(32784), &ram, &dep,  ImageManipulation::None, security_cnt);
416             let upgrades = install_image(&mut flash, &slots[1],
417                 maximal(41928), &ram, &dep, ImageManipulation::None, security_cnt.map(|v| v + 1));
418             OneImage {
419                 slots,
420                 primaries,
421                 upgrades,
422             }}).collect();
423         Images {
424             flash,
425             areadesc: self.areadesc,
426             images,
427             total_count: None,
428             ram: self.ram,
429         }
430     }
431 
432     /// Build the Flash and area descriptor for a given device.
make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, Rc<AreaDesc>, &'static [Caps])433     pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, Rc<AreaDesc>, &'static [Caps]) {
434         match device {
435             DeviceName::Stm32f4 => {
436                 // STM style flash.  Large sectors, with a large scratch area.
437                 // The flash layout as described is not present in any real STM32F4 device, but it
438                 // serves to exercise support for sectors of varying sizes inside a single slot,
439                 // as long as they are compatible in both slots and all fit in the scratch.
440                 let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024, 64 * 1024,
441                                         32 * 1024, 32 * 1024, 64 * 1024,
442                                         32 * 1024, 32 * 1024, 64 * 1024,
443                                         128 * 1024],
444                                         align as usize, erased_val);
445                 let dev_id = 0;
446                 let mut areadesc = AreaDesc::new();
447                 areadesc.add_flash_sectors(dev_id, &dev);
448                 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
449                 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
450                 areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
451 
452                 let mut flash = SimMultiFlash::new();
453                 flash.insert(dev_id, dev);
454                 (flash, Rc::new(areadesc), &[Caps::SwapUsingMove])
455             }
456             DeviceName::K64f => {
457                 // NXP style flash.  Small sectors, one small sector for scratch.
458                 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
459 
460                 let dev_id = 0;
461                 let mut areadesc = AreaDesc::new();
462                 areadesc.add_flash_sectors(dev_id, &dev);
463                 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
464                 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
465                 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
466 
467                 let mut flash = SimMultiFlash::new();
468                 flash.insert(dev_id, dev);
469                 (flash, Rc::new(areadesc), &[])
470             }
471             DeviceName::K64fBig => {
472                 // Simulating an STM style flash on top of an NXP style flash.  Underlying flash device
473                 // uses small sectors, but we tell the bootloader they are large.
474                 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
475 
476                 let dev_id = 0;
477                 let mut areadesc = AreaDesc::new();
478                 areadesc.add_flash_sectors(dev_id, &dev);
479                 areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
480                 areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
481                 areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
482 
483                 let mut flash = SimMultiFlash::new();
484                 flash.insert(dev_id, dev);
485                 (flash, Rc::new(areadesc), &[Caps::SwapUsingMove])
486             }
487             DeviceName::Nrf52840 => {
488                 // Simulating the flash on the nrf52840 with partitions set up so that the scratch size
489                 // does not divide into the image size.
490                 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
491 
492                 let dev_id = 0;
493                 let mut areadesc = AreaDesc::new();
494                 areadesc.add_flash_sectors(dev_id, &dev);
495                 areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
496                 areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
497                 areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
498 
499                 let mut flash = SimMultiFlash::new();
500                 flash.insert(dev_id, dev);
501                 (flash, Rc::new(areadesc), &[])
502             }
503             DeviceName::Nrf52840UnequalSlots => {
504                 let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
505 
506                 let dev_id = 0;
507                 let mut areadesc = AreaDesc::new();
508                 areadesc.add_flash_sectors(dev_id, &dev);
509                 areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
510                 areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
511 
512                 let mut flash = SimMultiFlash::new();
513                 flash.insert(dev_id, dev);
514                 (flash, Rc::new(areadesc), &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
515             }
516             DeviceName::Nrf52840SpiFlash => {
517                 // Simulate nrf52840 with external SPI flash. The external SPI flash
518                 // has a larger sector size so for now store scratch on that flash.
519                 let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
520                 let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
521 
522                 let mut areadesc = AreaDesc::new();
523                 areadesc.add_flash_sectors(0, &dev0);
524                 areadesc.add_flash_sectors(1, &dev1);
525 
526                 areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
527                 areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
528                 areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
529 
530                 let mut flash = SimMultiFlash::new();
531                 flash.insert(0, dev0);
532                 flash.insert(1, dev1);
533                 (flash, Rc::new(areadesc), &[Caps::SwapUsingMove])
534             }
535             DeviceName::K64fMulti => {
536                 // NXP style flash, but larger, to support multiple images.
537                 let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
538 
539                 let dev_id = 0;
540                 let mut areadesc = AreaDesc::new();
541                 areadesc.add_flash_sectors(dev_id, &dev);
542                 areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
543                 areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
544                 areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
545                 areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
546                 areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
547 
548                 let mut flash = SimMultiFlash::new();
549                 flash.insert(dev_id, dev);
550                 (flash, Rc::new(areadesc), &[])
551             }
552         }
553     }
554 
num_images(&self) -> usize555     pub fn num_images(&self) -> usize {
556         self.slots.len()
557     }
558 }
559 
560 impl Images {
561     /// A simple upgrade without forced failures.
562     ///
563     /// Returns the number of flash operations which can later be used to
564     /// inject failures at chosen steps.  Returns None if it was unable to
565     /// count the operations in a basic upgrade.
run_basic_upgrade(&self, permanent: bool) -> Option<i32>566     pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
567         let (flash, total_count) = self.try_upgrade(None, permanent);
568         info!("Total flash operation count={}", total_count);
569 
570         if !self.verify_images(&flash, 0, 1) {
571             warn!("Image mismatch after first boot");
572             None
573         } else {
574             Some(total_count)
575         }
576     }
577 
run_bootstrap(&self) -> bool578     pub fn run_bootstrap(&self) -> bool {
579         let mut flash = self.flash.clone();
580         let mut fails = 0;
581 
582         if Caps::Bootstrap.present() {
583             info!("Try bootstraping image in the primary");
584 
585             if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
586                 warn!("Failed first boot");
587                 fails += 1;
588             }
589 
590             if !self.verify_images(&flash, 0, 1) {
591                 warn!("Image in the first slot was not bootstrapped");
592                 fails += 1;
593             }
594 
595             if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
596                                      BOOT_FLAG_SET, BOOT_FLAG_SET) {
597                 warn!("Mismatched trailer for the primary slot");
598                 fails += 1;
599             }
600         }
601 
602         if fails > 0 {
603             error!("Expected trailer on secondary slot to be erased");
604         }
605 
606         fails > 0
607     }
608 
run_oversized_bootstrap(&self) -> bool609     pub fn run_oversized_bootstrap(&self) -> bool {
610         let mut flash = self.flash.clone();
611         let mut fails = 0;
612 
613         if Caps::Bootstrap.present() {
614             info!("Try bootstraping image in the primary");
615 
616             let boot_result = c::boot_go(&mut flash, &self.areadesc, None, None, false).interrupted();
617 
618             if boot_result {
619                 warn!("Failed first boot");
620                 fails += 1;
621             }
622 
623             if self.verify_images(&flash, 0, 1) {
624                 warn!("Image in the first slot was not bootstrapped");
625                 fails += 1;
626             }
627 
628             if self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
629                                      BOOT_FLAG_SET, BOOT_FLAG_SET) {
630                 warn!("Mismatched trailer for the primary slot");
631                 fails += 1;
632             }
633         }
634 
635         if fails > 0 {
636             error!("Expected trailer on secondary slot to be erased");
637         }
638 
639         fails > 0
640     }
641 
642 
643     /// Test a simple upgrade, with dependencies given, and verify that the
644     /// image does as is described in the test.
run_check_deps(&self, deps: &DepTest) -> bool645     pub fn run_check_deps(&self, deps: &DepTest) -> bool {
646         if !Caps::modifies_flash() {
647             return false;
648         }
649 
650         let (flash, _) = self.try_upgrade(None, true);
651 
652         self.verify_dep_images(&flash, deps)
653     }
654 
is_swap_upgrade(&self) -> bool655     fn is_swap_upgrade(&self) -> bool {
656         Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
657     }
658 
run_basic_revert(&self) -> bool659     pub fn run_basic_revert(&self) -> bool {
660         if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
661             return false;
662         }
663 
664         let mut fails = 0;
665 
666         // FIXME: this test would also pass if no swap is ever performed???
667         if self.is_swap_upgrade() {
668             for count in 2 .. 5 {
669                 info!("Try revert: {}", count);
670                 let flash = self.try_revert(count);
671                 if !self.verify_images(&flash, 0, 0) {
672                     error!("Revert failure on count {}", count);
673                     fails += 1;
674                 }
675             }
676         }
677 
678         fails > 0
679     }
680 
run_perm_with_fails(&self) -> bool681     pub fn run_perm_with_fails(&self) -> bool {
682         if !Caps::modifies_flash() {
683             return false;
684         }
685 
686         let mut fails = 0;
687         let total_flash_ops = self.total_count.unwrap();
688 
689         if skip_slow_test() {
690             return false;
691         }
692 
693         // Let's try an image halfway through.
694         for i in 1 .. total_flash_ops {
695             info!("Try interruption at {}", i);
696             let (flash, count) = self.try_upgrade(Some(i), true);
697             info!("Second boot, count={}", count);
698             if !self.verify_images(&flash, 0, 1) {
699                 warn!("FAIL at step {} of {}", i, total_flash_ops);
700                 fails += 1;
701             }
702 
703             if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
704                                      BOOT_FLAG_SET, BOOT_FLAG_SET) {
705                 warn!("Mismatched trailer for the primary slot");
706                 fails += 1;
707             }
708 
709             if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
710                                      BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
711                 warn!("Mismatched trailer for the secondary slot");
712                 fails += 1;
713             }
714 
715             if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
716                 warn!("Secondary slot FAIL at step {} of {}",
717                     i, total_flash_ops);
718                 fails += 1;
719             }
720         }
721 
722         if fails > 0 {
723             error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
724                    fails as f32 * 100.0 / total_flash_ops as f32);
725         }
726 
727         fails > 0
728     }
729 
run_perm_with_random_fails(&self, total_fails: usize) -> bool730     pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
731         if !Caps::modifies_flash() {
732             return false;
733         }
734 
735         let mut fails = 0;
736         let total_flash_ops = self.total_count.unwrap();
737         let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
738         info!("Random interruptions at reset points={:?}", total_counts);
739 
740         let primary_slot_ok = self.verify_images(&flash, 0, 1);
741         let secondary_slot_ok = if self.is_swap_upgrade() {
742             // TODO: This result is ignored.
743             self.verify_images(&flash, 1, 0)
744         } else {
745             true
746         };
747         if !primary_slot_ok || !secondary_slot_ok {
748             error!("Image mismatch after random interrupts: primary slot={} \
749                     secondary slot={}",
750                    if primary_slot_ok { "ok" } else { "fail" },
751                    if secondary_slot_ok { "ok" } else { "fail" });
752             fails += 1;
753         }
754         if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
755                                  BOOT_FLAG_SET, BOOT_FLAG_SET) {
756             error!("Mismatched trailer for the primary slot");
757             fails += 1;
758         }
759         if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
760                                  BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
761             error!("Mismatched trailer for the secondary slot");
762             fails += 1;
763         }
764 
765         if fails > 0 {
766             error!("Error testing perm upgrade with {} fails", total_fails);
767         }
768 
769         fails > 0
770     }
771 
run_revert_with_fails(&self) -> bool772     pub fn run_revert_with_fails(&self) -> bool {
773         if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
774             return false;
775         }
776 
777         let mut fails = 0;
778 
779         if skip_slow_test() {
780             return false;
781         }
782 
783         if self.is_swap_upgrade() {
784             for i in 1 .. self.total_count.unwrap() {
785                 info!("Try interruption at {}", i);
786                 if self.try_revert_with_fail_at(i) {
787                     error!("Revert failed at interruption {}", i);
788                     fails += 1;
789                 }
790             }
791         }
792 
793         fails > 0
794     }
795 
run_norevert(&self) -> bool796     pub fn run_norevert(&self) -> bool {
797         if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
798             return false;
799         }
800 
801         let mut flash = self.flash.clone();
802         let mut fails = 0;
803 
804         info!("Try norevert");
805 
806         // First do a normal upgrade...
807         if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
808             warn!("Failed first boot");
809             fails += 1;
810         }
811 
812         //FIXME: copy_done is written by boot_go, is it ok if no copy
813         //       was ever done?
814 
815         if !self.verify_images(&flash, 0, 1) {
816             warn!("Primary slot image verification FAIL");
817             fails += 1;
818         }
819         if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
820                                  BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
821             warn!("Mismatched trailer for the primary slot");
822             fails += 1;
823         }
824         if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
825                                  BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
826             warn!("Mismatched trailer for the secondary slot");
827             fails += 1;
828         }
829 
830         // Marks image in the primary slot as permanent,
831         // no revert should happen...
832         self.mark_permanent_upgrades(&mut flash, 0);
833 
834         if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
835                                  BOOT_FLAG_SET, BOOT_FLAG_SET) {
836             warn!("Mismatched trailer for the primary slot");
837             fails += 1;
838         }
839 
840         if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
841             warn!("Failed second boot");
842             fails += 1;
843         }
844 
845         if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
846                                  BOOT_FLAG_SET, BOOT_FLAG_SET) {
847             warn!("Mismatched trailer for the primary slot");
848             fails += 1;
849         }
850         if !self.verify_images(&flash, 0, 1) {
851             warn!("Failed image verification");
852             fails += 1;
853         }
854 
855         if fails > 0 {
856             error!("Error running upgrade without revert");
857         }
858 
859         fails > 0
860     }
861 
862     // Test taht too big upgrade image will be rejected
run_oversizefail_upgrade(&self) -> bool863     pub fn run_oversizefail_upgrade(&self) -> bool {
864         let mut flash = self.flash.clone();
865         let mut fails = 0;
866 
867         info!("Try upgrade image with to big size");
868 
869         // Only perform this test if an upgrade is expected to happen.
870         if !Caps::modifies_flash() {
871             info!("Skipping upgrade image with bad signature");
872             return false;
873         }
874 
875         self.mark_upgrades(&mut flash, 0);
876         self.mark_permanent_upgrades(&mut flash, 0);
877         self.mark_upgrades(&mut flash, 1);
878 
879         if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
880                                  BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
881             warn!("1. Mismatched trailer for the primary slot");
882             fails += 1;
883         }
884 
885         // Run the bootloader...
886         if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
887             warn!("Failed first boot");
888             fails += 1;
889         }
890 
891         // State should not have changed
892         if !self.verify_images(&flash, 0, 0) {
893             warn!("Failed image verification");
894             fails += 1;
895         }
896         if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
897                                  BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
898             warn!("2. Mismatched trailer for the primary slot");
899             fails += 1;
900         }
901 
902         if fails > 0 {
903             error!("Expected an upgrade failure when image has to big size");
904         }
905 
906         fails > 0
907     }
908 
909     // Test that an upgrade is rejected.  Assumes that the image was build
910     // such that the upgrade is instead a downgrade.
run_nodowngrade(&self) -> bool911     pub fn run_nodowngrade(&self) -> bool {
912         if !Caps::DowngradePrevention.present() {
913             return false;
914         }
915 
916         let mut flash = self.flash.clone();
917         let mut fails = 0;
918 
919         info!("Try no downgrade");
920 
921         // First, do a normal upgrade.
922         if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
923             warn!("Failed first boot");
924             fails += 1;
925         }
926 
927         if !self.verify_images(&flash, 0, 0) {
928             warn!("Failed verification after downgrade rejection");
929             fails += 1;
930         }
931 
932         if fails > 0 {
933             error!("Error testing downgrade rejection");
934         }
935 
936         fails > 0
937     }
938 
939     // Tests a new image written to the primary slot that already has magic and
940     // image_ok set while there is no image on the secondary slot, so no revert
941     // should ever happen...
run_norevert_newimage(&self) -> bool942     pub fn run_norevert_newimage(&self) -> bool {
943         if !Caps::modifies_flash() {
944             info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
945             return false;
946         }
947 
948         let mut flash = self.flash.clone();
949         let mut fails = 0;
950 
951         info!("Try non-revert on imgtool generated image");
952 
953         self.mark_upgrades(&mut flash, 0);
954 
955         // This simulates writing an image created by imgtool to
956         // the primary slot
957         if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
958                                  BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
959             warn!("Mismatched trailer for the primary slot");
960             fails += 1;
961         }
962 
963         // Run the bootloader...
964         if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
965             warn!("Failed first boot");
966             fails += 1;
967         }
968 
969         // State should not have changed
970         if !self.verify_images(&flash, 0, 0) {
971             warn!("Failed image verification");
972             fails += 1;
973         }
974         if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
975                                  BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
976             warn!("Mismatched trailer for the primary slot");
977             fails += 1;
978         }
979         if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
980                                  BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
981             warn!("Mismatched trailer for the secondary slot");
982             fails += 1;
983         }
984 
985         if fails > 0 {
986             error!("Expected a non revert with new image");
987         }
988 
989         fails > 0
990     }
991 
992     // Tests a new image written to the primary slot that already has magic and
993     // image_ok set while there is no image on the secondary slot, so no revert
994     // should ever happen...
run_signfail_upgrade(&self) -> bool995     pub fn run_signfail_upgrade(&self) -> bool {
996         let mut flash = self.flash.clone();
997         let mut fails = 0;
998 
999         info!("Try upgrade image with bad signature");
1000 
1001         // Only perform this test if an upgrade is expected to happen.
1002         if !Caps::modifies_flash() {
1003             info!("Skipping upgrade image with bad signature");
1004             return false;
1005         }
1006 
1007         self.mark_upgrades(&mut flash, 0);
1008         self.mark_permanent_upgrades(&mut flash, 0);
1009         self.mark_upgrades(&mut flash, 1);
1010 
1011         if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1012                                  BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
1013             warn!("Mismatched trailer for the primary slot");
1014             fails += 1;
1015         }
1016 
1017         // Run the bootloader...
1018         if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
1019             warn!("Failed first boot");
1020             fails += 1;
1021         }
1022 
1023         // State should not have changed
1024         if !self.verify_images(&flash, 0, 0) {
1025             warn!("Failed image verification");
1026             fails += 1;
1027         }
1028         if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1029                                  BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
1030             warn!("Mismatched trailer for the primary slot");
1031             fails += 1;
1032         }
1033 
1034         if fails > 0 {
1035             error!("Expected an upgrade failure when image has bad signature");
1036         }
1037 
1038         fails > 0
1039     }
1040 
1041     // Should detect there is a leftover trailer in an otherwise erased
1042     // secondary slot and erase its trailer.
run_secondary_leftover_trailer(&self) -> bool1043     pub fn run_secondary_leftover_trailer(&self) -> bool {
1044         if !Caps::modifies_flash() {
1045             return false;
1046         }
1047 
1048         let mut flash = self.flash.clone();
1049         let mut fails = 0;
1050 
1051         info!("Try with a leftover trailer in the secondary; must be erased");
1052 
1053         // Add a trailer on the secondary slot
1054         self.mark_permanent_upgrades(&mut flash, 1);
1055         self.mark_upgrades(&mut flash, 1);
1056 
1057         // Run the bootloader...
1058         if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
1059             warn!("Failed first boot");
1060             fails += 1;
1061         }
1062 
1063         // State should not have changed
1064         if !self.verify_images(&flash, 0, 0) {
1065             warn!("Failed image verification");
1066             fails += 1;
1067         }
1068         if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1069                                  BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
1070             warn!("Mismatched trailer for the secondary slot");
1071             fails += 1;
1072         }
1073 
1074         if fails > 0 {
1075             error!("Expected trailer on secondary slot to be erased");
1076         }
1077 
1078         fails > 0
1079     }
1080 
trailer_sz(&self, align: usize) -> usize1081     fn trailer_sz(&self, align: usize) -> usize {
1082         c::boot_trailer_sz(align as u32) as usize
1083     }
1084 
status_sz(&self, align: usize) -> usize1085     fn status_sz(&self, align: usize) -> usize {
1086         c::boot_status_sz(align as u32) as usize
1087     }
1088 
1089     /// This test runs a simple upgrade with no fails in the images, but
1090     /// allowing for fails in the status area. This should run to the end
1091     /// and warn that write fails were detected...
run_with_status_fails_complete(&self) -> bool1092     pub fn run_with_status_fails_complete(&self) -> bool {
1093         if !Caps::ValidatePrimarySlot.present() || !Caps::modifies_flash() {
1094             return false;
1095         }
1096 
1097         let mut flash = self.flash.clone();
1098         let mut fails = 0;
1099 
1100         info!("Try swap with status fails");
1101 
1102         self.mark_permanent_upgrades(&mut flash, 1);
1103         self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
1104 
1105         let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
1106         if !result.success() {
1107             warn!("Failed!");
1108             fails += 1;
1109         }
1110 
1111         // Failed writes to the marked "bad" region don't assert anymore.
1112         // Any detected assert() is happening in another part of the code.
1113         if result.asserts() != 0 {
1114             warn!("At least one assert() was called");
1115             fails += 1;
1116         }
1117 
1118         if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1119                                  BOOT_FLAG_SET, BOOT_FLAG_SET) {
1120             warn!("Mismatched trailer for the primary slot");
1121             fails += 1;
1122         }
1123 
1124         if !self.verify_images(&flash, 0, 1) {
1125             warn!("Failed image verification");
1126             fails += 1;
1127         }
1128 
1129         info!("validate primary slot enabled; \
1130                re-run of boot_go should just work");
1131         if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
1132             warn!("Failed!");
1133             fails += 1;
1134         }
1135 
1136         if fails > 0 {
1137             error!("Error running upgrade with status write fails");
1138         }
1139 
1140         fails > 0
1141     }
1142 
1143     /// This test runs a simple upgrade with no fails in the images, but
1144     /// allowing for fails in the status area. This should run to the end
1145     /// and warn that write fails were detected...
run_with_status_fails_with_reset(&self) -> bool1146     pub fn run_with_status_fails_with_reset(&self) -> bool {
1147         if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
1148             false
1149         } else if Caps::ValidatePrimarySlot.present() {
1150 
1151             let mut flash = self.flash.clone();
1152             let mut fails = 0;
1153             let mut count = self.total_count.unwrap() / 2;
1154 
1155             //info!("count={}\n", count);
1156 
1157             info!("Try interrupted swap with status fails");
1158 
1159             self.mark_permanent_upgrades(&mut flash, 1);
1160             self.mark_bad_status_with_rate(&mut flash, 0, 0.5);
1161 
1162             // Should not fail, writing to bad regions does not assert
1163             let asserts = c::boot_go(&mut flash, &self.areadesc,
1164                                      Some(&mut count), None, true).asserts();
1165             if asserts != 0 {
1166                 warn!("At least one assert() was called");
1167                 fails += 1;
1168             }
1169 
1170             self.reset_bad_status(&mut flash, 0);
1171 
1172             info!("Resuming an interrupted swap operation");
1173             let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1174                                      true).asserts();
1175 
1176             // This might throw no asserts, for large sector devices, where
1177             // a single failure writing is indistinguishable from no failure,
1178             // or throw a single assert for small sector devices that fail
1179             // multiple times...
1180             if asserts > 1 {
1181                 warn!("Expected single assert validating the primary slot, \
1182                        more detected {}", asserts);
1183                 fails += 1;
1184             }
1185 
1186             if fails > 0 {
1187                 error!("Error running upgrade with status write fails");
1188             }
1189 
1190             fails > 0
1191         } else {
1192             let mut flash = self.flash.clone();
1193             let mut fails = 0;
1194 
1195             info!("Try interrupted swap with status fails");
1196 
1197             self.mark_permanent_upgrades(&mut flash, 1);
1198             self.mark_bad_status_with_rate(&mut flash, 0, 1.0);
1199 
1200             // This is expected to fail while writing to bad regions...
1201             let asserts = c::boot_go(&mut flash, &self.areadesc, None, None,
1202                                      true).asserts();
1203             if asserts == 0 {
1204                 warn!("No assert() detected");
1205                 fails += 1;
1206             }
1207 
1208             fails > 0
1209         }
1210     }
1211 
1212     /// Test the direct XIP configuration.  With this mode, flash images are never moved, and the
1213     /// bootloader merely selects which partition is the proper one to boot.
run_direct_xip(&self) -> bool1214     pub fn run_direct_xip(&self) -> bool {
1215         if !Caps::DirectXip.present() {
1216             return false;
1217         }
1218 
1219         // Clone the flash so we can tell if unchanged.
1220         let mut flash = self.flash.clone();
1221 
1222         let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
1223 
1224         // Ensure the boot was successful.
1225         let resp = if let Some(resp) = result.resp() {
1226             resp
1227         } else {
1228             panic!("Boot didn't return a valid result");
1229         };
1230 
1231         // This configuration should always try booting from the first upgrade slot.
1232         if let Some((offset, _, dev_id)) = self.areadesc.find(FlashId::Image1) {
1233             assert_eq!(offset, resp.image_off as usize);
1234             assert_eq!(dev_id, resp.flash_dev_id);
1235         } else {
1236             panic!("Unable to find upgrade image");
1237         }
1238         false
1239     }
1240 
1241     /// Test the ram-loading.
run_ram_load(&self) -> bool1242     pub fn run_ram_load(&self) -> bool {
1243         if !Caps::RamLoad.present() {
1244             return false;
1245         }
1246 
1247         // Clone the flash so we can tell if unchanged.
1248         let mut flash = self.flash.clone();
1249 
1250         // Setup ram based on the ram configuration we determined earlier for the images.
1251         let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1252 
1253         // println!("Ram: {:#?}", self.ram);
1254 
1255         // Verify that the images area loaded into this.
1256         let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None,
1257                                               None, true));
1258         if !result.success() {
1259             error!("Failed to execute ram-load");
1260             return true;
1261         }
1262 
1263         // Verify each image.
1264         for image in &self.images {
1265             let place = self.ram.lookup(&image.slots[0]);
1266             let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1267                 place.size as usize);
1268             let src_sz = image.upgrades.size();
1269             if src_sz > ram_image.len() {
1270                 error!("Image ended up too large, nonsensical");
1271                 return true;
1272             }
1273             let src_image = &image.upgrades.plain[0..src_sz];
1274             let ram_image = &ram_image[0..src_sz];
1275             if ram_image != src_image {
1276                 error!("Image not loaded correctly");
1277                 return true;
1278             }
1279 
1280         }
1281 
1282         return false;
1283     }
1284 
1285     /// Test the split ram-loading.
run_split_ram_load(&self) -> bool1286     pub fn run_split_ram_load(&self) -> bool {
1287         if !Caps::RamLoad.present() {
1288             return false;
1289         }
1290 
1291         // Clone the flash so we can tell if unchanged.
1292         let mut flash = self.flash.clone();
1293 
1294         // Setup ram based on the ram configuration we determined earlier for the images.
1295         let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1296 
1297         for (idx, _image) in (&self.images).iter().enumerate() {
1298             // Verify that the images area loaded into this.
1299             let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc,
1300                                                   None, Some(idx as i32), true));
1301             if !result.success() {
1302                 error!("Failed to execute ram-load");
1303                 return true;
1304             }
1305         }
1306 
1307         // Verify each image.
1308         for image in &self.images {
1309             let place = self.ram.lookup(&image.slots[0]);
1310             let ram_image = ram.borrow_part(place.offset as usize - RAM_LOAD_ADDR as usize,
1311                 place.size as usize);
1312             let src_sz = image.upgrades.size();
1313             if src_sz > ram_image.len() {
1314                 error!("Image ended up too large, nonsensical");
1315                 return true;
1316             }
1317             let src_image = &image.upgrades.plain[0..src_sz];
1318             let ram_image = &ram_image[0..src_sz];
1319             if ram_image != src_image {
1320                 error!("Image not loaded correctly");
1321                 return true;
1322             }
1323 
1324         }
1325 
1326         return false;
1327     }
1328 
run_hw_rollback_prot(&self) -> bool1329     pub fn run_hw_rollback_prot(&self) -> bool {
1330         if !Caps::HwRollbackProtection.present() {
1331             return false;
1332         }
1333 
1334         let mut flash = self.flash.clone();
1335 
1336         // set the "stored" security counter to a fixed value.
1337         c::set_security_counter(0, 30);
1338 
1339         let result = c::boot_go(&mut flash, &self.areadesc, None, None, true);
1340 
1341         if result.success() {
1342             warn!("Successful boot when it did not suppose to happen!");
1343             return true;
1344         }
1345         let counter_val =  c::get_security_counter(0);
1346         if counter_val != 30 {
1347             warn!("Counter was changed when it did not suppose to!");
1348             return true;
1349         }
1350 
1351         false
1352     }
1353 
run_ram_load_boot_with_result(&self, expected_result: bool) -> bool1354     pub fn run_ram_load_boot_with_result(&self, expected_result: bool) -> bool {
1355         if !Caps::RamLoad.present() {
1356             return false;
1357         }
1358         // Clone the flash so we can tell if unchanged.
1359         let mut flash = self.flash.clone();
1360 
1361         // Create RAM config.
1362         let ram = RamBlock::new(self.ram.total - RAM_LOAD_ADDR, RAM_LOAD_ADDR);
1363 
1364         // Run the bootloader, and verify that it couldn't run to completion.
1365         let result = ram.invoke(|| c::boot_go(&mut flash, &self.areadesc, None,
1366             None, true));
1367 
1368         if result.success() != expected_result {
1369             error!("RAM load boot result was not of the expected value! (was: {}, expected: {})", result.success(), expected_result);
1370             return true;
1371         }
1372 
1373         false
1374     }
1375 
1376     /// Adds a new flash area that fails statistically
mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize, rate: f32)1377     fn mark_bad_status_with_rate(&self, flash: &mut SimMultiFlash, slot: usize,
1378                                  rate: f32) {
1379         if Caps::OverwriteUpgrade.present() {
1380             return;
1381         }
1382 
1383         // Set this for each image.
1384         for image in &self.images {
1385             let dev_id = &image.slots[slot].dev_id;
1386             let dev = flash.get_mut(&dev_id).unwrap();
1387             let align = dev.align();
1388             let off = &image.slots[slot].base_off;
1389             let len = &image.slots[slot].len;
1390             let status_off = off + len - self.trailer_sz(align);
1391 
1392             // Mark the status area as a bad area
1393             let _ = dev.add_bad_region(status_off, self.status_sz(align), rate);
1394         }
1395     }
1396 
reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize)1397     fn reset_bad_status(&self, flash: &mut SimMultiFlash, slot: usize) {
1398         if !Caps::ValidatePrimarySlot.present() {
1399             return;
1400         }
1401 
1402         for image in &self.images {
1403             let dev_id = &image.slots[slot].dev_id;
1404             let dev = flash.get_mut(&dev_id).unwrap();
1405             dev.reset_bad_regions();
1406 
1407             // Disabling write verification the only assert triggered by
1408             // boot_go should be checking for integrity of status bytes.
1409             dev.set_verify_writes(false);
1410         }
1411     }
1412 
1413     /// Test a boot, optionally stopping after 'n' flash options.  Returns a count
1414     /// of the number of flash operations done total.
try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32)1415     fn try_upgrade(&self, stop: Option<i32>, permanent: bool) -> (SimMultiFlash, i32) {
1416         // Clone the flash to have a new copy.
1417         let mut flash = self.flash.clone();
1418 
1419         if permanent {
1420             self.mark_permanent_upgrades(&mut flash, 1);
1421         }
1422 
1423         let mut counter = stop.unwrap_or(0);
1424 
1425         let (first_interrupted, count) = match c::boot_go(&mut flash,
1426                                                           &self.areadesc,
1427                                                           Some(&mut counter),
1428                                                           None, false) {
1429             x if x.interrupted() => (true, stop.unwrap()),
1430             x if x.success() => (false, -counter),
1431             x => panic!("Unknown return: {:?}", x),
1432         };
1433 
1434         counter = 0;
1435         if first_interrupted {
1436             // fl.dump();
1437             match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1438                              None, false) {
1439                 x if x.interrupted() => panic!("Shouldn't stop again"),
1440                 x if x.success() => (),
1441                 x => panic!("Unknown return: {:?}", x),
1442             }
1443         }
1444 
1445         (flash, count - counter)
1446     }
1447 
try_revert(&self, count: usize) -> SimMultiFlash1448     fn try_revert(&self, count: usize) -> SimMultiFlash {
1449         let mut flash = self.flash.clone();
1450 
1451         // fl.write_file("image0.bin").unwrap();
1452         for i in 0 .. count {
1453             info!("Running boot pass {}", i + 1);
1454             assert!(c::boot_go(&mut flash, &self.areadesc, None, None, false).success_no_asserts());
1455         }
1456         flash
1457     }
1458 
try_revert_with_fail_at(&self, stop: i32) -> bool1459     fn try_revert_with_fail_at(&self, stop: i32) -> bool {
1460         let mut flash = self.flash.clone();
1461         let mut fails = 0;
1462 
1463         let mut counter = stop;
1464         if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1465                        false).interrupted() {
1466             warn!("Should have stopped test at interruption point");
1467             fails += 1;
1468         }
1469 
1470         // In a multi-image setup, copy done might be set if any number of
1471         // images was already successfully swapped.
1472         if !self.verify_trailers_loose(&flash, 0, None, None, BOOT_FLAG_UNSET) {
1473             warn!("copy_done should be unset");
1474             fails += 1;
1475         }
1476 
1477         if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
1478             warn!("Should have finished test upgrade");
1479             fails += 1;
1480         }
1481 
1482         if !self.verify_images(&flash, 0, 1) {
1483             warn!("Image in the primary slot before revert is invalid at stop={}",
1484                   stop);
1485             fails += 1;
1486         }
1487         if !self.verify_images(&flash, 1, 0) {
1488             warn!("Image in the secondary slot before revert is invalid at stop={}",
1489                   stop);
1490             fails += 1;
1491         }
1492         if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1493                                  BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
1494             warn!("Mismatched trailer for the primary slot before revert");
1495             fails += 1;
1496         }
1497         if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1498                                 BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
1499             warn!("Mismatched trailer for the secondary slot before revert");
1500             fails += 1;
1501         }
1502 
1503         // Do Revert
1504         let mut counter = stop;
1505         if !c::boot_go(&mut flash, &self.areadesc, Some(&mut counter), None,
1506                        false).interrupted() {
1507             warn!("Should have stopped revert at interruption point");
1508             fails += 1;
1509         }
1510 
1511         if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
1512             warn!("Should have finished revert upgrade");
1513             fails += 1;
1514         }
1515 
1516         if !self.verify_images(&flash, 0, 0) {
1517             warn!("Image in the primary slot after revert is invalid at stop={}",
1518                   stop);
1519             fails += 1;
1520         }
1521         if !self.verify_images(&flash, 1, 1) {
1522             warn!("Image in the secondary slot after revert is invalid at stop={}",
1523                   stop);
1524             fails += 1;
1525         }
1526 
1527         if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
1528                                  BOOT_FLAG_SET, BOOT_FLAG_SET) {
1529             warn!("Mismatched trailer for the primary slot after revert");
1530             fails += 1;
1531         }
1532         if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
1533                                  BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
1534             warn!("Mismatched trailer for the secondary slot after revert");
1535             fails += 1;
1536         }
1537 
1538         if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
1539             warn!("Should have finished 3rd boot");
1540             fails += 1;
1541         }
1542 
1543         if !self.verify_images(&flash, 0, 0) {
1544             warn!("Image in the primary slot is invalid on 1st boot after revert");
1545             fails += 1;
1546         }
1547         if !self.verify_images(&flash, 1, 1) {
1548             warn!("Image in the secondary slot is invalid on 1st boot after revert");
1549             fails += 1;
1550         }
1551 
1552         fails > 0
1553     }
1554 
1555 
try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>)1556     fn try_random_fails(&self, total_ops: i32, count: usize) -> (SimMultiFlash, Vec<i32>) {
1557         let mut flash = self.flash.clone();
1558 
1559         self.mark_permanent_upgrades(&mut flash, 1);
1560 
1561         let mut rng = rand::thread_rng();
1562         let mut resets = vec![0i32; count];
1563         let mut remaining_ops = total_ops;
1564         for reset in &mut resets {
1565             let reset_counter = rng.gen_range(1 ..= remaining_ops / 2);
1566             let mut counter = reset_counter;
1567             match c::boot_go(&mut flash, &self.areadesc, Some(&mut counter),
1568                              None, false) {
1569                 x if x.interrupted() => (),
1570                 x => panic!("Unknown return: {:?}", x),
1571             }
1572             remaining_ops -= reset_counter;
1573             *reset = reset_counter;
1574         }
1575 
1576         match c::boot_go(&mut flash, &self.areadesc, None, None, false) {
1577             x if x.interrupted() => panic!("Should not be have been interrupted!"),
1578             x if x.success() => (),
1579             x => panic!("Unknown return: {:?}", x),
1580         }
1581 
1582         (flash, resets)
1583     }
1584 
1585     /// Verify the image in the given flash device, the specified slot
1586     /// against the expected image.
verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool1587     fn verify_images(&self, flash: &SimMultiFlash, slot: usize, against: usize) -> bool {
1588         self.images.iter().all(|image| {
1589             verify_image(flash, &image.slots[slot],
1590                          match against {
1591                              0 => &image.primaries,
1592                              1 => &image.upgrades,
1593                              _ => panic!("Invalid 'against'")
1594                              })
1595         })
1596     }
1597 
1598     /// Verify the images, according to the dependency test.
verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool1599     fn verify_dep_images(&self, flash: &SimMultiFlash, deps: &DepTest) -> bool {
1600         for (image_num, (image, upgrade)) in self.images.iter().zip(deps.upgrades.iter()).enumerate() {
1601             info!("Upgrade: slot:{}, {:?}", image_num, upgrade);
1602             if !verify_image(flash, &image.slots[0],
1603                             match upgrade {
1604                                 UpgradeInfo::Upgraded => &image.upgrades,
1605                                 UpgradeInfo::Held => &image.primaries,
1606                             }) {
1607                 error!("Failed to upgrade properly: image: {}, upgrade: {:?}", image_num, upgrade);
1608                 return true;
1609             }
1610         }
1611 
1612         false
1613     }
1614 
1615     /// Verify that at least one of the trailers of the images have the
1616     /// specified values.
verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize, magic: Option<u8>, image_ok: Option<u8>, copy_done: Option<u8>) -> bool1617     fn verify_trailers_loose(&self, flash: &SimMultiFlash, slot: usize,
1618                              magic: Option<u8>, image_ok: Option<u8>,
1619                              copy_done: Option<u8>) -> bool {
1620         self.images.iter().any(|image| {
1621             verify_trailer(flash, &image.slots[slot],
1622                            magic, image_ok, copy_done)
1623         })
1624     }
1625 
1626     /// Verify that the trailers of the images have the specified
1627     /// values.
verify_trailers(&self, flash: &SimMultiFlash, slot: usize, magic: Option<u8>, image_ok: Option<u8>, copy_done: Option<u8>) -> bool1628     fn verify_trailers(&self, flash: &SimMultiFlash, slot: usize,
1629                        magic: Option<u8>, image_ok: Option<u8>,
1630                        copy_done: Option<u8>) -> bool {
1631         self.images.iter().all(|image| {
1632             verify_trailer(flash, &image.slots[slot],
1633                            magic, image_ok, copy_done)
1634         })
1635     }
1636 
1637     /// Mark each of the images for permanent upgrade.
mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize)1638     fn mark_permanent_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1639         for image in &self.images {
1640             mark_permanent_upgrade(flash, &image.slots[slot]);
1641         }
1642     }
1643 
1644     /// Mark each of the images for permanent upgrade.
mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize)1645     fn mark_upgrades(&self, flash: &mut SimMultiFlash, slot: usize) {
1646         for image in &self.images {
1647             mark_upgrade(flash, &image.slots[slot]);
1648         }
1649     }
1650 
1651     /// Dump out the flash image(s) to one or more files for debugging
1652     /// purposes.  The names will be written as either "{prefix}.mcubin" or
1653     /// "{prefix}-001.mcubin" depending on how many images there are.
debug_dump(&self, prefix: &str)1654     pub fn debug_dump(&self, prefix: &str) {
1655         for (id, fdev) in &self.flash {
1656             let name = if self.flash.len() == 1 {
1657                 format!("{}.mcubin", prefix)
1658             } else {
1659                 format!("{}-{:>0}.mcubin", prefix, id)
1660             };
1661             fdev.write_file(&name).unwrap();
1662         }
1663     }
1664 }
1665 
1666 impl RamData {
1667     // TODO: This is not correct. The second slot of each image should be at the same address as
1668     // the primary.
new(slots: &[[SlotInfo; 2]]) -> RamData1669     fn new(slots: &[[SlotInfo; 2]]) -> RamData {
1670         let mut addr = RAM_LOAD_ADDR;
1671         let mut places = BTreeMap::new();
1672         // println!("Setup:-------------");
1673         for imgs in slots {
1674             for si in imgs {
1675                 // println!("Setup: si: {:?}", si);
1676                 let offset = addr;
1677                 let size = si.len as u32;
1678                 places.insert(SlotKey {
1679                     dev_id: si.dev_id,
1680                     base_off: si.base_off,
1681                 }, SlotPlace { offset, size });
1682                 // println!("  load: offset: {}, size: {}", offset, size);
1683             }
1684             addr += imgs[0].len as u32;
1685         }
1686         RamData {
1687             places,
1688             total: addr,
1689         }
1690     }
1691 
1692     /// Lookup the ram data associated with a given flash partition.  We just panic if not present,
1693     /// because all slots used should be in the map.
lookup(&self, slot: &SlotInfo) -> &SlotPlace1694     fn lookup(&self, slot: &SlotInfo) -> &SlotPlace {
1695         self.places.get(&SlotKey{dev_id: slot.dev_id, base_off: slot.base_off})
1696             .expect("RamData should contain all slots")
1697     }
1698 }
1699 
1700 /// Show the flash layout.
1701 #[allow(dead_code)]
show_flash(flash: &dyn Flash)1702 fn show_flash(flash: &dyn Flash) {
1703     println!("---- Flash configuration ----");
1704     for sector in flash.sector_iter() {
1705         println!("    {:3}: 0x{:08x}, 0x{:08x}",
1706                  sector.num, sector.base, sector.size);
1707     }
1708     println!();
1709 }
1710 
1711 #[derive(Debug)]
1712 enum ImageSize {
1713     /// Make the image the specified given size.
1714     Given(usize),
1715     /// Make the image as large as it can be for the partition/device.
1716     Largest,
1717     /// Make the image quite larger than it can be for the partition/device/
1718     Oversized,
1719 }
1720 
1721 #[cfg(not(feature = "max-align-32"))]
tralier_estimation(dev: &dyn Flash) -> usize1722 fn tralier_estimation(dev: &dyn Flash) -> usize {
1723     c::boot_trailer_sz(dev.align() as u32) as usize
1724 }
1725 
1726 #[cfg(feature = "max-align-32")]
tralier_estimation(dev: &dyn Flash) -> usize1727 fn tralier_estimation(dev: &dyn Flash) -> usize {
1728 
1729     let sector_size = dev.sector_iter().next().unwrap().size as u32;
1730 
1731     align_up(c::boot_trailer_sz(dev.align() as u32), sector_size) as usize
1732 }
1733 
image_largest_trailer(dev: &dyn Flash) -> usize1734 fn image_largest_trailer(dev: &dyn Flash) -> usize {
1735             // Using the header size we know, the trailer size, and the slot size, we can compute
1736             // the largest image possible.
1737             let trailer = if Caps::OverwriteUpgrade.present() {
1738                 // This computation is incorrect, and we need to figure out the correct size.
1739                 // c::boot_status_sz(dev.align() as u32) as usize
1740                 16 + 4 * dev.align()
1741             } else if Caps::SwapUsingMove.present() {
1742                 let sector_size = dev.sector_iter().next().unwrap().size as u32;
1743                 align_up(c::boot_trailer_sz(dev.align() as u32), sector_size) as usize
1744             } else if Caps::SwapUsingScratch.present() {
1745                 tralier_estimation(dev)
1746             } else {
1747                 panic!("The maximum image size can't be calculated.")
1748             };
1749 
1750             trailer
1751 }
1752 
1753 /// Install a "program" into the given image.  This fakes the image header, or at least all of the
1754 /// fields used by the given code.  Returns a copy of the image that was written.
install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: ImageSize, ram: &RamData, deps: &dyn Depender, img_manipulation: ImageManipulation, security_counter:Option<u32>) -> ImageData1755 fn install_image(flash: &mut SimMultiFlash, slot: &SlotInfo, len: ImageSize,
1756                  ram: &RamData,
1757                  deps: &dyn Depender, img_manipulation: ImageManipulation, security_counter:Option<u32>) -> ImageData {
1758     let offset = slot.base_off;
1759     let slot_len = slot.len;
1760     let dev_id = slot.dev_id;
1761     let dev = flash.get_mut(&dev_id).unwrap();
1762 
1763     let mut tlv: Box<dyn ManifestGen> = Box::new(make_tlv());
1764     if img_manipulation == ImageManipulation::IgnoreRamLoadFlag {
1765         tlv.set_ignore_ram_load_flag();
1766     }
1767 
1768     tlv.set_security_counter(security_counter);
1769 
1770 
1771     // Add the dependencies early to the tlv.
1772     for dep in deps.my_deps(offset, slot.index) {
1773         tlv.add_dependency(deps.other_id(), &dep);
1774     }
1775 
1776     const HDR_SIZE: usize = 32;
1777     let place = ram.lookup(&slot);
1778     let load_addr = if Caps::RamLoad.present() {
1779         match img_manipulation {
1780             ImageManipulation::WrongOffset => u32::MAX,
1781             ImageManipulation::OverlapImages(true) => RAM_LOAD_ADDR,
1782             ImageManipulation::OverlapImages(false) => place.offset - 1,
1783             _ => place.offset
1784         }
1785     } else {
1786         0
1787     };
1788 
1789     let len = match len {
1790         ImageSize::Given(size) => size,
1791         ImageSize::Largest => {
1792             let trailer = image_largest_trailer(dev);
1793             let tlv_len = tlv.estimate_size();
1794             info!("slot: 0x{:x}, HDR: 0x{:x}, trailer: 0x{:x}",
1795                 slot_len, HDR_SIZE, trailer);
1796             slot_len - HDR_SIZE - trailer - tlv_len
1797         },
1798         ImageSize::Oversized => {
1799             let trailer = image_largest_trailer(dev);
1800             let tlv_len = tlv.estimate_size();
1801             info!("slot: 0x{:x}, HDR: 0x{:x}, trailer: 0x{:x}",
1802                 slot_len, HDR_SIZE, trailer);
1803             // the overflow size is rougly estimated to work for all
1804             // configurations. It might be precise if tlv_len will be maked precise.
1805             slot_len - HDR_SIZE - trailer - tlv_len + dev.align()*4
1806         }
1807 
1808     };
1809 
1810     // Generate a boot header.  Note that the size doesn't include the header.
1811     let header = ImageHeader {
1812         magic: tlv.get_magic(),
1813         load_addr,
1814         hdr_size: HDR_SIZE as u16,
1815         protect_tlv_size: tlv.protect_size(),
1816         img_size: len as u32,
1817         flags: tlv.get_flags(),
1818         ver: deps.my_version(offset, slot.index),
1819         _pad2: 0,
1820     };
1821 
1822     let mut b_header = [0; HDR_SIZE];
1823     b_header[..32].clone_from_slice(header.as_raw());
1824     assert_eq!(b_header.len(), HDR_SIZE);
1825 
1826     tlv.add_bytes(&b_header);
1827 
1828     // The core of the image itself is just pseudorandom data.
1829     let mut b_img = vec![0; len];
1830     splat(&mut b_img, offset);
1831 
1832     // Add some information at the start of the payload to make it easier
1833     // to see what it is.  This will fail if the image itself is too small.
1834     {
1835         let mut wr = Cursor::new(&mut b_img);
1836         writeln!(&mut wr, "offset: {:#x}, dev_id: {:#x}, slot_info: {:?}",
1837                  offset, dev_id, slot).unwrap();
1838         writeln!(&mut wr, "version: {:?}", deps.my_version(offset, slot.index)).unwrap();
1839     }
1840 
1841     // TLV signatures work over plain image
1842     tlv.add_bytes(&b_img);
1843 
1844     // Generate encrypted images
1845     let flag = TlvFlags::ENCRYPTED_AES128 as u32 | TlvFlags::ENCRYPTED_AES256 as u32;
1846     let is_encrypted = (tlv.get_flags() & flag) != 0;
1847     let mut b_encimg = vec![];
1848     if is_encrypted {
1849         let flag = TlvFlags::ENCRYPTED_AES256 as u32;
1850         let aes256 = (tlv.get_flags() & flag) == flag;
1851         tlv.generate_enc_key();
1852         let enc_key = tlv.get_enc_key();
1853         let nonce = GenericArray::from_slice(&[0; 16]);
1854         b_encimg = b_img.clone();
1855         if aes256 {
1856             let key: &GenericArray<u8, U32> = GenericArray::from_slice(enc_key.as_slice());
1857             let block = Aes256::new(&key);
1858             let mut cipher = Aes256Ctr::from_block_cipher(block, &nonce);
1859             cipher.apply_keystream(&mut b_encimg);
1860         } else {
1861             let key: &GenericArray<u8, U16> = GenericArray::from_slice(enc_key.as_slice());
1862             let block = Aes128::new(&key);
1863             let mut cipher = Aes128Ctr::from_block_cipher(block, &nonce);
1864             cipher.apply_keystream(&mut b_encimg);
1865         }
1866     }
1867 
1868     // Build the TLV itself.
1869     if img_manipulation == ImageManipulation::BadSignature  {
1870         tlv.corrupt_sig();
1871     }
1872     let mut b_tlv = tlv.make_tlv();
1873 
1874     let mut buf = vec![];
1875     buf.append(&mut b_header.to_vec());
1876     buf.append(&mut b_img);
1877     buf.append(&mut b_tlv.clone());
1878 
1879     // Pad the buffer to a multiple of the flash alignment.
1880     let align = dev.align();
1881     let image_sz = buf.len();
1882     while buf.len() % align != 0 {
1883         buf.push(dev.erased_val());
1884     }
1885 
1886     let mut encbuf = vec![];
1887     if is_encrypted {
1888         encbuf.append(&mut b_header.to_vec());
1889         encbuf.append(&mut b_encimg);
1890         encbuf.append(&mut b_tlv);
1891 
1892         while encbuf.len() % align != 0 {
1893             encbuf.push(dev.erased_val());
1894         }
1895     }
1896 
1897     // Since images are always non-encrypted in the primary slot, we first write
1898     // an encrypted image, re-read to use for verification, erase + flash
1899     // un-encrypted. In the secondary slot the image is written un-encrypted,
1900     // and if encryption is requested, it follows an erase + flash encrypted.
1901     //
1902     // In the case of ram-load when encryption is enabled both slots have to
1903     // be encrypted so in the event when the image is in the primary slot
1904     // the verification will fail as the image is not encrypted.
1905     if slot.index == 0 && !Caps::RamLoad.present() {
1906         let enc_copy: Option<Vec<u8>>;
1907 
1908         if is_encrypted {
1909             dev.write(offset, &encbuf).unwrap();
1910 
1911             let mut enc = vec![0u8; encbuf.len()];
1912             dev.read(offset, &mut enc).unwrap();
1913 
1914             enc_copy = Some(enc);
1915 
1916             dev.erase(offset, slot_len).unwrap();
1917         } else {
1918             enc_copy = None;
1919         }
1920 
1921         dev.write(offset, &buf).unwrap();
1922 
1923         let mut copy = vec![0u8; buf.len()];
1924         dev.read(offset, &mut copy).unwrap();
1925 
1926         ImageData {
1927             size: image_sz,
1928             plain: copy,
1929             cipher: enc_copy,
1930         }
1931     } else {
1932 
1933         dev.write(offset, &buf).unwrap();
1934 
1935         let mut copy = vec![0u8; buf.len()];
1936         dev.read(offset, &mut copy).unwrap();
1937 
1938         let enc_copy: Option<Vec<u8>>;
1939 
1940         if is_encrypted {
1941             dev.erase(offset, slot_len).unwrap();
1942 
1943             dev.write(offset, &encbuf).unwrap();
1944 
1945             let mut enc = vec![0u8; encbuf.len()];
1946             dev.read(offset, &mut enc).unwrap();
1947 
1948             enc_copy = Some(enc);
1949         } else {
1950             enc_copy = None;
1951         }
1952 
1953         ImageData {
1954             size: image_sz,
1955             plain: copy,
1956             cipher: enc_copy,
1957         }
1958     }
1959 }
1960 
1961 /// Install no image.  This is used when no upgrade happens.
install_no_image() -> ImageData1962 fn install_no_image() -> ImageData {
1963     ImageData {
1964         size: 0,
1965         plain: vec![],
1966         cipher: None,
1967     }
1968 }
1969 
1970 /// Construct a TLV generator based on how MCUboot is currently configured.  The returned
1971 /// ManifestGen will generate the appropriate entries based on this configuration.
make_tlv() -> TlvGen1972 fn make_tlv() -> TlvGen {
1973     let aes_key_size = if Caps::Aes256.present() { 256 } else { 128 };
1974 
1975     if Caps::EncKw.present() {
1976         if Caps::RSA2048.present() {
1977             TlvGen::new_rsa_kw(aes_key_size)
1978         } else if Caps::EcdsaP256.present() {
1979             TlvGen::new_ecdsa_kw(aes_key_size)
1980         } else {
1981             TlvGen::new_enc_kw(aes_key_size)
1982         }
1983     } else if Caps::EncRsa.present() {
1984         if Caps::RSA2048.present() {
1985             TlvGen::new_sig_enc_rsa(aes_key_size)
1986         } else {
1987             TlvGen::new_enc_rsa(aes_key_size)
1988         }
1989     } else if Caps::EncEc256.present() {
1990         if Caps::EcdsaP256.present() {
1991             TlvGen::new_ecdsa_ecies_p256(aes_key_size)
1992         } else {
1993             TlvGen::new_ecies_p256(aes_key_size)
1994         }
1995     } else if Caps::EncX25519.present() {
1996         if Caps::Ed25519.present() {
1997             TlvGen::new_ed25519_ecies_x25519(aes_key_size)
1998         } else {
1999             TlvGen::new_ecies_x25519(aes_key_size)
2000         }
2001     } else {
2002         // The non-encrypted configuration.
2003         if Caps::RSA2048.present() {
2004             TlvGen::new_rsa_pss()
2005         } else if Caps::RSA3072.present() {
2006             TlvGen::new_rsa3072_pss()
2007         } else if Caps::EcdsaP256.present() || Caps::EcdsaP384.present() {
2008             TlvGen::new_ecdsa()
2009         } else if Caps::Ed25519.present() {
2010             TlvGen::new_ed25519()
2011         } else if Caps::HwRollbackProtection.present() {
2012             TlvGen::new_sec_cnt()
2013         } else {
2014             TlvGen::new_hash_only()
2015         }
2016     }
2017 }
2018 
2019 impl ImageData {
2020     /// Find the image contents for the given slot.  This assumes that slot 0
2021     /// is unencrypted, and slot 1 is encrypted.
find(&self, slot: usize) -> &Vec<u8>2022     fn find(&self, slot: usize) -> &Vec<u8> {
2023         let encrypted = Caps::EncRsa.present() || Caps::EncKw.present() ||
2024             Caps::EncEc256.present() || Caps::EncX25519.present();
2025         match (encrypted, slot) {
2026             (false, _) => &self.plain,
2027             (true, 0) => &self.plain,
2028             (true, 1) => self.cipher.as_ref().expect("Invalid image"),
2029             _ => panic!("Invalid slot requested"),
2030         }
2031     }
2032 
size(&self) -> usize2033     fn size(&self) -> usize {
2034         self.size
2035     }
2036 }
2037 
2038 /// Verify that given image is present in the flash at the given offset.
verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool2039 fn verify_image(flash: &SimMultiFlash, slot: &SlotInfo, images: &ImageData) -> bool {
2040     let image = images.find(slot.index);
2041     let buf = image.as_slice();
2042     let dev_id = slot.dev_id;
2043 
2044     let mut copy = vec![0u8; buf.len()];
2045     let offset = slot.base_off;
2046     let dev = flash.get(&dev_id).unwrap();
2047     dev.read(offset, &mut copy).unwrap();
2048 
2049     if buf != &copy[..] {
2050         for i in 0 .. buf.len() {
2051             if buf[i] != copy[i] {
2052                 info!("First failure for slot{} at {:#x} ({:#x} within) {:#x}!={:#x}",
2053                       slot.index, offset + i, i, buf[i], copy[i]);
2054                 break;
2055             }
2056         }
2057         false
2058     } else {
2059         true
2060     }
2061 }
2062 
verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo, magic: Option<u8>, image_ok: Option<u8>, copy_done: Option<u8>) -> bool2063 fn verify_trailer(flash: &SimMultiFlash, slot: &SlotInfo,
2064                   magic: Option<u8>, image_ok: Option<u8>,
2065                   copy_done: Option<u8>) -> bool {
2066     if Caps::OverwriteUpgrade.present() {
2067         return true;
2068     }
2069 
2070     let offset = slot.trailer_off + c::boot_max_align();
2071     let dev_id = slot.dev_id;
2072     let mut copy = vec![0u8; c::boot_magic_sz() + c::boot_max_align() * 3];
2073     let mut failed = false;
2074 
2075     let dev = flash.get(&dev_id).unwrap();
2076     let erased_val = dev.erased_val();
2077     dev.read(offset, &mut copy).unwrap();
2078 
2079     failed |= match magic {
2080         Some(v) => {
2081             let magic_off = (c::boot_max_align() * 3) + (c::boot_magic_sz() - MAGIC.len());
2082             if v == 1 && &copy[magic_off..] != MAGIC {
2083                 warn!("\"magic\" mismatch at {:#x}", offset);
2084                 true
2085             } else if v == 3 {
2086                 let expected = [erased_val; 16];
2087                 if copy[magic_off..] != expected {
2088                     warn!("\"magic\" mismatch at {:#x}", offset);
2089                     true
2090                 } else {
2091                     false
2092                 }
2093             } else {
2094                 false
2095             }
2096         },
2097         None => false,
2098     };
2099 
2100     failed |= match image_ok {
2101         Some(v) => {
2102             let image_ok_off = c::boot_max_align() * 2;
2103             if (v == 1 && copy[image_ok_off] != v) || (v == 3 && copy[image_ok_off] != erased_val) {
2104                 warn!("\"image_ok\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[image_ok_off]);
2105                 true
2106             } else {
2107                 false
2108             }
2109         },
2110         None => false,
2111     };
2112 
2113     failed |= match copy_done {
2114         Some(v) => {
2115             let copy_done_off = c::boot_max_align();
2116             if (v == 1 && copy[copy_done_off] != v) || (v == 3 && copy[copy_done_off] != erased_val) {
2117                 warn!("\"copy_done\" mismatch at {:#x} v={} val={:#x}", offset, v, copy[copy_done_off]);
2118                 true
2119             } else {
2120                 false
2121             }
2122         },
2123         None => false,
2124     };
2125 
2126     !failed
2127 }
2128 
2129 /// Install a partition table.  This is a simplified partition table that
2130 /// we write at the beginning of flash so make it easier for external tools
2131 /// to analyze these images.
install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc)2132 fn install_ptable(flash: &mut SimMultiFlash, areadesc: &AreaDesc) {
2133     let ids: HashSet<u8> = areadesc.iter_areas().map(|area| area.device_id).collect();
2134     for &id in &ids {
2135         // If there are any partitions in this device that start at 0, and
2136         // aren't marked as the BootLoader partition, avoid adding the
2137         // partition table.  This makes it harder to view the image, but
2138         // avoids messing up images already written.
2139         let skip_ptable = areadesc
2140             .iter_areas()
2141             .any(|area| {
2142                 area.device_id == id &&
2143                     area.off == 0 &&
2144                     area.flash_id != FlashId::BootLoader
2145             });
2146         if skip_ptable {
2147             if log_enabled!(Info) {
2148                 let special: Vec<FlashId> = areadesc.iter_areas()
2149                     .filter(|area| area.device_id == id && area.off == 0)
2150                     .map(|area| area.flash_id)
2151                     .collect();
2152                 info!("Skipping partition table: {:?}", special);
2153             }
2154             break;
2155         }
2156 
2157         let mut buf: Vec<u8> = vec![];
2158         write!(&mut buf, "mcuboot\0").unwrap();
2159 
2160         // Iterate through all of the partitions in that device, and encode
2161         // into the table.
2162         let count = areadesc.iter_areas().filter(|area| area.device_id == id).count();
2163         buf.write_u32::<LittleEndian>(count as u32).unwrap();
2164 
2165         for area in areadesc.iter_areas().filter(|area| area.device_id == id) {
2166             buf.write_u32::<LittleEndian>(area.flash_id as u32).unwrap();
2167             buf.write_u32::<LittleEndian>(area.off).unwrap();
2168             buf.write_u32::<LittleEndian>(area.size).unwrap();
2169             buf.write_u32::<LittleEndian>(0).unwrap();
2170         }
2171 
2172         let dev = flash.get_mut(&id).unwrap();
2173 
2174         // Pad to alignment.
2175         while buf.len() % dev.align() != 0 {
2176             buf.push(0);
2177         }
2178 
2179         dev.write(0, &buf).unwrap();
2180     }
2181 }
2182 
2183 /// The image header
2184 #[repr(C)]
2185 #[derive(Debug)]
2186 pub struct ImageHeader {
2187     magic: u32,
2188     load_addr: u32,
2189     hdr_size: u16,
2190     protect_tlv_size: u16,
2191     img_size: u32,
2192     flags: u32,
2193     ver: ImageVersion,
2194     _pad2: u32,
2195 }
2196 
2197 impl AsRaw for ImageHeader {}
2198 
2199 #[repr(C)]
2200 #[derive(Clone, Debug)]
2201 pub struct ImageVersion {
2202     pub major: u8,
2203     pub minor: u8,
2204     pub revision: u16,
2205     pub build_num: u32,
2206 }
2207 
2208 #[derive(Clone, Debug)]
2209 pub struct SlotInfo {
2210     pub base_off: usize,
2211     pub trailer_off: usize,
2212     pub len: usize,
2213     // Which slot within this device.
2214     pub index: usize,
2215     pub dev_id: u8,
2216 }
2217 
2218 #[cfg(not(feature = "max-align-32"))]
2219 const MAGIC: &[u8] = &[0x77, 0xc2, 0x95, 0xf3,
2220                        0x60, 0xd2, 0xef, 0x7f,
2221                        0x35, 0x52, 0x50, 0x0f,
2222                        0x2c, 0xb6, 0x79, 0x80];
2223 
2224 #[cfg(feature = "max-align-32")]
2225 const MAGIC: &[u8] = &[0x20, 0x00, 0x2d, 0xe1,
2226                        0x5d, 0x29, 0x41, 0x0b,
2227                        0x8d, 0x77, 0x67, 0x9c,
2228                        0x11, 0x0f, 0x1f, 0x8a];
2229 
2230 // Replicates defines found in bootutil.h
2231 const BOOT_MAGIC_GOOD: Option<u8> = Some(1);
2232 const BOOT_MAGIC_UNSET: Option<u8> = Some(3);
2233 
2234 const BOOT_FLAG_SET: Option<u8> = Some(1);
2235 const BOOT_FLAG_UNSET: Option<u8> = Some(3);
2236 
2237 /// Write out the magic so that the loader tries doing an upgrade.
mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo)2238 pub fn mark_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
2239     let dev = flash.get_mut(&slot.dev_id).unwrap();
2240     let align = dev.align();
2241     let offset = slot.trailer_off + c::boot_max_align() * 4;
2242     if offset % align != 0 || MAGIC.len() % align != 0 {
2243         // The write size is larger than the magic value.  Fill a buffer
2244         // with the erased value, put the MAGIC in it, and write it in its
2245         // entirety.
2246         let mut buf = vec![dev.erased_val(); c::boot_max_align()];
2247         let magic_off = (offset % align) + (c::boot_magic_sz() - MAGIC.len());
2248         buf[magic_off..].copy_from_slice(MAGIC);
2249         dev.write(offset - (offset % align), &buf).unwrap();
2250     } else {
2251         dev.write(offset, MAGIC).unwrap();
2252     }
2253 }
2254 
2255 /// Writes the image_ok flag which, guess what, tells the bootloader
2256 /// the this image is ok (not a test, and no revert is to be performed).
mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo)2257 fn mark_permanent_upgrade(flash: &mut SimMultiFlash, slot: &SlotInfo) {
2258     // Overwrite mode always is permanent, and only the magic is used in
2259     // the trailer.  To avoid problems with large write sizes, don't try to
2260     // set anything in this case.
2261     if Caps::OverwriteUpgrade.present() {
2262         return;
2263     }
2264 
2265     let dev = flash.get_mut(&slot.dev_id).unwrap();
2266     let align = dev.align();
2267     let mut ok = vec![dev.erased_val(); align];
2268     ok[0] = 1u8;
2269     let off = slot.trailer_off + c::boot_max_align() * 3;
2270     dev.write(off, &ok).unwrap();
2271 }
2272 
2273 // Drop some pseudo-random gibberish onto the data.
splat(data: &mut [u8], seed: usize)2274 fn splat(data: &mut [u8], seed: usize) {
2275     let mut seed_block = [0u8; 32];
2276     let mut buf = Cursor::new(&mut seed_block[..]);
2277     buf.write_u32::<LittleEndian>(0x135782ea).unwrap();
2278     buf.write_u32::<LittleEndian>(0x92184728).unwrap();
2279     buf.write_u32::<LittleEndian>(data.len() as u32).unwrap();
2280     buf.write_u32::<LittleEndian>(seed as u32).unwrap();
2281     let mut rng: SmallRng = SeedableRng::from_seed(seed_block);
2282     rng.fill_bytes(data);
2283 }
2284 
2285 /// Return a read-only view into the raw bytes of this object
2286 trait AsRaw : Sized {
as_raw(&self) -> &[u8]2287     fn as_raw(&self) -> &[u8] {
2288         unsafe { slice::from_raw_parts(self as *const _ as *const u8,
2289                                        mem::size_of::<Self>()) }
2290     }
2291 }
2292 
2293 /// Determine whether it makes sense to test this configuration with a maximally-sized image.
2294 /// Returns an ImageSize representing the best size to test, possibly just with the given size.
maximal(size: usize) -> ImageSize2295 fn maximal(size: usize) -> ImageSize {
2296     if Caps::OverwriteUpgrade.present() ||
2297         Caps::SwapUsingMove.present()
2298     {
2299         ImageSize::Given(size)
2300     } else {
2301         ImageSize::Largest
2302     }
2303 }
2304 
show_sizes()2305 pub fn show_sizes() {
2306     // This isn't panic safe.
2307     for min in &[1, 2, 4, 8] {
2308         let msize = c::boot_trailer_sz(*min);
2309         println!("{:2}: {} (0x{:x})", min, msize, msize);
2310     }
2311 }
2312 
2313 #[cfg(not(feature = "max-align-32"))]
test_alignments() -> &'static [usize]2314 fn test_alignments() -> &'static [usize] {
2315     &[1, 2, 4, 8]
2316 }
2317 
2318 #[cfg(feature = "max-align-32")]
test_alignments() -> &'static [usize]2319 fn test_alignments() -> &'static [usize] {
2320     &[32]
2321 }
2322 
2323 /// For testing, some of the tests are quite slow. This will query for an
2324 /// environment variable `MCUBOOT_SKIP_SLOW_TESTS`, which can be set to avoid
2325 /// running these tests.
skip_slow_test() -> bool2326 fn skip_slow_test() -> bool {
2327     if let Ok(_) = std::env::var("MCUBOOT_SKIP_SLOW_TESTS") {
2328         true
2329     } else {
2330         false
2331     }
2332 }
2333