forked from oxidecomputer/amd-apcb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapcb.rs
1472 lines (1396 loc) · 51.7 KB
/
apcb.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use crate::types::{ApcbContext, Error, FileSystemError, PtrMut, Result};
use crate::entry::EntryItemBody;
use crate::group::{GroupItem, GroupMutItem};
use crate::ondisk::GroupId;
use crate::ondisk::ENTRY_ALIGNMENT;
use crate::ondisk::ENTRY_HEADER;
use crate::ondisk::GROUP_HEADER;
use crate::ondisk::TOKEN_ENTRY;
use crate::ondisk::V2_HEADER;
use crate::ondisk::V3_HEADER_EXT;
use crate::ondisk::{
take_body_from_collection, take_body_from_collection_mut,
take_header_from_collection, take_header_from_collection_mut,
HeaderWithTail, ParameterAttributes, SequenceElementAsBytes,
};
pub use crate::ondisk::{
BoardInstances, ContextType, EntryCompatible, EntryId, Parameter,
PriorityLevels,
};
use crate::token_accessors::{Tokens, TokensMut};
use core::convert::TryInto;
use core::default::Default;
use core::mem::size_of;
use num_traits::FromPrimitive;
use num_traits::ToPrimitive;
use pre::pre;
use static_assertions::const_assert;
use zerocopy::AsBytes;
use zerocopy::LayoutVerified;
// The following imports are only used for std enviroments and serde.
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "serde")]
use crate::entry::{EntryItem, SerdeEntryItem};
#[cfg(feature = "serde")]
use crate::group::SerdeGroupItem;
#[cfg(feature = "serde")]
use serde::de::{Deserialize, Deserializer};
#[cfg(feature = "serde")]
use serde::ser::{Serialize, SerializeStruct, Serializer};
#[cfg(feature = "serde")]
use std::borrow::Cow;
#[derive(Clone)]
pub struct ApcbIoOptions {
pub check_checksum: bool,
pub check_signature_ending: bool,
pub context: ApcbContext,
}
impl Default for ApcbIoOptions {
fn default() -> Self {
Self {
check_checksum: true,
check_signature_ending: true,
context: ApcbContext::default(),
}
}
}
impl ApcbIoOptions {
pub fn builder() -> Self {
Self::default()
}
pub fn check_checksum(&self) -> bool {
self.check_checksum
}
pub fn check_signature_ending(&self) -> bool {
self.check_signature_ending
}
pub fn context(&self) -> ApcbContext {
self.context
}
pub fn with_check_checksum(&mut self, value: bool) -> &mut Self {
self.check_checksum = value;
self
}
pub fn with_check_signature_ending(&mut self, value: bool) -> &mut Self {
self.check_signature_ending = value;
self
}
pub fn with_context(&mut self, value: ApcbContext) -> &mut Self {
self.context = value;
self
}
pub fn build(&self) -> Self {
self.clone()
}
}
#[cfg_attr(feature = "std", derive(Clone))]
pub struct Apcb<'a> {
context: ApcbContext,
used_size: usize,
pub backing_store: PtrMut<'a, [u8]>,
}
#[cfg(feature = "serde")]
#[cfg_attr(feature = "serde", derive(Default, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename = "Apcb"))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct SerdeApcb {
/// This field is out-of-band information. At the cost of slight redundancy
/// in user config and another extra field that isn't actually in the blob,
/// we can actually handle the out-of-band information quite natually.
#[cfg_attr(feature = "serde", serde(default))]
pub context: ApcbContext,
pub version: String,
pub header: V2_HEADER,
pub v3_header_ext: Option<V3_HEADER_EXT>,
pub groups: Vec<SerdeGroupItem>,
//#[cfg_attr(feature = "serde", serde(borrow))]
pub entries: Vec<SerdeEntryItem>,
}
#[cfg(feature = "schemars")]
impl<'a> schemars::JsonSchema for Apcb<'a> {
fn schema_name() -> std::string::String {
SerdeApcb::schema_name()
}
fn json_schema(
gen: &mut schemars::gen::SchemaGenerator,
) -> schemars::schema::Schema {
SerdeApcb::json_schema(gen)
}
fn is_referenceable() -> bool {
SerdeApcb::is_referenceable()
}
}
#[cfg(feature = "serde")]
impl<'a> Apcb<'a> {
pub fn context(&self) -> ApcbContext {
self.context
}
// type Error = Error;
fn try_from(serde_apcb: SerdeApcb) -> Result<Self> {
let buf = Cow::from(vec![0xFFu8; Self::MAX_SIZE]);
let mut apcb = Apcb::create(
buf,
42,
&ApcbIoOptions::default().with_context(serde_apcb.context).build(),
)?;
*apcb.header_mut()? = serde_apcb.header;
match serde_apcb.v3_header_ext {
Some(v3) => {
assert!(
size_of::<V3_HEADER_EXT>() + size_of::<V2_HEADER>() == 128
);
apcb.header_mut()?.header_size.set(128);
if let Some(mut v) = apcb.v3_header_ext_mut()? {
*v = v3;
}
}
None => {
apcb.header_mut()?
.header_size
.set(size_of::<V2_HEADER>().try_into().unwrap());
}
}
// We reset apcb_size to header_size as this is naturally extended as we
// add groups and entries.
let mut header = apcb.header_mut()?;
let header_size = header.header_size.get();
header.apcb_size.set(header_size.into());
// These groups already exist: We've just successfully parsed them,
// there's no reason the groupid should be invalid.
for g in serde_apcb.groups {
apcb.insert_group(
GroupId::from_u16(g.header.group_id.get()).unwrap(),
g.header.signature,
)?;
}
for e in serde_apcb.entries {
let buf = &e.body[..];
apcb.insert_entry(
EntryId::decode(
e.header.group_id.get(),
e.header.entry_id.get(),
),
e.header.instance_id.get(),
BoardInstances::from(e.header.board_instance_mask.get()),
ContextType::from_u8(e.header.context_type).unwrap(),
PriorityLevels::from(e.header.priority_mask),
buf,
)?;
}
apcb.update_checksum()?;
Ok(apcb)
}
}
#[cfg(feature = "serde")]
impl<'a> Serialize for Apcb<'a> {
fn serialize<S>(
&self,
serializer: S,
) -> core::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
// In a better world we would implement From<Apcb> for SerdeApcb
// however we can't do that as we'd be returning borrowed data from
// Apcb.
let mut state = serializer.serialize_struct("Apcb", 5)?;
state.serialize_field("version", env!("CARGO_PKG_VERSION"))?;
let groups = self
.groups()
.map_err(|e| serde::ser::Error::custom(format!("{e:?}")))?
.collect::<Vec<_>>();
let mut entries: Vec<EntryItem<'_>> = Vec::new();
for g in &groups {
entries.extend((g.entries()).collect::<Vec<_>>());
}
state.serialize_field(
"header",
&*self
.header()
.map_err(|_| serde::ser::Error::custom("invalid V2_HEADER"))?,
)?;
let v3_header_ext: Option<V3_HEADER_EXT> = self
.v3_header_ext()
.map_err(|e| serde::ser::Error::custom(format!("{e:?}")))?
.as_ref()
.map(|h| **h);
state.serialize_field("v3_header_ext", &v3_header_ext)?;
state.serialize_field("groups", &groups)?;
state.serialize_field("entries", &entries)?;
state.end()
}
}
/// Note: Caller should probably verify sanity of context() afterwards
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Apcb<'_> {
fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let sa: SerdeApcb = SerdeApcb::deserialize(deserializer)?;
Apcb::try_from(sa)
.map_err(|e| serde::de::Error::custom(format!("{e:?}")))
}
}
pub struct ApcbIterMut<'a> {
context: ApcbContext,
buf: &'a mut [u8],
remaining_used_size: usize,
}
pub struct ApcbIter<'a> {
context: ApcbContext,
buf: &'a [u8],
remaining_used_size: usize,
}
impl<'a> ApcbIterMut<'a> {
/// It's useful to have some way of NOT mutating self.buf. This is what
/// this function does. Note: The caller needs to manually decrease
/// remaining_used_size for each call if desired.
fn next_item<'b>(
context: ApcbContext,
buf: &mut &'b mut [u8],
) -> Result<GroupMutItem<'b>> {
if buf.is_empty() {
return Err(Error::FileSystem(
FileSystemError::InconsistentHeader,
"GROUP_HEADER",
));
}
let header = take_header_from_collection_mut::<GROUP_HEADER>(&mut *buf)
.ok_or(Error::FileSystem(
FileSystemError::InconsistentHeader,
"GROUP_HEADER",
))?;
let group_size = header.group_size.get() as usize;
let payload_size = group_size
.checked_sub(size_of::<GROUP_HEADER>())
.ok_or(Error::FileSystem(
FileSystemError::InconsistentHeader,
"GROUP_HEADER::group_size",
))?;
let body = take_body_from_collection_mut(&mut *buf, payload_size, 1)
.ok_or(Error::FileSystem(
FileSystemError::InconsistentHeader,
"GROUP_HEADER",
))?;
let body_len = body.len();
Ok(GroupMutItem { context, header, buf: body, used_size: body_len })
}
/// Moves the point to the group with the given GROUP_ID. Returns (offset,
/// group_size) of it.
pub(crate) fn move_point_to(
&'_ mut self,
group_id: GroupId,
) -> Result<(usize, usize)> {
let group_id = group_id.to_u16().unwrap();
let mut remaining_used_size = self.remaining_used_size;
let mut offset = 0usize;
loop {
let mut buf = &mut self.buf[..remaining_used_size];
if buf.is_empty() {
break;
}
let group = ApcbIterMut::next_item(self.context, &mut buf)?;
let group_size = group.header.group_size.get();
if group.header.group_id.get() == group_id {
return Ok((offset, group_size as usize));
}
let group = ApcbIterMut::next_item(self.context, &mut self.buf)?;
let group_size = group.header.group_size.get() as usize;
offset = offset
.checked_add(group_size)
.ok_or(Error::ArithmeticOverflow)?;
remaining_used_size = remaining_used_size
.checked_sub(group_size)
.ok_or(Error::FileSystem(
FileSystemError::InconsistentHeader,
"GROUP_HEADER::group_size",
))?;
}
Err(Error::GroupNotFound)
}
pub(crate) fn next1(&mut self) -> Result<GroupMutItem<'a>> {
assert!(self.remaining_used_size != 0, "Internal error");
let item = Self::next_item(self.context, &mut self.buf)?;
let group_size = item.header.group_size.get() as usize;
if group_size <= self.remaining_used_size {
self.remaining_used_size -= group_size;
Ok(item)
} else {
Err(Error::FileSystem(
FileSystemError::InconsistentHeader,
"GROUP_HEADER::group_size",
))
}
}
}
impl<'a> Iterator for ApcbIterMut<'a> {
type Item = GroupMutItem<'a>;
fn next(&mut self) -> Option<Self::Item> {
if self.remaining_used_size == 0 {
return None;
}
self.next1().ok()
}
}
impl<'a> ApcbIter<'a> {
/// It's useful to have some way of NOT mutating self.buf. This is what
/// this function does. Note: The caller needs to manually decrease
/// remaining_used_size for each call if desired.
fn next_item<'b>(
context: ApcbContext,
buf: &mut &'b [u8],
) -> Result<GroupItem<'b>> {
if buf.is_empty() {
return Err(Error::FileSystem(
FileSystemError::InconsistentHeader,
"GROUP_HEADER",
));
}
let header = take_header_from_collection::<GROUP_HEADER>(&mut *buf)
.ok_or(Error::FileSystem(
FileSystemError::InconsistentHeader,
"GROUP_HEADER",
))?;
let group_size = header.group_size.get() as usize;
let payload_size = group_size
.checked_sub(size_of::<GROUP_HEADER>())
.ok_or(Error::FileSystem(
FileSystemError::InconsistentHeader,
"GROUP_HEADER",
))?;
let body = take_body_from_collection(&mut *buf, payload_size, 1)
.ok_or(Error::FileSystem(
FileSystemError::InconsistentHeader,
"GROUP_HEADER",
))?;
let body_len = body.len();
Ok(GroupItem { context, header, buf: body, used_size: body_len })
}
pub(crate) fn next1(&mut self) -> Result<GroupItem<'a>> {
assert!(self.remaining_used_size != 0, "Internal error");
let item = Self::next_item(self.context, &mut self.buf)?;
let group_size = item.header.group_size.get() as usize;
if group_size <= self.remaining_used_size {
self.remaining_used_size -= group_size;
Ok(item)
} else {
Err(Error::FileSystem(
FileSystemError::InconsistentHeader,
"GROUP_HEADER::group_size",
))
}
}
/// Validates the entries (recursively). Also consumes iterator.
pub(crate) fn validate(mut self) -> Result<()> {
while self.remaining_used_size > 0 {
let item = self.next1()?;
GroupId::from_u16(item.header.group_id.get()).ok_or(
Error::FileSystem(
FileSystemError::InconsistentHeader,
"GROUP_HEADER::group_id",
),
)?;
item.entries().validate()?;
}
Ok(())
}
}
impl<'a> Iterator for ApcbIter<'a> {
type Item = GroupItem<'a>;
fn next(&mut self) -> Option<Self::Item> {
if self.remaining_used_size == 0 {
return None;
}
self.next1().ok()
}
}
impl<'a> Apcb<'a> {
const NAPLES_VERSION: u16 = 0x20;
const ROME_VERSION: u16 = 0x30;
const V3_HEADER_EXT_SIZE: usize =
size_of::<V2_HEADER>() + size_of::<V3_HEADER_EXT>();
pub const MAX_SIZE: usize = 0x8000;
pub fn header(&self) -> Result<LayoutVerified<&[u8], V2_HEADER>> {
LayoutVerified::<&[u8], V2_HEADER>::new_unaligned_from_prefix(
&*self.backing_store,
)
.map(|(layout, _)| layout)
.ok_or(Error::FileSystem(
FileSystemError::InconsistentHeader,
"V2_HEADER",
))
}
pub fn header_mut(
&mut self,
) -> Result<LayoutVerified<&mut [u8], V2_HEADER>> {
#[cfg(not(feature = "std"))]
let bs: &mut [u8] = self.backing_store;
#[cfg(feature = "std")]
let bs: &mut [u8] = self.backing_store.to_mut();
LayoutVerified::<&mut [u8], V2_HEADER>::new_unaligned_from_prefix(bs)
.map(|(layout, _)| layout)
.ok_or(Error::FileSystem(
FileSystemError::InconsistentHeader,
"V2_HEADER",
))
}
pub fn v3_header_ext(
&self,
) -> Result<Option<LayoutVerified<&[u8], V3_HEADER_EXT>>> {
let (header, rest) =
LayoutVerified::<&[u8], V2_HEADER>::new_unaligned_from_prefix(
&*self.backing_store,
)
.ok_or(Error::FileSystem(
FileSystemError::InconsistentHeader,
"V2_HEADER",
))?;
let v3_header_ext =
if usize::from(header.header_size) == Self::V3_HEADER_EXT_SIZE {
let (ext, _) =
LayoutVerified::<&[u8], V3_HEADER_EXT>
::new_unaligned_from_prefix(rest)
.ok_or(Error::FileSystem(
FileSystemError::InconsistentHeader,
"V3_HEADER_EXT",
))?;
Some(ext)
} else {
None
};
Ok(v3_header_ext)
}
pub fn v3_header_ext_mut(
&mut self,
) -> Result<Option<LayoutVerified<&mut [u8], V3_HEADER_EXT>>> {
#[cfg(not(feature = "std"))]
let bs: &mut [u8] = self.backing_store;
#[cfg(feature = "std")]
let bs: &mut [u8] = self.backing_store.to_mut();
let (header, rest) =
LayoutVerified::<&mut [u8], V2_HEADER>::new_unaligned_from_prefix(
bs,
)
.ok_or(Error::FileSystem(
FileSystemError::InconsistentHeader,
"V2_HEADER",
))?;
let v3_header_ext =
if usize::from(header.header_size) == Self::V3_HEADER_EXT_SIZE {
let (header_ext, _) =
LayoutVerified::<&mut [u8], V3_HEADER_EXT>
::new_unaligned_from_prefix(rest)
.ok_or(Error::FileSystem(
FileSystemError::InconsistentHeader,
"V3_HEADER_EXT",
))?;
Some(header_ext)
} else {
None
};
Ok(v3_header_ext)
}
pub fn beginning_of_groups(&self) -> Result<&'_ [u8]> {
let offset = if self.v3_header_ext()?.is_some() {
size_of::<V2_HEADER>() + size_of::<V3_HEADER_EXT>()
} else {
size_of::<V2_HEADER>()
};
Ok(&self.backing_store[offset..])
}
pub fn beginning_of_groups_mut(&mut self) -> Result<&'_ mut [u8]> {
let offset = if self.v3_header_ext()?.is_some() {
size_of::<V2_HEADER>() + size_of::<V3_HEADER_EXT>()
} else {
size_of::<V2_HEADER>()
};
#[cfg(feature = "std")]
return Ok(&mut self.backing_store.to_mut()[offset..]);
#[cfg(not(feature = "std"))]
Ok(&mut self.backing_store[offset..])
}
pub fn groups(&self) -> Result<ApcbIter<'_>> {
Ok(ApcbIter {
context: self.context,
buf: self.beginning_of_groups()?,
remaining_used_size: self.used_size,
})
}
pub fn group(&self, group_id: GroupId) -> Result<Option<GroupItem<'_>>> {
Ok(self.groups()?.find(|group| group.id() == group_id))
}
/// Validates the contents.
/// If ABL0_VERSION is Some, also validates against that AGESA
/// bootloader version.
pub fn validate(&self, abl0_version: Option<u32>) -> Result<()> {
self.groups()?.validate()?;
self.ensure_abl0_compatibility(abl0_version)
}
pub fn groups_mut(&mut self) -> Result<ApcbIterMut<'_>> {
let used_size = self.used_size;
Ok(ApcbIterMut {
context: self.context,
buf: &mut *self.beginning_of_groups_mut()?,
remaining_used_size: used_size,
})
}
pub fn group_mut(
&mut self,
group_id: GroupId,
) -> Result<Option<GroupMutItem<'_>>> {
Ok(self.groups_mut()?.find(|group| group.id() == group_id))
}
/// Note: BOARD_INSTANCE_MASK needs to be exact.
pub fn delete_entry(
&mut self,
entry_id: EntryId,
instance_id: u16,
board_instance_mask: BoardInstances,
) -> Result<()> {
let group_id = entry_id.group_id();
let mut group =
self.group_mut(group_id)?.ok_or(Error::GroupNotFound)?;
let size_diff =
group.delete_entry(entry_id, instance_id, board_instance_mask)?;
if size_diff > 0 {
let size_diff = size_diff as i64;
self.resize_group_by(group_id, -size_diff)?;
}
Ok(())
}
fn resize_group_by(
&mut self,
group_id: GroupId,
size_diff: i64,
) -> Result<GroupMutItem<'_>> {
let old_used_size = self.used_size;
let apcb_size = self.header()?.apcb_size.get();
if size_diff > 0 {
let size_diff: u32 = (size_diff as u64)
.try_into()
.map_err(|_| Error::ArithmeticOverflow)?;
self.header_mut()?.apcb_size.set(
apcb_size.checked_add(size_diff).ok_or(Error::FileSystem(
FileSystemError::PayloadTooBig,
"HEADER_V2::apcb_size",
))?,
);
} else {
let size_diff: u32 = ((-size_diff) as u64)
.try_into()
.map_err(|_| Error::ArithmeticOverflow)?;
self.header_mut()?.apcb_size.set(
apcb_size.checked_sub(size_diff).ok_or(Error::FileSystem(
FileSystemError::InconsistentHeader,
"HEADER_V2::apcb_size",
))?,
);
}
let self_beginning_of_groups_len = self.beginning_of_groups()?.len();
let mut groups = self.groups_mut()?;
let (offset, old_group_size) = groups.move_point_to(group_id)?;
#[allow(clippy::comparison_chain)]
if size_diff > 0 {
// Grow
let old_group_size: u32 = old_group_size
.try_into()
.map_err(|_| Error::ArithmeticOverflow)?;
let size_diff: u32 = (size_diff as u64)
.try_into()
.map_err(|_| Error::ArithmeticOverflow)?;
let new_group_size = old_group_size.checked_add(size_diff).ok_or(
Error::FileSystem(
FileSystemError::PayloadTooBig,
"GROUP_HEADER::group_size",
),
)?;
let new_used_size = old_used_size
.checked_add(size_diff as usize)
.ok_or(Error::FileSystem(
FileSystemError::PayloadTooBig,
"ENTRY_HEADER::entry_size",
))?;
if new_used_size <= self_beginning_of_groups_len {
} else {
return Err(Error::OutOfSpace);
}
let group = groups.next().ok_or(Error::GroupNotFound)?;
group.header.group_size.set(new_group_size);
let buf = &mut self.beginning_of_groups_mut()?[offset..];
if old_group_size as usize > old_used_size {
return Err(Error::FileSystem(
FileSystemError::InconsistentHeader,
"GROUP_HEADER::group_size",
));
}
buf.copy_within(
(old_group_size as usize)..(old_used_size - offset),
new_group_size as usize,
);
self.used_size = new_used_size;
} else if size_diff < 0 {
let old_group_size: u32 = old_group_size
.try_into()
.map_err(|_| Error::ArithmeticOverflow)?;
let size_diff: u32 = ((-size_diff) as u64)
.try_into()
.map_err(|_| Error::ArithmeticOverflow)?;
let new_group_size = old_group_size.checked_sub(size_diff).ok_or(
Error::FileSystem(
FileSystemError::InconsistentHeader,
"GROUP_HEADER::group_size",
),
)?;
let new_used_size = old_used_size
.checked_sub(size_diff as usize)
.ok_or(Error::FileSystem(
FileSystemError::InconsistentHeader,
"ENTRY_HEADER::entry_size",
))?;
let group = groups.next().ok_or(Error::GroupNotFound)?;
group.header.group_size.set(new_group_size);
let buf = &mut self.beginning_of_groups_mut()?[offset..];
buf.copy_within(
(old_group_size as usize)..old_used_size,
new_group_size as usize,
);
self.used_size = new_used_size;
}
self.group_mut(group_id)?.ok_or(Error::GroupNotFound)
}
/// Note: board_instance_mask needs to be exact.
#[allow(clippy::too_many_arguments)]
#[pre]
fn internal_insert_entry(
&mut self,
entry_id: EntryId,
instance_id: u16,
board_instance_mask: BoardInstances,
context_type: ContextType,
payload_size: usize,
priority_mask: PriorityLevels,
payload_initializer: impl Fn(&mut [u8]),
) -> Result<()> {
let group_id = entry_id.group_id();
let mut group =
self.group_mut(group_id)?.ok_or(Error::GroupNotFound)?;
if group
.entry_exact_mut(entry_id, instance_id, board_instance_mask)
.is_some()
{
return Err(Error::EntryUniqueKeyViolation);
}
let mut entry_allocation: u16 = (size_of::<ENTRY_HEADER>() as u16)
.checked_add(
payload_size
.try_into()
.map_err(|_| Error::ArithmeticOverflow)?,
)
.ok_or(Error::OutOfSpace)?;
while entry_allocation % (ENTRY_ALIGNMENT as u16) != 0 {
entry_allocation += 1;
}
let mut group =
self.resize_group_by(group_id, entry_allocation.into())?;
let mut entries = group.entries_mut();
// Note: On some errors, group.used_size will be reduced by insert_entry
// again!
let rv = #[assure(
"Caller already grew the group by `payload_size + size_of::<ENTRY_HEADER>()`",
reason = "See above"
)]
entries.insert_entry(
entry_id,
instance_id,
board_instance_mask,
entry_allocation,
context_type,
payload_size,
payload_initializer,
priority_mask,
);
rv.map(|_| ())
}
// Security--and it would be nicer if the person using this would instead
// contribute a struct layout so we can use it normally
#[pre]
pub(crate) fn insert_entry(
&mut self,
entry_id: EntryId,
instance_id: u16,
board_instance_mask: BoardInstances,
context_type: ContextType,
priority_mask: PriorityLevels,
payload: &[u8],
) -> Result<()> {
let payload_size = payload.len();
self.internal_insert_entry(
entry_id,
instance_id,
board_instance_mask,
context_type,
payload_size,
priority_mask,
|body: &mut [u8]| {
body.copy_from_slice(payload);
},
)
}
/// Inserts a new entry (see insert_entry), puts PAYLOAD into it. Usually
/// that's for platform_specific_override or platform_tuning structs.
/// Note: Currently, INSTANCE_ID is always supposed to be 0.
pub fn insert_struct_sequence_as_entry(
&mut self,
entry_id: EntryId,
instance_id: u16,
board_instance_mask: BoardInstances,
priority_mask: PriorityLevels,
payload: &[&dyn SequenceElementAsBytes],
) -> Result<()> {
let mut payload_size: usize = 0;
for item in payload {
let blob = item
.checked_as_bytes(entry_id)
.ok_or(Error::EntryTypeMismatch)?;
payload_size = payload_size
.checked_add(blob.len())
.ok_or(Error::ArithmeticOverflow)?;
}
self.internal_insert_entry(
entry_id,
instance_id,
board_instance_mask,
ContextType::Struct,
payload_size,
priority_mask,
|body: &mut [u8]| {
let mut body = body;
for item in payload {
let source = item.checked_as_bytes(entry_id).unwrap();
let (a, rest) = body.split_at_mut(source.len());
a.copy_from_slice(source);
body = rest;
}
},
)
}
/// Inserts a new entry (see insert_entry), puts PAYLOAD into it. T can be
/// a enum of struct refs (PlatformSpecificElementRef,
/// PlatformTuningElementRef) or just one struct. Note: Currently,
/// INSTANCE_ID is always supposed to be 0.
pub fn insert_struct_array_as_entry<T: EntryCompatible + AsBytes>(
&mut self,
entry_id: EntryId,
instance_id: u16,
board_instance_mask: BoardInstances,
priority_mask: PriorityLevels,
payload: &[T],
) -> Result<()> {
let mut payload_size: usize = 0;
for item in payload {
let blob = item.as_bytes();
if !T::is_entry_compatible(entry_id, blob) {
return Err(Error::EntryTypeMismatch);
}
payload_size = payload_size
.checked_add(blob.len())
.ok_or(Error::ArithmeticOverflow)?;
}
self.internal_insert_entry(
entry_id,
instance_id,
board_instance_mask,
ContextType::Struct,
payload_size,
priority_mask,
|body: &mut [u8]| {
let mut body = body;
for item in payload {
let source = item.as_bytes();
let (a, rest) = body.split_at_mut(source.len());
a.copy_from_slice(source);
body = rest;
}
},
)
}
/// Inserts a new entry (see insert_entry), puts HEADER and then TAIL into
/// it. TAIL is allowed to be &[], and often has to be.
/// Note: Currently, INSTANCE_ID is always supposed to be 0.
pub fn insert_struct_entry<
H: EntryCompatible + AsBytes + HeaderWithTail,
>(
&mut self,
entry_id: EntryId,
instance_id: u16,
board_instance_mask: BoardInstances,
priority_mask: PriorityLevels,
header: &H,
tail: &[H::TailArrayItemType<'_>],
) -> Result<()> {
let blob = header.as_bytes();
if H::is_entry_compatible(entry_id, blob) {
let payload_size = size_of::<H>()
.checked_add(
size_of::<H::TailArrayItemType<'_>>()
.checked_mul(tail.len())
.ok_or(Error::ArithmeticOverflow)?,
)
.ok_or(Error::ArithmeticOverflow)?;
self.internal_insert_entry(
entry_id,
instance_id,
board_instance_mask,
ContextType::Struct,
payload_size,
priority_mask,
|body: &mut [u8]| {
let mut body = body;
let (a, rest) = body.split_at_mut(blob.len());
a.copy_from_slice(blob);
body = rest;
for item in tail {
let source = item.as_bytes();
let (a, rest) = body.split_at_mut(source.len());
a.copy_from_slice(source);
body = rest;
}
},
)
} else {
Err(Error::EntryTypeMismatch)
}
}
/// This inserts a Naples-style Parameters entry.
/// Note: Keep in sync with new_tail_from_vec.
pub fn insert_parameters_entry(
&mut self,
entry_id: EntryId,
items: &[Parameter],
) -> Result<()> {
let mut payload_size = size_of::<u32>() + size_of::<u8>(); // terminator attribute and its value
for parameter in items {
payload_size = payload_size
.checked_add(size_of::<ParameterAttributes>())
.ok_or(Error::ArithmeticOverflow)?;
let value_size = usize::from(parameter.value_size()?);
let value = parameter.value()?;
payload_size = payload_size
.checked_add(value_size)
.ok_or(Error::ArithmeticOverflow)?;
if value_size > 8 || value >= (8u64 << value_size) {
return Err(Error::ParameterRange);
}
}
self.internal_insert_entry(
entry_id,
0,
BoardInstances::new(),
ContextType::Struct,
payload_size,
PriorityLevels::new(),
|body: &mut [u8]| {
let mut body = body;
for parameter in items {
let raw_key =
parameter.attributes().unwrap().to_u32().unwrap();
let (a, rest) = body.split_at_mut(size_of::<u32>());
a.copy_from_slice(raw_key.as_bytes());
body = rest;
}
let key = ParameterAttributes::terminator();
let raw_key = key.to_u32().unwrap();
let (a, rest) = body.split_at_mut(size_of::<u32>());
a.copy_from_slice(raw_key.as_bytes());
body = rest;
for parameter in items {
let size = usize::from(parameter.value_size().unwrap());
let (a, rest) = body.split_at_mut(size);
let value = parameter.value().unwrap();
let raw_value = value.as_bytes();
a.copy_from_slice(&raw_value[0..size]);
body = rest;
}
let (a, _rest) = body.split_at_mut(size_of::<u8>());
a.copy_from_slice(&[0xffu8]);
},
)
}
/// Note: INSTANCE_ID is sometimes != 0.
#[pre]
pub fn insert_token(
&mut self,
entry_id: EntryId,
instance_id: u16,
board_instance_mask: BoardInstances,
token_id: u32,
token_value: u32,
) -> Result<()> {
let group_id = entry_id.group_id();
// Make sure that the entry exists before resizing the group
let group = self.group(group_id)?.ok_or(Error::GroupNotFound)?;
let entry = group
.entry_exact(entry_id, instance_id, board_instance_mask)
.ok_or(Error::EntryNotFound)?;
let EntryItemBody::<_>::Tokens(a) = &entry.body else {
return Err(Error::EntryTypeMismatch);
};
if a.token(token_id).is_some() {
return Err(Error::TokenUniqueKeyViolation);
}
// Tokens that destroy the alignment in the container have not been
// tested, are impossible right now anyway and have never been seen. So
// disallow those.
const TOKEN_SIZE: u16 = size_of::<TOKEN_ENTRY>() as u16;
const_assert!(TOKEN_SIZE % (ENTRY_ALIGNMENT as u16) == 0);