blob: 4b6f9d245c79ea98d1e76c09c0adca6ec8557c77 [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;
22
23#[repr(C, packed)]
24#[derive(Clone, Copy, Debug)]
25struct Header {
26 magic: u32,
27 version: u32,
28 total_size: u32,
29 flags: u32,
30 entries: [HeaderEntry; Entry::COUNT],
31}
32
33#[derive(Debug)]
34pub enum Error {
35 /// Reserved region can't fit configuration header.
36 BufferTooSmall,
37 /// Header doesn't contain the expect magic value.
38 InvalidMagic,
39 /// Version of the header isn't supported.
40 UnsupportedVersion(u16, u16),
41 /// Header sets flags incorrectly or uses reserved flags.
42 InvalidFlags(u32),
43 /// Header describes configuration data that doesn't fit in the expected buffer.
44 InvalidSize(usize),
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +000045 /// Header entry is missing.
46 MissingEntry(Entry),
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010047 /// Header entry is invalid.
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +000048 InvalidEntry(Entry, EntryError),
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010049}
50
51impl fmt::Display for Error {
52 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
53 match self {
54 Self::BufferTooSmall => write!(f, "Reserved region is smaller than config header"),
55 Self::InvalidMagic => write!(f, "Wrong magic number"),
56 Self::UnsupportedVersion(x, y) => write!(f, "Version {x}.{y} not supported"),
57 Self::InvalidFlags(v) => write!(f, "Flags value {v:#x} is incorrect or reserved"),
58 Self::InvalidSize(sz) => write!(f, "Total size ({sz:#x}) overflows reserved region"),
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +000059 Self::MissingEntry(entry) => write!(f, "Mandatory {entry:?} entry is missing"),
60 Self::InvalidEntry(entry, e) => write!(f, "Invalid {entry:?} entry: {e}"),
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010061 }
62 }
63}
64
65pub type Result<T> = result::Result<T, Error>;
66
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +000067#[derive(Debug)]
68pub enum EntryError {
69 /// Offset isn't between the fixed minimum value and size of configuration data.
70 InvalidOffset(usize),
71 /// Size must be zero when offset is and not be when it isn't.
72 InvalidSize(usize),
73 /// Entry isn't fully within the configuration data structure.
74 OutOfBounds { offset: usize, size: usize, limit: usize },
75}
76
77impl fmt::Display for EntryError {
78 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
79 match self {
80 Self::InvalidOffset(offset) => write!(f, "Invalid offset: {offset:#x?}"),
81 Self::InvalidSize(sz) => write!(f, "Invalid size: {sz:#x?}"),
82 Self::OutOfBounds { offset, size, limit } => {
83 let range = Header::PADDED_SIZE..*limit;
84 let entry = *offset..(*offset + *size);
85 write!(f, "Out of bounds: {entry:#x?} must be within range {range:#x?}")
86 }
87 }
88 }
89}
90
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +010091impl Header {
92 const MAGIC: u32 = u32::from_ne_bytes(*b"pvmf");
93 const PADDED_SIZE: usize =
94 helpers::unchecked_align_up(mem::size_of::<Self>(), mem::size_of::<u64>());
95
96 pub const fn version(major: u16, minor: u16) -> u32 {
97 ((major as u32) << 16) | (minor as u32)
98 }
99
100 pub const fn version_tuple(&self) -> (u16, u16) {
101 ((self.version >> 16) as u16, self.version as u16)
102 }
103
104 pub fn total_size(&self) -> usize {
105 self.total_size as usize
106 }
107
108 pub fn body_size(&self) -> usize {
109 self.total_size() - Self::PADDED_SIZE
110 }
111
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000112 fn get_body_range(&self, entry: Entry) -> Result<Option<Range<usize>>> {
113 let e = self.entries[entry as usize];
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +0000114 let offset = e.offset as usize;
115 let size = e.size as usize;
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000116
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +0000117 self._get_body_range(offset, size).map_err(|e| Error::InvalidEntry(entry, e))
118 }
119
120 fn _get_body_range(
121 &self,
122 offset: usize,
123 size: usize,
124 ) -> result::Result<Option<Range<usize>>, EntryError> {
125 match (offset, size) {
126 (0, 0) => Ok(None),
127 (0, size) | (_, size @ 0) => Err(EntryError::InvalidSize(size)),
128 _ => {
129 let start = offset
130 .checked_sub(Header::PADDED_SIZE)
131 .ok_or(EntryError::InvalidOffset(offset))?;
132 let end = start
133 .checked_add(size)
134 .filter(|x| *x <= self.body_size())
135 .ok_or(EntryError::OutOfBounds { offset, size, limit: self.total_size() })?;
136
137 Ok(Some(start..end))
138 }
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000139 }
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100140 }
141}
142
143#[derive(Clone, Copy, Debug)]
144pub enum Entry {
145 Bcc = 0,
146 DebugPolicy = 1,
147}
148
149impl Entry {
150 const COUNT: usize = 2;
151}
152
153#[repr(packed)]
154#[derive(Clone, Copy, Debug)]
155struct HeaderEntry {
156 offset: u32,
157 size: u32,
158}
159
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100160#[derive(Debug)]
161pub struct Config<'a> {
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100162 body: &'a mut [u8],
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000163 bcc_range: Range<usize>,
164 dp_range: Option<Range<usize>>,
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100165}
166
167impl<'a> Config<'a> {
168 /// Take ownership of a pvmfw configuration consisting of its header and following entries.
169 ///
170 /// SAFETY - 'data' should respect the alignment of Header.
171 pub unsafe fn new(data: &'a mut [u8]) -> Result<Self> {
172 let header = data.get(..Header::PADDED_SIZE).ok_or(Error::BufferTooSmall)?;
173
174 let header = &*(header.as_ptr() as *const Header);
175
176 if header.magic != Header::MAGIC {
177 return Err(Error::InvalidMagic);
178 }
179
180 if header.version != Header::version(1, 0) {
181 let (major, minor) = header.version_tuple();
182 return Err(Error::UnsupportedVersion(major, minor));
183 }
184
185 if header.flags != 0 {
186 return Err(Error::InvalidFlags(header.flags));
187 }
188
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000189 let bcc_range =
Pierre-Clément Tosi292e0992022-12-12 13:01:27 +0000190 header.get_body_range(Entry::Bcc)?.ok_or(Error::MissingEntry(Entry::Bcc))?;
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000191 let dp_range = header.get_body_range(Entry::DebugPolicy)?;
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100192
193 let body = data
194 .get_mut(Header::PADDED_SIZE..)
195 .ok_or(Error::BufferTooSmall)?
196 .get_mut(..header.body_size())
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000197 .ok_or_else(|| Error::InvalidSize(header.total_size()))?;
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100198
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000199 Ok(Self { body, bcc_range, dp_range })
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100200 }
201
202 /// Get slice containing the platform BCC.
203 pub fn get_bcc_mut(&mut self) -> &mut [u8] {
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000204 &mut self.body[self.bcc_range.clone()]
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100205 }
206
207 /// Get slice containing the platform debug policy.
208 pub fn get_debug_policy(&mut self) -> Option<&mut [u8]> {
Pierre-Clément Tosi71d7d5b2022-12-12 13:15:45 +0000209 self.dp_range.as_ref().map(|r| &mut self.body[r.clone()])
Pierre-Clément Tosi20b60962022-10-17 13:35:27 +0100210 }
211}