blob: 3f78a88713fc6f6df47a790156fd83335bf2bf2c [file] [log] [blame]
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +01001// Copyright 2022, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Support for the pvmfw configuration data format.
16
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010017use core::fmt;
18use core::mem;
Jaewan Kim3dfc0ab2023-09-27 14:00:59 +090019use core::num::NonZeroUsize;
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +000020use core::ops::Range;
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010021use core::result;
Pierre-Clément Tosice3e3132023-08-17 10:24:22 +010022use log::{info, warn};
Pierre-Clément Tosifd694c72023-08-14 14:24:07 +010023use static_assertions::const_assert_eq;
Pierre-Clément Tosi33001492023-08-14 17:57:30 +010024use vmbase::util::RangeExt;
Alan Stokes65618332023-12-15 14:09:25 +000025use zerocopy::{FromBytes, FromZeroes};
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010026
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +000027/// Configuration data header.
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010028#[repr(C, packed)]
Frederick Mayle2e779942023-10-15 18:27:31 +000029#[derive(Clone, Copy, Debug, FromZeroes, FromBytes)]
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010030struct Header {
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +000031 /// Magic number; must be `Header::MAGIC`.
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010032 magic: u32,
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +000033 /// Version of the header format.
Jaewan Kim6b7fb3c2023-08-08 18:00:43 +090034 version: Version,
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +000035 /// Total size of the configuration data.
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010036 total_size: u32,
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +000037 /// Feature flags; currently reserved and must be zero.
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010038 flags: u32,
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010039}
40
41#[derive(Debug)]
42pub enum Error {
43 /// Reserved region can't fit configuration header.
44 BufferTooSmall,
Alan Stokesa0e42962023-04-14 17:59:50 +010045 /// Header has the wrong alignment
46 HeaderMisaligned,
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010047 /// Header doesn't contain the expect magic value.
48 InvalidMagic,
49 /// Version of the header isn't supported.
Jaewan Kim6b7fb3c2023-08-08 18:00:43 +090050 UnsupportedVersion(Version),
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010051 /// Header describes configuration data that doesn't fit in the expected buffer.
52 InvalidSize(usize),
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +000053 /// Header entry is missing.
54 MissingEntry(Entry),
Pierre-Clément Tosifd694c72023-08-14 14:24:07 +010055 /// Range described by entry does not fit within config data.
56 EntryOutOfBounds(Entry, Range<usize>, Range<usize>),
Jaewan Kimb266e0e2023-09-27 15:44:53 +090057 /// Entries are in out of order
58 EntryOutOfOrder,
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010059}
60
61impl fmt::Display for Error {
62 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63 match self {
64 Self::BufferTooSmall => write!(f, "Reserved region is smaller than config header"),
Alan Stokesa0e42962023-04-14 17:59:50 +010065 Self::HeaderMisaligned => write!(f, "Reserved region is misaligned"),
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010066 Self::InvalidMagic => write!(f, "Wrong magic number"),
Jaewan Kim6b7fb3c2023-08-08 18:00:43 +090067 Self::UnsupportedVersion(v) => write!(f, "Version {v} not supported"),
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010068 Self::InvalidSize(sz) => write!(f, "Total size ({sz:#x}) overflows reserved region"),
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +000069 Self::MissingEntry(entry) => write!(f, "Mandatory {entry:?} entry is missing"),
Pierre-Clément Tosifd694c72023-08-14 14:24:07 +010070 Self::EntryOutOfBounds(entry, range, limits) => {
71 write!(
72 f,
73 "Entry {entry:?} out of bounds: {range:#x?} must be within range {limits:#x?}"
74 )
75 }
Jaewan Kimb266e0e2023-09-27 15:44:53 +090076 Self::EntryOutOfOrder => write!(f, "Entries are out of order"),
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010077 }
78 }
79}
80
81pub type Result<T> = result::Result<T, Error>;
82
83impl Header {
84 const MAGIC: u32 = u32::from_ne_bytes(*b"pvmf");
Jaewan Kim6b7fb3c2023-08-08 18:00:43 +090085 const VERSION_1_0: Version = Version { major: 1, minor: 0 };
Jaewan Kimbf5978c2023-07-28 11:30:54 +000086 const VERSION_1_1: Version = Version { major: 1, minor: 1 };
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010087
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010088 pub fn total_size(&self) -> usize {
89 self.total_size as usize
90 }
91
Pierre-Clément Tosice3e3132023-08-17 10:24:22 +010092 pub fn body_lowest_bound(&self) -> Result<usize> {
Pierre-Clément Tosi33001492023-08-14 17:57:30 +010093 let entries_offset = mem::size_of::<Self>();
94
95 // Ensure that the entries are properly aligned and do not require padding.
96 const_assert_eq!(mem::align_of::<Header>() % mem::align_of::<HeaderEntry>(), 0);
97 const_assert_eq!(mem::size_of::<Header>() % mem::align_of::<HeaderEntry>(), 0);
98
99 let entries_size = self.entry_count()?.checked_mul(mem::size_of::<HeaderEntry>()).unwrap();
100
101 Ok(entries_offset.checked_add(entries_size).unwrap())
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100102 }
103
Pierre-Clément Tosi33001492023-08-14 17:57:30 +0100104 pub fn entry_count(&self) -> Result<usize> {
105 let last_entry = match self.version {
106 Self::VERSION_1_0 => Entry::DebugPolicy,
Jaewan Kimbf5978c2023-07-28 11:30:54 +0000107 Self::VERSION_1_1 => Entry::VmDtbo,
Pierre-Clément Tosice3e3132023-08-17 10:24:22 +0100108 v @ Version { major: 1, .. } => {
109 const LATEST: Version = Header::VERSION_1_1;
110 warn!("Parsing unknown config data version {v} as version {LATEST}");
111 return Ok(Entry::COUNT);
112 }
Pierre-Clément Tosi33001492023-08-14 17:57:30 +0100113 v => return Err(Error::UnsupportedVersion(v)),
Pierre-Clément Tosifd694c72023-08-14 14:24:07 +0100114 };
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000115
Pierre-Clément Tosi33001492023-08-14 17:57:30 +0100116 Ok(last_entry as usize + 1)
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100117 }
118}
119
120#[derive(Clone, Copy, Debug)]
121pub enum Entry {
Pierre-Clément Tosi33001492023-08-14 17:57:30 +0100122 Bcc,
123 DebugPolicy,
Jaewan Kimbf5978c2023-07-28 11:30:54 +0000124 VmDtbo,
Pierre-Clément Tosi33001492023-08-14 17:57:30 +0100125 #[allow(non_camel_case_types)] // TODO: Use mem::variant_count once stable.
126 _VARIANT_COUNT,
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100127}
128
129impl Entry {
Pierre-Clément Tosi33001492023-08-14 17:57:30 +0100130 const COUNT: usize = Self::_VARIANT_COUNT as usize;
Alan Stokes65618332023-12-15 14:09:25 +0000131
132 const ALL_ENTRIES: [Entry; Self::COUNT] = [Self::Bcc, Self::DebugPolicy, Self::VmDtbo];
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100133}
134
Alan Stokesd0cf3cd2023-12-12 14:36:37 +0000135#[derive(Default)]
136pub struct Entries<'a> {
137 pub bcc: &'a mut [u8],
Alan Stokes65618332023-12-15 14:09:25 +0000138 pub debug_policy: Option<&'a [u8]>,
Alan Stokesd0cf3cd2023-12-12 14:36:37 +0000139 pub vm_dtbo: Option<&'a mut [u8]>,
140}
141
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100142#[repr(packed)]
Frederick Mayle2e779942023-10-15 18:27:31 +0000143#[derive(Clone, Copy, Debug, FromZeroes, FromBytes)]
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100144struct HeaderEntry {
145 offset: u32,
146 size: u32,
147}
148
Jaewan Kim6b7fb3c2023-08-08 18:00:43 +0900149#[repr(C, packed)]
Frederick Mayle2e779942023-10-15 18:27:31 +0000150#[derive(Clone, Copy, Debug, Eq, FromZeroes, FromBytes, PartialEq)]
Jaewan Kim6b7fb3c2023-08-08 18:00:43 +0900151pub struct Version {
152 minor: u16,
153 major: u16,
154}
155
156impl fmt::Display for Version {
157 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
158 // Copy the fields to local variables to prevent unaligned access.
159 let (major, minor) = (self.major, self.minor);
160 write!(f, "{}.{}", major, minor)
161 }
162}
163
Jaewan Kim3dfc0ab2023-09-27 14:00:59 +0900164/// Range with non-empty length.
165#[derive(Debug, Copy, Clone)]
166struct NonEmptyRange {
167 start: usize,
168 size: NonZeroUsize,
169}
170
171impl NonEmptyRange {
172 pub fn new(start: usize, size: usize) -> Option<Self> {
173 // Ensure end() is safe.
174 start.checked_add(size).unwrap();
175
176 Some(Self { start, size: NonZeroUsize::new(size)? })
177 }
178
179 fn end(&self) -> usize {
180 self.start + self.len()
181 }
182
183 fn len(&self) -> usize {
184 self.size.into()
185 }
186
187 fn as_range(&self) -> Range<usize> {
188 self.start..self.end()
189 }
190}
191
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100192#[derive(Debug)]
193pub struct Config<'a> {
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100194 body: &'a mut [u8],
Jaewan Kim3dfc0ab2023-09-27 14:00:59 +0900195 ranges: [Option<NonEmptyRange>; Entry::COUNT],
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100196}
197
198impl<'a> Config<'a> {
199 /// Take ownership of a pvmfw configuration consisting of its header and following entries.
Pierre-Clément Tosifd694c72023-08-14 14:24:07 +0100200 pub fn new(bytes: &'a mut [u8]) -> Result<Self> {
201 const HEADER_SIZE: usize = mem::size_of::<Header>();
202 if bytes.len() < HEADER_SIZE {
203 return Err(Error::BufferTooSmall);
204 }
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100205
Pierre-Clément Tosifd694c72023-08-14 14:24:07 +0100206 let (header, rest) =
Alan Stokes65618332023-12-15 14:09:25 +0000207 zerocopy::Ref::<_, Header>::new_from_prefix(bytes).ok_or(Error::HeaderMisaligned)?;
Alan Stokesa0e42962023-04-14 17:59:50 +0100208 let header = header.into_ref();
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100209
210 if header.magic != Header::MAGIC {
211 return Err(Error::InvalidMagic);
212 }
213
Pierre-Clément Tosice3e3132023-08-17 10:24:22 +0100214 let header_flags = header.flags;
215 if header_flags != 0 {
216 warn!("Ignoring unknown config flags: {header_flags:#x}");
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100217 }
218
Jaewan Kimbf5978c2023-07-28 11:30:54 +0000219 info!("pvmfw config version: {}", header.version);
220
Pierre-Clément Tosifd694c72023-08-14 14:24:07 +0100221 // Validate that we won't get an invalid alignment in the following due to padding to u64.
222 const_assert_eq!(HEADER_SIZE % mem::size_of::<u64>(), 0);
223
224 // Ensure that Header::total_size isn't larger than anticipated by the caller and resize
225 // the &[u8] to catch OOB accesses to entries/blobs.
226 let total_size = header.total_size();
227 let rest = if let Some(rest_size) = total_size.checked_sub(HEADER_SIZE) {
228 rest.get_mut(..rest_size).ok_or(Error::InvalidSize(total_size))?
229 } else {
230 return Err(Error::InvalidSize(total_size));
231 };
232
Pierre-Clément Tosi33001492023-08-14 17:57:30 +0100233 let (header_entries, body) =
Alan Stokes65618332023-12-15 14:09:25 +0000234 zerocopy::Ref::<_, [HeaderEntry]>::new_slice_from_prefix(rest, header.entry_count()?)
Pierre-Clément Tosi33001492023-08-14 17:57:30 +0100235 .ok_or(Error::BufferTooSmall)?;
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100236
Pierre-Clément Tosi33001492023-08-14 17:57:30 +0100237 // Validate that we won't get an invalid alignment in the following due to padding to u64.
238 const_assert_eq!(mem::size_of::<HeaderEntry>() % mem::size_of::<u64>(), 0);
239
Jaewan Kim3dfc0ab2023-09-27 14:00:59 +0900240 // Ensure entries are in the body.
Pierre-Clément Tosice3e3132023-08-17 10:24:22 +0100241 let limits = header.body_lowest_bound()?..total_size;
Jaewan Kim3dfc0ab2023-09-27 14:00:59 +0900242 let mut ranges: [Option<NonEmptyRange>; Entry::COUNT] = [None; Entry::COUNT];
Jaewan Kimb266e0e2023-09-27 15:44:53 +0900243 let mut last_end = 0;
Alan Stokes65618332023-12-15 14:09:25 +0000244 for entry in Entry::ALL_ENTRIES {
Jaewan Kim3dfc0ab2023-09-27 14:00:59 +0900245 let Some(header_entry) = header_entries.get(entry as usize) else { continue };
246 let entry_offset = header_entry.offset.try_into().unwrap();
247 let entry_size = header_entry.size.try_into().unwrap();
248 let Some(range) = NonEmptyRange::new(entry_offset, entry_size) else { continue };
249 let range = range.as_range();
250 if !range.is_within(&limits) {
251 return Err(Error::EntryOutOfBounds(entry, range, limits));
252 }
253
Jaewan Kimb266e0e2023-09-27 15:44:53 +0900254 if last_end > range.start {
255 return Err(Error::EntryOutOfOrder);
256 }
257 last_end = range.end;
258
Jaewan Kim3dfc0ab2023-09-27 14:00:59 +0900259 ranges[entry as usize] = NonEmptyRange::new(
260 entry_offset - limits.start, // is_within() validates safety of this.
261 entry_size,
262 );
263 }
Jaewan Kimb266e0e2023-09-27 15:44:53 +0900264 // Ensures that BCC exists.
265 ranges[Entry::Bcc as usize].ok_or(Error::MissingEntry(Entry::Bcc))?;
Pierre-Clément Tosi33001492023-08-14 17:57:30 +0100266
267 Ok(Self { body, ranges })
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100268 }
269
Alan Stokes65618332023-12-15 14:09:25 +0000270 /// Locate the various config entries.
271 pub fn get_entries(self) -> Entries<'a> {
272 // We require the blobs to be in the same order as the `Entry` enum (and this is checked
273 // in `new` above)
274 // So we can just work through the body range and split off the parts we are interested in.
275 let mut offset = 0;
276 let mut body = self.body;
277
278 let mut entries: [Option<&mut [u8]>; Entry::COUNT] = Default::default();
279 for (i, range) in self.ranges.iter().enumerate() {
280 if let Some(range) = range {
281 body = &mut body[range.start - offset..];
282 let (chunk, rest) = body.split_at_mut(range.len());
283 offset = range.end();
284 body = rest;
285 entries[i] = Some(chunk);
286 }
Jaewan Kimbf5978c2023-07-28 11:30:54 +0000287 }
Alan Stokes65618332023-12-15 14:09:25 +0000288 let [bcc, debug_policy, vm_dtbo] = entries;
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100289
Alan Stokes65618332023-12-15 14:09:25 +0000290 // The platform BCC has always been required.
291 let bcc = bcc.unwrap();
292
293 // We have no reason to mutate so drop the `mut`.
294 let debug_policy = debug_policy.map(|x| &*x);
Alan Stokesd0cf3cd2023-12-12 14:36:37 +0000295 Entries { bcc, debug_policy, vm_dtbo }
Pierre-Clément Tosi33001492023-08-14 17:57:30 +0100296 }
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100297}