blob: b90b136ecf4b1bf1361ad803fd71c6b5345c3c33 [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
17use crate::helpers;
18use core::fmt;
19use core::mem;
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;
Alan Stokesa0e42962023-04-14 17:59:50 +010022use zerocopy::{FromBytes, LayoutVerified};
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010023
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +000024/// Configuration data header.
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010025#[repr(C, packed)]
Alan Stokesa0e42962023-04-14 17:59:50 +010026#[derive(Clone, Copy, Debug, FromBytes)]
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010027struct Header {
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +000028 /// Magic number; must be `Header::MAGIC`.
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010029 magic: u32,
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +000030 /// Version of the header format.
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010031 version: u32,
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +000032 /// Total size of the configuration data.
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010033 total_size: u32,
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +000034 /// Feature flags; currently reserved and must be zero.
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010035 flags: u32,
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +000036 /// (offset, size) pairs used to locate individual entries appended to the header.
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010037 entries: [HeaderEntry; Entry::COUNT],
38}
39
40#[derive(Debug)]
41pub enum Error {
42 /// Reserved region can't fit configuration header.
43 BufferTooSmall,
Alan Stokesa0e42962023-04-14 17:59:50 +010044 /// Header has the wrong alignment
45 HeaderMisaligned,
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010046 /// Header doesn't contain the expect magic value.
47 InvalidMagic,
48 /// Version of the header isn't supported.
49 UnsupportedVersion(u16, u16),
50 /// Header sets flags incorrectly or uses reserved flags.
51 InvalidFlags(u32),
52 /// Header describes configuration data that doesn't fit in the expected buffer.
53 InvalidSize(usize),
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +000054 /// Header entry is missing.
55 MissingEntry(Entry),
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010056 /// Header entry is invalid.
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +000057 InvalidEntry(Entry, EntryError),
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010058}
59
60impl fmt::Display for Error {
61 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62 match self {
63 Self::BufferTooSmall => write!(f, "Reserved region is smaller than config header"),
Alan Stokesa0e42962023-04-14 17:59:50 +010064 Self::HeaderMisaligned => write!(f, "Reserved region is misaligned"),
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010065 Self::InvalidMagic => write!(f, "Wrong magic number"),
66 Self::UnsupportedVersion(x, y) => write!(f, "Version {x}.{y} not supported"),
67 Self::InvalidFlags(v) => write!(f, "Flags value {v:#x} is incorrect or reserved"),
68 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"),
70 Self::InvalidEntry(entry, e) => write!(f, "Invalid {entry:?} entry: {e}"),
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010071 }
72 }
73}
74
75pub type Result<T> = result::Result<T, Error>;
76
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +000077#[derive(Debug)]
78pub enum EntryError {
79 /// Offset isn't between the fixed minimum value and size of configuration data.
80 InvalidOffset(usize),
81 /// Size must be zero when offset is and not be when it isn't.
82 InvalidSize(usize),
83 /// Entry isn't fully within the configuration data structure.
84 OutOfBounds { offset: usize, size: usize, limit: usize },
85}
86
87impl fmt::Display for EntryError {
88 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
89 match self {
90 Self::InvalidOffset(offset) => write!(f, "Invalid offset: {offset:#x?}"),
91 Self::InvalidSize(sz) => write!(f, "Invalid size: {sz:#x?}"),
92 Self::OutOfBounds { offset, size, limit } => {
93 let range = Header::PADDED_SIZE..*limit;
94 let entry = *offset..(*offset + *size);
95 write!(f, "Out of bounds: {entry:#x?} must be within range {range:#x?}")
96 }
97 }
98 }
99}
100
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100101impl Header {
102 const MAGIC: u32 = u32::from_ne_bytes(*b"pvmf");
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +0000103 const VERSION_1_0: u32 = Self::version(1, 0);
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100104 const PADDED_SIZE: usize =
105 helpers::unchecked_align_up(mem::size_of::<Self>(), mem::size_of::<u64>());
106
107 pub const fn version(major: u16, minor: u16) -> u32 {
108 ((major as u32) << 16) | (minor as u32)
109 }
110
111 pub const fn version_tuple(&self) -> (u16, u16) {
112 ((self.version >> 16) as u16, self.version as u16)
113 }
114
115 pub fn total_size(&self) -> usize {
116 self.total_size as usize
117 }
118
119 pub fn body_size(&self) -> usize {
120 self.total_size() - Self::PADDED_SIZE
121 }
122
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000123 fn get_body_range(&self, entry: Entry) -> Result<Option<Range<usize>>> {
124 let e = self.entries[entry as usize];
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +0000125 let offset = e.offset as usize;
126 let size = e.size as usize;
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000127
Pierre-Clément Tosi706a10c2022-12-14 10:33:24 +0000128 match self._get_body_range(offset, size) {
129 Ok(r) => Ok(r),
130 Err(EntryError::InvalidSize(0)) => {
131 // As our bootloader currently uses this (non-compliant) case, permit it for now.
132 log::warn!("Config entry {entry:?} uses non-zero offset with zero size");
133 // TODO(b/262181812): Either make this case valid or fix the bootloader.
134 Ok(None)
135 }
136 Err(e) => Err(Error::InvalidEntry(entry, e)),
137 }
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +0000138 }
139
140 fn _get_body_range(
141 &self,
142 offset: usize,
143 size: usize,
144 ) -> result::Result<Option<Range<usize>>, EntryError> {
145 match (offset, size) {
146 (0, 0) => Ok(None),
147 (0, size) | (_, size @ 0) => Err(EntryError::InvalidSize(size)),
148 _ => {
149 let start = offset
150 .checked_sub(Header::PADDED_SIZE)
151 .ok_or(EntryError::InvalidOffset(offset))?;
152 let end = start
153 .checked_add(size)
154 .filter(|x| *x <= self.body_size())
155 .ok_or(EntryError::OutOfBounds { offset, size, limit: self.total_size() })?;
156
157 Ok(Some(start..end))
158 }
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000159 }
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100160 }
161}
162
163#[derive(Clone, Copy, Debug)]
164pub enum Entry {
165 Bcc = 0,
166 DebugPolicy = 1,
167}
168
169impl Entry {
170 const COUNT: usize = 2;
171}
172
173#[repr(packed)]
Alan Stokesa0e42962023-04-14 17:59:50 +0100174#[derive(Clone, Copy, Debug, FromBytes)]
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100175struct HeaderEntry {
176 offset: u32,
177 size: u32,
178}
179
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100180#[derive(Debug)]
181pub struct Config<'a> {
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100182 body: &'a mut [u8],
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000183 bcc_range: Range<usize>,
184 dp_range: Option<Range<usize>>,
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100185}
186
187impl<'a> Config<'a> {
188 /// Take ownership of a pvmfw configuration consisting of its header and following entries.
189 ///
190 /// SAFETY - 'data' should respect the alignment of Header.
191 pub unsafe fn new(data: &'a mut [u8]) -> Result<Self> {
192 let header = data.get(..Header::PADDED_SIZE).ok_or(Error::BufferTooSmall)?;
193
Alan Stokesa0e42962023-04-14 17:59:50 +0100194 let (header, _) =
195 LayoutVerified::<_, Header>::new_from_prefix(header).ok_or(Error::HeaderMisaligned)?;
196 let header = header.into_ref();
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100197
198 if header.magic != Header::MAGIC {
199 return Err(Error::InvalidMagic);
200 }
201
Pierre-Clément Tosi43592a42022-12-19 14:17:38 +0000202 if header.version != Header::VERSION_1_0 {
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100203 let (major, minor) = header.version_tuple();
204 return Err(Error::UnsupportedVersion(major, minor));
205 }
206
207 if header.flags != 0 {
208 return Err(Error::InvalidFlags(header.flags));
209 }
210
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000211 let bcc_range =
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +0000212 header.get_body_range(Entry::Bcc)?.ok_or(Error::MissingEntry(Entry::Bcc))?;
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000213 let dp_range = header.get_body_range(Entry::DebugPolicy)?;
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100214
Alan Stokesa0e42962023-04-14 17:59:50 +0100215 let body_size = header.body_size();
216 let total_size = header.total_size();
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100217 let body = data
218 .get_mut(Header::PADDED_SIZE..)
219 .ok_or(Error::BufferTooSmall)?
Alan Stokesa0e42962023-04-14 17:59:50 +0100220 .get_mut(..body_size)
221 .ok_or(Error::InvalidSize(total_size))?;
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100222
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000223 Ok(Self { body, bcc_range, dp_range })
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100224 }
225
226 /// Get slice containing the platform BCC.
Pierre-Clément Tosiefe780c2023-02-21 21:36:30 +0000227 pub fn get_entries(&mut self) -> (&mut [u8], Option<&mut [u8]>) {
228 let bcc_start = self.bcc_range.start;
229 let bcc_end = self.bcc_range.len();
230 let (_, rest) = self.body.split_at_mut(bcc_start);
231 let (bcc, rest) = rest.split_at_mut(bcc_end);
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100232
Pierre-Clément Tosiefe780c2023-02-21 21:36:30 +0000233 let dp = if let Some(dp_range) = &self.dp_range {
234 let dp_start = dp_range.start.checked_sub(self.bcc_range.end).unwrap();
235 let dp_end = dp_range.len();
236 let (_, rest) = rest.split_at_mut(dp_start);
237 let (dp, _) = rest.split_at_mut(dp_end);
238 Some(dp)
239 } else {
240 None
241 };
242
243 (bcc, dp)
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100244 }
245}