-
Notifications
You must be signed in to change notification settings - Fork 681
/
image.rs
2332 lines (1997 loc) · 80 KB
/
image.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2019-2021 Linaro LTD
// Copyright (c) 2019-2020 JUUL Labs
// Copyright (c) 2019-2023 Arm Limited
//
// SPDX-License-Identifier: Apache-2.0
use byteorder::{
LittleEndian, WriteBytesExt,
};
use log::{
Level::Info,
error,
info,
log_enabled,
warn,
};
use rand::{
Rng, RngCore, SeedableRng,
rngs::SmallRng,
};
use std::{
collections::{BTreeMap, HashSet}, io::{Cursor, Write}, mem, rc::Rc, slice
};
use aes::{
Aes128,
Aes128Ctr,
Aes256,
Aes256Ctr,
NewBlockCipher,
};
use cipher::{
FromBlockCipher,
generic_array::GenericArray,
StreamCipher,
};
use simflash::{Flash, SimFlash, SimMultiFlash};
use mcuboot_sys::{c, AreaDesc, FlashId, RamBlock};
use crate::{
ALL_DEVICES,
DeviceName,
};
use crate::caps::Caps;
use crate::depends::{
BoringDep,
Depender,
DepTest,
DepType,
NO_DEPS,
PairDep,
UpgradeInfo,
};
use crate::tlv::{ManifestGen, TlvGen, TlvFlags};
use crate::utils::align_up;
use typenum::{U32, U16};
/// For testing, use a non-zero offset for the ram-load, to make sure the offset is getting used
/// properly, but the value is not really that important.
const RAM_LOAD_ADDR: u32 = 1024;
/// A builder for Images. This describes a single run of the simulator,
/// capturing the configuration of a particular set of devices, including
/// the flash simulator(s) and the information about the slots.
#[derive(Clone)]
pub struct ImagesBuilder {
flash: SimMultiFlash,
areadesc: Rc<AreaDesc>,
slots: Vec<[SlotInfo; 2]>,
ram: RamData,
}
/// Images represents the state of a simulation for a given set of images.
/// The flash holds the state of the simulated flash, whereas primaries
/// and upgrades hold the expected contents of these images.
pub struct Images {
flash: SimMultiFlash,
areadesc: Rc<AreaDesc>,
images: Vec<OneImage>,
total_count: Option<i32>,
ram: RamData,
}
/// When doing multi-image, there is an instance of this information for
/// each of the images. Single image there will be one of these.
struct OneImage {
slots: [SlotInfo; 2],
primaries: ImageData,
upgrades: ImageData,
}
/// The Rust-side representation of an image. For unencrypted images, this
/// is just the unencrypted payload. For encrypted images, we store both
/// the encrypted and the plaintext.
struct ImageData {
size: usize,
plain: Vec<u8>,
cipher: Option<Vec<u8>>,
}
/// For the RamLoad test cases, we need a contiguous area of RAM to load these images into. For
/// multi-image builds, these may not correspond with the offsets. This has to be computed early,
/// before images are built, because each image contains the offset where the image is to be loaded
/// in the header, which is contained within the signature.
#[derive(Clone, Debug)]
struct RamData {
places: BTreeMap<SlotKey, SlotPlace>,
total: u32,
}
/// Every slot is indexed by this key.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
struct SlotKey {
dev_id: u8,
base_off: usize,
}
#[derive(Clone, Debug)]
struct SlotPlace {
offset: u32,
size: u32,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ImageManipulation {
None,
BadSignature,
WrongOffset,
IgnoreRamLoadFlag,
/// True to use same address,
/// false to overlap by 1 byte
OverlapImages(bool),
CorruptHigherVersionImage,
}
impl ImagesBuilder {
/// Construct a new image builder for the given device. Returns
/// Some(builder) if is possible to test this configuration, or None if
/// not possible (for example, if there aren't enough image slots).
pub fn new(device: DeviceName, align: usize, erased_val: u8) -> Result<Self, String> {
let (flash, areadesc, unsupported_caps) = Self::make_device(device, align, erased_val);
for cap in unsupported_caps {
if cap.present() {
return Err(format!("unsupported {:?}", cap));
}
}
let num_images = Caps::get_num_images();
let mut slots = Vec::with_capacity(num_images);
for image in 0..num_images {
// This mapping must match that defined in
// `boot/zephyr/include/sysflash/sysflash.h`.
let id0 = match image {
0 => FlashId::Image0,
1 => FlashId::Image2,
_ => panic!("More than 2 images not supported"),
};
let (primary_base, primary_len, primary_dev_id) = match areadesc.find(id0) {
Some(info) => info,
None => return Err("insufficient partitions".to_string()),
};
let id1 = match image {
0 => FlashId::Image1,
1 => FlashId::Image3,
_ => panic!("More than 2 images not supported"),
};
let (secondary_base, secondary_len, secondary_dev_id) = match areadesc.find(id1) {
Some(info) => info,
None => return Err("insufficient partitions".to_string()),
};
let offset_from_end = c::boot_magic_sz() + c::boot_max_align() * 4;
// Construct a primary image.
let primary = SlotInfo {
base_off: primary_base as usize,
trailer_off: primary_base + primary_len - offset_from_end,
len: primary_len as usize,
dev_id: primary_dev_id,
index: 0,
};
// And an upgrade image.
let secondary = SlotInfo {
base_off: secondary_base as usize,
trailer_off: secondary_base + secondary_len - offset_from_end,
len: secondary_len as usize,
dev_id: secondary_dev_id,
index: 1,
};
slots.push([primary, secondary]);
}
let ram = RamData::new(&slots);
Ok(ImagesBuilder {
flash,
areadesc,
slots,
ram,
})
}
pub fn each_device<F>(f: F)
where F: Fn(Self)
{
for &dev in ALL_DEVICES {
for &align in test_alignments() {
for &erased_val in &[0, 0xff] {
match Self::new(dev, align, erased_val) {
Ok(run) => f(run),
Err(msg) => warn!("Skipping {}: {}", dev, msg),
}
}
}
}
}
/// Construct an `Images` that doesn't expect an upgrade to happen.
pub fn make_no_upgrade_image(self, deps: &DepTest, img_manipulation: ImageManipulation) -> Images {
let num_images = self.num_images();
let mut flash = self.flash;
let ram = self.ram.clone(); // TODO: Avoid this clone.
let mut higher_version_corrupted = false;
let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
let dep: Box<dyn Depender> = if num_images > 1 {
Box::new(PairDep::new(num_images, image_num, deps))
} else {
Box::new(BoringDep::new(image_num, deps))
};
let (primaries,upgrades) = if img_manipulation == ImageManipulation::CorruptHigherVersionImage && !higher_version_corrupted {
higher_version_corrupted = true;
let prim = install_image(&mut flash, &slots[0],
maximal(42784), &ram, &*dep, ImageManipulation::None, Some(0));
let upgr = match deps.depends[image_num] {
DepType::NoUpgrade => install_no_image(),
_ => install_image(&mut flash, &slots[1],
maximal(46928), &ram, &*dep, ImageManipulation::BadSignature, Some(0))
};
(prim, upgr)
} else {
let prim = install_image(&mut flash, &slots[0],
maximal(42784), &ram, &*dep, img_manipulation, Some(0));
let upgr = match deps.depends[image_num] {
DepType::NoUpgrade => install_no_image(),
_ => install_image(&mut flash, &slots[1],
maximal(46928), &ram, &*dep, img_manipulation, Some(0))
};
(prim, upgr)
};
OneImage {
slots,
primaries,
upgrades,
}}).collect();
install_ptable(&mut flash, &self.areadesc);
Images {
flash,
areadesc: self.areadesc,
images,
total_count: None,
ram: self.ram,
}
}
pub fn make_image(self, deps: &DepTest, permanent: bool) -> Images {
let mut images = self.make_no_upgrade_image(deps, ImageManipulation::None);
for image in &images.images {
mark_upgrade(&mut images.flash, &image.slots[1]);
}
// The count is meaningless if no flash operations are performed.
if !Caps::modifies_flash() {
return images;
}
// upgrades without fails, counts number of flash operations
let total_count = match images.run_basic_upgrade(permanent) {
Some(v) => v,
None =>
if deps.upgrades.iter().any(|u| *u == UpgradeInfo::Held) {
0
} else {
panic!("Unable to perform basic upgrade");
}
};
images.total_count = Some(total_count);
images
}
pub fn make_bad_secondary_slot_image(self) -> Images {
let mut bad_flash = self.flash;
let ram = self.ram.clone(); // TODO: Avoid this clone.
let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
let dep = BoringDep::new(image_num, &NO_DEPS);
let primaries = install_image(&mut bad_flash, &slots[0],
maximal(32784), &ram, &dep, ImageManipulation::None, Some(0));
let upgrades = install_image(&mut bad_flash, &slots[1],
maximal(41928), &ram, &dep, ImageManipulation::BadSignature, Some(0));
OneImage {
slots,
primaries,
upgrades,
}}).collect();
Images {
flash: bad_flash,
areadesc: self.areadesc,
images,
total_count: None,
ram: self.ram,
}
}
pub fn make_oversized_secondary_slot_image(self) -> Images {
let mut bad_flash = self.flash;
let ram = self.ram.clone(); // TODO: Avoid this clone.
let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
let dep = BoringDep::new(image_num, &NO_DEPS);
let primaries = install_image(&mut bad_flash, &slots[0],
maximal(32784), &ram, &dep, ImageManipulation::None, Some(0));
let upgrades = install_image(&mut bad_flash, &slots[1],
ImageSize::Oversized, &ram, &dep, ImageManipulation::None, Some(0));
OneImage {
slots,
primaries,
upgrades,
}}).collect();
Images {
flash: bad_flash,
areadesc: self.areadesc,
images,
total_count: None,
ram: self.ram,
}
}
pub fn make_erased_secondary_image(self) -> Images {
let mut flash = self.flash;
let ram = self.ram.clone(); // TODO: Avoid this clone.
let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
let dep = BoringDep::new(image_num, &NO_DEPS);
let primaries = install_image(&mut flash, &slots[0],
maximal(32784), &ram, &dep,ImageManipulation::None, Some(0));
let upgrades = install_no_image();
OneImage {
slots,
primaries,
upgrades,
}}).collect();
Images {
flash,
areadesc: self.areadesc,
images,
total_count: None,
ram: self.ram,
}
}
pub fn make_bootstrap_image(self) -> Images {
let mut flash = self.flash;
let ram = self.ram.clone(); // TODO: Avoid this clone.
let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
let dep = BoringDep::new(image_num, &NO_DEPS);
let primaries = install_no_image();
let upgrades = install_image(&mut flash, &slots[1],
maximal(32784), &ram, &dep, ImageManipulation::None, Some(0));
OneImage {
slots,
primaries,
upgrades,
}}).collect();
Images {
flash,
areadesc: self.areadesc,
images,
total_count: None,
ram: self.ram,
}
}
pub fn make_oversized_bootstrap_image(self) -> Images {
let mut flash = self.flash;
let ram = self.ram.clone(); // TODO: Avoid this clone.
let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
let dep = BoringDep::new(image_num, &NO_DEPS);
let primaries = install_no_image();
let upgrades = install_image(&mut flash, &slots[1],
ImageSize::Oversized, &ram, &dep, ImageManipulation::None, Some(0));
OneImage {
slots,
primaries,
upgrades,
}}).collect();
Images {
flash,
areadesc: self.areadesc,
images,
total_count: None,
ram: self.ram,
}
}
/// If security_cnt is None then do not add a security counter TLV, otherwise add the specified value.
pub fn make_image_with_security_counter(self, security_cnt: Option<u32>) -> Images {
let mut flash = self.flash;
let ram = self.ram.clone(); // TODO: Avoid this clone.
let images = self.slots.into_iter().enumerate().map(|(image_num, slots)| {
let dep = BoringDep::new(image_num, &NO_DEPS);
let primaries = install_image(&mut flash, &slots[0],
maximal(32784), &ram, &dep, ImageManipulation::None, security_cnt);
let upgrades = install_image(&mut flash, &slots[1],
maximal(41928), &ram, &dep, ImageManipulation::None, security_cnt.map(|v| v + 1));
OneImage {
slots,
primaries,
upgrades,
}}).collect();
Images {
flash,
areadesc: self.areadesc,
images,
total_count: None,
ram: self.ram,
}
}
/// Build the Flash and area descriptor for a given device.
pub fn make_device(device: DeviceName, align: usize, erased_val: u8) -> (SimMultiFlash, Rc<AreaDesc>, &'static [Caps]) {
match device {
DeviceName::Stm32f4 => {
// STM style flash. Large sectors, with a large scratch area.
// The flash layout as described is not present in any real STM32F4 device, but it
// serves to exercise support for sectors of varying sizes inside a single slot,
// as long as they are compatible in both slots and all fit in the scratch.
let dev = SimFlash::new(vec![16 * 1024, 16 * 1024, 16 * 1024, 16 * 1024, 64 * 1024,
32 * 1024, 32 * 1024, 64 * 1024,
32 * 1024, 32 * 1024, 64 * 1024,
128 * 1024],
align as usize, erased_val);
let dev_id = 0;
let mut areadesc = AreaDesc::new();
areadesc.add_flash_sectors(dev_id, &dev);
areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
areadesc.add_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
let mut flash = SimMultiFlash::new();
flash.insert(dev_id, dev);
(flash, Rc::new(areadesc), &[Caps::SwapUsingMove])
}
DeviceName::K64f => {
// NXP style flash. Small sectors, one small sector for scratch.
let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
let dev_id = 0;
let mut areadesc = AreaDesc::new();
areadesc.add_flash_sectors(dev_id, &dev);
areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
let mut flash = SimMultiFlash::new();
flash.insert(dev_id, dev);
(flash, Rc::new(areadesc), &[])
}
DeviceName::K64fBig => {
// Simulating an STM style flash on top of an NXP style flash. Underlying flash device
// uses small sectors, but we tell the bootloader they are large.
let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
let dev_id = 0;
let mut areadesc = AreaDesc::new();
areadesc.add_flash_sectors(dev_id, &dev);
areadesc.add_simple_image(0x020000, 0x020000, FlashId::Image0, dev_id);
areadesc.add_simple_image(0x040000, 0x020000, FlashId::Image1, dev_id);
areadesc.add_simple_image(0x060000, 0x020000, FlashId::ImageScratch, dev_id);
let mut flash = SimMultiFlash::new();
flash.insert(dev_id, dev);
(flash, Rc::new(areadesc), &[Caps::SwapUsingMove])
}
DeviceName::Nrf52840 => {
// Simulating the flash on the nrf52840 with partitions set up so that the scratch size
// does not divide into the image size.
let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
let dev_id = 0;
let mut areadesc = AreaDesc::new();
areadesc.add_flash_sectors(dev_id, &dev);
areadesc.add_image(0x008000, 0x034000, FlashId::Image0, dev_id);
areadesc.add_image(0x03c000, 0x034000, FlashId::Image1, dev_id);
areadesc.add_image(0x070000, 0x00d000, FlashId::ImageScratch, dev_id);
let mut flash = SimMultiFlash::new();
flash.insert(dev_id, dev);
(flash, Rc::new(areadesc), &[])
}
DeviceName::Nrf52840UnequalSlots => {
let dev = SimFlash::new(vec![4096; 128], align as usize, erased_val);
let dev_id = 0;
let mut areadesc = AreaDesc::new();
areadesc.add_flash_sectors(dev_id, &dev);
areadesc.add_image(0x008000, 0x03c000, FlashId::Image0, dev_id);
areadesc.add_image(0x044000, 0x03b000, FlashId::Image1, dev_id);
let mut flash = SimMultiFlash::new();
flash.insert(dev_id, dev);
(flash, Rc::new(areadesc), &[Caps::SwapUsingScratch, Caps::OverwriteUpgrade])
}
DeviceName::Nrf52840SpiFlash => {
// Simulate nrf52840 with external SPI flash. The external SPI flash
// has a larger sector size so for now store scratch on that flash.
let dev0 = SimFlash::new(vec![4096; 128], align as usize, erased_val);
let dev1 = SimFlash::new(vec![8192; 64], align as usize, erased_val);
let mut areadesc = AreaDesc::new();
areadesc.add_flash_sectors(0, &dev0);
areadesc.add_flash_sectors(1, &dev1);
areadesc.add_image(0x008000, 0x068000, FlashId::Image0, 0);
areadesc.add_image(0x000000, 0x068000, FlashId::Image1, 1);
areadesc.add_image(0x068000, 0x018000, FlashId::ImageScratch, 1);
let mut flash = SimMultiFlash::new();
flash.insert(0, dev0);
flash.insert(1, dev1);
(flash, Rc::new(areadesc), &[Caps::SwapUsingMove])
}
DeviceName::K64fMulti => {
// NXP style flash, but larger, to support multiple images.
let dev = SimFlash::new(vec![4096; 256], align as usize, erased_val);
let dev_id = 0;
let mut areadesc = AreaDesc::new();
areadesc.add_flash_sectors(dev_id, &dev);
areadesc.add_image(0x020000, 0x020000, FlashId::Image0, dev_id);
areadesc.add_image(0x040000, 0x020000, FlashId::Image1, dev_id);
areadesc.add_image(0x060000, 0x001000, FlashId::ImageScratch, dev_id);
areadesc.add_image(0x080000, 0x020000, FlashId::Image2, dev_id);
areadesc.add_image(0x0a0000, 0x020000, FlashId::Image3, dev_id);
let mut flash = SimMultiFlash::new();
flash.insert(dev_id, dev);
(flash, Rc::new(areadesc), &[])
}
}
}
pub fn num_images(&self) -> usize {
self.slots.len()
}
}
impl Images {
/// A simple upgrade without forced failures.
///
/// Returns the number of flash operations which can later be used to
/// inject failures at chosen steps. Returns None if it was unable to
/// count the operations in a basic upgrade.
pub fn run_basic_upgrade(&self, permanent: bool) -> Option<i32> {
let (flash, total_count) = self.try_upgrade(None, permanent);
info!("Total flash operation count={}", total_count);
if !self.verify_images(&flash, 0, 1) {
warn!("Image mismatch after first boot");
None
} else {
Some(total_count)
}
}
pub fn run_bootstrap(&self) -> bool {
let mut flash = self.flash.clone();
let mut fails = 0;
if Caps::Bootstrap.present() {
info!("Try bootstraping image in the primary");
if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
warn!("Failed first boot");
fails += 1;
}
if !self.verify_images(&flash, 0, 1) {
warn!("Image in the first slot was not bootstrapped");
fails += 1;
}
if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
BOOT_FLAG_SET, BOOT_FLAG_SET) {
warn!("Mismatched trailer for the primary slot");
fails += 1;
}
}
if fails > 0 {
error!("Expected trailer on secondary slot to be erased");
}
fails > 0
}
pub fn run_oversized_bootstrap(&self) -> bool {
let mut flash = self.flash.clone();
let mut fails = 0;
if Caps::Bootstrap.present() {
info!("Try bootstraping image in the primary");
let boot_result = c::boot_go(&mut flash, &self.areadesc, None, None, false).interrupted();
if boot_result {
warn!("Failed first boot");
fails += 1;
}
if self.verify_images(&flash, 0, 1) {
warn!("Image in the first slot was not bootstrapped");
fails += 1;
}
if self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
BOOT_FLAG_SET, BOOT_FLAG_SET) {
warn!("Mismatched trailer for the primary slot");
fails += 1;
}
}
if fails > 0 {
error!("Expected trailer on secondary slot to be erased");
}
fails > 0
}
/// Test a simple upgrade, with dependencies given, and verify that the
/// image does as is described in the test.
pub fn run_check_deps(&self, deps: &DepTest) -> bool {
if !Caps::modifies_flash() {
return false;
}
let (flash, _) = self.try_upgrade(None, true);
self.verify_dep_images(&flash, deps)
}
fn is_swap_upgrade(&self) -> bool {
Caps::SwapUsingScratch.present() || Caps::SwapUsingMove.present()
}
pub fn run_basic_revert(&self) -> bool {
if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
return false;
}
let mut fails = 0;
// FIXME: this test would also pass if no swap is ever performed???
if self.is_swap_upgrade() {
for count in 2 .. 5 {
info!("Try revert: {}", count);
let flash = self.try_revert(count);
if !self.verify_images(&flash, 0, 0) {
error!("Revert failure on count {}", count);
fails += 1;
}
}
}
fails > 0
}
pub fn run_perm_with_fails(&self) -> bool {
if !Caps::modifies_flash() {
return false;
}
let mut fails = 0;
let total_flash_ops = self.total_count.unwrap();
if skip_slow_test() {
return false;
}
// Let's try an image halfway through.
for i in 1 .. total_flash_ops {
info!("Try interruption at {}", i);
let (flash, count) = self.try_upgrade(Some(i), true);
info!("Second boot, count={}", count);
if !self.verify_images(&flash, 0, 1) {
warn!("FAIL at step {} of {}", i, total_flash_ops);
fails += 1;
}
if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
BOOT_FLAG_SET, BOOT_FLAG_SET) {
warn!("Mismatched trailer for the primary slot");
fails += 1;
}
if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
warn!("Mismatched trailer for the secondary slot");
fails += 1;
}
if self.is_swap_upgrade() && !self.verify_images(&flash, 1, 0) {
warn!("Secondary slot FAIL at step {} of {}",
i, total_flash_ops);
fails += 1;
}
}
if fails > 0 {
error!("{} out of {} failed {:.2}%", fails, total_flash_ops,
fails as f32 * 100.0 / total_flash_ops as f32);
}
fails > 0
}
pub fn run_perm_with_random_fails(&self, total_fails: usize) -> bool {
if !Caps::modifies_flash() {
return false;
}
let mut fails = 0;
let total_flash_ops = self.total_count.unwrap();
let (flash, total_counts) = self.try_random_fails(total_flash_ops, total_fails);
info!("Random interruptions at reset points={:?}", total_counts);
let primary_slot_ok = self.verify_images(&flash, 0, 1);
let secondary_slot_ok = if self.is_swap_upgrade() {
// TODO: This result is ignored.
self.verify_images(&flash, 1, 0)
} else {
true
};
if !primary_slot_ok || !secondary_slot_ok {
error!("Image mismatch after random interrupts: primary slot={} \
secondary slot={}",
if primary_slot_ok { "ok" } else { "fail" },
if secondary_slot_ok { "ok" } else { "fail" });
fails += 1;
}
if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
BOOT_FLAG_SET, BOOT_FLAG_SET) {
error!("Mismatched trailer for the primary slot");
fails += 1;
}
if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
error!("Mismatched trailer for the secondary slot");
fails += 1;
}
if fails > 0 {
error!("Error testing perm upgrade with {} fails", total_fails);
}
fails > 0
}
pub fn run_revert_with_fails(&self) -> bool {
if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
return false;
}
let mut fails = 0;
if skip_slow_test() {
return false;
}
if self.is_swap_upgrade() {
for i in 1 .. self.total_count.unwrap() {
info!("Try interruption at {}", i);
if self.try_revert_with_fail_at(i) {
error!("Revert failed at interruption {}", i);
fails += 1;
}
}
}
fails > 0
}
pub fn run_norevert(&self) -> bool {
if Caps::OverwriteUpgrade.present() || !Caps::modifies_flash() {
return false;
}
let mut flash = self.flash.clone();
let mut fails = 0;
info!("Try norevert");
// First do a normal upgrade...
if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
warn!("Failed first boot");
fails += 1;
}
//FIXME: copy_done is written by boot_go, is it ok if no copy
// was ever done?
if !self.verify_images(&flash, 0, 1) {
warn!("Primary slot image verification FAIL");
fails += 1;
}
if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
BOOT_FLAG_UNSET, BOOT_FLAG_SET) {
warn!("Mismatched trailer for the primary slot");
fails += 1;
}
if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
warn!("Mismatched trailer for the secondary slot");
fails += 1;
}
// Marks image in the primary slot as permanent,
// no revert should happen...
self.mark_permanent_upgrades(&mut flash, 0);
if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
BOOT_FLAG_SET, BOOT_FLAG_SET) {
warn!("Mismatched trailer for the primary slot");
fails += 1;
}
if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
warn!("Failed second boot");
fails += 1;
}
if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
BOOT_FLAG_SET, BOOT_FLAG_SET) {
warn!("Mismatched trailer for the primary slot");
fails += 1;
}
if !self.verify_images(&flash, 0, 1) {
warn!("Failed image verification");
fails += 1;
}
if fails > 0 {
error!("Error running upgrade without revert");
}
fails > 0
}
// Test taht too big upgrade image will be rejected
pub fn run_oversizefail_upgrade(&self) -> bool {
let mut flash = self.flash.clone();
let mut fails = 0;
info!("Try upgrade image with to big size");
// Only perform this test if an upgrade is expected to happen.
if !Caps::modifies_flash() {
info!("Skipping upgrade image with bad signature");
return false;
}
self.mark_upgrades(&mut flash, 0);
self.mark_permanent_upgrades(&mut flash, 0);
self.mark_upgrades(&mut flash, 1);
if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
warn!("1. Mismatched trailer for the primary slot");
fails += 1;
}
// Run the bootloader...
if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
warn!("Failed first boot");
fails += 1;
}
// State should not have changed
if !self.verify_images(&flash, 0, 0) {
warn!("Failed image verification");
fails += 1;
}
if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
BOOT_FLAG_SET, BOOT_FLAG_UNSET) {
warn!("2. Mismatched trailer for the primary slot");
fails += 1;
}
if fails > 0 {
error!("Expected an upgrade failure when image has to big size");
}
fails > 0
}
// Test that an upgrade is rejected. Assumes that the image was build
// such that the upgrade is instead a downgrade.
pub fn run_nodowngrade(&self) -> bool {
if !Caps::DowngradePrevention.present() {
return false;
}
let mut flash = self.flash.clone();
let mut fails = 0;
info!("Try no downgrade");
// First, do a normal upgrade.
if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
warn!("Failed first boot");
fails += 1;
}
if !self.verify_images(&flash, 0, 0) {
warn!("Failed verification after downgrade rejection");
fails += 1;
}
if fails > 0 {
error!("Error testing downgrade rejection");
}
fails > 0
}
// Tests a new image written to the primary slot that already has magic and
// image_ok set while there is no image on the secondary slot, so no revert
// should ever happen...
pub fn run_norevert_newimage(&self) -> bool {
if !Caps::modifies_flash() {
info!("Skipping run_norevert_newimage, as configuration doesn't modify flash");
return false;
}
let mut flash = self.flash.clone();
let mut fails = 0;
info!("Try non-revert on imgtool generated image");
self.mark_upgrades(&mut flash, 0);
// This simulates writing an image created by imgtool to
// the primary slot
if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
warn!("Mismatched trailer for the primary slot");
fails += 1;
}
// Run the bootloader...
if !c::boot_go(&mut flash, &self.areadesc, None, None, false).success() {
warn!("Failed first boot");
fails += 1;
}
// State should not have changed
if !self.verify_images(&flash, 0, 0) {
warn!("Failed image verification");
fails += 1;
}
if !self.verify_trailers(&flash, 0, BOOT_MAGIC_GOOD,
BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
warn!("Mismatched trailer for the primary slot");
fails += 1;
}
if !self.verify_trailers(&flash, 1, BOOT_MAGIC_UNSET,
BOOT_FLAG_UNSET, BOOT_FLAG_UNSET) {
warn!("Mismatched trailer for the secondary slot");
fails += 1;
}
if fails > 0 {
error!("Expected a non revert with new image");
}
fails > 0
}
// Tests a new image written to the primary slot that already has magic and
// image_ok set while there is no image on the secondary slot, so no revert
// should ever happen...
pub fn run_signfail_upgrade(&self) -> bool {
let mut flash = self.flash.clone();
let mut fails = 0;
info!("Try upgrade image with bad signature");