1 // Copyright 2023, 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 //! Struct and functions relating to well-known partition names. 16 17 use avb::IoError; 18 use core::ffi::CStr; 19 20 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] 21 pub(crate) enum PartitionName { 22 /// The default `PartitionName` is needed to build the default `HashDescriptor`. 23 #[default] 24 Kernel, 25 InitrdNormal, 26 InitrdDebug, 27 } 28 29 impl PartitionName { 30 const KERNEL_PARTITION_NAME: &'static [u8] = b"boot\0"; 31 const INITRD_NORMAL_PARTITION_NAME: &'static [u8] = b"initrd_normal\0"; 32 const INITRD_DEBUG_PARTITION_NAME: &'static [u8] = b"initrd_debug\0"; 33 as_cstr(&self) -> &CStr34 pub(crate) fn as_cstr(&self) -> &CStr { 35 CStr::from_bytes_with_nul(self.as_bytes()).unwrap() 36 } 37 as_non_null_terminated_bytes(&self) -> &[u8]38 fn as_non_null_terminated_bytes(&self) -> &[u8] { 39 let partition_name = self.as_bytes(); 40 &partition_name[..partition_name.len() - 1] 41 } 42 as_bytes(&self) -> &[u8]43 fn as_bytes(&self) -> &[u8] { 44 match self { 45 Self::Kernel => Self::KERNEL_PARTITION_NAME, 46 Self::InitrdNormal => Self::INITRD_NORMAL_PARTITION_NAME, 47 Self::InitrdDebug => Self::INITRD_DEBUG_PARTITION_NAME, 48 } 49 } 50 } 51 52 impl TryFrom<&CStr> for PartitionName { 53 type Error = IoError; 54 try_from(partition_name: &CStr) -> Result<Self, Self::Error>55 fn try_from(partition_name: &CStr) -> Result<Self, Self::Error> { 56 match partition_name.to_bytes_with_nul() { 57 Self::KERNEL_PARTITION_NAME => Ok(Self::Kernel), 58 Self::INITRD_NORMAL_PARTITION_NAME => Ok(Self::InitrdNormal), 59 Self::INITRD_DEBUG_PARTITION_NAME => Ok(Self::InitrdDebug), 60 _ => Err(IoError::NoSuchPartition), 61 } 62 } 63 } 64 65 impl TryFrom<&[u8]> for PartitionName { 66 type Error = IoError; 67 try_from(non_null_terminated_name: &[u8]) -> Result<Self, Self::Error>68 fn try_from(non_null_terminated_name: &[u8]) -> Result<Self, Self::Error> { 69 match non_null_terminated_name { 70 x if x == Self::Kernel.as_non_null_terminated_bytes() => Ok(Self::Kernel), 71 x if x == Self::InitrdNormal.as_non_null_terminated_bytes() => Ok(Self::InitrdNormal), 72 x if x == Self::InitrdDebug.as_non_null_terminated_bytes() => Ok(Self::InitrdDebug), 73 _ => Err(IoError::NoSuchPartition), 74 } 75 } 76 } 77