repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,411 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use super::ramfs::RamDirectory; +use super::*; + +use crate::error::SvsmError; +use crate::locking::SpinLock; + +use core::cmp::min; + +extern crate alloc; +use alloc::sync::Arc; +use alloc::vec::Vec; + +struct RawFileHandle { + file: Arc<dyn File>, + current: usize, +} + +impl RawFileHandle { + pub fn new(file: &Arc<dyn File>) -> Self { + RawFileHandle { + file: file.clone(), + current: 0, + } + } + + pub fn read(&mut self, buf: &mut [u8]) -> Result<usize, SvsmError> { + let result = self.file.read(buf, self.current); + if result.is_ok() { + self.current += result.unwrap(); + } + result + } + + pub fn write(&mut self, buf: &mut [u8]) -> Result<usize, SvsmError> { + let result = self.file.write(buf, self.current); + if result.is_ok() { + self.current += result.unwrap(); + } + result + } + + pub fn seek(&mut self, pos: usize) { + self.current = min(pos, self.file.size()); + } + + pub fn size(&self) -> usize { + self.file.size() + } +} + +pub struct FileHandle { + handle: SpinLock<RawFileHandle>, +} + +unsafe impl Sync for FileHandle {} + +impl FileHandle { + pub fn new(file: &Arc<dyn File>) -> Self { + FileHandle { + handle: SpinLock::new(RawFileHandle::new(file)), + } + } + + pub fn read(&self, buf: &mut [u8]) -> Result<usize, SvsmError> { + self.handle.lock().read(buf) + } + + pub fn write(&self, buf: &mut [u8]) -> Result<usize, SvsmError> { + self.handle.lock().write(buf) + } + + pub fn seek(&self, pos: usize) { + self.handle.lock().seek(pos); + } + + pub fn size(&self) -> usize { + self.handle.lock().size() + } +} + +struct SvsmFs { + root: Option<Arc<RamDirectory>>, +} + +unsafe impl Sync for SvsmFs {} + +impl SvsmFs { + pub const fn new() -> Self { + SvsmFs { root: None } + } + + pub fn initialize(&mut self, root: &Arc<RamDirectory>) { + assert!(!self.initialized()); + self.root = Some(root.clone()); + } + + #[cfg(test)] + pub fn uninitialize(&mut self) { + self.root = None; + } + + pub fn initialized(&self) -> bool { + self.root.is_some() + } + + pub fn root_dir(&self) -> Arc<dyn Directory> { + assert!(self.initialized()); + self.root.as_ref().unwrap().clone() + } +} + +static mut FS_ROOT: SvsmFs = SvsmFs::new(); + +pub fn initialize_fs() { + let root_dir = Arc::new(RamDirectory::new()); + unsafe { + FS_ROOT.initialize(&root_dir); + } +} + +#[cfg(test)] +fn uninitialize_fs() { + unsafe { + FS_ROOT.uninitialize(); + } +} + +fn split_path_allow_empty(path: &str) -> Vec<&str> { + let mut path_items: Vec<&str> = path.split('/').collect(); + path_items.retain(|x| x.len() > 0);
Filtering before collecting could reduce the initial allocation size. Something like: ```rust fn split_path_allow_empty(path: &str) -> Vec<&str> { path.split('/') .filter(|x| x.len() > 0) .collect() } ```
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -219,6 +219,19 @@ impl Directory for RamDirectory { Ok(new_dir) } + + fn unlink(&self, name: FileName) -> Result<(), SvsmError> { + let mut vec = self.entries.lock(); + let pos = vec.iter().position(|e| e.name == name); + + match pos { + Some(idx) => { + vec.remove(idx);
If we do not care about the order of entries the entry could be removed with `vec.swap_remove(idx)`, which is O(1).
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,223 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +extern crate alloc; +use super::*; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use crate::mm::{allocate_file_page_ref, PageRef}; +use crate::types::PAGE_SIZE; +use crate::utils::{page_align_up, page_offset}; + +use alloc::vec::Vec; +use core::cmp::{max, min}; + +struct RawRamFile { + capacity: usize, + size: usize, + pages: Vec<PageRef>, +} + +impl RawRamFile { + pub fn new() -> Self { + RawRamFile { + capacity: 0, + size: 0, + pages: Vec::new(), + } + } + + fn increase_capacity(&mut self) -> Result<(), SvsmError> { + let page_ref = allocate_file_page_ref()?; + self.pages.push(page_ref); + self.capacity += PAGE_SIZE; + Ok(()) + } + + fn set_capacity(&mut self, capacity: usize) -> Result<(), SvsmError> { + let cap = page_align_up(capacity); + + while cap > self.capacity { + self.increase_capacity()?; + } + + Ok(()) + } + + fn read_from_page(&mut self, buf: &mut [u8], offset: usize) { + let page_index = offset % PAGE_SIZE;
Maybe I'm missing something but this does not need to be `&mut self`, right?
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,223 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +extern crate alloc; +use super::*; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use crate::mm::{allocate_file_page_ref, PageRef}; +use crate::types::PAGE_SIZE; +use crate::utils::{page_align_up, page_offset}; + +use alloc::vec::Vec; +use core::cmp::{max, min}; + +struct RawRamFile { + capacity: usize, + size: usize, + pages: Vec<PageRef>, +} + +impl RawRamFile { + pub fn new() -> Self { + RawRamFile { + capacity: 0, + size: 0, + pages: Vec::new(), + } + } + + fn increase_capacity(&mut self) -> Result<(), SvsmError> { + let page_ref = allocate_file_page_ref()?; + self.pages.push(page_ref); + self.capacity += PAGE_SIZE; + Ok(()) + } + + fn set_capacity(&mut self, capacity: usize) -> Result<(), SvsmError> { + let cap = page_align_up(capacity); + + while cap > self.capacity { + self.increase_capacity()?; + } + + Ok(()) + } + + fn read_from_page(&mut self, buf: &mut [u8], offset: usize) { + let page_index = offset % PAGE_SIZE; + let index = offset / PAGE_SIZE; + let len = buf.len(); + let page_end = page_index + len; + + assert!(page_end <= PAGE_SIZE); + + let page_buf = self.pages[index].as_ref(); + buf.copy_from_slice(&page_buf[page_index..page_end]); + } + + fn write_to_page(&mut self, buf: &mut [u8], offset: usize) { + let page_index = offset % PAGE_SIZE; + let index = offset / PAGE_SIZE; + let len = buf.len(); + let page_end = page_index + len; + + assert!(page_end <= PAGE_SIZE); + + let page_buf = self.pages[index].as_ref(); + page_buf[page_index..page_end].copy_from_slice(buf); + } +} + +impl File for RawRamFile { + fn read(&mut self, buf: &mut [u8], offset: usize) -> Result<usize, SvsmError> { + let mut current = offset; + let mut len = buf.len(); + let mut bytes: usize = 0; + let mut buf_offset = 0; + + while len > 0 { + let page_end = min(page_align_up(current + 1), self.size); + let page_len = min(page_end - current, len);
If `current` is greater than `self.size` then `page_end - current` will overflow, which, as far as I know, causes a panic in debug builds. We should probably either check this and return an error, or use something like [`wrapping_sub()`](https://doc.rust-lang.org/std/primitive.u32.html#method.wrapping_sub).
svsm
github_2023
others
27
coconut-svsm
roy-hopkins
@@ -0,0 +1,411 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use super::ramfs::RamDirectory; +use super::*; + +use crate::error::SvsmError; +use crate::locking::SpinLock; + +use core::cmp::min; + +extern crate alloc; +use alloc::sync::Arc; +use alloc::vec::Vec; + +struct RawFileHandle { + file: Arc<dyn File>, + current: usize, +} + +impl RawFileHandle { + pub fn new(file: &Arc<dyn File>) -> Self { + RawFileHandle { + file: file.clone(), + current: 0, + } + } + + pub fn read(&mut self, buf: &mut [u8]) -> Result<usize, SvsmError> { + let result = self.file.read(buf, self.current); + if result.is_ok() { + self.current += result.unwrap(); + } + result + } + + pub fn write(&mut self, buf: &mut [u8]) -> Result<usize, SvsmError> { + let result = self.file.write(buf, self.current); + if result.is_ok() { + self.current += result.unwrap(); + } + result + } + + pub fn seek(&mut self, pos: usize) { + self.current = min(pos, self.file.size()); + } + + pub fn size(&self) -> usize { + self.file.size() + } +} + +pub struct FileHandle { + handle: SpinLock<RawFileHandle>, +} + +unsafe impl Sync for FileHandle {} + +impl FileHandle { + pub fn new(file: &Arc<dyn File>) -> Self { + FileHandle { + handle: SpinLock::new(RawFileHandle::new(file)), + } + } + + pub fn read(&self, buf: &mut [u8]) -> Result<usize, SvsmError> { + self.handle.lock().read(buf) + } + + pub fn write(&self, buf: &mut [u8]) -> Result<usize, SvsmError> { + self.handle.lock().write(buf) + } + + pub fn seek(&self, pos: usize) { + self.handle.lock().seek(pos); + } + + pub fn size(&self) -> usize { + self.handle.lock().size() + } +} + +struct SvsmFs { + root: Option<Arc<RamDirectory>>, +} + +unsafe impl Sync for SvsmFs {} + +impl SvsmFs { + pub const fn new() -> Self { + SvsmFs { root: None } + } + + pub fn initialize(&mut self, root: &Arc<RamDirectory>) { + assert!(!self.initialized()); + self.root = Some(root.clone()); + } + + #[cfg(test)] + pub fn uninitialize(&mut self) { + self.root = None; + } + + pub fn initialized(&self) -> bool { + self.root.is_some() + } + + pub fn root_dir(&self) -> Arc<dyn Directory> { + assert!(self.initialized()); + self.root.as_ref().unwrap().clone() + } +} + +static mut FS_ROOT: SvsmFs = SvsmFs::new(); + +pub fn initialize_fs() { + let root_dir = Arc::new(RamDirectory::new()); + unsafe { + FS_ROOT.initialize(&root_dir); + } +} + +#[cfg(test)] +fn uninitialize_fs() { + unsafe { + FS_ROOT.uninitialize(); + } +} + +fn split_path_allow_empty(path: &str) -> Vec<&str> { + let mut path_items: Vec<&str> = path.split('/').collect(); + path_items.retain(|x| x.len() > 0); + path_items +} + +fn split_path(path: &str) -> Result<Vec<&str>, SvsmError> { + let path_items = split_path_allow_empty(path); + + if path_items.is_empty() { + return Err(SvsmError::FileSystem(FsError::file_not_found())); + } + + Ok(path_items) +} + +fn walk_path(path_items: &Vec<&str>) -> Result<Arc<dyn Directory>, SvsmError> { + let mut current_dir = unsafe { FS_ROOT.root_dir() }; + + for item in path_items.iter() { + let dir_name = FileName::from(*item); + let dir_entry = current_dir.lookup_entry(dir_name)?; + current_dir = match dir_entry { + DirEntry::File(_) => return Err(SvsmError::FileSystem(FsError::file_not_found())), + DirEntry::Directory(dir) => dir, + }; + } + + Ok(current_dir) +} + +pub fn open(path: &str) -> Result<FileHandle, SvsmError> { + let mut path_items = split_path(path)?; + let file_name = FileName::from(path_items.pop().unwrap()); + let current_dir = walk_path(&path_items)?; + + let dir_entry = current_dir.lookup_entry(file_name)?; + + match dir_entry { + DirEntry::Directory(_) => Err(SvsmError::FileSystem(FsError::file_not_found())), + DirEntry::File(f) => Ok(FileHandle::new(&f)),
There is no check for existing file handles being opened against the same file meaning there could be concurrent changes to the file contents and size. Is that something that should be protected against?
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,89 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +extern crate alloc; +use alloc::sync::Arc; +use alloc::vec::Vec; + +use crate::error::SvsmError; +use crate::string::FixedString; + +/// Maximum supported length for a single filename +const MAX_FILENAME_LENGTH: usize = 64; +pub type FileName = FixedString<MAX_FILENAME_LENGTH>; + +#[derive(Copy, Clone, Debug)] +pub enum FsError { + FileExists, + FileNotFound, +} + +impl FsError { + pub fn file_exists() -> Self { + Self::FileExists + } + + pub fn file_not_found() -> Self { + Self::FileNotFound
Any particular reason we have these constructors? If not, just as a suggestion, we could probably get away with simply constructing the particular variant inline wherever needed.
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,95 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +extern crate alloc; +use alloc::sync::Arc; +use alloc::vec::Vec; + +use crate::error::SvsmError; +use crate::string::FixedString; + +/// Maximum supported length for a single filename +const MAX_FILENAME_LENGTH: usize = 64; +pub type FileName = FixedString<MAX_FILENAME_LENGTH>; + +#[derive(Copy, Clone, Debug)] +pub enum FsError { + Inval, + FileExists, + FileNotFound, +} + +macro_rules! impl_fs_err { + ($name:ident, $v:ident) => { + pub fn $name() -> Self { + Self::$v + } + }; +} + +impl FsError { + impl_fs_err!(inval, Inval); + impl_fs_err!(file_exists, FileExists); + impl_fs_err!(file_not_found, FileNotFound); +} + +pub trait File { + fn read(&self, buf: &mut [u8], offset: usize) -> Result<usize, SvsmError>; + fn write(&self, buf: &[u8], offset: usize) -> Result<usize, SvsmError>; + fn truncate(&self, size: usize) -> Result<usize, SvsmError>; + fn size(&self) -> usize; +} + +pub trait Directory { + fn list(&self) -> Vec<FileName>; + fn lookup_entry(&self, name: FileName) -> Result<DirEntry, SvsmError>; + fn create_file(&mut self, name: FileName) -> Result<Arc<dyn File>, SvsmError>; + fn create_directory(&mut self, name: FileName) -> Result<Arc<dyn Directory>, SvsmError>; +} + +pub enum DirEntry { + File(Arc<dyn File>), + Directory(Arc<dyn Directory>), +} + +impl DirEntry { + pub fn is_file(&self) -> bool { + match self { + DirEntry::File(_) => true, + _ => false, + } + }
This could be shortened to: ```rust pub fn is_file(&self) -> bool { matches!(self, Self::File(_)) } ``` Same for `is_dir()` below.
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,95 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +extern crate alloc; +use alloc::sync::Arc; +use alloc::vec::Vec; + +use crate::error::SvsmError; +use crate::string::FixedString; + +/// Maximum supported length for a single filename +const MAX_FILENAME_LENGTH: usize = 64; +pub type FileName = FixedString<MAX_FILENAME_LENGTH>; + +#[derive(Copy, Clone, Debug)] +pub enum FsError { + Inval, + FileExists, + FileNotFound, +} + +macro_rules! impl_fs_err { + ($name:ident, $v:ident) => { + pub fn $name() -> Self { + Self::$v + } + }; +} + +impl FsError { + impl_fs_err!(inval, Inval); + impl_fs_err!(file_exists, FileExists); + impl_fs_err!(file_not_found, FileNotFound); +} + +pub trait File { + fn read(&self, buf: &mut [u8], offset: usize) -> Result<usize, SvsmError>; + fn write(&self, buf: &[u8], offset: usize) -> Result<usize, SvsmError>; + fn truncate(&self, size: usize) -> Result<usize, SvsmError>; + fn size(&self) -> usize; +} + +pub trait Directory { + fn list(&self) -> Vec<FileName>; + fn lookup_entry(&self, name: FileName) -> Result<DirEntry, SvsmError>; + fn create_file(&mut self, name: FileName) -> Result<Arc<dyn File>, SvsmError>; + fn create_directory(&mut self, name: FileName) -> Result<Arc<dyn Directory>, SvsmError>; +} + +pub enum DirEntry { + File(Arc<dyn File>), + Directory(Arc<dyn Directory>), +} + +impl DirEntry { + pub fn is_file(&self) -> bool { + match self { + DirEntry::File(_) => true, + _ => false, + } + } + + pub fn is_dir(&self) -> bool { + match self { + DirEntry::Directory(_) => true, + _ => false, + } + } +} + +impl Clone for DirEntry { + fn clone(&self) -> Self { + match self { + DirEntry::File(f) => DirEntry::File(f.clone()), + DirEntry::Directory(d) => DirEntry::Directory(d.clone()), + } + } +} + +pub struct DirectoryEntry { + pub name: FileName, + pub entry: DirEntry, +} + +impl DirectoryEntry { + pub fn new(name: FileName, entry: DirEntry) -> Self { + DirectoryEntry { + name: name, + entry: entry,
Field names can be omitted here (clippy will complain)
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,258 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +extern crate alloc; +use super::*; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use crate::mm::{allocate_file_page_ref, PageRef}; +use crate::types::PAGE_SIZE; +use crate::utils::{page_align_up, page_offset}; + +use alloc::vec::Vec; +use core::cmp::{max, min}; + +struct RawRamFile { + capacity: usize, + size: usize, + pages: Vec<PageRef>, +} + +impl RawRamFile { + pub fn new() -> Self { + RawRamFile { + capacity: 0, + size: 0, + pages: Vec::new(), + } + } + + fn increase_capacity(&mut self) -> Result<(), SvsmError> { + let page_ref = allocate_file_page_ref()?; + self.pages.push(page_ref); + self.capacity += PAGE_SIZE; + Ok(()) + } + + fn set_capacity(&mut self, capacity: usize) -> Result<(), SvsmError> { + let cap = page_align_up(capacity); + + while cap > self.capacity { + self.increase_capacity()?; + } + + Ok(()) + } + + fn read_from_page(&self, buf: &mut [u8], offset: usize) { + let page_index = page_offset(offset); + let index = offset / PAGE_SIZE; + let len = buf.len(); + let page_end = page_index + len; + + assert!(page_end <= PAGE_SIZE); + + let page_buf = self.pages[index].as_ref(); + buf.copy_from_slice(&page_buf[page_index..page_end]); + } + + fn write_to_page(&mut self, buf: &[u8], offset: usize) { + let page_index = page_offset(offset); + let index = offset / PAGE_SIZE; + let len = buf.len(); + let page_end = page_index + len; + + assert!(page_end <= PAGE_SIZE); + + let page_buf = self.pages[index].as_mut_ref(); + page_buf[page_index..page_end].copy_from_slice(buf); + } + + fn read(&self, buf: &mut [u8], offset: usize) -> Result<usize, SvsmError> { + let mut current = min(offset, self.size); + let mut len = buf.len(); + let mut bytes: usize = 0; + let mut buf_offset = 0; + + while len > 0 { + let page_end = min(page_align_up(current + 1), self.size); + let page_len = min(page_end - current, len); + let buf_end = buf_offset + page_len; + + if page_len == 0 { + break; + } + + self.read_from_page(&mut buf[buf_offset..buf_end], current); + + buf_offset = buf_end; + current += page_len; + len -= page_len; + bytes += page_len; + } + + Ok(bytes) + } + + fn write(&mut self, buf: &[u8], offset: usize) -> Result<usize, SvsmError> { + let mut current = offset; + let mut bytes: usize = 0; + let mut len = buf.len(); + let mut buf_offset: usize = 0; + + self.set_capacity(offset + len)?;
This addition could overflow if the caller supplies a big enough offset. Perhaps we could use `checked_add` to harden it against these edge cases: ```rust let capacity = offset.checked_add(len) .ok_or(SvsmError::FileSystem(FsError::inval()))?; self.set_capacity(capacity)?; ```
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,258 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +extern crate alloc; +use super::*; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use crate::mm::{allocate_file_page_ref, PageRef}; +use crate::types::PAGE_SIZE; +use crate::utils::{page_align_up, page_offset}; + +use alloc::vec::Vec; +use core::cmp::{max, min}; + +struct RawRamFile { + capacity: usize, + size: usize, + pages: Vec<PageRef>, +} + +impl RawRamFile { + pub fn new() -> Self { + RawRamFile { + capacity: 0, + size: 0, + pages: Vec::new(), + } + } + + fn increase_capacity(&mut self) -> Result<(), SvsmError> { + let page_ref = allocate_file_page_ref()?; + self.pages.push(page_ref); + self.capacity += PAGE_SIZE; + Ok(()) + } + + fn set_capacity(&mut self, capacity: usize) -> Result<(), SvsmError> { + let cap = page_align_up(capacity); + + while cap > self.capacity { + self.increase_capacity()?; + } + + Ok(()) + } + + fn read_from_page(&self, buf: &mut [u8], offset: usize) { + let page_index = page_offset(offset); + let index = offset / PAGE_SIZE; + let len = buf.len(); + let page_end = page_index + len; + + assert!(page_end <= PAGE_SIZE); + + let page_buf = self.pages[index].as_ref(); + buf.copy_from_slice(&page_buf[page_index..page_end]); + } + + fn write_to_page(&mut self, buf: &[u8], offset: usize) { + let page_index = page_offset(offset); + let index = offset / PAGE_SIZE; + let len = buf.len(); + let page_end = page_index + len; + + assert!(page_end <= PAGE_SIZE); + + let page_buf = self.pages[index].as_mut_ref(); + page_buf[page_index..page_end].copy_from_slice(buf); + } + + fn read(&self, buf: &mut [u8], offset: usize) -> Result<usize, SvsmError> { + let mut current = min(offset, self.size); + let mut len = buf.len(); + let mut bytes: usize = 0; + let mut buf_offset = 0; + + while len > 0 { + let page_end = min(page_align_up(current + 1), self.size); + let page_len = min(page_end - current, len); + let buf_end = buf_offset + page_len; + + if page_len == 0 { + break; + } + + self.read_from_page(&mut buf[buf_offset..buf_end], current); + + buf_offset = buf_end; + current += page_len; + len -= page_len; + bytes += page_len; + } + + Ok(bytes) + } + + fn write(&mut self, buf: &[u8], offset: usize) -> Result<usize, SvsmError> { + let mut current = offset; + let mut bytes: usize = 0; + let mut len = buf.len(); + let mut buf_offset: usize = 0; + + self.set_capacity(offset + len)?; + + while len > 0 { + let page_len = min(PAGE_SIZE - page_offset(current), len); + let buf_end = buf_offset + page_len; + + self.write_to_page(&buf[buf_offset..buf_end], current); + self.size = max(self.size, current + page_len);
Same here, `current + page_len` could overflow with a big enough offset.
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,174 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{Address, PhysAddr}; +use crate::error::SvsmError; +use crate::mm::ptguards::PerCPUPageMappingGuard; + +use super::*; + +extern crate alloc; +use alloc::slice; +use alloc::string::String; +use alloc::vec::Vec; + +const PACKIT_MAGIC: [u8; 4] = [0x50, 0x4b, 0x49, 0x54]; + +struct PackItHeader { + /// Header Magic (PKIT) + magic: [u8; 4], + /// Header Size + header_size: u32, +} + +impl PackItHeader { + pub const fn new() -> Self {
Since this structure is not pub, its methods don't need to be pub either. pub only affects visibility at the module level.
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,174 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{Address, PhysAddr}; +use crate::error::SvsmError; +use crate::mm::ptguards::PerCPUPageMappingGuard; + +use super::*; + +extern crate alloc; +use alloc::slice; +use alloc::string::String; +use alloc::vec::Vec; + +const PACKIT_MAGIC: [u8; 4] = [0x50, 0x4b, 0x49, 0x54]; + +struct PackItHeader { + /// Header Magic (PKIT) + magic: [u8; 4], + /// Header Size + header_size: u32, +} + +impl PackItHeader { + pub const fn new() -> Self { + PackItHeader { + magic: [0; 4], + header_size: 8, + } + } + + pub fn load(buf: &[u8]) -> Self { + if buf.len() < 8 { + return PackItHeader::new(); + } + + let mut hdr = PackItHeader::new(); + hdr.magic.copy_from_slice(&buf[0..4]); + hdr.header_size = u32::from_le_bytes(buf[4..8].try_into().unwrap()); + + hdr + } + + pub fn check_magic(&self) -> bool { + self.magic == PACKIT_MAGIC + }
We should probably replace the `unwrap()` after `try_into()` with a returned SvsmError. On top of that, we could also check the magic bytes at the end of `load()`, returning an error if they do not match.
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,174 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{Address, PhysAddr}; +use crate::error::SvsmError; +use crate::mm::ptguards::PerCPUPageMappingGuard; + +use super::*; + +extern crate alloc; +use alloc::slice; +use alloc::string::String; +use alloc::vec::Vec; + +const PACKIT_MAGIC: [u8; 4] = [0x50, 0x4b, 0x49, 0x54]; + +struct PackItHeader { + /// Header Magic (PKIT) + magic: [u8; 4], + /// Header Size + header_size: u32, +} + +impl PackItHeader { + pub const fn new() -> Self { + PackItHeader { + magic: [0; 4], + header_size: 8, + } + } + + pub fn load(buf: &[u8]) -> Self { + if buf.len() < 8 { + return PackItHeader::new(); + } + + let mut hdr = PackItHeader::new(); + hdr.magic.copy_from_slice(&buf[0..4]); + hdr.header_size = u32::from_le_bytes(buf[4..8].try_into().unwrap()); + + hdr + } + + pub fn check_magic(&self) -> bool { + self.magic == PACKIT_MAGIC + } + + pub fn len(&self) -> usize { + self.header_size as usize + } +} + +struct FileHeader { + hdr_type: u16, + name_len: u16, + file_size: u64, + name: String, +} + +impl FileHeader { + pub const fn new() -> Self { + FileHeader { + hdr_type: 0, + name_len: 0, + file_size: 0, + name: String::new(), + } + } + + pub fn load(buf: &[u8]) -> Self { + if buf.len() < 12 { + return FileHeader::new(); + } + let hdr_type = u16::from_le_bytes(buf[0..2].try_into().unwrap()); + let name_len = u16::from_le_bytes(buf[2..4].try_into().unwrap()); + let file_size = u64::from_le_bytes(buf[4..12].try_into().unwrap()); + + let header_len: usize = (12 + name_len).into(); + + if buf.len() < header_len { + return FileHeader::new(); + } + + let result = String::from_utf8(Vec::from(&buf[12..header_len])); + if result.is_err() { + return FileHeader::new(); + } + + FileHeader { + hdr_type, + name_len, + file_size, + name: result.unwrap(), + } + } + + pub fn valid(&self) -> bool { + self.hdr_type == 1 && self.name_len > 0 + }
Same here. Since this function can fail in multiple places, perhaps we could return a `Result<Self, SvsmError>`. As before, we could move the check in `valid()` to this function.
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,174 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{Address, PhysAddr}; +use crate::error::SvsmError; +use crate::mm::ptguards::PerCPUPageMappingGuard; + +use super::*; + +extern crate alloc; +use alloc::slice; +use alloc::string::String; +use alloc::vec::Vec; + +const PACKIT_MAGIC: [u8; 4] = [0x50, 0x4b, 0x49, 0x54]; + +struct PackItHeader { + /// Header Magic (PKIT) + magic: [u8; 4], + /// Header Size + header_size: u32, +} + +impl PackItHeader { + pub const fn new() -> Self { + PackItHeader { + magic: [0; 4], + header_size: 8, + } + } + + pub fn load(buf: &[u8]) -> Self { + if buf.len() < 8 { + return PackItHeader::new(); + } + + let mut hdr = PackItHeader::new(); + hdr.magic.copy_from_slice(&buf[0..4]); + hdr.header_size = u32::from_le_bytes(buf[4..8].try_into().unwrap()); + + hdr + } + + pub fn check_magic(&self) -> bool { + self.magic == PACKIT_MAGIC + } + + pub fn len(&self) -> usize { + self.header_size as usize + } +} + +struct FileHeader { + hdr_type: u16, + name_len: u16, + file_size: u64, + name: String, +} + +impl FileHeader { + pub const fn new() -> Self { + FileHeader { + hdr_type: 0, + name_len: 0, + file_size: 0, + name: String::new(), + } + } + + pub fn load(buf: &[u8]) -> Self { + if buf.len() < 12 { + return FileHeader::new(); + } + let hdr_type = u16::from_le_bytes(buf[0..2].try_into().unwrap()); + let name_len = u16::from_le_bytes(buf[2..4].try_into().unwrap()); + let file_size = u64::from_le_bytes(buf[4..12].try_into().unwrap()); + + let header_len: usize = (12 + name_len).into(); + + if buf.len() < header_len { + return FileHeader::new(); + } + + let result = String::from_utf8(Vec::from(&buf[12..header_len])); + if result.is_err() { + return FileHeader::new(); + } + + FileHeader { + hdr_type, + name_len, + file_size, + name: result.unwrap(), + }
We can remove the unwrap with `let-else` syntax: ```rust let Ok(name) = String::from_utf8(Vec::from(&buf[12..header_len])) else { return FileHeader::new(); }; FileHeader { hdr_type, name_len, file_size, name } ```
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,174 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{Address, PhysAddr}; +use crate::error::SvsmError; +use crate::mm::ptguards::PerCPUPageMappingGuard; + +use super::*; + +extern crate alloc; +use alloc::slice; +use alloc::string::String; +use alloc::vec::Vec; + +const PACKIT_MAGIC: [u8; 4] = [0x50, 0x4b, 0x49, 0x54]; + +struct PackItHeader { + /// Header Magic (PKIT) + magic: [u8; 4], + /// Header Size + header_size: u32, +} + +impl PackItHeader { + pub const fn new() -> Self { + PackItHeader { + magic: [0; 4], + header_size: 8, + } + } + + pub fn load(buf: &[u8]) -> Self { + if buf.len() < 8 { + return PackItHeader::new(); + } + + let mut hdr = PackItHeader::new(); + hdr.magic.copy_from_slice(&buf[0..4]); + hdr.header_size = u32::from_le_bytes(buf[4..8].try_into().unwrap()); + + hdr + } + + pub fn check_magic(&self) -> bool { + self.magic == PACKIT_MAGIC + } + + pub fn len(&self) -> usize { + self.header_size as usize + } +} + +struct FileHeader { + hdr_type: u16, + name_len: u16, + file_size: u64, + name: String, +} + +impl FileHeader { + pub const fn new() -> Self { + FileHeader { + hdr_type: 0, + name_len: 0, + file_size: 0, + name: String::new(), + } + } + + pub fn load(buf: &[u8]) -> Self { + if buf.len() < 12 { + return FileHeader::new(); + } + let hdr_type = u16::from_le_bytes(buf[0..2].try_into().unwrap()); + let name_len = u16::from_le_bytes(buf[2..4].try_into().unwrap()); + let file_size = u64::from_le_bytes(buf[4..12].try_into().unwrap()); + + let header_len: usize = (12 + name_len).into(); + + if buf.len() < header_len { + return FileHeader::new(); + } + + let result = String::from_utf8(Vec::from(&buf[12..header_len])); + if result.is_err() { + return FileHeader::new(); + } + + FileHeader { + hdr_type, + name_len, + file_size, + name: result.unwrap(), + } + } + + pub fn valid(&self) -> bool { + self.hdr_type == 1 && self.name_len > 0 + } + + pub fn file_name(&self) -> &String {
Returning `&str` here is a bit more conventional.
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,174 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{Address, PhysAddr}; +use crate::error::SvsmError; +use crate::mm::ptguards::PerCPUPageMappingGuard; + +use super::*; + +extern crate alloc; +use alloc::slice; +use alloc::string::String; +use alloc::vec::Vec; + +const PACKIT_MAGIC: [u8; 4] = [0x50, 0x4b, 0x49, 0x54]; + +struct PackItHeader { + /// Header Magic (PKIT) + magic: [u8; 4], + /// Header Size + header_size: u32, +} + +impl PackItHeader { + pub const fn new() -> Self { + PackItHeader { + magic: [0; 4], + header_size: 8, + } + } + + pub fn load(buf: &[u8]) -> Self { + if buf.len() < 8 { + return PackItHeader::new(); + } + + let mut hdr = PackItHeader::new(); + hdr.magic.copy_from_slice(&buf[0..4]); + hdr.header_size = u32::from_le_bytes(buf[4..8].try_into().unwrap()); + + hdr + } + + pub fn check_magic(&self) -> bool { + self.magic == PACKIT_MAGIC + } + + pub fn len(&self) -> usize { + self.header_size as usize + } +} + +struct FileHeader { + hdr_type: u16, + name_len: u16, + file_size: u64, + name: String, +} + +impl FileHeader { + pub const fn new() -> Self { + FileHeader { + hdr_type: 0, + name_len: 0, + file_size: 0, + name: String::new(), + } + } + + pub fn load(buf: &[u8]) -> Self { + if buf.len() < 12 { + return FileHeader::new(); + } + let hdr_type = u16::from_le_bytes(buf[0..2].try_into().unwrap()); + let name_len = u16::from_le_bytes(buf[2..4].try_into().unwrap()); + let file_size = u64::from_le_bytes(buf[4..12].try_into().unwrap()); + + let header_len: usize = (12 + name_len).into(); + + if buf.len() < header_len { + return FileHeader::new(); + } + + let result = String::from_utf8(Vec::from(&buf[12..header_len])); + if result.is_err() { + return FileHeader::new(); + } + + FileHeader { + hdr_type, + name_len, + file_size, + name: result.unwrap(), + } + } + + pub fn valid(&self) -> bool { + self.hdr_type == 1 && self.name_len > 0 + } + + pub fn file_name(&self) -> &String { + &self.name + } + + pub fn file_size(&self) -> usize { + let size: usize = self.file_size.try_into().unwrap(); + size + } + + pub fn header_size(&self) -> usize { + let len: usize = self.name_len.into(); + 12usize + len + } + + pub fn total_size(&self) -> usize { + self.file_size() + self.header_size() + } +} + +pub fn populate_ram_fs(kernel_fs_start: u64, kernel_fs_end: u64) -> Result<(), SvsmError> { + assert!(kernel_fs_end >= kernel_fs_start); + + let pstart = PhysAddr::from(kernel_fs_start); + let pend = PhysAddr::from(kernel_fs_end); + let size = pend - pstart; + + if size == 0 { + return Ok(()); + } + + log::info!("Unpacking FS archive..."); + + let guard = PerCPUPageMappingGuard::create(pstart.page_align(), pend.page_align_up(), 0) + .expect("Failed to map FS archive");
This is fine, but we could also use the question mark operator.
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,174 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{Address, PhysAddr}; +use crate::error::SvsmError; +use crate::mm::ptguards::PerCPUPageMappingGuard; + +use super::*; + +extern crate alloc; +use alloc::slice; +use alloc::string::String; +use alloc::vec::Vec; + +const PACKIT_MAGIC: [u8; 4] = [0x50, 0x4b, 0x49, 0x54]; + +struct PackItHeader { + /// Header Magic (PKIT) + magic: [u8; 4], + /// Header Size + header_size: u32, +} + +impl PackItHeader { + pub const fn new() -> Self { + PackItHeader { + magic: [0; 4], + header_size: 8, + } + } + + pub fn load(buf: &[u8]) -> Self { + if buf.len() < 8 { + return PackItHeader::new(); + } + + let mut hdr = PackItHeader::new(); + hdr.magic.copy_from_slice(&buf[0..4]); + hdr.header_size = u32::from_le_bytes(buf[4..8].try_into().unwrap()); + + hdr + } + + pub fn check_magic(&self) -> bool { + self.magic == PACKIT_MAGIC + } + + pub fn len(&self) -> usize { + self.header_size as usize + } +} + +struct FileHeader { + hdr_type: u16, + name_len: u16, + file_size: u64, + name: String, +} + +impl FileHeader { + pub const fn new() -> Self { + FileHeader { + hdr_type: 0, + name_len: 0, + file_size: 0, + name: String::new(), + } + } + + pub fn load(buf: &[u8]) -> Self { + if buf.len() < 12 { + return FileHeader::new(); + } + let hdr_type = u16::from_le_bytes(buf[0..2].try_into().unwrap()); + let name_len = u16::from_le_bytes(buf[2..4].try_into().unwrap()); + let file_size = u64::from_le_bytes(buf[4..12].try_into().unwrap()); + + let header_len: usize = (12 + name_len).into(); + + if buf.len() < header_len { + return FileHeader::new(); + } + + let result = String::from_utf8(Vec::from(&buf[12..header_len])); + if result.is_err() { + return FileHeader::new(); + } + + FileHeader { + hdr_type, + name_len, + file_size, + name: result.unwrap(), + } + } + + pub fn valid(&self) -> bool { + self.hdr_type == 1 && self.name_len > 0 + } + + pub fn file_name(&self) -> &String { + &self.name + } + + pub fn file_size(&self) -> usize { + let size: usize = self.file_size.try_into().unwrap(); + size + } + + pub fn header_size(&self) -> usize { + let len: usize = self.name_len.into(); + 12usize + len + } + + pub fn total_size(&self) -> usize { + self.file_size() + self.header_size() + } +} + +pub fn populate_ram_fs(kernel_fs_start: u64, kernel_fs_end: u64) -> Result<(), SvsmError> { + assert!(kernel_fs_end >= kernel_fs_start); + + let pstart = PhysAddr::from(kernel_fs_start); + let pend = PhysAddr::from(kernel_fs_end); + let size = pend - pstart; + + if size == 0 { + return Ok(()); + } + + log::info!("Unpacking FS archive..."); + + let guard = PerCPUPageMappingGuard::create(pstart.page_align(), pend.page_align_up(), 0) + .expect("Failed to map FS archive"); + let vstart = guard.virt_addr().offset(pstart.page_offset()); + + let data: &[u8] = unsafe { slice::from_raw_parts(vstart.as_ptr(), size) }; + let hdr = PackItHeader::load(data); + + if !hdr.check_magic() { + log::error!("Unexpected header in FS archive"); + return Err(SvsmError::FileSystem(FsError::inval())); + } + + let mut current = hdr.len(); + while current < size { + let fh = FileHeader::load(&data[current..]); + if !fh.valid() { + log::error!("Invalid data in FS archive"); + return Err(SvsmError::FileSystem(FsError::inval())); + } + + let start = current + fh.header_size(); + let end = start + fh.file_size();
These look dangerous to me, especially the second one, for two reasons: they could go out of bounds in `data`, and they could overflow when adding them. `current` comes from `PackItHeader::len()`, which returns `PackItHeader::header_size`, which is never validated (although it is bounded by `size` in this loop). `FileHeader::file_size()` returns `FileHeader::file_size + 12`, which is also not validated. We should use a [safe slicing method](https://doc.rust-lang.org/std/primitive.slice.html#method.get) when using these values below, e.g.: ```rust let file_data = data.get(start..end) .ok_or(SvsmError::FileSystem(FsError::inval()))?; let written = file.write(file_data)?; ``` This would at least ensure that we do not go out of bounds, avoiding a panic. The values could still accidentally overflow I suspect, panicking in debug builds. If we want to be extra careful, we could use `checked_add`, e.g.: ```rust let start = current.checked_add(fh.header_size()) .ok_or(SvsmError::FileSystem(FsError::inval()))?; let end = start.checked_add(fh.file_size()) .ok_or(SvsmError::FileSystem(FsError::inval()))?; ``` Take these with a grain of salt, I have not tested whether they can actually overflow.
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,174 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{Address, PhysAddr}; +use crate::error::SvsmError; +use crate::mm::ptguards::PerCPUPageMappingGuard; + +use super::*; + +extern crate alloc; +use alloc::slice; +use alloc::string::String; +use alloc::vec::Vec; + +const PACKIT_MAGIC: [u8; 4] = [0x50, 0x4b, 0x49, 0x54]; + +struct PackItHeader { + /// Header Magic (PKIT) + magic: [u8; 4], + /// Header Size + header_size: u32, +} + +impl PackItHeader { + pub const fn new() -> Self { + PackItHeader { + magic: [0; 4], + header_size: 8, + } + } + + pub fn load(buf: &[u8]) -> Self { + if buf.len() < 8 { + return PackItHeader::new(); + } + + let mut hdr = PackItHeader::new(); + hdr.magic.copy_from_slice(&buf[0..4]); + hdr.header_size = u32::from_le_bytes(buf[4..8].try_into().unwrap()); + + hdr + } + + pub fn check_magic(&self) -> bool { + self.magic == PACKIT_MAGIC + } + + pub fn len(&self) -> usize { + self.header_size as usize + } +} + +struct FileHeader { + hdr_type: u16, + name_len: u16, + file_size: u64, + name: String, +} + +impl FileHeader { + pub const fn new() -> Self { + FileHeader { + hdr_type: 0, + name_len: 0, + file_size: 0, + name: String::new(), + } + } + + pub fn load(buf: &[u8]) -> Self { + if buf.len() < 12 { + return FileHeader::new(); + } + let hdr_type = u16::from_le_bytes(buf[0..2].try_into().unwrap()); + let name_len = u16::from_le_bytes(buf[2..4].try_into().unwrap()); + let file_size = u64::from_le_bytes(buf[4..12].try_into().unwrap()); + + let header_len: usize = (12 + name_len).into();
This can also overflow, since the addition is done before the conversion to `usize`.
svsm
github_2023
others
27
coconut-svsm
osteffenrh
@@ -0,0 +1,263 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +extern crate alloc; +use super::*; +use crate::error::SvsmError; +use crate::locking::RWLock; +use crate::mm::{allocate_file_page_ref, PageRef}; +use crate::types::PAGE_SIZE; +use crate::utils::{page_align_up, page_offset}; + +use alloc::vec::Vec; +use core::cmp::{max, min}; + +struct RawRamFile { + capacity: usize, + size: usize, + pages: Vec<PageRef>, +} + +impl RawRamFile { + pub fn new() -> Self { + RawRamFile { + capacity: 0, + size: 0, + pages: Vec::new(), + } + } + + fn increase_capacity(&mut self) -> Result<(), SvsmError> { + let page_ref = allocate_file_page_ref()?; + self.pages.push(page_ref); + self.capacity += PAGE_SIZE; + Ok(()) + } + + fn set_capacity(&mut self, capacity: usize) -> Result<(), SvsmError> { + let cap = page_align_up(capacity); + + while cap > self.capacity { + self.increase_capacity()?; + } + + Ok(()) + } + + fn read_from_page(&self, buf: &mut [u8], offset: usize) { + let page_index = page_offset(offset); + let index = offset / PAGE_SIZE; + let len = buf.len(); + let page_end = page_index + len; + + assert!(page_end <= PAGE_SIZE); + + let page_buf = self.pages[index].as_ref(); + buf.copy_from_slice(&page_buf[page_index..page_end]); + } + + fn write_to_page(&mut self, buf: &[u8], offset: usize) { + let page_index = page_offset(offset); + let index = offset / PAGE_SIZE; + let len = buf.len(); + let page_end = page_index + len; + + assert!(page_end <= PAGE_SIZE); + + let page_buf = self.pages[index].as_mut_ref(); + page_buf[page_index..page_end].copy_from_slice(buf); + } + + fn read(&self, buf: &mut [u8], offset: usize) -> Result<usize, SvsmError> { + let mut current = min(offset, self.size); + let mut len = buf.len(); + let mut bytes: usize = 0; + let mut buf_offset = 0; + + while len > 0 { + let page_end = min(page_align_up(current + 1), self.size); + let page_len = min(page_end - current, len); + let buf_end = buf_offset + page_len; + + if page_len == 0 { + break; + } + + self.read_from_page(&mut buf[buf_offset..buf_end], current); + + buf_offset = buf_end; + current += page_len; + len -= page_len; + bytes += page_len; + } + + Ok(bytes) + } + + fn write(&mut self, buf: &[u8], offset: usize) -> Result<usize, SvsmError> { + let mut current = offset; + let mut bytes: usize = 0; + let mut len = buf.len(); + let mut buf_offset: usize = 0; + let capacity = offset + .checked_add(len) + .ok_or(SvsmError::FileSystem(FsError::inval()))?; + + self.set_capacity(capacity)?; + + while len > 0 { + let page_len = min(PAGE_SIZE - page_offset(current), len); + let buf_end = buf_offset + page_len; + + self.write_to_page(&buf[buf_offset..buf_end], current); + self.size = max(self.size, current + page_len); + + current += page_len; + buf_offset += page_len; + len -= page_len; + bytes += page_len; + } + + Ok(bytes) + } + + fn truncate(&mut self, size: usize) -> Result<usize, SvsmError> { + if size > self.size { + return Err(SvsmError::FileSystem(FsError::inval())); + } + + let base_pages = size / PAGE_SIZE; + let new_pages = if page_offset(size) > 0 { + base_pages + 1 + } else { + base_pages + }; + + while self.pages.len() > new_pages { + self.pages.pop(); + } + self.capacity = new_pages * PAGE_SIZE; + self.size = size; + + Ok(size) + } + + fn size(&self) -> usize { + self.size + } +} + +pub struct RamFile { + rawfile: RWLock<RawRamFile>, +} + +unsafe impl Sync for RamFile {} + +impl RamFile { + #[allow(dead_code)] + pub fn new() -> Self { + RamFile { + rawfile: RWLock::new(RawRamFile::new()), + } + } +} + +impl File for RamFile { + fn read(&self, buf: &mut [u8], offset: usize) -> Result<usize, SvsmError> { + self.rawfile.lock_read().read(buf, offset) + } + + fn write(&self, buf: &[u8], offset: usize) -> Result<usize, SvsmError> { + self.rawfile.lock_write().write(buf, offset) + } + + fn truncate(&self, size: usize) -> Result<usize, SvsmError> { + self.rawfile.lock_write().truncate(size) + } + + fn size(&self) -> usize { + self.rawfile.lock_read().size() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::mm::alloc::{destroy_test_root_mem, setup_test_root_mem, DEFAULT_TEST_MEMORY_SIZE}; + + #[test] + fn test_ramfs_file_read_write() { + let test_mem_lock = setup_test_root_mem(DEFAULT_TEST_MEMORY_SIZE); + + let file = RamFile::new(); + let mut buf1 = [0xffu8; 512]; + + // Write first buffer at offset 0 + file.write(&mut buf1, 0).expect("Failed to write file data"); + assert!(file.size() == 512); + + // Write second buffer at offset 4096 - 256 - cross-page write + let mut buf2 = [0xaau8; 512]; + file.write(&mut buf2, PAGE_SIZE - 256) + .expect("Failed to write file cross-page"); + assert!(file.size() == PAGE_SIZE + 256); + + // Read back and check first buffer + let size = file + .read(&mut buf1, 0)
I would zero `buf1` before reading into it, to make sure it does not already contain the data we are looking for.
svsm
github_2023
others
27
coconut-svsm
osteffenrh
@@ -0,0 +1,263 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +extern crate alloc; +use super::*; +use crate::error::SvsmError; +use crate::locking::RWLock; +use crate::mm::{allocate_file_page_ref, PageRef}; +use crate::types::PAGE_SIZE; +use crate::utils::{page_align_up, page_offset}; + +use alloc::vec::Vec; +use core::cmp::{max, min}; + +struct RawRamFile { + capacity: usize, + size: usize, + pages: Vec<PageRef>, +} + +impl RawRamFile { + pub fn new() -> Self { + RawRamFile { + capacity: 0, + size: 0, + pages: Vec::new(), + } + } + + fn increase_capacity(&mut self) -> Result<(), SvsmError> { + let page_ref = allocate_file_page_ref()?; + self.pages.push(page_ref); + self.capacity += PAGE_SIZE; + Ok(()) + } + + fn set_capacity(&mut self, capacity: usize) -> Result<(), SvsmError> { + let cap = page_align_up(capacity); + + while cap > self.capacity { + self.increase_capacity()?; + } + + Ok(()) + } + + fn read_from_page(&self, buf: &mut [u8], offset: usize) { + let page_index = page_offset(offset); + let index = offset / PAGE_SIZE; + let len = buf.len(); + let page_end = page_index + len; + + assert!(page_end <= PAGE_SIZE); + + let page_buf = self.pages[index].as_ref(); + buf.copy_from_slice(&page_buf[page_index..page_end]); + } + + fn write_to_page(&mut self, buf: &[u8], offset: usize) { + let page_index = page_offset(offset); + let index = offset / PAGE_SIZE; + let len = buf.len(); + let page_end = page_index + len; + + assert!(page_end <= PAGE_SIZE); + + let page_buf = self.pages[index].as_mut_ref(); + page_buf[page_index..page_end].copy_from_slice(buf); + } + + fn read(&self, buf: &mut [u8], offset: usize) -> Result<usize, SvsmError> { + let mut current = min(offset, self.size); + let mut len = buf.len(); + let mut bytes: usize = 0; + let mut buf_offset = 0; + + while len > 0 { + let page_end = min(page_align_up(current + 1), self.size); + let page_len = min(page_end - current, len); + let buf_end = buf_offset + page_len; + + if page_len == 0 { + break; + } + + self.read_from_page(&mut buf[buf_offset..buf_end], current); + + buf_offset = buf_end; + current += page_len; + len -= page_len; + bytes += page_len; + } + + Ok(bytes) + } + + fn write(&mut self, buf: &[u8], offset: usize) -> Result<usize, SvsmError> { + let mut current = offset; + let mut bytes: usize = 0; + let mut len = buf.len(); + let mut buf_offset: usize = 0; + let capacity = offset + .checked_add(len) + .ok_or(SvsmError::FileSystem(FsError::inval()))?; + + self.set_capacity(capacity)?; + + while len > 0 { + let page_len = min(PAGE_SIZE - page_offset(current), len); + let buf_end = buf_offset + page_len; + + self.write_to_page(&buf[buf_offset..buf_end], current); + self.size = max(self.size, current + page_len); + + current += page_len; + buf_offset += page_len; + len -= page_len; + bytes += page_len; + } + + Ok(bytes) + } + + fn truncate(&mut self, size: usize) -> Result<usize, SvsmError> { + if size > self.size { + return Err(SvsmError::FileSystem(FsError::inval())); + } + + let base_pages = size / PAGE_SIZE; + let new_pages = if page_offset(size) > 0 { + base_pages + 1 + } else { + base_pages + }; + + while self.pages.len() > new_pages { + self.pages.pop(); + } + self.capacity = new_pages * PAGE_SIZE; + self.size = size; + + Ok(size) + } + + fn size(&self) -> usize { + self.size + } +} + +pub struct RamFile { + rawfile: RWLock<RawRamFile>, +} + +unsafe impl Sync for RamFile {} + +impl RamFile { + #[allow(dead_code)] + pub fn new() -> Self { + RamFile { + rawfile: RWLock::new(RawRamFile::new()), + } + } +} + +impl File for RamFile { + fn read(&self, buf: &mut [u8], offset: usize) -> Result<usize, SvsmError> { + self.rawfile.lock_read().read(buf, offset) + } + + fn write(&self, buf: &[u8], offset: usize) -> Result<usize, SvsmError> { + self.rawfile.lock_write().write(buf, offset) + } + + fn truncate(&self, size: usize) -> Result<usize, SvsmError> { + self.rawfile.lock_write().truncate(size) + } + + fn size(&self) -> usize { + self.rawfile.lock_read().size() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::mm::alloc::{destroy_test_root_mem, setup_test_root_mem, DEFAULT_TEST_MEMORY_SIZE}; + + #[test] + fn test_ramfs_file_read_write() { + let test_mem_lock = setup_test_root_mem(DEFAULT_TEST_MEMORY_SIZE); + + let file = RamFile::new(); + let mut buf1 = [0xffu8; 512]; + + // Write first buffer at offset 0 + file.write(&mut buf1, 0).expect("Failed to write file data"); + assert!(file.size() == 512); + + // Write second buffer at offset 4096 - 256 - cross-page write + let mut buf2 = [0xaau8; 512]; + file.write(&mut buf2, PAGE_SIZE - 256) + .expect("Failed to write file cross-page"); + assert!(file.size() == PAGE_SIZE + 256); + + // Read back and check first buffer + let size = file + .read(&mut buf1, 0) + .expect("Failed to read from offset 0"); + assert!(size == 512); + + for byte in buf1.iter() { + assert!(*byte == 0xff); + } + + // Read back and check second buffer + let size = file + .read(&mut buf2, PAGE_SIZE - 256)
dito
svsm
github_2023
others
27
coconut-svsm
osteffenrh
@@ -0,0 +1,263 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +extern crate alloc; +use super::*; +use crate::error::SvsmError; +use crate::locking::RWLock; +use crate::mm::{allocate_file_page_ref, PageRef}; +use crate::types::PAGE_SIZE; +use crate::utils::{page_align_up, page_offset}; + +use alloc::vec::Vec; +use core::cmp::{max, min}; + +struct RawRamFile { + capacity: usize, + size: usize, + pages: Vec<PageRef>, +} + +impl RawRamFile { + pub fn new() -> Self { + RawRamFile { + capacity: 0, + size: 0, + pages: Vec::new(), + } + } + + fn increase_capacity(&mut self) -> Result<(), SvsmError> { + let page_ref = allocate_file_page_ref()?; + self.pages.push(page_ref); + self.capacity += PAGE_SIZE; + Ok(()) + } + + fn set_capacity(&mut self, capacity: usize) -> Result<(), SvsmError> { + let cap = page_align_up(capacity); + + while cap > self.capacity { + self.increase_capacity()?; + } + + Ok(()) + } + + fn read_from_page(&self, buf: &mut [u8], offset: usize) { + let page_index = page_offset(offset); + let index = offset / PAGE_SIZE; + let len = buf.len(); + let page_end = page_index + len; + + assert!(page_end <= PAGE_SIZE); + + let page_buf = self.pages[index].as_ref(); + buf.copy_from_slice(&page_buf[page_index..page_end]); + } + + fn write_to_page(&mut self, buf: &[u8], offset: usize) { + let page_index = page_offset(offset); + let index = offset / PAGE_SIZE; + let len = buf.len(); + let page_end = page_index + len; + + assert!(page_end <= PAGE_SIZE); + + let page_buf = self.pages[index].as_mut_ref(); + page_buf[page_index..page_end].copy_from_slice(buf); + } + + fn read(&self, buf: &mut [u8], offset: usize) -> Result<usize, SvsmError> { + let mut current = min(offset, self.size); + let mut len = buf.len(); + let mut bytes: usize = 0; + let mut buf_offset = 0; + + while len > 0 { + let page_end = min(page_align_up(current + 1), self.size); + let page_len = min(page_end - current, len); + let buf_end = buf_offset + page_len; + + if page_len == 0 { + break; + } + + self.read_from_page(&mut buf[buf_offset..buf_end], current); + + buf_offset = buf_end; + current += page_len; + len -= page_len; + bytes += page_len; + } + + Ok(bytes) + } + + fn write(&mut self, buf: &[u8], offset: usize) -> Result<usize, SvsmError> { + let mut current = offset; + let mut bytes: usize = 0; + let mut len = buf.len(); + let mut buf_offset: usize = 0; + let capacity = offset + .checked_add(len) + .ok_or(SvsmError::FileSystem(FsError::inval()))?; + + self.set_capacity(capacity)?; + + while len > 0 { + let page_len = min(PAGE_SIZE - page_offset(current), len); + let buf_end = buf_offset + page_len; + + self.write_to_page(&buf[buf_offset..buf_end], current); + self.size = max(self.size, current + page_len); + + current += page_len; + buf_offset += page_len; + len -= page_len; + bytes += page_len; + } + + Ok(bytes) + } + + fn truncate(&mut self, size: usize) -> Result<usize, SvsmError> { + if size > self.size { + return Err(SvsmError::FileSystem(FsError::inval())); + } + + let base_pages = size / PAGE_SIZE; + let new_pages = if page_offset(size) > 0 { + base_pages + 1 + } else { + base_pages + }; + + while self.pages.len() > new_pages { + self.pages.pop(); + } + self.capacity = new_pages * PAGE_SIZE; + self.size = size; + + Ok(size) + } + + fn size(&self) -> usize { + self.size + } +} + +pub struct RamFile { + rawfile: RWLock<RawRamFile>, +} + +unsafe impl Sync for RamFile {} + +impl RamFile { + #[allow(dead_code)] + pub fn new() -> Self { + RamFile { + rawfile: RWLock::new(RawRamFile::new()), + } + } +} + +impl File for RamFile { + fn read(&self, buf: &mut [u8], offset: usize) -> Result<usize, SvsmError> { + self.rawfile.lock_read().read(buf, offset) + } + + fn write(&self, buf: &[u8], offset: usize) -> Result<usize, SvsmError> { + self.rawfile.lock_write().write(buf, offset) + } + + fn truncate(&self, size: usize) -> Result<usize, SvsmError> { + self.rawfile.lock_write().truncate(size) + } + + fn size(&self) -> usize { + self.rawfile.lock_read().size() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::mm::alloc::{destroy_test_root_mem, setup_test_root_mem, DEFAULT_TEST_MEMORY_SIZE}; + + #[test] + fn test_ramfs_file_read_write() { + let test_mem_lock = setup_test_root_mem(DEFAULT_TEST_MEMORY_SIZE); + + let file = RamFile::new(); + let mut buf1 = [0xffu8; 512]; + + // Write first buffer at offset 0 + file.write(&mut buf1, 0).expect("Failed to write file data"); + assert!(file.size() == 512); + + // Write second buffer at offset 4096 - 256 - cross-page write + let mut buf2 = [0xaau8; 512]; + file.write(&mut buf2, PAGE_SIZE - 256) + .expect("Failed to write file cross-page"); + assert!(file.size() == PAGE_SIZE + 256); + + // Read back and check first buffer + let size = file + .read(&mut buf1, 0) + .expect("Failed to read from offset 0"); + assert!(size == 512); + + for byte in buf1.iter() { + assert!(*byte == 0xff); + } + + // Read back and check second buffer + let size = file + .read(&mut buf2, PAGE_SIZE - 256) + .expect("Failed to read from offset PAGE_SIZE - 256"); + assert!(size == 512); + + for byte in buf2.iter() { + assert!(*byte == 0xaa); + } + + // Check complete file + let mut buf3: [u8; 8192] = [0xcc; 8192]; + let size = file.read(&mut buf3, 0).expect("Failed to read whole file"); + assert!(size == PAGE_SIZE + 256); + + for i in 0..buf3.len() { + let expected: u8 = if i < 512 { + 0xff + } else if i < PAGE_SIZE - 256 { + 0 + } else if i < PAGE_SIZE + 256 { + 0xaa + } else { + 0xcc + }; + assert!(buf3[i] == expected); + } + + assert_eq!(file.truncate(1024).unwrap(), 1024); + assert_eq!(file.size(), 1024); + + // read file again + let size = file.read(&mut buf3, 0).expect("Failed to read whole file");
and here
svsm
github_2023
others
27
coconut-svsm
roy-hopkins
@@ -0,0 +1,263 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +extern crate alloc; +use super::*; +use crate::error::SvsmError; +use crate::locking::RWLock; +use crate::mm::{allocate_file_page_ref, PageRef}; +use crate::types::PAGE_SIZE; +use crate::utils::{page_align_up, page_offset}; + +use alloc::vec::Vec; +use core::cmp::{max, min}; + +struct RawRamFile { + capacity: usize, + size: usize, + pages: Vec<PageRef>, +} + +impl RawRamFile { + pub fn new() -> Self { + RawRamFile { + capacity: 0, + size: 0, + pages: Vec::new(), + } + } + + fn increase_capacity(&mut self) -> Result<(), SvsmError> { + let page_ref = allocate_file_page_ref()?; + self.pages.push(page_ref); + self.capacity += PAGE_SIZE; + Ok(()) + } + + fn set_capacity(&mut self, capacity: usize) -> Result<(), SvsmError> { + let cap = page_align_up(capacity); + + while cap > self.capacity { + self.increase_capacity()?; + } + + Ok(()) + } + + fn read_from_page(&self, buf: &mut [u8], offset: usize) { + let page_index = page_offset(offset); + let index = offset / PAGE_SIZE; + let len = buf.len(); + let page_end = page_index + len; + + assert!(page_end <= PAGE_SIZE); + + let page_buf = self.pages[index].as_ref(); + buf.copy_from_slice(&page_buf[page_index..page_end]); + } + + fn write_to_page(&mut self, buf: &[u8], offset: usize) { + let page_index = page_offset(offset); + let index = offset / PAGE_SIZE; + let len = buf.len(); + let page_end = page_index + len; + + assert!(page_end <= PAGE_SIZE); + + let page_buf = self.pages[index].as_mut_ref(); + page_buf[page_index..page_end].copy_from_slice(buf); + } + + fn read(&self, buf: &mut [u8], offset: usize) -> Result<usize, SvsmError> { + let mut current = min(offset, self.size); + let mut len = buf.len(); + let mut bytes: usize = 0; + let mut buf_offset = 0; + + while len > 0 { + let page_end = min(page_align_up(current + 1), self.size); + let page_len = min(page_end - current, len); + let buf_end = buf_offset + page_len; + + if page_len == 0 { + break; + } + + self.read_from_page(&mut buf[buf_offset..buf_end], current); + + buf_offset = buf_end; + current += page_len; + len -= page_len; + bytes += page_len; + } + + Ok(bytes) + } + + fn write(&mut self, buf: &[u8], offset: usize) -> Result<usize, SvsmError> { + let mut current = offset; + let mut bytes: usize = 0; + let mut len = buf.len(); + let mut buf_offset: usize = 0; + let capacity = offset + .checked_add(len) + .ok_or(SvsmError::FileSystem(FsError::inval()))?; + + self.set_capacity(capacity)?; + + while len > 0 { + let page_len = min(PAGE_SIZE - page_offset(current), len); + let buf_end = buf_offset + page_len; + + self.write_to_page(&buf[buf_offset..buf_end], current); + self.size = max(self.size, current + page_len); + + current += page_len; + buf_offset += page_len; + len -= page_len; + bytes += page_len; + } + + Ok(bytes) + } + + fn truncate(&mut self, size: usize) -> Result<usize, SvsmError> { + if size > self.size { + return Err(SvsmError::FileSystem(FsError::inval())); + } + + let base_pages = size / PAGE_SIZE; + let new_pages = if page_offset(size) > 0 { + base_pages + 1 + } else { + base_pages + }; + + while self.pages.len() > new_pages { + self.pages.pop(); + } + self.capacity = new_pages * PAGE_SIZE; + self.size = size;
The remaining bytes between self.size and self.capacity should be zeroed to prevent previous file contents being visible if the file is increased in size again.
svsm
github_2023
others
27
coconut-svsm
roy-hopkins
@@ -197,7 +197,7 @@ global_asm!( shrq $3, %rcx rep stosq - popq %rdi + movq %rsi, %rdi
Are the top 32 bits of %rsi guaranteed to be zero after switching from 32-bit to 64-bit mode?
svsm
github_2023
others
27
coconut-svsm
osteffenrh
@@ -0,0 +1,465 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use super::ramfs::RamDirectory; +use super::*; + +use crate::error::SvsmError; +use crate::locking::SpinLock; + +use core::cmp::min; + +extern crate alloc; +use alloc::sync::Arc; +use alloc::vec::Vec; + +struct RawFileHandle { + file: Arc<dyn File>, + current: usize, +} + +impl RawFileHandle { + pub fn new(file: &Arc<dyn File>) -> Self { + RawFileHandle { + file: file.clone(), + current: 0, + } + } + + pub fn read(&mut self, buf: &mut [u8]) -> Result<usize, SvsmError> { + let result = self.file.read(buf, self.current); + if let Ok(v) = result { + self.current += v; + } + result + } + + pub fn write(&mut self, buf: &[u8]) -> Result<usize, SvsmError> { + let result = self.file.write(buf, self.current); + if result.is_ok() { + self.current += result.unwrap(); + } + result + } + + pub fn truncate(&mut self, offset: usize) -> Result<usize, SvsmError> { + self.file.truncate(offset) + } + + pub fn seek(&mut self, pos: usize) { + self.current = min(pos, self.file.size()); + } + + pub fn size(&self) -> usize { + self.file.size() + } +} + +pub struct FileHandle { + // Use a SpinLock here because the read operation also needs to be mutable + // (changes file pointer). Parallel reads are still possible with multiple + // file handles + handle: SpinLock<RawFileHandle>, +} + +unsafe impl Sync for FileHandle {} + +impl FileHandle { + pub fn new(file: &Arc<dyn File>) -> Self { + FileHandle { + handle: SpinLock::new(RawFileHandle::new(file)), + } + } + + pub fn read(&self, buf: &mut [u8]) -> Result<usize, SvsmError> { + self.handle.lock().read(buf) + } + + pub fn write(&self, buf: &[u8]) -> Result<usize, SvsmError> { + self.handle.lock().write(buf) + } + + pub fn truncate(&self, offset: usize) -> Result<usize, SvsmError> { + self.handle.lock().truncate(offset) + } + + pub fn seek(&self, pos: usize) { + self.handle.lock().seek(pos); + } + + pub fn size(&self) -> usize { + self.handle.lock().size() + } +} + +struct SvsmFs { + root: Option<Arc<RamDirectory>>, +} + +unsafe impl Sync for SvsmFs {} + +impl SvsmFs { + pub const fn new() -> Self { + SvsmFs { root: None } + } + + pub fn initialize(&mut self, root: &Arc<RamDirectory>) { + assert!(!self.initialized()); + self.root = Some(root.clone()); + } + + #[cfg(test)] + pub fn uninitialize(&mut self) { + self.root = None; + } + + pub fn initialized(&self) -> bool { + self.root.is_some() + } + + pub fn root_dir(&self) -> Arc<dyn Directory> { + assert!(self.initialized()); + self.root.as_ref().unwrap().clone() + } +} + +static mut FS_ROOT: SvsmFs = SvsmFs::new(); + +pub fn initialize_fs() { + let root_dir = Arc::new(RamDirectory::new()); + unsafe { + FS_ROOT.initialize(&root_dir); + } +} + +#[cfg(test)] +fn uninitialize_fs() { + unsafe { + FS_ROOT.uninitialize(); + } +} + +fn split_path_allow_empty(path: &str) -> Vec<&str> { + path.split('/').filter(|x| x.len() > 0).collect() +} + +fn split_path(path: &str) -> Result<Vec<&str>, SvsmError> { + let path_items = split_path_allow_empty(path); + + if path_items.is_empty() { + return Err(SvsmError::FileSystem(FsError::file_not_found())); + } + + Ok(path_items) +} + +fn walk_path(path_items: &Vec<&str>) -> Result<Arc<dyn Directory>, SvsmError> { + let mut current_dir = unsafe { FS_ROOT.root_dir() }; + + for item in path_items.iter() { + let dir_name = FileName::from(*item); + let dir_entry = current_dir.lookup_entry(dir_name)?; + current_dir = match dir_entry { + DirEntry::File(_) => return Err(SvsmError::FileSystem(FsError::file_not_found())), + DirEntry::Directory(dir) => dir, + }; + } + + Ok(current_dir) +} + +pub fn open(path: &str) -> Result<FileHandle, SvsmError> { + let mut path_items = split_path(path)?; + let file_name = FileName::from(path_items.pop().unwrap()); + let current_dir = walk_path(&path_items)?; + + let dir_entry = current_dir.lookup_entry(file_name)?; + + match dir_entry { + DirEntry::Directory(_) => Err(SvsmError::FileSystem(FsError::file_not_found())), + DirEntry::File(f) => Ok(FileHandle::new(&f)), + } +} + +pub fn create(path: &str) -> Result<FileHandle, SvsmError> { + let mut path_items = split_path(path)?; + let file_name = FileName::from(path_items.pop().unwrap()); + let current_dir = walk_path(&path_items)?; + + if file_name.length() == 0 {
Why this check here? This should not happen, because `split_paths_allow_empty` filters these. Somehow I would have expected this check in the lower level create function(s). But if it is desired/needed here, then I would also expect it for `mkdir()`?
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,163 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{Address, PhysAddr}; +use crate::error::SvsmError; +use crate::mm::ptguards::PerCPUPageMappingGuard; + +use super::*; + +extern crate alloc; +use alloc::slice; +use alloc::string::String; +use alloc::vec::Vec; + +const PACKIT_MAGIC: [u8; 4] = [0x50, 0x4b, 0x49, 0x54]; + +struct PackItHeader { + /// Header Magic (PKIT) + magic: [u8; 4], + /// Header Size + header_size: u32, +} + +impl PackItHeader { + const fn new() -> Self { + PackItHeader { + magic: [0; 4], + header_size: 8, + } + } + + fn load(buf: &[u8]) -> Result<Self, SvsmError> { + assert!(buf.len() >= 8);
I'd vote to return an error here instead to keep everything consistent.
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,163 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{Address, PhysAddr}; +use crate::error::SvsmError; +use crate::mm::ptguards::PerCPUPageMappingGuard; + +use super::*; + +extern crate alloc; +use alloc::slice; +use alloc::string::String; +use alloc::vec::Vec; + +const PACKIT_MAGIC: [u8; 4] = [0x50, 0x4b, 0x49, 0x54]; + +struct PackItHeader { + /// Header Magic (PKIT) + magic: [u8; 4], + /// Header Size + header_size: u32, +} + +impl PackItHeader { + const fn new() -> Self { + PackItHeader { + magic: [0; 4], + header_size: 8, + } + } + + fn load(buf: &[u8]) -> Result<Self, SvsmError> { + assert!(buf.len() >= 8); + + let mut hdr = PackItHeader::new(); + hdr.magic.copy_from_slice(&buf[0..4]); + + // array indexes are static so the try_into() never fails + hdr.header_size = u32::from_le_bytes(buf[4..8].try_into().unwrap()); + + if hdr.magic != PACKIT_MAGIC { + log::error!("Unexpected header in FS archive"); + return Err(SvsmError::FileSystem(FsError::inval())); + } + + Ok(hdr) + } + + fn len(&self) -> usize { + self.header_size as usize + } +} + +struct FileHeader { + name_len: u16, + file_size: u64, + name: String, +} + +impl FileHeader { + fn load(buf: &[u8]) -> Result<Self, SvsmError> { + assert!(buf.len() >= 12);
Same here, returning an error seems more natural.
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,163 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{Address, PhysAddr}; +use crate::error::SvsmError; +use crate::mm::ptguards::PerCPUPageMappingGuard; + +use super::*; + +extern crate alloc; +use alloc::slice; +use alloc::string::String; +use alloc::vec::Vec; + +const PACKIT_MAGIC: [u8; 4] = [0x50, 0x4b, 0x49, 0x54]; + +struct PackItHeader { + /// Header Magic (PKIT) + magic: [u8; 4], + /// Header Size + header_size: u32, +} + +impl PackItHeader { + const fn new() -> Self { + PackItHeader { + magic: [0; 4], + header_size: 8, + } + } + + fn load(buf: &[u8]) -> Result<Self, SvsmError> { + assert!(buf.len() >= 8); + + let mut hdr = PackItHeader::new(); + hdr.magic.copy_from_slice(&buf[0..4]); + + // array indexes are static so the try_into() never fails + hdr.header_size = u32::from_le_bytes(buf[4..8].try_into().unwrap()); + + if hdr.magic != PACKIT_MAGIC { + log::error!("Unexpected header in FS archive"); + return Err(SvsmError::FileSystem(FsError::inval())); + } + + Ok(hdr) + } + + fn len(&self) -> usize { + self.header_size as usize + } +} + +struct FileHeader { + name_len: u16, + file_size: u64, + name: String, +} + +impl FileHeader { + fn load(buf: &[u8]) -> Result<Self, SvsmError> { + assert!(buf.len() >= 12); + + // array indexes are static so the try_into() never fails + let hdr_type = u16::from_le_bytes(buf[0..2].try_into().unwrap()); + let name_len = u16::from_le_bytes(buf[2..4].try_into().unwrap()); + let file_size = u64::from_le_bytes(buf[4..12].try_into().unwrap()); + + let header_len: usize = name_len as usize + 12; + + if buf.len() < header_len { + log::error!("Unexpected end of archive"); + return Err(SvsmError::FileSystem(FsError::inval())); + } + + let Ok(name) = String::from_utf8(Vec::from(&buf[12..header_len])) else { + log::error!("Invalid filename in archive"); + return Err(SvsmError::FileSystem(FsError::inval())); + }; + + if hdr_type != 1 || name_len == 0 { + log::error!("Invalid file header in archive"); + return Err(SvsmError::FileSystem(FsError::inval())); + } + + Ok(FileHeader { + name_len, + file_size, + name: name,
Field could be omitted here, clippy will complain.
svsm
github_2023
others
28
coconut-svsm
roy-hopkins
@@ -467,6 +479,20 @@ impl PerCpu { base: (&self.tss as *const X86Tss) as u64, } } + + pub fn virt_range_init(&mut self) { + // Initialize 4k range + let page_count = (SVSM_PERCPU_TEMP_END_4K - SVSM_PERCPU_TEMP_BASE_4K) / PAGE_SIZE; + assert!(page_count <= VirtualRange::CAPACITY); + self.vrange_4k + .init(VirtAddr::from(SVSM_PERCPU_TEMP_BASE_4K), page_count); + + // Initialize 2M range + let page_count = (SVSM_PERCPU_TEMP_END_2M - SVSM_PERCPU_TEMP_BASE_2M) / PAGE_SIZE_2M; + assert!(page_count <= VirtualRange::CAPACITY); + self.vrange_2m + .init(VirtAddr::from(SVSM_PERCPU_TEMP_BASE_2M), page_count);
I've just noticed a bug (my bug) in the VirtualRange initialisation. `VirtualRange::alloc()` returns a contiguous virtual address range based on the allocated page count therefore it needs to know the page size. At the moment it incorrectly assumes it's 4k. Therefore the `init()` function will need to take the page size, or at least the page shift as a parameter. I can fix this in a separate PR if you would prefer?
svsm
github_2023
others
21
coconut-svsm
Freax13
@@ -0,0 +1,1612 @@ +// SPDX-License-Identifier: (GPL-2.0-or-later OR MIT) +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Nicolai Stange <nstange@suse.de> +// +// vim: ts=4 sw=4 et + +extern crate alloc; + +use alloc::vec::Vec; +use bitflags::bitflags; +use core::cmp; +use core::convert; +use core::ffi; +use core::fmt; +use core::matches; +use core::mem; + +#[derive(Debug)] +pub enum ElfError { + FileTooShort, + + InvalidAddressRange, + InvalidAddressAlignment, + InvalidFileRange, + UnmappedVaddrRange, + UnbackedVaddrRange, + + UnrecognizedMagic, + UnsupportedClass, + UnsupportedEndianess, + UnsupportedOsAbi, + UnsupportedType, + UnsupportedMachine, + UnsupportedVersion, + InvalidPhdrSize, + InvalidShdrSize, + + InvalidSegmentSize, + UnalignedSegmentAddress, + LoadSegmentConflict, + DynamicPhdrConflict, + + UnterminatedDynamicSection, + DynamicFieldConflict, + UnrecognizedDynamicField, + MissingDynamicField, + + InvalidSectionIndex, + IncompatibleSectionType, + + InvalidStrtabString, + + InvalidSymbolEntrySize, + InvalidSymbolIndex, + + InvalidRelocationEntrySize, + UnrecognizedRelocationType, + InvalidRelocationOffset, + RelocationAgainstUndefSymbol, +} + +impl fmt::Display for ElfError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::FileTooShort => { + write!(f, "ELF file too short") + } + + Self::InvalidAddressRange => { + write!(f, "invalid ELF address range") + } + Self::InvalidAddressAlignment => { + write!(f, "invalid ELF address alignment") + } + Self::InvalidFileRange => { + write!(f, "invalid ELF file range") + } + Self::UnmappedVaddrRange => { + write!(f, "reference to unmapped ELF address range") + } + Self::UnbackedVaddrRange => { + write!(f, "reference ELF address range not backed by file") + } + + Self::UnrecognizedMagic => { + write!(f, "unrecognized ELF magic") + } + Self::UnsupportedClass => { + write!(f, "unsupported ELF class") + } + Self::UnsupportedEndianess => { + write!(f, "unsupported ELF endianess") + } + Self::UnsupportedOsAbi => { + write!(f, "unsupported ELF ABI") + } + Self::UnsupportedType => { + write!(f, "unsupported ELF file type") + } + Self::UnsupportedMachine => { + write!(f, "unsupported ELF machine") + } + Self::UnsupportedVersion => { + write!(f, "unsupported ELF version") + } + Self::InvalidPhdrSize => { + write!(f, "invalid ELF program header size") + } + Self::InvalidShdrSize => { + write!(f, "invalid ELF section header size") + } + + Self::InvalidSegmentSize => { + write!(f, "invalid ELF segment size") + } + Self::UnalignedSegmentAddress => { + write!(f, "unaligned ELF segment address") + } + Self::LoadSegmentConflict => { + write!(f, "ELF PT_LOAD segment conflict") + } + Self::DynamicPhdrConflict => { + write!(f, "multiple ELF PT_DYNAMIC program headers") + } + + Self::UnterminatedDynamicSection => { + write!(f, "unterminated ELF dynamic section") + } + Self::DynamicFieldConflict => { + write!(f, "conflicting fields in ELF dynamic section") + } + Self::UnrecognizedDynamicField => { + write!(f, "unrecognized field in ELF dynamic section") + } + Self::MissingDynamicField => { + write!(f, "missing field in ELF dynamic section") + } + + Self::InvalidSectionIndex => { + write!(f, "invalid ELF section index") + } + Self::IncompatibleSectionType => { + write!(f, "unexpected ELF section type") + } + + Self::InvalidStrtabString => { + write!(f, "invalid ELF strtab string") + } + + Self::InvalidSymbolEntrySize => { + write!(f, "invalid ELF symbol entry size") + } + Self::InvalidSymbolIndex => { + write!(f, "invalid ELF symbol index") + } + + Self::InvalidRelocationEntrySize => { + write!(f, "invalid ELF relocation entry size") + } + Self::UnrecognizedRelocationType => { + write!(f, "unrecognized ELF relocation type") + } + Self::InvalidRelocationOffset => { + write!(f, "ELF relocation offset out of bounds") + } + Self::RelocationAgainstUndefSymbol => { + write!(f, "ELF relocation against undefined symbol") + } + } + } +}
Have you considered using the [thiserror](https://docs.rs/thiserror/latest/thiserror/) crate?
svsm
github_2023
others
21
coconut-svsm
Freax13
@@ -0,0 +1,1612 @@ +// SPDX-License-Identifier: (GPL-2.0-or-later OR MIT) +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Nicolai Stange <nstange@suse.de> +// +// vim: ts=4 sw=4 et + +extern crate alloc; + +use alloc::vec::Vec; +use bitflags::bitflags; +use core::cmp; +use core::convert; +use core::ffi; +use core::fmt; +use core::matches; +use core::mem; + +#[derive(Debug)] +pub enum ElfError { + FileTooShort, + + InvalidAddressRange, + InvalidAddressAlignment, + InvalidFileRange, + UnmappedVaddrRange, + UnbackedVaddrRange, + + UnrecognizedMagic, + UnsupportedClass, + UnsupportedEndianess, + UnsupportedOsAbi, + UnsupportedType, + UnsupportedMachine, + UnsupportedVersion, + InvalidPhdrSize, + InvalidShdrSize, + + InvalidSegmentSize, + UnalignedSegmentAddress, + LoadSegmentConflict, + DynamicPhdrConflict, + + UnterminatedDynamicSection, + DynamicFieldConflict, + UnrecognizedDynamicField, + MissingDynamicField, + + InvalidSectionIndex, + IncompatibleSectionType, + + InvalidStrtabString, + + InvalidSymbolEntrySize, + InvalidSymbolIndex, + + InvalidRelocationEntrySize, + UnrecognizedRelocationType, + InvalidRelocationOffset, + RelocationAgainstUndefSymbol, +} + +impl fmt::Display for ElfError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::FileTooShort => { + write!(f, "ELF file too short") + } + + Self::InvalidAddressRange => { + write!(f, "invalid ELF address range") + } + Self::InvalidAddressAlignment => { + write!(f, "invalid ELF address alignment") + } + Self::InvalidFileRange => { + write!(f, "invalid ELF file range") + } + Self::UnmappedVaddrRange => { + write!(f, "reference to unmapped ELF address range") + } + Self::UnbackedVaddrRange => { + write!(f, "reference ELF address range not backed by file") + } + + Self::UnrecognizedMagic => { + write!(f, "unrecognized ELF magic") + } + Self::UnsupportedClass => { + write!(f, "unsupported ELF class") + } + Self::UnsupportedEndianess => { + write!(f, "unsupported ELF endianess") + } + Self::UnsupportedOsAbi => { + write!(f, "unsupported ELF ABI") + } + Self::UnsupportedType => { + write!(f, "unsupported ELF file type") + } + Self::UnsupportedMachine => { + write!(f, "unsupported ELF machine") + } + Self::UnsupportedVersion => { + write!(f, "unsupported ELF version") + } + Self::InvalidPhdrSize => { + write!(f, "invalid ELF program header size") + } + Self::InvalidShdrSize => { + write!(f, "invalid ELF section header size") + } + + Self::InvalidSegmentSize => { + write!(f, "invalid ELF segment size") + } + Self::UnalignedSegmentAddress => { + write!(f, "unaligned ELF segment address") + } + Self::LoadSegmentConflict => { + write!(f, "ELF PT_LOAD segment conflict") + } + Self::DynamicPhdrConflict => { + write!(f, "multiple ELF PT_DYNAMIC program headers") + } + + Self::UnterminatedDynamicSection => { + write!(f, "unterminated ELF dynamic section") + } + Self::DynamicFieldConflict => { + write!(f, "conflicting fields in ELF dynamic section") + } + Self::UnrecognizedDynamicField => { + write!(f, "unrecognized field in ELF dynamic section") + } + Self::MissingDynamicField => { + write!(f, "missing field in ELF dynamic section") + } + + Self::InvalidSectionIndex => { + write!(f, "invalid ELF section index") + } + Self::IncompatibleSectionType => { + write!(f, "unexpected ELF section type") + } + + Self::InvalidStrtabString => { + write!(f, "invalid ELF strtab string") + } + + Self::InvalidSymbolEntrySize => { + write!(f, "invalid ELF symbol entry size") + } + Self::InvalidSymbolIndex => { + write!(f, "invalid ELF symbol index") + } + + Self::InvalidRelocationEntrySize => { + write!(f, "invalid ELF relocation entry size") + } + Self::UnrecognizedRelocationType => { + write!(f, "unrecognized ELF relocation type") + } + Self::InvalidRelocationOffset => { + write!(f, "ELF relocation offset out of bounds") + } + Self::RelocationAgainstUndefSymbol => { + write!(f, "ELF relocation against undefined symbol") + } + } + } +} + +pub type Elf64Addr = u64; +pub type Elf64Off = u64; +pub type Elf64Half = u16; +pub type Elf64Word = u32; +#[allow(unused)] +pub type Elf64Sword = i32; +pub type Elf64Xword = u64; +pub type Elf64Sxword = i64; +pub type Elf64char = u8; + +#[derive(PartialEq, Eq, Debug)] +pub struct Elf64AddrRange { + pub vaddr_begin: Elf64Addr, + pub vaddr_end: Elf64Addr, +} + +impl Elf64AddrRange { + pub fn len(&self) -> Elf64Xword { + self.vaddr_end - self.vaddr_begin + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +impl convert::TryFrom<(Elf64Addr, Elf64Xword)> for Elf64AddrRange { + type Error = ElfError; + + fn try_from(value: (Elf64Addr, Elf64Xword)) -> Result<Self, Self::Error> { + let vaddr_begin = value.0; + let size = value.1; + let vaddr_end = vaddr_begin + .checked_add(size) + .ok_or(ElfError::InvalidAddressRange)?; + Ok(Self { + vaddr_begin, + vaddr_end, + }) + } +} + +impl cmp::PartialOrd for Elf64AddrRange { + fn partial_cmp(&self, other: &Elf64AddrRange) -> Option<cmp::Ordering> { + if self.vaddr_end <= other.vaddr_begin { + Some(cmp::Ordering::Less) + } else if self.vaddr_begin >= other.vaddr_end { + Some(cmp::Ordering::Greater) + } else if self == other { + Some(cmp::Ordering::Equal) + } else { + None + } + } +} + +pub struct Elf64FileRange { + pub offset_begin: usize, + pub offset_end: usize, +} + +impl convert::TryFrom<(Elf64Off, Elf64Xword)> for Elf64FileRange { + type Error = ElfError; + + fn try_from(value: (Elf64Off, Elf64Xword)) -> Result<Self, Self::Error> { + let offset_begin = usize::try_from(value.0).map_err(|_| ElfError::InvalidFileRange)?; + let size = usize::try_from(value.1).map_err(|_| ElfError::InvalidFileRange)?; + let offset_end = offset_begin + .checked_add(size) + .ok_or(ElfError::InvalidFileRange)?; + Ok(Self { + offset_begin, + offset_end, + }) + } +} + +pub struct Elf64File<'a> { + elf_file_buf: &'a [u8], + elf_hdr: Elf64Hdr, + load_segments: Elf64LoadSegments, + max_load_segment_align: Elf64Xword, + #[allow(unused)] + sh_strtab: Option<Elf64Strtab<'a>>, + dynamic: Option<Elf64Dynamic>, +} + +impl<'a> Elf64File<'a> { + pub fn read(elf_file_buf: &'a [u8]) -> Result<Self, ElfError> { + let mut elf_hdr = Elf64Hdr::read(elf_file_buf)?; + + // Verify that the program header table is within the file bounds. + let phdrs_off = usize::try_from(elf_hdr.e_phoff).map_err(|_| ElfError::FileTooShort)?; + let phdr_size = usize::try_from(elf_hdr.e_phentsize).unwrap(); + if phdr_size < 56 { + return Err(ElfError::InvalidPhdrSize); + } + let phdrs_num = usize::try_from(elf_hdr.e_phnum).unwrap(); + let phdrs_size = phdrs_num + .checked_mul(phdr_size) + .ok_or(ElfError::FileTooShort)?; + let phdrs_end = phdrs_off + .checked_add(phdrs_size) + .ok_or(ElfError::FileTooShort)?; + if phdrs_end > elf_file_buf.len() { + return Err(ElfError::FileTooShort); + } + + // Verify that the section header table is within the file bounds. + let shdr_size = usize::try_from(elf_hdr.e_shentsize).unwrap(); + if shdr_size < 64 { + return Err(ElfError::InvalidShdrSize); + } + if elf_hdr.e_shnum == 0 && elf_hdr.e_shoff != 0 { + // The number of section headers is stored in the first section header's + // ->sh_size member. + elf_hdr.e_shnum = 1; + Self::check_section_header_table_bounds(&elf_hdr, elf_file_buf.len())?; + let shdr0 = Self::read_shdr_from_file(elf_file_buf, &elf_hdr, 0); + elf_hdr.e_shnum = match Elf64Word::try_from(shdr0.sh_size) { + Ok(shnum) => shnum, + Err(_) => return Err(ElfError::InvalidSectionIndex), + }; + } + Self::check_section_header_table_bounds(&elf_hdr, elf_file_buf.len())?; + + // Verify all headers once at load time, so that no error checking will + // be neeeded at each and every subsequent access.
```suggestion // be needed at each and every subsequent access. ```
svsm
github_2023
others
21
coconut-svsm
Freax13
@@ -0,0 +1,1612 @@ +// SPDX-License-Identifier: (GPL-2.0-or-later OR MIT) +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Nicolai Stange <nstange@suse.de> +// +// vim: ts=4 sw=4 et + +extern crate alloc; + +use alloc::vec::Vec; +use bitflags::bitflags; +use core::cmp; +use core::convert; +use core::ffi; +use core::fmt; +use core::matches; +use core::mem; + +#[derive(Debug)] +pub enum ElfError { + FileTooShort, + + InvalidAddressRange, + InvalidAddressAlignment, + InvalidFileRange, + UnmappedVaddrRange, + UnbackedVaddrRange, + + UnrecognizedMagic, + UnsupportedClass, + UnsupportedEndianess, + UnsupportedOsAbi, + UnsupportedType, + UnsupportedMachine, + UnsupportedVersion, + InvalidPhdrSize, + InvalidShdrSize, + + InvalidSegmentSize, + UnalignedSegmentAddress, + LoadSegmentConflict, + DynamicPhdrConflict, + + UnterminatedDynamicSection, + DynamicFieldConflict, + UnrecognizedDynamicField, + MissingDynamicField, + + InvalidSectionIndex, + IncompatibleSectionType, + + InvalidStrtabString, + + InvalidSymbolEntrySize, + InvalidSymbolIndex, + + InvalidRelocationEntrySize, + UnrecognizedRelocationType, + InvalidRelocationOffset, + RelocationAgainstUndefSymbol, +} + +impl fmt::Display for ElfError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::FileTooShort => { + write!(f, "ELF file too short") + } + + Self::InvalidAddressRange => { + write!(f, "invalid ELF address range") + } + Self::InvalidAddressAlignment => { + write!(f, "invalid ELF address alignment") + } + Self::InvalidFileRange => { + write!(f, "invalid ELF file range") + } + Self::UnmappedVaddrRange => { + write!(f, "reference to unmapped ELF address range") + } + Self::UnbackedVaddrRange => { + write!(f, "reference ELF address range not backed by file") + } + + Self::UnrecognizedMagic => { + write!(f, "unrecognized ELF magic") + } + Self::UnsupportedClass => { + write!(f, "unsupported ELF class") + } + Self::UnsupportedEndianess => { + write!(f, "unsupported ELF endianess") + } + Self::UnsupportedOsAbi => { + write!(f, "unsupported ELF ABI") + } + Self::UnsupportedType => { + write!(f, "unsupported ELF file type") + } + Self::UnsupportedMachine => { + write!(f, "unsupported ELF machine") + } + Self::UnsupportedVersion => { + write!(f, "unsupported ELF version") + } + Self::InvalidPhdrSize => { + write!(f, "invalid ELF program header size") + } + Self::InvalidShdrSize => { + write!(f, "invalid ELF section header size") + } + + Self::InvalidSegmentSize => { + write!(f, "invalid ELF segment size") + } + Self::UnalignedSegmentAddress => { + write!(f, "unaligned ELF segment address") + } + Self::LoadSegmentConflict => { + write!(f, "ELF PT_LOAD segment conflict") + } + Self::DynamicPhdrConflict => { + write!(f, "multiple ELF PT_DYNAMIC program headers") + } + + Self::UnterminatedDynamicSection => { + write!(f, "unterminated ELF dynamic section") + } + Self::DynamicFieldConflict => { + write!(f, "conflicting fields in ELF dynamic section") + } + Self::UnrecognizedDynamicField => { + write!(f, "unrecognized field in ELF dynamic section") + } + Self::MissingDynamicField => { + write!(f, "missing field in ELF dynamic section") + } + + Self::InvalidSectionIndex => { + write!(f, "invalid ELF section index") + } + Self::IncompatibleSectionType => { + write!(f, "unexpected ELF section type") + } + + Self::InvalidStrtabString => { + write!(f, "invalid ELF strtab string") + } + + Self::InvalidSymbolEntrySize => { + write!(f, "invalid ELF symbol entry size") + } + Self::InvalidSymbolIndex => { + write!(f, "invalid ELF symbol index") + } + + Self::InvalidRelocationEntrySize => { + write!(f, "invalid ELF relocation entry size") + } + Self::UnrecognizedRelocationType => { + write!(f, "unrecognized ELF relocation type") + } + Self::InvalidRelocationOffset => { + write!(f, "ELF relocation offset out of bounds") + } + Self::RelocationAgainstUndefSymbol => { + write!(f, "ELF relocation against undefined symbol") + } + } + } +} + +pub type Elf64Addr = u64; +pub type Elf64Off = u64; +pub type Elf64Half = u16; +pub type Elf64Word = u32; +#[allow(unused)] +pub type Elf64Sword = i32; +pub type Elf64Xword = u64; +pub type Elf64Sxword = i64; +pub type Elf64char = u8; + +#[derive(PartialEq, Eq, Debug)] +pub struct Elf64AddrRange { + pub vaddr_begin: Elf64Addr, + pub vaddr_end: Elf64Addr, +} + +impl Elf64AddrRange { + pub fn len(&self) -> Elf64Xword { + self.vaddr_end - self.vaddr_begin + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +impl convert::TryFrom<(Elf64Addr, Elf64Xword)> for Elf64AddrRange { + type Error = ElfError; + + fn try_from(value: (Elf64Addr, Elf64Xword)) -> Result<Self, Self::Error> { + let vaddr_begin = value.0; + let size = value.1; + let vaddr_end = vaddr_begin + .checked_add(size) + .ok_or(ElfError::InvalidAddressRange)?; + Ok(Self { + vaddr_begin, + vaddr_end, + }) + } +} + +impl cmp::PartialOrd for Elf64AddrRange { + fn partial_cmp(&self, other: &Elf64AddrRange) -> Option<cmp::Ordering> { + if self.vaddr_end <= other.vaddr_begin { + Some(cmp::Ordering::Less) + } else if self.vaddr_begin >= other.vaddr_end { + Some(cmp::Ordering::Greater) + } else if self == other { + Some(cmp::Ordering::Equal) + } else { + None + } + } +} + +pub struct Elf64FileRange { + pub offset_begin: usize, + pub offset_end: usize, +} + +impl convert::TryFrom<(Elf64Off, Elf64Xword)> for Elf64FileRange { + type Error = ElfError; + + fn try_from(value: (Elf64Off, Elf64Xword)) -> Result<Self, Self::Error> { + let offset_begin = usize::try_from(value.0).map_err(|_| ElfError::InvalidFileRange)?; + let size = usize::try_from(value.1).map_err(|_| ElfError::InvalidFileRange)?; + let offset_end = offset_begin + .checked_add(size) + .ok_or(ElfError::InvalidFileRange)?; + Ok(Self { + offset_begin, + offset_end, + }) + } +} + +pub struct Elf64File<'a> { + elf_file_buf: &'a [u8], + elf_hdr: Elf64Hdr, + load_segments: Elf64LoadSegments, + max_load_segment_align: Elf64Xword, + #[allow(unused)] + sh_strtab: Option<Elf64Strtab<'a>>, + dynamic: Option<Elf64Dynamic>, +} + +impl<'a> Elf64File<'a> { + pub fn read(elf_file_buf: &'a [u8]) -> Result<Self, ElfError> { + let mut elf_hdr = Elf64Hdr::read(elf_file_buf)?; + + // Verify that the program header table is within the file bounds. + let phdrs_off = usize::try_from(elf_hdr.e_phoff).map_err(|_| ElfError::FileTooShort)?; + let phdr_size = usize::try_from(elf_hdr.e_phentsize).unwrap(); + if phdr_size < 56 { + return Err(ElfError::InvalidPhdrSize); + } + let phdrs_num = usize::try_from(elf_hdr.e_phnum).unwrap(); + let phdrs_size = phdrs_num + .checked_mul(phdr_size) + .ok_or(ElfError::FileTooShort)?; + let phdrs_end = phdrs_off + .checked_add(phdrs_size) + .ok_or(ElfError::FileTooShort)?; + if phdrs_end > elf_file_buf.len() { + return Err(ElfError::FileTooShort); + } + + // Verify that the section header table is within the file bounds. + let shdr_size = usize::try_from(elf_hdr.e_shentsize).unwrap(); + if shdr_size < 64 { + return Err(ElfError::InvalidShdrSize); + } + if elf_hdr.e_shnum == 0 && elf_hdr.e_shoff != 0 { + // The number of section headers is stored in the first section header's + // ->sh_size member. + elf_hdr.e_shnum = 1; + Self::check_section_header_table_bounds(&elf_hdr, elf_file_buf.len())?; + let shdr0 = Self::read_shdr_from_file(elf_file_buf, &elf_hdr, 0); + elf_hdr.e_shnum = match Elf64Word::try_from(shdr0.sh_size) { + Ok(shnum) => shnum, + Err(_) => return Err(ElfError::InvalidSectionIndex), + }; + } + Self::check_section_header_table_bounds(&elf_hdr, elf_file_buf.len())?; + + // Verify all headers once at load time, so that no error checking will + // be neeeded at each and every subsequent access. + let mut load_segments = Elf64LoadSegments::new(); + let mut max_load_segment_align = 0; + let mut dynamic_file_range: Option<Elf64FileRange> = None; + for i in 0..elf_hdr.e_phnum { + let phdr = Self::read_phdr_from_file(elf_file_buf, &elf_hdr, i); + Self::verify_phdr(&phdr, elf_file_buf.len())?; + if phdr.p_type == Elf64Phdr::PT_LOAD { + let vaddr_range = phdr.vaddr_range(); + if vaddr_range.vaddr_begin == vaddr_range.vaddr_end { + continue; + } + if load_segments.try_insert(vaddr_range, i).is_err() { + return Err(ElfError::LoadSegmentConflict); + } + max_load_segment_align = max_load_segment_align.max(phdr.p_align); + } else if phdr.p_type == Elf64Phdr::PT_DYNAMIC { + if dynamic_file_range.is_some() { + return Err(ElfError::DynamicPhdrConflict); + } + dynamic_file_range = Some(phdr.file_range()); + } + } + + // If ->e_shstrndx == SHN_XINDEX, the actual strndx is stored in first + // section header table's ->sh_link member. + if elf_hdr.e_shstrndx == Elf64Shdr::SHN_XINDEX { + if elf_hdr.e_shnum == 0 { + return Err(ElfError::InvalidSectionIndex); + } + let shdr0 = Self::read_shdr_from_file(elf_file_buf, &elf_hdr, 0); + elf_hdr.e_shstrndx = shdr0.sh_link; + } + if elf_hdr.e_shstrndx != Elf64Shdr::SHN_UNDEF && elf_hdr.e_shstrndx > elf_hdr.e_shnum { + return Err(ElfError::InvalidSectionIndex); + } + + let mut sh_strtab: Option<Elf64Strtab> = None; + for i in 0..elf_hdr.e_shnum { + let shdr = Self::read_shdr_from_file(elf_file_buf, &elf_hdr, i); + Self::verify_shdr(&shdr, elf_file_buf.len(), elf_hdr.e_shnum)?; + + if elf_hdr.e_shstrndx != Elf64Shdr::SHN_UNDEF && i == elf_hdr.e_shstrndx { + if shdr.sh_type != Elf64Shdr::SHT_STRTAB { + return Err(ElfError::IncompatibleSectionType); + } + + let sh_strtab_buf_range = shdr.file_range(); + let sh_strtab_buf = + &elf_file_buf[sh_strtab_buf_range.offset_begin..sh_strtab_buf_range.offset_end]; + sh_strtab = Some(Elf64Strtab::new(sh_strtab_buf)); + } + } + + let dynamic = if let Some(dynamic_file_range) = dynamic_file_range { + let dynamic_buf = + &elf_file_buf[dynamic_file_range.offset_begin..dynamic_file_range.offset_end]; + let dynamic = Elf64Dynamic::read(dynamic_buf)?; + Self::verify_dynamic(&dynamic)?; + Some(dynamic) + } else { + None + }; + + Ok(Self { + elf_file_buf, + elf_hdr, + load_segments, + max_load_segment_align, + sh_strtab, + dynamic, + }) + } + + fn read_phdr_from_file(elf_file_buf: &'a [u8], elf_hdr: &Elf64Hdr, i: Elf64Half) -> Elf64Phdr { + let phdrs_off = usize::try_from(elf_hdr.e_phoff).unwrap(); + let phdr_size = usize::try_from(elf_hdr.e_phentsize).unwrap(); + let i = usize::try_from(i).unwrap(); + let phdr_off = phdrs_off + i * phdr_size; + let phdr_buf = &elf_file_buf[phdr_off..(phdr_off + phdr_size)]; + Elf64Phdr::read(phdr_buf) + } + + fn verify_phdr(phdr: &Elf64Phdr, elf_file_buf_len: usize) -> Result<(), ElfError> { + if phdr.p_type == Elf64Phdr::PT_NULL { + return Ok(()); + } + + phdr.verify()?; + + if phdr.p_filesz != 0 { + let file_range = phdr.file_range(); + if file_range.offset_end > elf_file_buf_len { + return Err(ElfError::FileTooShort); + } + } + + Ok(()) + } + + fn read_phdr(&self, i: Elf64Half) -> Elf64Phdr { + Self::read_phdr_from_file(self.elf_file_buf, &self.elf_hdr, i) + } + + fn check_section_header_table_bounds( + elf_hdr: &Elf64Hdr, + elf_file_buf_len: usize, + ) -> Result<(), ElfError> { + // Verify that the section header table is within the file bounds. + let shdrs_off = usize::try_from(elf_hdr.e_shoff).map_err(|_| ElfError::FileTooShort)?; + let shdr_size = usize::try_from(elf_hdr.e_shentsize).unwrap(); + let shdrs_num = usize::try_from(elf_hdr.e_shnum).unwrap(); + let shdrs_size = shdrs_num + .checked_mul(shdr_size) + .ok_or(ElfError::FileTooShort)?; + let shdrs_end = shdrs_off + .checked_add(shdrs_size) + .ok_or(ElfError::FileTooShort)?; + if shdrs_end > elf_file_buf_len { + return Err(ElfError::FileTooShort); + } + Ok(()) + } + + fn read_shdr_from_file(elf_file_buf: &'a [u8], elf_hdr: &Elf64Hdr, i: Elf64Word) -> Elf64Shdr { + let shdrs_off = usize::try_from(elf_hdr.e_shoff).unwrap(); + let shdr_size = usize::try_from(elf_hdr.e_shentsize).unwrap(); + let i = usize::try_from(i).unwrap(); + let shdr_off = shdrs_off + i * shdr_size; + let shdr_buf = &elf_file_buf[shdr_off..(shdr_off + shdr_size)]; + Elf64Shdr::read(shdr_buf) + } + + fn verify_shdr( + shdr: &Elf64Shdr, + elf_file_buf_len: usize, + shnum: Elf64Word, + ) -> Result<(), ElfError> { + if shdr.sh_type == Elf64Shdr::SHT_NULL { + return Ok(()); + } + + shdr.verify()?; + + if shdr.sh_link > shnum + || shdr.sh_flags.contains(Elf64ShdrFlags::INFO_LINK) && shdr.sh_info > shnum + { + return Err(ElfError::InvalidSectionIndex); + } + + let file_range = shdr.file_range(); + if file_range.offset_end > elf_file_buf_len { + return Err(ElfError::FileTooShort); + } + + Ok(()) + } + + fn read_shdr(&self, i: Elf64Word) -> Elf64Shdr { + Self::read_shdr_from_file(self.elf_file_buf, &self.elf_hdr, i) + } + + pub fn shdrs_iter(&self) -> Elf64ShdrIterator { + Elf64ShdrIterator::new(self) + } + + fn verify_dynamic(dynamic: &Elf64Dynamic) -> Result<(), ElfError> { + dynamic.verify()?; + Ok(()) + } + + fn map_vaddr_to_file_off( + &self, + vaddr_begin: Elf64Addr, + vaddr_end: Option<Elf64Addr>, + ) -> Result<Elf64FileRange, ElfError> { + if vaddr_begin == Elf64Addr::MAX { + return Err(ElfError::UnmappedVaddrRange); + } + let vaddr_range = Elf64AddrRange { + vaddr_begin, + vaddr_end: vaddr_end.unwrap_or(vaddr_begin + 1), + }; + let (phdr_index, offset) = match self.load_segments.lookup_vaddr_range(&vaddr_range) { + Some(load_segment) => (load_segment.0, load_segment.1), + None => return Err(ElfError::UnmappedVaddrRange), + }; + + let phdr = self.read_phdr(phdr_index); + let segment_file_range = phdr.file_range(); + let offset_in_segment = usize::try_from(offset).map_err(|_| ElfError::InvalidFileRange)?; + let offset_begin = segment_file_range + .offset_begin + .checked_add(offset_in_segment) + .ok_or(ElfError::InvalidFileRange)?; + let offset_end = match vaddr_end { + Some(vaddr_end) => { + let len = vaddr_end - vaddr_begin; + let len = usize::try_from(len).map_err(|_| ElfError::InvalidFileRange)?; + let offset_end = offset_begin + .checked_add(len) + .ok_or(ElfError::InvalidFileRange)?; + + // A PT_LOAD segment is not necessarily backed completely by ELF + // file content: ->p_filesz can be <= ->memsz. + if offset_end > segment_file_range.offset_end { + return Err(ElfError::UnbackedVaddrRange); + } + + offset_end + } + None => { + // The query did not specify an end address, as can e.g. happen + // when examining some table referenced from .dynamic with + // unknown size. Return the upper segment bound. + segment_file_range.offset_end + } + }; + Ok(Elf64FileRange { + offset_begin, + offset_end, + }) + } + + fn map_vaddr_to_file_buf( + &self, + vaddr_begin: Elf64Addr, + vaddr_end: Option<Elf64Addr>, + ) -> Result<&[u8], ElfError> { + let file_range = self.map_vaddr_to_file_off(vaddr_begin, vaddr_end)?; + Ok(&self.elf_file_buf[file_range.offset_begin..file_range.offset_end]) + } + + // For PIE executables, relieve the using code from offset calculations due + // to address alignment. Do it here and consistently. The address passed here + // may be either + // - a load address corresponding as-is to the first load segment's beginning or + // - the load address corresponding as-is to the first load segment's + // beginning rounded down to match the alginment constraints. + // The passed address will be mapped to the first variant in either case. + fn image_load_addr(&self, image_load_addr: Elf64Addr) -> Elf64Addr { + if self.max_load_segment_align == 0 { + image_load_addr + } else { + let aligned_image_load_addr = image_load_addr & !(self.max_load_segment_align - 1); + aligned_image_load_addr + self.image_load_align_offset() + } + } + + fn image_load_align_offset(&self) -> Elf64Off { + if self.max_load_segment_align == 0 { + return 0; + } + + // The first segment loaded is not necessarily aligned to the maximum of + // all segment alignment constraints. Determine the offset from the next + // lower aligned address to the first segment's beginning. + self.load_segments.total_vaddr_range().vaddr_begin & (self.max_load_segment_align - 1) + } + + // The ELF "base address" has a well-defined meaning: it is defined in the + // spec as the difference between the lowest address of the actual memory + // image the file has been loaded into and the lowest vaddr of all the + // PT_LOAD program headers. Calculate it in two's complement representation. + fn load_base(&self, image_load_addr: Elf64Addr) -> Elf64Xword { + let image_load_addr = self.image_load_addr(image_load_addr); + image_load_addr.wrapping_sub(self.load_segments.total_vaddr_range().vaddr_begin) + } + + pub fn image_load_vaddr_alloc_info(&self) -> Elf64ImageLoadVaddrAllocInfo { + let mut range = self.load_segments.total_vaddr_range(); + + if self.max_load_segment_align != 0 { + range.vaddr_begin &= !(self.max_load_segment_align - 1); + } + + let pie = self.dynamic.as_ref().map(|d| d.is_pie()).unwrap_or(false); + let align = if pie { + Some(self.max_load_segment_align) + } else { + None + }; + + Elf64ImageLoadVaddrAllocInfo { range, align } + } + + pub fn image_load_segment_iter( + &'a self, + image_load_addr: Elf64Addr, + ) -> Elf64ImageLoadSegmentIterator<'a> { + let load_base = self.load_base(image_load_addr); + Elf64ImageLoadSegmentIterator { + elf_file: self, + load_base, + next: 0, + } + } + + pub fn apply_dyn_relas<RP: Elf64RelocProcessor>( + &'a self, + rela_proc: RP, + image_load_addr: Elf64Addr, + ) -> Result<Option<Elf64AppliedRelaIterator<'a, RP>>, ElfError> { + let dynamic = match &self.dynamic { + Some(dynamic) => dynamic, + None => return Ok(None), + }; + let dynamic_rela = match &dynamic.rela { + Some(dynamic_rela) => dynamic_rela, + None => return Ok(None), + }; + + let load_base = self.load_base(image_load_addr); + + let relas_file_range = dynamic_rela.vaddr_range(); + let relas_buf = self.map_vaddr_to_file_buf( + relas_file_range.vaddr_begin, + Some(relas_file_range.vaddr_end), + )?; + let relas = Elf64Relas::new(relas_buf, dynamic_rela.entsize)?; + + let symtab = match &dynamic.symtab { + Some(dynamic_symtab) => { + let syms_buf = self.map_vaddr_to_file_buf(dynamic_symtab.base_vaddr, None)?; + let symtab = Elf64Symtab::new(syms_buf, dynamic_symtab.entsize)?; + Some(symtab) + } + None => None, + }; + + Ok(Some(Elf64AppliedRelaIterator::new( + rela_proc, + load_base, + &self.load_segments, + relas, + symtab, + ))) + } + + pub fn get_entry(&self, image_load_addr: Elf64Addr) -> Elf64Addr { + self.elf_hdr + .e_entry + .wrapping_add(self.load_base(image_load_addr)) + } +} + +#[derive(Debug)] +pub struct Elf64Hdr { + #[allow(unused)] + e_ident: [Elf64char; 16], + #[allow(unused)] + e_type: Elf64Half, + #[allow(unused)] + e_machine: Elf64Half, + #[allow(unused)] + e_version: Elf64Word, + e_entry: Elf64Addr, + e_phoff: Elf64Off, + e_shoff: Elf64Off, + #[allow(unused)] + e_flags: Elf64Word, + #[allow(unused)] + e_ehsize: Elf64Half, + e_phentsize: Elf64Half, + e_phnum: Elf64Half, + e_shentsize: Elf64Half, + e_shnum: Elf64Word, // The actual Elf64Hdr entry is Elf64Half, on overflow it's read from section + // table entry zero + e_shstrndx: Elf64Word, // The actual Elf64Hdr entry is Elf64Half, on overflow it's read from section + // table entry zero +} + +impl Elf64Hdr { + const EI_MAG0: usize = 0; + const EI_CLASS: usize = 4; + const EI_DATA: usize = 5; + const EI_VERSION: usize = 6; + const EI_OSABI: usize = 7; + + const ELFMAG: [Elf64char; 4] = [0x7f, b'E', b'L', b'F']; + + const ELFCLASS64: Elf64char = 2; + + const ELFDATA2LSB: Elf64char = 1; + + const ELFOSABI_NONE: Elf64char = 0; + const ELFOSABI_GNU: Elf64char = 3; + + const ET_EXEC: Elf64Half = 2; + + const EM_X86_64: Elf64Half = 62; + + const EV_CURRENT: Elf64Word = 1; + + fn read(buf: &[u8]) -> Result<Self, ElfError> { + // Examine the e_ident[] magic. + if buf.len() < 16 { + return Err(ElfError::FileTooShort); + } + let e_ident: [Elf64char; 16] = buf[..16].try_into().unwrap(); + if e_ident[Self::EI_MAG0..(Self::EI_MAG0 + mem::size_of_val(&Self::ELFMAG))] != Self::ELFMAG + { + return Err(ElfError::UnrecognizedMagic); + } else if e_ident[Self::EI_CLASS] != Self::ELFCLASS64 { + return Err(ElfError::UnsupportedClass); + } else if e_ident[Self::EI_DATA] != Self::ELFDATA2LSB { + return Err(ElfError::UnsupportedEndianess); + } else if e_ident[Self::EI_VERSION] != Self::EV_CURRENT as Elf64char { + return Err(ElfError::UnsupportedVersion); + } else if e_ident[Self::EI_OSABI] != Self::ELFOSABI_NONE + && e_ident[Self::EI_OSABI] != Self::ELFOSABI_GNU + { + return Err(ElfError::UnsupportedOsAbi); + } + + // ELF file is confirmed to be of ELFCLASS64, so the total header size + // should equal 64 bytes. + if buf.len() < 64 { + return Err(ElfError::FileTooShort); + } + let e_type = Elf64Half::from_le_bytes(buf[16..18].try_into().unwrap()); + let e_machine = Elf64Half::from_le_bytes(buf[18..20].try_into().unwrap()); + let e_version = Elf64Word::from_le_bytes(buf[20..24].try_into().unwrap()); + let e_entry = Elf64Addr::from_le_bytes(buf[24..32].try_into().unwrap()); + let e_phoff = Elf64Off::from_le_bytes(buf[32..40].try_into().unwrap()); + let e_shoff = Elf64Off::from_le_bytes(buf[40..48].try_into().unwrap()); + let e_flags = Elf64Word::from_le_bytes(buf[48..52].try_into().unwrap()); + let e_ehsize = Elf64Half::from_le_bytes(buf[52..54].try_into().unwrap()); + let e_phentsize = Elf64Half::from_le_bytes(buf[54..56].try_into().unwrap()); + let e_phnum = Elf64Half::from_le_bytes(buf[56..58].try_into().unwrap()); + let e_shentsize = Elf64Half::from_le_bytes(buf[58..60].try_into().unwrap()); + let e_shnum = Elf64Half::from_le_bytes(buf[60..62].try_into().unwrap()) as Elf64Word; + let e_shstrndx = Elf64Half::from_le_bytes(buf[62..64].try_into().unwrap()) as Elf64Word; + + if e_type != Self::ET_EXEC { + return Err(ElfError::UnsupportedType); + } + if e_machine != Self::EM_X86_64 { + return Err(ElfError::UnsupportedMachine); + } + if e_version != Self::EV_CURRENT { + return Err(ElfError::UnsupportedVersion); + } + + Ok(Self { + e_ident, + e_type, + e_machine, + e_version, + e_entry, + e_phoff, + e_shoff, + e_flags, + e_ehsize, + e_phentsize, + e_phnum, + e_shentsize, + e_shnum, + e_shstrndx, + }) + } +} + +#[derive(Debug)] +pub struct Elf64Phdr { + pub p_type: Elf64Word, + pub p_flags: Elf64PhdrFlags, + pub p_offset: Elf64Off, + pub p_vaddr: Elf64Addr, + pub p_paddr: Elf64Addr, + pub p_filesz: Elf64Xword, + pub p_memsz: Elf64Xword, + pub p_align: Elf64Xword, +} + +bitflags! { + pub struct Elf64PhdrFlags : Elf64Word { + const EXECUTE = 0x01; + const WRITE = 0x02; + const READ = 0x04; + } +} + +impl Elf64Phdr { + pub const PT_NULL: Elf64Word = 1; + pub const PT_LOAD: Elf64Word = 1; + pub const PT_DYNAMIC: Elf64Word = 2; + + fn read(phdr_buf: &[u8]) -> Self { + let p_type = Elf64Word::from_le_bytes(phdr_buf[0..4].try_into().unwrap()); + let p_flags = Elf64Word::from_le_bytes(phdr_buf[4..8].try_into().unwrap()); + let p_offset = Elf64Off::from_le_bytes(phdr_buf[8..16].try_into().unwrap()); + let p_vaddr = Elf64Addr::from_le_bytes(phdr_buf[16..24].try_into().unwrap()); + let p_paddr = Elf64Addr::from_le_bytes(phdr_buf[24..32].try_into().unwrap()); + let p_filesz = Elf64Xword::from_le_bytes(phdr_buf[32..40].try_into().unwrap()); + let p_memsz = Elf64Xword::from_le_bytes(phdr_buf[40..48].try_into().unwrap()); + let p_align = Elf64Xword::from_le_bytes(phdr_buf[48..56].try_into().unwrap()); + + let p_flags = Elf64PhdrFlags::from_bits_truncate(p_flags); + + Self { + p_type, + p_flags, + p_offset, + p_vaddr, + p_paddr, + p_filesz, + p_memsz, + p_align, + } + } + + fn verify(&self) -> Result<(), ElfError> { + if self.p_type == Self::PT_NULL { + return Ok(()); + } + + if self.p_type == Self::PT_LOAD && self.p_memsz < self.p_filesz { + return Err(ElfError::InvalidSegmentSize); + } + + if self.p_align != 0 { + if !self.p_align.is_power_of_two() { + return Err(ElfError::InvalidAddressAlignment); + } + if self.p_vaddr & (self.p_align - 1) != 0 { + return Err(ElfError::UnalignedSegmentAddress); + } + } + + if self.p_filesz != 0 { + Elf64FileRange::try_from((self.p_offset, self.p_filesz))?; + } + if self.p_memsz != 0 { + Elf64AddrRange::try_from((self.p_vaddr, self.p_memsz))?; + } + + Ok(()) + } + + fn file_range(&self) -> Elf64FileRange { + Elf64FileRange::try_from((self.p_offset, self.p_filesz)).unwrap() + } + + fn vaddr_range(&self) -> Elf64AddrRange { + Elf64AddrRange::try_from((self.p_vaddr, self.p_memsz)).unwrap() + } +} + +#[derive(Debug)] +pub struct Elf64Shdr { + pub sh_name: Elf64Word, + sh_type: Elf64Word, + sh_flags: Elf64ShdrFlags, + sh_addr: Elf64Addr, + sh_offset: Elf64Off, + sh_size: Elf64Xword, + sh_link: Elf64Word, + sh_info: Elf64Word, + sh_addralign: Elf64Xword, + #[allow(unused)] + sh_entsize: Elf64Xword, +} + +bitflags! { + pub struct Elf64ShdrFlags : Elf64Xword { + const WRITE = 0x001; + const ALLOC = 0x002; + const EXECINSTR = 0x004; + const MERGE = 0x010; + const STRINGS = 0x020; + const INFO_LINK = 0x040; + const LINK_ORDER = 0x080; + const OS_NONCONFORMING = 0x100; + const GROUP = 0x200; + const TLS = 0x400; + const COMPRESSED = 0x800; + } +} + +impl Elf64Shdr { + const SHN_UNDEF: Elf64Word = 0; + const SHN_ABS: Elf64Word = 0xfff1; + const SHN_XINDEX: Elf64Word = 0xffff; + + pub const SHT_NULL: Elf64Word = 0; + pub const SHT_STRTAB: Elf64Word = 3; + pub const SHT_NOBITS: Elf64Word = 8; + + fn read(shdr_buf: &'_ [u8]) -> Self { + let sh_name = Elf64Word::from_le_bytes(shdr_buf[0..4].try_into().unwrap()); + let sh_type = Elf64Word::from_le_bytes(shdr_buf[4..8].try_into().unwrap()); + let sh_flags = Elf64Xword::from_le_bytes(shdr_buf[8..16].try_into().unwrap()); + let sh_addr = Elf64Addr::from_le_bytes(shdr_buf[16..24].try_into().unwrap()); + let sh_offset = Elf64Off::from_le_bytes(shdr_buf[24..32].try_into().unwrap()); + let sh_size = Elf64Xword::from_le_bytes(shdr_buf[32..40].try_into().unwrap()); + let sh_link = Elf64Word::from_le_bytes(shdr_buf[40..44].try_into().unwrap()); + let sh_info = Elf64Word::from_le_bytes(shdr_buf[44..48].try_into().unwrap()); + let sh_addralign = Elf64Xword::from_le_bytes(shdr_buf[48..56].try_into().unwrap()); + let sh_entsize = Elf64Xword::from_le_bytes(shdr_buf[56..64].try_into().unwrap()); + + let sh_flags = Elf64ShdrFlags::from_bits_truncate(sh_flags); + + Self { + sh_name, + sh_type, + sh_flags, + sh_addr, + sh_offset, + sh_size, + sh_link, + sh_info, + sh_addralign, + sh_entsize, + } + } + + fn verify(&self) -> Result<(), ElfError> { + if self.sh_type == Self::SHT_NULL { + return Ok(()); + } + + if self.sh_type != Self::SHT_NOBITS { + Elf64FileRange::try_from((self.sh_offset, self.sh_size))?; + } else { + Elf64FileRange::try_from((self.sh_offset, 0))?; + } + + if self.sh_flags.contains(Elf64ShdrFlags::ALLOC) { + Elf64AddrRange::try_from((self.sh_addr, self.sh_size))?; + + if self.sh_addralign != 0 { + if self.sh_addralign != 0 && !self.sh_addralign.is_power_of_two() { + return Err(ElfError::InvalidAddressAlignment); + } + if self.sh_addr & (self.sh_addralign - 1) != 0 { + return Err(ElfError::InvalidAddressAlignment); + } + } + } else if self.sh_addr != 0 { + return Err(ElfError::InvalidAddressRange); + } + + Ok(()) + } + + fn file_range(&self) -> Elf64FileRange { + if self.sh_type != Self::SHT_NOBITS { + Elf64FileRange::try_from((self.sh_offset, self.sh_size)).unwrap() + } else { + Elf64FileRange::try_from((self.sh_offset, 0)).unwrap() + } + } +} + +#[derive(Debug)] +struct Elf64LoadSegments { + segments: Vec<(Elf64AddrRange, Elf64Half)>, +} + +impl Elf64LoadSegments { + fn new() -> Self { + Self { + segments: Vec::new(), + } + } + + fn find_first_not_before(&self, range: &Elf64AddrRange) -> Option<usize> { + let i = self.segments.partition_point(|segment| { + matches!(segment.0.partial_cmp(range), Some(cmp::Ordering::Less)) + }); + + if i != self.segments.len() { + Some(i) + } else { + None + } + } + + fn try_insert(&mut self, segment: Elf64AddrRange, phdr_index: Elf64Half) -> Result<(), ()> { + let i = self.find_first_not_before(&segment); + match i { + Some(i) => { + match segment.partial_cmp(&self.segments[i].0) { + Some(cmp::Ordering::Less) => { + // Ok, no overlap. + self.segments.insert(i, (segment, phdr_index)); + Ok(()) + } + _ => Err(()), + } + } + None => { + self.segments.push((segment, phdr_index)); + Ok(()) + } + } + } + + fn lookup_vaddr_range(&self, range: &Elf64AddrRange) -> Option<(Elf64Half, Elf64Xword)> { + let i = self.find_first_not_before(range); + let i = match i { + Some(i) => i, + None => return None, + }; + + let segment = &self.segments[i]; + if segment.0.vaddr_begin <= range.vaddr_begin && range.vaddr_end <= segment.0.vaddr_end { + let offset_in_segment = range.vaddr_begin - segment.0.vaddr_begin; + Some((segment.1, offset_in_segment)) + } else { + None + } + } + + fn total_vaddr_range(&self) -> Elf64AddrRange { + Elf64AddrRange { + vaddr_begin: self + .segments + .first() + .map(|first| first.0.vaddr_begin) + .unwrap_or(0), + vaddr_end: self + .segments + .last() + .map(|last| last.0.vaddr_end) + .unwrap_or(0), + } + }
```suggestion fn total_vaddr_range(&self) -> Elf64AddrRange { Elf64AddrRange { vaddr_begin: self .segments .first() .map_or(0, |first| first.0.vaddr_begin), vaddr_end: self .segments .last() .map_or(0, |last| last.0.vaddr_end), } } ```
svsm
github_2023
others
21
coconut-svsm
Freax13
@@ -0,0 +1,1612 @@ +// SPDX-License-Identifier: (GPL-2.0-or-later OR MIT) +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Nicolai Stange <nstange@suse.de> +// +// vim: ts=4 sw=4 et + +extern crate alloc; + +use alloc::vec::Vec; +use bitflags::bitflags; +use core::cmp; +use core::convert; +use core::ffi; +use core::fmt; +use core::matches; +use core::mem; + +#[derive(Debug)] +pub enum ElfError { + FileTooShort, + + InvalidAddressRange, + InvalidAddressAlignment, + InvalidFileRange, + UnmappedVaddrRange, + UnbackedVaddrRange, + + UnrecognizedMagic, + UnsupportedClass, + UnsupportedEndianess, + UnsupportedOsAbi, + UnsupportedType, + UnsupportedMachine, + UnsupportedVersion, + InvalidPhdrSize, + InvalidShdrSize, + + InvalidSegmentSize, + UnalignedSegmentAddress, + LoadSegmentConflict, + DynamicPhdrConflict, + + UnterminatedDynamicSection, + DynamicFieldConflict, + UnrecognizedDynamicField, + MissingDynamicField, + + InvalidSectionIndex, + IncompatibleSectionType, + + InvalidStrtabString, + + InvalidSymbolEntrySize, + InvalidSymbolIndex, + + InvalidRelocationEntrySize, + UnrecognizedRelocationType, + InvalidRelocationOffset, + RelocationAgainstUndefSymbol, +} + +impl fmt::Display for ElfError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::FileTooShort => { + write!(f, "ELF file too short") + } + + Self::InvalidAddressRange => { + write!(f, "invalid ELF address range") + } + Self::InvalidAddressAlignment => { + write!(f, "invalid ELF address alignment") + } + Self::InvalidFileRange => { + write!(f, "invalid ELF file range") + } + Self::UnmappedVaddrRange => { + write!(f, "reference to unmapped ELF address range") + } + Self::UnbackedVaddrRange => { + write!(f, "reference ELF address range not backed by file") + } + + Self::UnrecognizedMagic => { + write!(f, "unrecognized ELF magic") + } + Self::UnsupportedClass => { + write!(f, "unsupported ELF class") + } + Self::UnsupportedEndianess => { + write!(f, "unsupported ELF endianess") + } + Self::UnsupportedOsAbi => { + write!(f, "unsupported ELF ABI") + } + Self::UnsupportedType => { + write!(f, "unsupported ELF file type") + } + Self::UnsupportedMachine => { + write!(f, "unsupported ELF machine") + } + Self::UnsupportedVersion => { + write!(f, "unsupported ELF version") + } + Self::InvalidPhdrSize => { + write!(f, "invalid ELF program header size") + } + Self::InvalidShdrSize => { + write!(f, "invalid ELF section header size") + } + + Self::InvalidSegmentSize => { + write!(f, "invalid ELF segment size") + } + Self::UnalignedSegmentAddress => { + write!(f, "unaligned ELF segment address") + } + Self::LoadSegmentConflict => { + write!(f, "ELF PT_LOAD segment conflict") + } + Self::DynamicPhdrConflict => { + write!(f, "multiple ELF PT_DYNAMIC program headers") + } + + Self::UnterminatedDynamicSection => { + write!(f, "unterminated ELF dynamic section") + } + Self::DynamicFieldConflict => { + write!(f, "conflicting fields in ELF dynamic section") + } + Self::UnrecognizedDynamicField => { + write!(f, "unrecognized field in ELF dynamic section") + } + Self::MissingDynamicField => { + write!(f, "missing field in ELF dynamic section") + } + + Self::InvalidSectionIndex => { + write!(f, "invalid ELF section index") + } + Self::IncompatibleSectionType => { + write!(f, "unexpected ELF section type") + } + + Self::InvalidStrtabString => { + write!(f, "invalid ELF strtab string") + } + + Self::InvalidSymbolEntrySize => { + write!(f, "invalid ELF symbol entry size") + } + Self::InvalidSymbolIndex => { + write!(f, "invalid ELF symbol index") + } + + Self::InvalidRelocationEntrySize => { + write!(f, "invalid ELF relocation entry size") + } + Self::UnrecognizedRelocationType => { + write!(f, "unrecognized ELF relocation type") + } + Self::InvalidRelocationOffset => { + write!(f, "ELF relocation offset out of bounds") + } + Self::RelocationAgainstUndefSymbol => { + write!(f, "ELF relocation against undefined symbol") + } + } + } +} + +pub type Elf64Addr = u64; +pub type Elf64Off = u64; +pub type Elf64Half = u16; +pub type Elf64Word = u32; +#[allow(unused)] +pub type Elf64Sword = i32; +pub type Elf64Xword = u64; +pub type Elf64Sxword = i64; +pub type Elf64char = u8; + +#[derive(PartialEq, Eq, Debug)] +pub struct Elf64AddrRange { + pub vaddr_begin: Elf64Addr, + pub vaddr_end: Elf64Addr, +} + +impl Elf64AddrRange { + pub fn len(&self) -> Elf64Xword { + self.vaddr_end - self.vaddr_begin + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +impl convert::TryFrom<(Elf64Addr, Elf64Xword)> for Elf64AddrRange { + type Error = ElfError; + + fn try_from(value: (Elf64Addr, Elf64Xword)) -> Result<Self, Self::Error> { + let vaddr_begin = value.0; + let size = value.1; + let vaddr_end = vaddr_begin + .checked_add(size) + .ok_or(ElfError::InvalidAddressRange)?; + Ok(Self { + vaddr_begin, + vaddr_end, + }) + } +} + +impl cmp::PartialOrd for Elf64AddrRange { + fn partial_cmp(&self, other: &Elf64AddrRange) -> Option<cmp::Ordering> { + if self.vaddr_end <= other.vaddr_begin { + Some(cmp::Ordering::Less) + } else if self.vaddr_begin >= other.vaddr_end { + Some(cmp::Ordering::Greater) + } else if self == other { + Some(cmp::Ordering::Equal) + } else { + None + } + } +} + +pub struct Elf64FileRange { + pub offset_begin: usize, + pub offset_end: usize, +} + +impl convert::TryFrom<(Elf64Off, Elf64Xword)> for Elf64FileRange { + type Error = ElfError; + + fn try_from(value: (Elf64Off, Elf64Xword)) -> Result<Self, Self::Error> { + let offset_begin = usize::try_from(value.0).map_err(|_| ElfError::InvalidFileRange)?; + let size = usize::try_from(value.1).map_err(|_| ElfError::InvalidFileRange)?; + let offset_end = offset_begin + .checked_add(size) + .ok_or(ElfError::InvalidFileRange)?; + Ok(Self { + offset_begin, + offset_end, + }) + } +} + +pub struct Elf64File<'a> { + elf_file_buf: &'a [u8], + elf_hdr: Elf64Hdr, + load_segments: Elf64LoadSegments, + max_load_segment_align: Elf64Xword, + #[allow(unused)] + sh_strtab: Option<Elf64Strtab<'a>>, + dynamic: Option<Elf64Dynamic>, +} + +impl<'a> Elf64File<'a> { + pub fn read(elf_file_buf: &'a [u8]) -> Result<Self, ElfError> { + let mut elf_hdr = Elf64Hdr::read(elf_file_buf)?; + + // Verify that the program header table is within the file bounds. + let phdrs_off = usize::try_from(elf_hdr.e_phoff).map_err(|_| ElfError::FileTooShort)?; + let phdr_size = usize::try_from(elf_hdr.e_phentsize).unwrap(); + if phdr_size < 56 { + return Err(ElfError::InvalidPhdrSize); + } + let phdrs_num = usize::try_from(elf_hdr.e_phnum).unwrap(); + let phdrs_size = phdrs_num + .checked_mul(phdr_size) + .ok_or(ElfError::FileTooShort)?; + let phdrs_end = phdrs_off + .checked_add(phdrs_size) + .ok_or(ElfError::FileTooShort)?; + if phdrs_end > elf_file_buf.len() { + return Err(ElfError::FileTooShort); + } + + // Verify that the section header table is within the file bounds. + let shdr_size = usize::try_from(elf_hdr.e_shentsize).unwrap(); + if shdr_size < 64 { + return Err(ElfError::InvalidShdrSize); + } + if elf_hdr.e_shnum == 0 && elf_hdr.e_shoff != 0 { + // The number of section headers is stored in the first section header's + // ->sh_size member. + elf_hdr.e_shnum = 1; + Self::check_section_header_table_bounds(&elf_hdr, elf_file_buf.len())?; + let shdr0 = Self::read_shdr_from_file(elf_file_buf, &elf_hdr, 0); + elf_hdr.e_shnum = match Elf64Word::try_from(shdr0.sh_size) { + Ok(shnum) => shnum, + Err(_) => return Err(ElfError::InvalidSectionIndex), + }; + } + Self::check_section_header_table_bounds(&elf_hdr, elf_file_buf.len())?; + + // Verify all headers once at load time, so that no error checking will + // be neeeded at each and every subsequent access. + let mut load_segments = Elf64LoadSegments::new(); + let mut max_load_segment_align = 0; + let mut dynamic_file_range: Option<Elf64FileRange> = None; + for i in 0..elf_hdr.e_phnum { + let phdr = Self::read_phdr_from_file(elf_file_buf, &elf_hdr, i); + Self::verify_phdr(&phdr, elf_file_buf.len())?; + if phdr.p_type == Elf64Phdr::PT_LOAD { + let vaddr_range = phdr.vaddr_range(); + if vaddr_range.vaddr_begin == vaddr_range.vaddr_end { + continue; + } + if load_segments.try_insert(vaddr_range, i).is_err() { + return Err(ElfError::LoadSegmentConflict); + } + max_load_segment_align = max_load_segment_align.max(phdr.p_align); + } else if phdr.p_type == Elf64Phdr::PT_DYNAMIC { + if dynamic_file_range.is_some() { + return Err(ElfError::DynamicPhdrConflict); + } + dynamic_file_range = Some(phdr.file_range()); + } + } + + // If ->e_shstrndx == SHN_XINDEX, the actual strndx is stored in first + // section header table's ->sh_link member. + if elf_hdr.e_shstrndx == Elf64Shdr::SHN_XINDEX { + if elf_hdr.e_shnum == 0 { + return Err(ElfError::InvalidSectionIndex); + } + let shdr0 = Self::read_shdr_from_file(elf_file_buf, &elf_hdr, 0); + elf_hdr.e_shstrndx = shdr0.sh_link; + } + if elf_hdr.e_shstrndx != Elf64Shdr::SHN_UNDEF && elf_hdr.e_shstrndx > elf_hdr.e_shnum { + return Err(ElfError::InvalidSectionIndex); + } + + let mut sh_strtab: Option<Elf64Strtab> = None; + for i in 0..elf_hdr.e_shnum { + let shdr = Self::read_shdr_from_file(elf_file_buf, &elf_hdr, i); + Self::verify_shdr(&shdr, elf_file_buf.len(), elf_hdr.e_shnum)?; + + if elf_hdr.e_shstrndx != Elf64Shdr::SHN_UNDEF && i == elf_hdr.e_shstrndx { + if shdr.sh_type != Elf64Shdr::SHT_STRTAB { + return Err(ElfError::IncompatibleSectionType); + } + + let sh_strtab_buf_range = shdr.file_range(); + let sh_strtab_buf = + &elf_file_buf[sh_strtab_buf_range.offset_begin..sh_strtab_buf_range.offset_end]; + sh_strtab = Some(Elf64Strtab::new(sh_strtab_buf)); + } + } + + let dynamic = if let Some(dynamic_file_range) = dynamic_file_range { + let dynamic_buf = + &elf_file_buf[dynamic_file_range.offset_begin..dynamic_file_range.offset_end]; + let dynamic = Elf64Dynamic::read(dynamic_buf)?; + Self::verify_dynamic(&dynamic)?; + Some(dynamic) + } else { + None + }; + + Ok(Self { + elf_file_buf, + elf_hdr, + load_segments, + max_load_segment_align, + sh_strtab, + dynamic, + }) + } + + fn read_phdr_from_file(elf_file_buf: &'a [u8], elf_hdr: &Elf64Hdr, i: Elf64Half) -> Elf64Phdr { + let phdrs_off = usize::try_from(elf_hdr.e_phoff).unwrap(); + let phdr_size = usize::try_from(elf_hdr.e_phentsize).unwrap(); + let i = usize::try_from(i).unwrap(); + let phdr_off = phdrs_off + i * phdr_size; + let phdr_buf = &elf_file_buf[phdr_off..(phdr_off + phdr_size)]; + Elf64Phdr::read(phdr_buf) + } + + fn verify_phdr(phdr: &Elf64Phdr, elf_file_buf_len: usize) -> Result<(), ElfError> { + if phdr.p_type == Elf64Phdr::PT_NULL { + return Ok(()); + } + + phdr.verify()?; + + if phdr.p_filesz != 0 { + let file_range = phdr.file_range(); + if file_range.offset_end > elf_file_buf_len { + return Err(ElfError::FileTooShort); + } + } + + Ok(()) + } + + fn read_phdr(&self, i: Elf64Half) -> Elf64Phdr { + Self::read_phdr_from_file(self.elf_file_buf, &self.elf_hdr, i) + } + + fn check_section_header_table_bounds( + elf_hdr: &Elf64Hdr, + elf_file_buf_len: usize, + ) -> Result<(), ElfError> { + // Verify that the section header table is within the file bounds. + let shdrs_off = usize::try_from(elf_hdr.e_shoff).map_err(|_| ElfError::FileTooShort)?; + let shdr_size = usize::try_from(elf_hdr.e_shentsize).unwrap(); + let shdrs_num = usize::try_from(elf_hdr.e_shnum).unwrap(); + let shdrs_size = shdrs_num + .checked_mul(shdr_size) + .ok_or(ElfError::FileTooShort)?; + let shdrs_end = shdrs_off + .checked_add(shdrs_size) + .ok_or(ElfError::FileTooShort)?; + if shdrs_end > elf_file_buf_len { + return Err(ElfError::FileTooShort); + } + Ok(()) + } + + fn read_shdr_from_file(elf_file_buf: &'a [u8], elf_hdr: &Elf64Hdr, i: Elf64Word) -> Elf64Shdr { + let shdrs_off = usize::try_from(elf_hdr.e_shoff).unwrap(); + let shdr_size = usize::try_from(elf_hdr.e_shentsize).unwrap(); + let i = usize::try_from(i).unwrap(); + let shdr_off = shdrs_off + i * shdr_size; + let shdr_buf = &elf_file_buf[shdr_off..(shdr_off + shdr_size)]; + Elf64Shdr::read(shdr_buf) + } + + fn verify_shdr( + shdr: &Elf64Shdr, + elf_file_buf_len: usize, + shnum: Elf64Word, + ) -> Result<(), ElfError> { + if shdr.sh_type == Elf64Shdr::SHT_NULL { + return Ok(()); + } + + shdr.verify()?; + + if shdr.sh_link > shnum + || shdr.sh_flags.contains(Elf64ShdrFlags::INFO_LINK) && shdr.sh_info > shnum + { + return Err(ElfError::InvalidSectionIndex); + } + + let file_range = shdr.file_range(); + if file_range.offset_end > elf_file_buf_len { + return Err(ElfError::FileTooShort); + } + + Ok(()) + } + + fn read_shdr(&self, i: Elf64Word) -> Elf64Shdr { + Self::read_shdr_from_file(self.elf_file_buf, &self.elf_hdr, i) + } + + pub fn shdrs_iter(&self) -> Elf64ShdrIterator { + Elf64ShdrIterator::new(self) + } + + fn verify_dynamic(dynamic: &Elf64Dynamic) -> Result<(), ElfError> { + dynamic.verify()?; + Ok(()) + } + + fn map_vaddr_to_file_off( + &self, + vaddr_begin: Elf64Addr, + vaddr_end: Option<Elf64Addr>, + ) -> Result<Elf64FileRange, ElfError> { + if vaddr_begin == Elf64Addr::MAX { + return Err(ElfError::UnmappedVaddrRange); + } + let vaddr_range = Elf64AddrRange { + vaddr_begin, + vaddr_end: vaddr_end.unwrap_or(vaddr_begin + 1), + }; + let (phdr_index, offset) = match self.load_segments.lookup_vaddr_range(&vaddr_range) { + Some(load_segment) => (load_segment.0, load_segment.1), + None => return Err(ElfError::UnmappedVaddrRange), + }; + + let phdr = self.read_phdr(phdr_index); + let segment_file_range = phdr.file_range(); + let offset_in_segment = usize::try_from(offset).map_err(|_| ElfError::InvalidFileRange)?; + let offset_begin = segment_file_range + .offset_begin + .checked_add(offset_in_segment) + .ok_or(ElfError::InvalidFileRange)?; + let offset_end = match vaddr_end { + Some(vaddr_end) => { + let len = vaddr_end - vaddr_begin; + let len = usize::try_from(len).map_err(|_| ElfError::InvalidFileRange)?; + let offset_end = offset_begin + .checked_add(len) + .ok_or(ElfError::InvalidFileRange)?; + + // A PT_LOAD segment is not necessarily backed completely by ELF + // file content: ->p_filesz can be <= ->memsz. + if offset_end > segment_file_range.offset_end { + return Err(ElfError::UnbackedVaddrRange); + } + + offset_end + } + None => { + // The query did not specify an end address, as can e.g. happen + // when examining some table referenced from .dynamic with + // unknown size. Return the upper segment bound. + segment_file_range.offset_end + } + }; + Ok(Elf64FileRange { + offset_begin, + offset_end, + }) + } + + fn map_vaddr_to_file_buf( + &self, + vaddr_begin: Elf64Addr, + vaddr_end: Option<Elf64Addr>, + ) -> Result<&[u8], ElfError> { + let file_range = self.map_vaddr_to_file_off(vaddr_begin, vaddr_end)?; + Ok(&self.elf_file_buf[file_range.offset_begin..file_range.offset_end]) + } + + // For PIE executables, relieve the using code from offset calculations due + // to address alignment. Do it here and consistently. The address passed here + // may be either + // - a load address corresponding as-is to the first load segment's beginning or + // - the load address corresponding as-is to the first load segment's + // beginning rounded down to match the alginment constraints. + // The passed address will be mapped to the first variant in either case. + fn image_load_addr(&self, image_load_addr: Elf64Addr) -> Elf64Addr { + if self.max_load_segment_align == 0 { + image_load_addr + } else { + let aligned_image_load_addr = image_load_addr & !(self.max_load_segment_align - 1); + aligned_image_load_addr + self.image_load_align_offset() + } + } + + fn image_load_align_offset(&self) -> Elf64Off { + if self.max_load_segment_align == 0 { + return 0; + } + + // The first segment loaded is not necessarily aligned to the maximum of + // all segment alignment constraints. Determine the offset from the next + // lower aligned address to the first segment's beginning. + self.load_segments.total_vaddr_range().vaddr_begin & (self.max_load_segment_align - 1) + } + + // The ELF "base address" has a well-defined meaning: it is defined in the + // spec as the difference between the lowest address of the actual memory + // image the file has been loaded into and the lowest vaddr of all the + // PT_LOAD program headers. Calculate it in two's complement representation. + fn load_base(&self, image_load_addr: Elf64Addr) -> Elf64Xword { + let image_load_addr = self.image_load_addr(image_load_addr); + image_load_addr.wrapping_sub(self.load_segments.total_vaddr_range().vaddr_begin) + } + + pub fn image_load_vaddr_alloc_info(&self) -> Elf64ImageLoadVaddrAllocInfo { + let mut range = self.load_segments.total_vaddr_range(); + + if self.max_load_segment_align != 0 { + range.vaddr_begin &= !(self.max_load_segment_align - 1); + } + + let pie = self.dynamic.as_ref().map(|d| d.is_pie()).unwrap_or(false); + let align = if pie { + Some(self.max_load_segment_align) + } else { + None + }; + + Elf64ImageLoadVaddrAllocInfo { range, align } + } + + pub fn image_load_segment_iter( + &'a self, + image_load_addr: Elf64Addr, + ) -> Elf64ImageLoadSegmentIterator<'a> { + let load_base = self.load_base(image_load_addr); + Elf64ImageLoadSegmentIterator { + elf_file: self, + load_base, + next: 0, + } + } + + pub fn apply_dyn_relas<RP: Elf64RelocProcessor>( + &'a self, + rela_proc: RP, + image_load_addr: Elf64Addr, + ) -> Result<Option<Elf64AppliedRelaIterator<'a, RP>>, ElfError> { + let dynamic = match &self.dynamic { + Some(dynamic) => dynamic, + None => return Ok(None), + }; + let dynamic_rela = match &dynamic.rela { + Some(dynamic_rela) => dynamic_rela, + None => return Ok(None), + }; + + let load_base = self.load_base(image_load_addr); + + let relas_file_range = dynamic_rela.vaddr_range(); + let relas_buf = self.map_vaddr_to_file_buf( + relas_file_range.vaddr_begin, + Some(relas_file_range.vaddr_end), + )?; + let relas = Elf64Relas::new(relas_buf, dynamic_rela.entsize)?; + + let symtab = match &dynamic.symtab { + Some(dynamic_symtab) => { + let syms_buf = self.map_vaddr_to_file_buf(dynamic_symtab.base_vaddr, None)?; + let symtab = Elf64Symtab::new(syms_buf, dynamic_symtab.entsize)?; + Some(symtab) + } + None => None, + }; + + Ok(Some(Elf64AppliedRelaIterator::new( + rela_proc, + load_base, + &self.load_segments, + relas, + symtab, + ))) + } + + pub fn get_entry(&self, image_load_addr: Elf64Addr) -> Elf64Addr { + self.elf_hdr + .e_entry + .wrapping_add(self.load_base(image_load_addr)) + } +} + +#[derive(Debug)] +pub struct Elf64Hdr { + #[allow(unused)] + e_ident: [Elf64char; 16], + #[allow(unused)] + e_type: Elf64Half, + #[allow(unused)] + e_machine: Elf64Half, + #[allow(unused)] + e_version: Elf64Word, + e_entry: Elf64Addr, + e_phoff: Elf64Off, + e_shoff: Elf64Off, + #[allow(unused)] + e_flags: Elf64Word, + #[allow(unused)] + e_ehsize: Elf64Half, + e_phentsize: Elf64Half, + e_phnum: Elf64Half, + e_shentsize: Elf64Half, + e_shnum: Elf64Word, // The actual Elf64Hdr entry is Elf64Half, on overflow it's read from section + // table entry zero + e_shstrndx: Elf64Word, // The actual Elf64Hdr entry is Elf64Half, on overflow it's read from section + // table entry zero +} + +impl Elf64Hdr { + const EI_MAG0: usize = 0; + const EI_CLASS: usize = 4; + const EI_DATA: usize = 5; + const EI_VERSION: usize = 6; + const EI_OSABI: usize = 7; + + const ELFMAG: [Elf64char; 4] = [0x7f, b'E', b'L', b'F']; + + const ELFCLASS64: Elf64char = 2; + + const ELFDATA2LSB: Elf64char = 1; + + const ELFOSABI_NONE: Elf64char = 0; + const ELFOSABI_GNU: Elf64char = 3; + + const ET_EXEC: Elf64Half = 2; + + const EM_X86_64: Elf64Half = 62; + + const EV_CURRENT: Elf64Word = 1; + + fn read(buf: &[u8]) -> Result<Self, ElfError> { + // Examine the e_ident[] magic. + if buf.len() < 16 { + return Err(ElfError::FileTooShort); + } + let e_ident: [Elf64char; 16] = buf[..16].try_into().unwrap(); + if e_ident[Self::EI_MAG0..(Self::EI_MAG0 + mem::size_of_val(&Self::ELFMAG))] != Self::ELFMAG + { + return Err(ElfError::UnrecognizedMagic); + } else if e_ident[Self::EI_CLASS] != Self::ELFCLASS64 { + return Err(ElfError::UnsupportedClass); + } else if e_ident[Self::EI_DATA] != Self::ELFDATA2LSB { + return Err(ElfError::UnsupportedEndianess); + } else if e_ident[Self::EI_VERSION] != Self::EV_CURRENT as Elf64char { + return Err(ElfError::UnsupportedVersion); + } else if e_ident[Self::EI_OSABI] != Self::ELFOSABI_NONE + && e_ident[Self::EI_OSABI] != Self::ELFOSABI_GNU + { + return Err(ElfError::UnsupportedOsAbi); + } + + // ELF file is confirmed to be of ELFCLASS64, so the total header size + // should equal 64 bytes. + if buf.len() < 64 { + return Err(ElfError::FileTooShort); + } + let e_type = Elf64Half::from_le_bytes(buf[16..18].try_into().unwrap()); + let e_machine = Elf64Half::from_le_bytes(buf[18..20].try_into().unwrap()); + let e_version = Elf64Word::from_le_bytes(buf[20..24].try_into().unwrap()); + let e_entry = Elf64Addr::from_le_bytes(buf[24..32].try_into().unwrap()); + let e_phoff = Elf64Off::from_le_bytes(buf[32..40].try_into().unwrap()); + let e_shoff = Elf64Off::from_le_bytes(buf[40..48].try_into().unwrap()); + let e_flags = Elf64Word::from_le_bytes(buf[48..52].try_into().unwrap()); + let e_ehsize = Elf64Half::from_le_bytes(buf[52..54].try_into().unwrap()); + let e_phentsize = Elf64Half::from_le_bytes(buf[54..56].try_into().unwrap()); + let e_phnum = Elf64Half::from_le_bytes(buf[56..58].try_into().unwrap()); + let e_shentsize = Elf64Half::from_le_bytes(buf[58..60].try_into().unwrap()); + let e_shnum = Elf64Half::from_le_bytes(buf[60..62].try_into().unwrap()) as Elf64Word; + let e_shstrndx = Elf64Half::from_le_bytes(buf[62..64].try_into().unwrap()) as Elf64Word; + + if e_type != Self::ET_EXEC { + return Err(ElfError::UnsupportedType); + } + if e_machine != Self::EM_X86_64 { + return Err(ElfError::UnsupportedMachine); + } + if e_version != Self::EV_CURRENT { + return Err(ElfError::UnsupportedVersion); + } + + Ok(Self { + e_ident, + e_type, + e_machine, + e_version, + e_entry, + e_phoff, + e_shoff, + e_flags, + e_ehsize, + e_phentsize, + e_phnum, + e_shentsize, + e_shnum, + e_shstrndx, + }) + } +} + +#[derive(Debug)] +pub struct Elf64Phdr { + pub p_type: Elf64Word, + pub p_flags: Elf64PhdrFlags, + pub p_offset: Elf64Off, + pub p_vaddr: Elf64Addr, + pub p_paddr: Elf64Addr, + pub p_filesz: Elf64Xword, + pub p_memsz: Elf64Xword, + pub p_align: Elf64Xword, +} + +bitflags! { + pub struct Elf64PhdrFlags : Elf64Word { + const EXECUTE = 0x01; + const WRITE = 0x02; + const READ = 0x04; + } +} + +impl Elf64Phdr { + pub const PT_NULL: Elf64Word = 1; + pub const PT_LOAD: Elf64Word = 1; + pub const PT_DYNAMIC: Elf64Word = 2; + + fn read(phdr_buf: &[u8]) -> Self { + let p_type = Elf64Word::from_le_bytes(phdr_buf[0..4].try_into().unwrap()); + let p_flags = Elf64Word::from_le_bytes(phdr_buf[4..8].try_into().unwrap()); + let p_offset = Elf64Off::from_le_bytes(phdr_buf[8..16].try_into().unwrap()); + let p_vaddr = Elf64Addr::from_le_bytes(phdr_buf[16..24].try_into().unwrap()); + let p_paddr = Elf64Addr::from_le_bytes(phdr_buf[24..32].try_into().unwrap()); + let p_filesz = Elf64Xword::from_le_bytes(phdr_buf[32..40].try_into().unwrap()); + let p_memsz = Elf64Xword::from_le_bytes(phdr_buf[40..48].try_into().unwrap()); + let p_align = Elf64Xword::from_le_bytes(phdr_buf[48..56].try_into().unwrap()); + + let p_flags = Elf64PhdrFlags::from_bits_truncate(p_flags); + + Self { + p_type, + p_flags, + p_offset, + p_vaddr, + p_paddr, + p_filesz, + p_memsz, + p_align, + } + } + + fn verify(&self) -> Result<(), ElfError> { + if self.p_type == Self::PT_NULL { + return Ok(()); + } + + if self.p_type == Self::PT_LOAD && self.p_memsz < self.p_filesz { + return Err(ElfError::InvalidSegmentSize); + } + + if self.p_align != 0 { + if !self.p_align.is_power_of_two() { + return Err(ElfError::InvalidAddressAlignment); + } + if self.p_vaddr & (self.p_align - 1) != 0 { + return Err(ElfError::UnalignedSegmentAddress); + } + } + + if self.p_filesz != 0 { + Elf64FileRange::try_from((self.p_offset, self.p_filesz))?; + } + if self.p_memsz != 0 { + Elf64AddrRange::try_from((self.p_vaddr, self.p_memsz))?; + } + + Ok(()) + } + + fn file_range(&self) -> Elf64FileRange { + Elf64FileRange::try_from((self.p_offset, self.p_filesz)).unwrap() + } + + fn vaddr_range(&self) -> Elf64AddrRange { + Elf64AddrRange::try_from((self.p_vaddr, self.p_memsz)).unwrap() + } +} + +#[derive(Debug)] +pub struct Elf64Shdr { + pub sh_name: Elf64Word, + sh_type: Elf64Word, + sh_flags: Elf64ShdrFlags, + sh_addr: Elf64Addr, + sh_offset: Elf64Off, + sh_size: Elf64Xword, + sh_link: Elf64Word, + sh_info: Elf64Word, + sh_addralign: Elf64Xword, + #[allow(unused)] + sh_entsize: Elf64Xword, +} + +bitflags! { + pub struct Elf64ShdrFlags : Elf64Xword { + const WRITE = 0x001; + const ALLOC = 0x002; + const EXECINSTR = 0x004; + const MERGE = 0x010; + const STRINGS = 0x020; + const INFO_LINK = 0x040; + const LINK_ORDER = 0x080; + const OS_NONCONFORMING = 0x100; + const GROUP = 0x200; + const TLS = 0x400; + const COMPRESSED = 0x800; + } +} + +impl Elf64Shdr { + const SHN_UNDEF: Elf64Word = 0; + const SHN_ABS: Elf64Word = 0xfff1; + const SHN_XINDEX: Elf64Word = 0xffff; + + pub const SHT_NULL: Elf64Word = 0; + pub const SHT_STRTAB: Elf64Word = 3; + pub const SHT_NOBITS: Elf64Word = 8; + + fn read(shdr_buf: &'_ [u8]) -> Self { + let sh_name = Elf64Word::from_le_bytes(shdr_buf[0..4].try_into().unwrap()); + let sh_type = Elf64Word::from_le_bytes(shdr_buf[4..8].try_into().unwrap()); + let sh_flags = Elf64Xword::from_le_bytes(shdr_buf[8..16].try_into().unwrap()); + let sh_addr = Elf64Addr::from_le_bytes(shdr_buf[16..24].try_into().unwrap()); + let sh_offset = Elf64Off::from_le_bytes(shdr_buf[24..32].try_into().unwrap()); + let sh_size = Elf64Xword::from_le_bytes(shdr_buf[32..40].try_into().unwrap()); + let sh_link = Elf64Word::from_le_bytes(shdr_buf[40..44].try_into().unwrap()); + let sh_info = Elf64Word::from_le_bytes(shdr_buf[44..48].try_into().unwrap()); + let sh_addralign = Elf64Xword::from_le_bytes(shdr_buf[48..56].try_into().unwrap()); + let sh_entsize = Elf64Xword::from_le_bytes(shdr_buf[56..64].try_into().unwrap()); + + let sh_flags = Elf64ShdrFlags::from_bits_truncate(sh_flags); + + Self { + sh_name, + sh_type, + sh_flags, + sh_addr, + sh_offset, + sh_size, + sh_link, + sh_info, + sh_addralign, + sh_entsize, + } + } + + fn verify(&self) -> Result<(), ElfError> { + if self.sh_type == Self::SHT_NULL { + return Ok(()); + } + + if self.sh_type != Self::SHT_NOBITS { + Elf64FileRange::try_from((self.sh_offset, self.sh_size))?; + } else { + Elf64FileRange::try_from((self.sh_offset, 0))?; + } + + if self.sh_flags.contains(Elf64ShdrFlags::ALLOC) { + Elf64AddrRange::try_from((self.sh_addr, self.sh_size))?; + + if self.sh_addralign != 0 { + if self.sh_addralign != 0 && !self.sh_addralign.is_power_of_two() { + return Err(ElfError::InvalidAddressAlignment); + } + if self.sh_addr & (self.sh_addralign - 1) != 0 { + return Err(ElfError::InvalidAddressAlignment); + } + } + } else if self.sh_addr != 0 { + return Err(ElfError::InvalidAddressRange); + } + + Ok(()) + } + + fn file_range(&self) -> Elf64FileRange { + if self.sh_type != Self::SHT_NOBITS { + Elf64FileRange::try_from((self.sh_offset, self.sh_size)).unwrap() + } else { + Elf64FileRange::try_from((self.sh_offset, 0)).unwrap() + } + } +} + +#[derive(Debug)] +struct Elf64LoadSegments { + segments: Vec<(Elf64AddrRange, Elf64Half)>, +} + +impl Elf64LoadSegments { + fn new() -> Self { + Self { + segments: Vec::new(), + } + } + + fn find_first_not_before(&self, range: &Elf64AddrRange) -> Option<usize> { + let i = self.segments.partition_point(|segment| { + matches!(segment.0.partial_cmp(range), Some(cmp::Ordering::Less)) + }); + + if i != self.segments.len() { + Some(i) + } else { + None + } + } + + fn try_insert(&mut self, segment: Elf64AddrRange, phdr_index: Elf64Half) -> Result<(), ()> { + let i = self.find_first_not_before(&segment); + match i { + Some(i) => { + match segment.partial_cmp(&self.segments[i].0) { + Some(cmp::Ordering::Less) => { + // Ok, no overlap. + self.segments.insert(i, (segment, phdr_index)); + Ok(()) + } + _ => Err(()), + } + } + None => { + self.segments.push((segment, phdr_index)); + Ok(()) + } + } + } + + fn lookup_vaddr_range(&self, range: &Elf64AddrRange) -> Option<(Elf64Half, Elf64Xword)> { + let i = self.find_first_not_before(range); + let i = match i { + Some(i) => i, + None => return None, + }; + + let segment = &self.segments[i]; + if segment.0.vaddr_begin <= range.vaddr_begin && range.vaddr_end <= segment.0.vaddr_end { + let offset_in_segment = range.vaddr_begin - segment.0.vaddr_begin; + Some((segment.1, offset_in_segment)) + } else { + None + } + } + + fn total_vaddr_range(&self) -> Elf64AddrRange { + Elf64AddrRange { + vaddr_begin: self + .segments + .first() + .map(|first| first.0.vaddr_begin) + .unwrap_or(0), + vaddr_end: self + .segments + .last() + .map(|last| last.0.vaddr_end) + .unwrap_or(0), + } + } +} + +#[derive(Debug)] +struct Elf64DynamicRelocTable { + base_vaddr: Elf64Addr, // DT_RELA / DT_REL + size: Elf64Xword, // DT_RELASZ / DT_RELSZ + entsize: Elf64Xword, // DT_RELAENT / DT_RELENT +} + +impl Elf64DynamicRelocTable { + fn verify(&self) -> Result<(), ElfError> { + Elf64AddrRange::try_from((self.base_vaddr, self.size))?; + Ok(()) + } + + fn vaddr_range(&self) -> Elf64AddrRange { + Elf64AddrRange::try_from((self.base_vaddr, self.size)).unwrap() + } +} + +#[derive(Debug)] +struct Elf64DynamicSymtab { + base_vaddr: Elf64Addr, // DT_SYMTAB + entsize: Elf64Xword, // DT_SYMENT + #[allow(unused)] + shndx: Option<Elf64Addr>, // DT_SYMTAB_SHNDX +} + +impl Elf64DynamicSymtab { + fn verify(&self) -> Result<(), ElfError> { + Ok(()) + } +} + +#[derive(Debug)] +struct Elf64Dynamic { + // No DT_REL representation: "The AMD64 ABI architectures uses only + // Elf64_Rela relocation entries [...]". + rela: Option<Elf64DynamicRelocTable>, + symtab: Option<Elf64DynamicSymtab>, + flags_1: Elf64Xword, +} + +impl Elf64Dynamic { + const DT_NULL: Elf64Xword = 0; + const DT_HASH: Elf64Xword = 4; + const DT_STRTAB: Elf64Xword = 5; + const DT_SYMTAB: Elf64Xword = 6; + const DT_RELA: Elf64Xword = 7; + const DT_RELASZ: Elf64Xword = 8; + const DT_RELAENT: Elf64Xword = 9; + const DT_STRSZ: Elf64Xword = 10; + const DT_SYMENT: Elf64Xword = 11; + const DT_DEBUG: Elf64Xword = 21; + const DT_TEXTREL: Elf64Xword = 22; + const DT_FLAGS: Elf64Xword = 30; + const DT_SYMTAB_SHNDX: Elf64Xword = 34; + const DT_GNU_HASH: Elf64Xword = 0x6ffffef5; + const DT_RELACOUNT: Elf64Xword = 0x6ffffff9; + const DT_FLAGS_1: Elf64Xword = 0x6ffffffb; + + const DF_PIE_1: Elf64Xword = 0x08000000; + + fn read(buf: &[u8]) -> Result<Self, ElfError> { + let mut rela: Option<Elf64Addr> = None; + let mut relasz: Option<Elf64Xword> = None; + let mut relaent: Option<Elf64Xword> = None; + + let mut symtab: Option<Elf64Addr> = None; + let mut syment: Option<Elf64Xword> = None; + let mut symtab_shndx: Option<Elf64Addr> = None; + + let mut flags_1: Option<Elf64Xword> = None; + + let mut fields = [ + (Self::DT_RELA, &mut rela), + (Self::DT_RELASZ, &mut relasz), + (Self::DT_RELAENT, &mut relaent), + (Self::DT_SYMTAB, &mut symtab), + (Self::DT_SYMENT, &mut syment), + (Self::DT_SYMTAB_SHNDX, &mut symtab_shndx), + (Self::DT_FLAGS_1, &mut flags_1), + ]; + let ignored_fields = [ + Self::DT_HASH, + Self::DT_STRTAB, + Self::DT_STRSZ, + Self::DT_DEBUG, + Self::DT_TEXTREL, + Self::DT_FLAGS, + Self::DT_GNU_HASH, + Self::DT_RELACOUNT, + ]; + let mut null_seen = false; + let max_entries = buf.len() / 16; + for i in 0..max_entries { + let entry_buf = &buf[(i * 16)..((i + 1) * 16)];
```suggestion for entry_buf in buf.chunks(16) { ```
svsm
github_2023
others
21
coconut-svsm
Freax13
@@ -0,0 +1,1612 @@ +// SPDX-License-Identifier: (GPL-2.0-or-later OR MIT) +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Nicolai Stange <nstange@suse.de> +// +// vim: ts=4 sw=4 et + +extern crate alloc; + +use alloc::vec::Vec; +use bitflags::bitflags; +use core::cmp; +use core::convert; +use core::ffi; +use core::fmt; +use core::matches; +use core::mem; + +#[derive(Debug)] +pub enum ElfError { + FileTooShort, + + InvalidAddressRange, + InvalidAddressAlignment, + InvalidFileRange, + UnmappedVaddrRange, + UnbackedVaddrRange, + + UnrecognizedMagic, + UnsupportedClass, + UnsupportedEndianess, + UnsupportedOsAbi, + UnsupportedType, + UnsupportedMachine, + UnsupportedVersion, + InvalidPhdrSize, + InvalidShdrSize, + + InvalidSegmentSize, + UnalignedSegmentAddress, + LoadSegmentConflict, + DynamicPhdrConflict, + + UnterminatedDynamicSection, + DynamicFieldConflict, + UnrecognizedDynamicField, + MissingDynamicField, + + InvalidSectionIndex, + IncompatibleSectionType, + + InvalidStrtabString, + + InvalidSymbolEntrySize, + InvalidSymbolIndex, + + InvalidRelocationEntrySize, + UnrecognizedRelocationType, + InvalidRelocationOffset, + RelocationAgainstUndefSymbol, +} + +impl fmt::Display for ElfError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::FileTooShort => { + write!(f, "ELF file too short") + } + + Self::InvalidAddressRange => { + write!(f, "invalid ELF address range") + } + Self::InvalidAddressAlignment => { + write!(f, "invalid ELF address alignment") + } + Self::InvalidFileRange => { + write!(f, "invalid ELF file range") + } + Self::UnmappedVaddrRange => { + write!(f, "reference to unmapped ELF address range") + } + Self::UnbackedVaddrRange => { + write!(f, "reference ELF address range not backed by file") + } + + Self::UnrecognizedMagic => { + write!(f, "unrecognized ELF magic") + } + Self::UnsupportedClass => { + write!(f, "unsupported ELF class") + } + Self::UnsupportedEndianess => { + write!(f, "unsupported ELF endianess") + } + Self::UnsupportedOsAbi => { + write!(f, "unsupported ELF ABI") + } + Self::UnsupportedType => { + write!(f, "unsupported ELF file type") + } + Self::UnsupportedMachine => { + write!(f, "unsupported ELF machine") + } + Self::UnsupportedVersion => { + write!(f, "unsupported ELF version") + } + Self::InvalidPhdrSize => { + write!(f, "invalid ELF program header size") + } + Self::InvalidShdrSize => { + write!(f, "invalid ELF section header size") + } + + Self::InvalidSegmentSize => { + write!(f, "invalid ELF segment size") + } + Self::UnalignedSegmentAddress => { + write!(f, "unaligned ELF segment address") + } + Self::LoadSegmentConflict => { + write!(f, "ELF PT_LOAD segment conflict") + } + Self::DynamicPhdrConflict => { + write!(f, "multiple ELF PT_DYNAMIC program headers") + } + + Self::UnterminatedDynamicSection => { + write!(f, "unterminated ELF dynamic section") + } + Self::DynamicFieldConflict => { + write!(f, "conflicting fields in ELF dynamic section") + } + Self::UnrecognizedDynamicField => { + write!(f, "unrecognized field in ELF dynamic section") + } + Self::MissingDynamicField => { + write!(f, "missing field in ELF dynamic section") + } + + Self::InvalidSectionIndex => { + write!(f, "invalid ELF section index") + } + Self::IncompatibleSectionType => { + write!(f, "unexpected ELF section type") + } + + Self::InvalidStrtabString => { + write!(f, "invalid ELF strtab string") + } + + Self::InvalidSymbolEntrySize => { + write!(f, "invalid ELF symbol entry size") + } + Self::InvalidSymbolIndex => { + write!(f, "invalid ELF symbol index") + } + + Self::InvalidRelocationEntrySize => { + write!(f, "invalid ELF relocation entry size") + } + Self::UnrecognizedRelocationType => { + write!(f, "unrecognized ELF relocation type") + } + Self::InvalidRelocationOffset => { + write!(f, "ELF relocation offset out of bounds") + } + Self::RelocationAgainstUndefSymbol => { + write!(f, "ELF relocation against undefined symbol") + } + } + } +} + +pub type Elf64Addr = u64; +pub type Elf64Off = u64; +pub type Elf64Half = u16; +pub type Elf64Word = u32; +#[allow(unused)] +pub type Elf64Sword = i32; +pub type Elf64Xword = u64; +pub type Elf64Sxword = i64; +pub type Elf64char = u8; + +#[derive(PartialEq, Eq, Debug)] +pub struct Elf64AddrRange { + pub vaddr_begin: Elf64Addr, + pub vaddr_end: Elf64Addr, +} + +impl Elf64AddrRange { + pub fn len(&self) -> Elf64Xword { + self.vaddr_end - self.vaddr_begin + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +impl convert::TryFrom<(Elf64Addr, Elf64Xword)> for Elf64AddrRange { + type Error = ElfError; + + fn try_from(value: (Elf64Addr, Elf64Xword)) -> Result<Self, Self::Error> { + let vaddr_begin = value.0; + let size = value.1; + let vaddr_end = vaddr_begin + .checked_add(size) + .ok_or(ElfError::InvalidAddressRange)?; + Ok(Self { + vaddr_begin, + vaddr_end, + }) + } +} + +impl cmp::PartialOrd for Elf64AddrRange { + fn partial_cmp(&self, other: &Elf64AddrRange) -> Option<cmp::Ordering> { + if self.vaddr_end <= other.vaddr_begin { + Some(cmp::Ordering::Less) + } else if self.vaddr_begin >= other.vaddr_end { + Some(cmp::Ordering::Greater) + } else if self == other { + Some(cmp::Ordering::Equal) + } else { + None + } + } +} + +pub struct Elf64FileRange { + pub offset_begin: usize, + pub offset_end: usize, +} + +impl convert::TryFrom<(Elf64Off, Elf64Xword)> for Elf64FileRange { + type Error = ElfError; + + fn try_from(value: (Elf64Off, Elf64Xword)) -> Result<Self, Self::Error> { + let offset_begin = usize::try_from(value.0).map_err(|_| ElfError::InvalidFileRange)?; + let size = usize::try_from(value.1).map_err(|_| ElfError::InvalidFileRange)?; + let offset_end = offset_begin + .checked_add(size) + .ok_or(ElfError::InvalidFileRange)?; + Ok(Self { + offset_begin, + offset_end, + }) + } +} + +pub struct Elf64File<'a> { + elf_file_buf: &'a [u8], + elf_hdr: Elf64Hdr, + load_segments: Elf64LoadSegments, + max_load_segment_align: Elf64Xword, + #[allow(unused)] + sh_strtab: Option<Elf64Strtab<'a>>, + dynamic: Option<Elf64Dynamic>, +} + +impl<'a> Elf64File<'a> { + pub fn read(elf_file_buf: &'a [u8]) -> Result<Self, ElfError> { + let mut elf_hdr = Elf64Hdr::read(elf_file_buf)?; + + // Verify that the program header table is within the file bounds. + let phdrs_off = usize::try_from(elf_hdr.e_phoff).map_err(|_| ElfError::FileTooShort)?; + let phdr_size = usize::try_from(elf_hdr.e_phentsize).unwrap(); + if phdr_size < 56 { + return Err(ElfError::InvalidPhdrSize); + } + let phdrs_num = usize::try_from(elf_hdr.e_phnum).unwrap(); + let phdrs_size = phdrs_num + .checked_mul(phdr_size) + .ok_or(ElfError::FileTooShort)?; + let phdrs_end = phdrs_off + .checked_add(phdrs_size) + .ok_or(ElfError::FileTooShort)?; + if phdrs_end > elf_file_buf.len() { + return Err(ElfError::FileTooShort); + } + + // Verify that the section header table is within the file bounds. + let shdr_size = usize::try_from(elf_hdr.e_shentsize).unwrap(); + if shdr_size < 64 { + return Err(ElfError::InvalidShdrSize); + } + if elf_hdr.e_shnum == 0 && elf_hdr.e_shoff != 0 { + // The number of section headers is stored in the first section header's + // ->sh_size member. + elf_hdr.e_shnum = 1; + Self::check_section_header_table_bounds(&elf_hdr, elf_file_buf.len())?; + let shdr0 = Self::read_shdr_from_file(elf_file_buf, &elf_hdr, 0); + elf_hdr.e_shnum = match Elf64Word::try_from(shdr0.sh_size) { + Ok(shnum) => shnum, + Err(_) => return Err(ElfError::InvalidSectionIndex), + }; + } + Self::check_section_header_table_bounds(&elf_hdr, elf_file_buf.len())?; + + // Verify all headers once at load time, so that no error checking will + // be neeeded at each and every subsequent access. + let mut load_segments = Elf64LoadSegments::new(); + let mut max_load_segment_align = 0; + let mut dynamic_file_range: Option<Elf64FileRange> = None; + for i in 0..elf_hdr.e_phnum { + let phdr = Self::read_phdr_from_file(elf_file_buf, &elf_hdr, i); + Self::verify_phdr(&phdr, elf_file_buf.len())?; + if phdr.p_type == Elf64Phdr::PT_LOAD { + let vaddr_range = phdr.vaddr_range(); + if vaddr_range.vaddr_begin == vaddr_range.vaddr_end { + continue; + } + if load_segments.try_insert(vaddr_range, i).is_err() { + return Err(ElfError::LoadSegmentConflict); + } + max_load_segment_align = max_load_segment_align.max(phdr.p_align); + } else if phdr.p_type == Elf64Phdr::PT_DYNAMIC { + if dynamic_file_range.is_some() { + return Err(ElfError::DynamicPhdrConflict); + } + dynamic_file_range = Some(phdr.file_range()); + } + } + + // If ->e_shstrndx == SHN_XINDEX, the actual strndx is stored in first + // section header table's ->sh_link member. + if elf_hdr.e_shstrndx == Elf64Shdr::SHN_XINDEX { + if elf_hdr.e_shnum == 0 { + return Err(ElfError::InvalidSectionIndex); + } + let shdr0 = Self::read_shdr_from_file(elf_file_buf, &elf_hdr, 0); + elf_hdr.e_shstrndx = shdr0.sh_link; + } + if elf_hdr.e_shstrndx != Elf64Shdr::SHN_UNDEF && elf_hdr.e_shstrndx > elf_hdr.e_shnum { + return Err(ElfError::InvalidSectionIndex); + } + + let mut sh_strtab: Option<Elf64Strtab> = None; + for i in 0..elf_hdr.e_shnum { + let shdr = Self::read_shdr_from_file(elf_file_buf, &elf_hdr, i); + Self::verify_shdr(&shdr, elf_file_buf.len(), elf_hdr.e_shnum)?; + + if elf_hdr.e_shstrndx != Elf64Shdr::SHN_UNDEF && i == elf_hdr.e_shstrndx { + if shdr.sh_type != Elf64Shdr::SHT_STRTAB { + return Err(ElfError::IncompatibleSectionType); + } + + let sh_strtab_buf_range = shdr.file_range(); + let sh_strtab_buf = + &elf_file_buf[sh_strtab_buf_range.offset_begin..sh_strtab_buf_range.offset_end]; + sh_strtab = Some(Elf64Strtab::new(sh_strtab_buf)); + } + } + + let dynamic = if let Some(dynamic_file_range) = dynamic_file_range { + let dynamic_buf = + &elf_file_buf[dynamic_file_range.offset_begin..dynamic_file_range.offset_end]; + let dynamic = Elf64Dynamic::read(dynamic_buf)?; + Self::verify_dynamic(&dynamic)?; + Some(dynamic) + } else { + None + }; + + Ok(Self { + elf_file_buf, + elf_hdr, + load_segments, + max_load_segment_align, + sh_strtab, + dynamic, + }) + } + + fn read_phdr_from_file(elf_file_buf: &'a [u8], elf_hdr: &Elf64Hdr, i: Elf64Half) -> Elf64Phdr { + let phdrs_off = usize::try_from(elf_hdr.e_phoff).unwrap(); + let phdr_size = usize::try_from(elf_hdr.e_phentsize).unwrap(); + let i = usize::try_from(i).unwrap(); + let phdr_off = phdrs_off + i * phdr_size; + let phdr_buf = &elf_file_buf[phdr_off..(phdr_off + phdr_size)]; + Elf64Phdr::read(phdr_buf) + } + + fn verify_phdr(phdr: &Elf64Phdr, elf_file_buf_len: usize) -> Result<(), ElfError> { + if phdr.p_type == Elf64Phdr::PT_NULL { + return Ok(()); + } + + phdr.verify()?; + + if phdr.p_filesz != 0 { + let file_range = phdr.file_range(); + if file_range.offset_end > elf_file_buf_len { + return Err(ElfError::FileTooShort); + } + } + + Ok(()) + } + + fn read_phdr(&self, i: Elf64Half) -> Elf64Phdr { + Self::read_phdr_from_file(self.elf_file_buf, &self.elf_hdr, i) + } + + fn check_section_header_table_bounds( + elf_hdr: &Elf64Hdr, + elf_file_buf_len: usize, + ) -> Result<(), ElfError> { + // Verify that the section header table is within the file bounds. + let shdrs_off = usize::try_from(elf_hdr.e_shoff).map_err(|_| ElfError::FileTooShort)?; + let shdr_size = usize::try_from(elf_hdr.e_shentsize).unwrap(); + let shdrs_num = usize::try_from(elf_hdr.e_shnum).unwrap(); + let shdrs_size = shdrs_num + .checked_mul(shdr_size) + .ok_or(ElfError::FileTooShort)?; + let shdrs_end = shdrs_off + .checked_add(shdrs_size) + .ok_or(ElfError::FileTooShort)?; + if shdrs_end > elf_file_buf_len { + return Err(ElfError::FileTooShort); + } + Ok(()) + } + + fn read_shdr_from_file(elf_file_buf: &'a [u8], elf_hdr: &Elf64Hdr, i: Elf64Word) -> Elf64Shdr { + let shdrs_off = usize::try_from(elf_hdr.e_shoff).unwrap(); + let shdr_size = usize::try_from(elf_hdr.e_shentsize).unwrap(); + let i = usize::try_from(i).unwrap(); + let shdr_off = shdrs_off + i * shdr_size; + let shdr_buf = &elf_file_buf[shdr_off..(shdr_off + shdr_size)]; + Elf64Shdr::read(shdr_buf) + } + + fn verify_shdr( + shdr: &Elf64Shdr, + elf_file_buf_len: usize, + shnum: Elf64Word, + ) -> Result<(), ElfError> { + if shdr.sh_type == Elf64Shdr::SHT_NULL { + return Ok(()); + } + + shdr.verify()?; + + if shdr.sh_link > shnum + || shdr.sh_flags.contains(Elf64ShdrFlags::INFO_LINK) && shdr.sh_info > shnum + { + return Err(ElfError::InvalidSectionIndex); + } + + let file_range = shdr.file_range(); + if file_range.offset_end > elf_file_buf_len { + return Err(ElfError::FileTooShort); + } + + Ok(()) + } + + fn read_shdr(&self, i: Elf64Word) -> Elf64Shdr { + Self::read_shdr_from_file(self.elf_file_buf, &self.elf_hdr, i) + } + + pub fn shdrs_iter(&self) -> Elf64ShdrIterator { + Elf64ShdrIterator::new(self) + } + + fn verify_dynamic(dynamic: &Elf64Dynamic) -> Result<(), ElfError> { + dynamic.verify()?; + Ok(()) + } + + fn map_vaddr_to_file_off( + &self, + vaddr_begin: Elf64Addr, + vaddr_end: Option<Elf64Addr>, + ) -> Result<Elf64FileRange, ElfError> { + if vaddr_begin == Elf64Addr::MAX { + return Err(ElfError::UnmappedVaddrRange); + } + let vaddr_range = Elf64AddrRange { + vaddr_begin, + vaddr_end: vaddr_end.unwrap_or(vaddr_begin + 1), + }; + let (phdr_index, offset) = match self.load_segments.lookup_vaddr_range(&vaddr_range) { + Some(load_segment) => (load_segment.0, load_segment.1), + None => return Err(ElfError::UnmappedVaddrRange), + }; + + let phdr = self.read_phdr(phdr_index); + let segment_file_range = phdr.file_range(); + let offset_in_segment = usize::try_from(offset).map_err(|_| ElfError::InvalidFileRange)?; + let offset_begin = segment_file_range + .offset_begin + .checked_add(offset_in_segment) + .ok_or(ElfError::InvalidFileRange)?; + let offset_end = match vaddr_end { + Some(vaddr_end) => { + let len = vaddr_end - vaddr_begin; + let len = usize::try_from(len).map_err(|_| ElfError::InvalidFileRange)?; + let offset_end = offset_begin + .checked_add(len) + .ok_or(ElfError::InvalidFileRange)?; + + // A PT_LOAD segment is not necessarily backed completely by ELF + // file content: ->p_filesz can be <= ->memsz. + if offset_end > segment_file_range.offset_end { + return Err(ElfError::UnbackedVaddrRange); + } + + offset_end + } + None => { + // The query did not specify an end address, as can e.g. happen + // when examining some table referenced from .dynamic with + // unknown size. Return the upper segment bound. + segment_file_range.offset_end + } + }; + Ok(Elf64FileRange { + offset_begin, + offset_end, + }) + } + + fn map_vaddr_to_file_buf( + &self, + vaddr_begin: Elf64Addr, + vaddr_end: Option<Elf64Addr>, + ) -> Result<&[u8], ElfError> { + let file_range = self.map_vaddr_to_file_off(vaddr_begin, vaddr_end)?; + Ok(&self.elf_file_buf[file_range.offset_begin..file_range.offset_end]) + } + + // For PIE executables, relieve the using code from offset calculations due + // to address alignment. Do it here and consistently. The address passed here + // may be either + // - a load address corresponding as-is to the first load segment's beginning or + // - the load address corresponding as-is to the first load segment's + // beginning rounded down to match the alginment constraints. + // The passed address will be mapped to the first variant in either case. + fn image_load_addr(&self, image_load_addr: Elf64Addr) -> Elf64Addr { + if self.max_load_segment_align == 0 { + image_load_addr + } else { + let aligned_image_load_addr = image_load_addr & !(self.max_load_segment_align - 1); + aligned_image_load_addr + self.image_load_align_offset() + } + } + + fn image_load_align_offset(&self) -> Elf64Off { + if self.max_load_segment_align == 0 { + return 0; + } + + // The first segment loaded is not necessarily aligned to the maximum of + // all segment alignment constraints. Determine the offset from the next + // lower aligned address to the first segment's beginning. + self.load_segments.total_vaddr_range().vaddr_begin & (self.max_load_segment_align - 1) + } + + // The ELF "base address" has a well-defined meaning: it is defined in the + // spec as the difference between the lowest address of the actual memory + // image the file has been loaded into and the lowest vaddr of all the + // PT_LOAD program headers. Calculate it in two's complement representation. + fn load_base(&self, image_load_addr: Elf64Addr) -> Elf64Xword { + let image_load_addr = self.image_load_addr(image_load_addr); + image_load_addr.wrapping_sub(self.load_segments.total_vaddr_range().vaddr_begin) + } + + pub fn image_load_vaddr_alloc_info(&self) -> Elf64ImageLoadVaddrAllocInfo { + let mut range = self.load_segments.total_vaddr_range(); + + if self.max_load_segment_align != 0 { + range.vaddr_begin &= !(self.max_load_segment_align - 1); + } + + let pie = self.dynamic.as_ref().map(|d| d.is_pie()).unwrap_or(false); + let align = if pie { + Some(self.max_load_segment_align) + } else { + None + }; + + Elf64ImageLoadVaddrAllocInfo { range, align } + } + + pub fn image_load_segment_iter( + &'a self, + image_load_addr: Elf64Addr, + ) -> Elf64ImageLoadSegmentIterator<'a> { + let load_base = self.load_base(image_load_addr); + Elf64ImageLoadSegmentIterator { + elf_file: self, + load_base, + next: 0, + } + } + + pub fn apply_dyn_relas<RP: Elf64RelocProcessor>( + &'a self, + rela_proc: RP, + image_load_addr: Elf64Addr, + ) -> Result<Option<Elf64AppliedRelaIterator<'a, RP>>, ElfError> { + let dynamic = match &self.dynamic { + Some(dynamic) => dynamic, + None => return Ok(None), + }; + let dynamic_rela = match &dynamic.rela { + Some(dynamic_rela) => dynamic_rela, + None => return Ok(None), + }; + + let load_base = self.load_base(image_load_addr); + + let relas_file_range = dynamic_rela.vaddr_range(); + let relas_buf = self.map_vaddr_to_file_buf( + relas_file_range.vaddr_begin, + Some(relas_file_range.vaddr_end), + )?; + let relas = Elf64Relas::new(relas_buf, dynamic_rela.entsize)?; + + let symtab = match &dynamic.symtab { + Some(dynamic_symtab) => { + let syms_buf = self.map_vaddr_to_file_buf(dynamic_symtab.base_vaddr, None)?; + let symtab = Elf64Symtab::new(syms_buf, dynamic_symtab.entsize)?; + Some(symtab) + } + None => None, + }; + + Ok(Some(Elf64AppliedRelaIterator::new( + rela_proc, + load_base, + &self.load_segments, + relas, + symtab, + ))) + } + + pub fn get_entry(&self, image_load_addr: Elf64Addr) -> Elf64Addr { + self.elf_hdr + .e_entry + .wrapping_add(self.load_base(image_load_addr)) + } +} + +#[derive(Debug)] +pub struct Elf64Hdr { + #[allow(unused)] + e_ident: [Elf64char; 16], + #[allow(unused)] + e_type: Elf64Half, + #[allow(unused)] + e_machine: Elf64Half, + #[allow(unused)] + e_version: Elf64Word, + e_entry: Elf64Addr, + e_phoff: Elf64Off, + e_shoff: Elf64Off, + #[allow(unused)] + e_flags: Elf64Word, + #[allow(unused)] + e_ehsize: Elf64Half, + e_phentsize: Elf64Half, + e_phnum: Elf64Half, + e_shentsize: Elf64Half, + e_shnum: Elf64Word, // The actual Elf64Hdr entry is Elf64Half, on overflow it's read from section + // table entry zero + e_shstrndx: Elf64Word, // The actual Elf64Hdr entry is Elf64Half, on overflow it's read from section + // table entry zero +} + +impl Elf64Hdr { + const EI_MAG0: usize = 0; + const EI_CLASS: usize = 4; + const EI_DATA: usize = 5; + const EI_VERSION: usize = 6; + const EI_OSABI: usize = 7; + + const ELFMAG: [Elf64char; 4] = [0x7f, b'E', b'L', b'F']; + + const ELFCLASS64: Elf64char = 2; + + const ELFDATA2LSB: Elf64char = 1; + + const ELFOSABI_NONE: Elf64char = 0; + const ELFOSABI_GNU: Elf64char = 3; + + const ET_EXEC: Elf64Half = 2; + + const EM_X86_64: Elf64Half = 62; + + const EV_CURRENT: Elf64Word = 1; + + fn read(buf: &[u8]) -> Result<Self, ElfError> { + // Examine the e_ident[] magic. + if buf.len() < 16 { + return Err(ElfError::FileTooShort); + } + let e_ident: [Elf64char; 16] = buf[..16].try_into().unwrap(); + if e_ident[Self::EI_MAG0..(Self::EI_MAG0 + mem::size_of_val(&Self::ELFMAG))] != Self::ELFMAG + { + return Err(ElfError::UnrecognizedMagic); + } else if e_ident[Self::EI_CLASS] != Self::ELFCLASS64 { + return Err(ElfError::UnsupportedClass); + } else if e_ident[Self::EI_DATA] != Self::ELFDATA2LSB { + return Err(ElfError::UnsupportedEndianess); + } else if e_ident[Self::EI_VERSION] != Self::EV_CURRENT as Elf64char { + return Err(ElfError::UnsupportedVersion); + } else if e_ident[Self::EI_OSABI] != Self::ELFOSABI_NONE + && e_ident[Self::EI_OSABI] != Self::ELFOSABI_GNU + { + return Err(ElfError::UnsupportedOsAbi); + } + + // ELF file is confirmed to be of ELFCLASS64, so the total header size + // should equal 64 bytes. + if buf.len() < 64 { + return Err(ElfError::FileTooShort); + } + let e_type = Elf64Half::from_le_bytes(buf[16..18].try_into().unwrap()); + let e_machine = Elf64Half::from_le_bytes(buf[18..20].try_into().unwrap()); + let e_version = Elf64Word::from_le_bytes(buf[20..24].try_into().unwrap()); + let e_entry = Elf64Addr::from_le_bytes(buf[24..32].try_into().unwrap()); + let e_phoff = Elf64Off::from_le_bytes(buf[32..40].try_into().unwrap()); + let e_shoff = Elf64Off::from_le_bytes(buf[40..48].try_into().unwrap()); + let e_flags = Elf64Word::from_le_bytes(buf[48..52].try_into().unwrap()); + let e_ehsize = Elf64Half::from_le_bytes(buf[52..54].try_into().unwrap()); + let e_phentsize = Elf64Half::from_le_bytes(buf[54..56].try_into().unwrap()); + let e_phnum = Elf64Half::from_le_bytes(buf[56..58].try_into().unwrap()); + let e_shentsize = Elf64Half::from_le_bytes(buf[58..60].try_into().unwrap()); + let e_shnum = Elf64Half::from_le_bytes(buf[60..62].try_into().unwrap()) as Elf64Word; + let e_shstrndx = Elf64Half::from_le_bytes(buf[62..64].try_into().unwrap()) as Elf64Word; + + if e_type != Self::ET_EXEC { + return Err(ElfError::UnsupportedType); + } + if e_machine != Self::EM_X86_64 { + return Err(ElfError::UnsupportedMachine); + } + if e_version != Self::EV_CURRENT { + return Err(ElfError::UnsupportedVersion); + } + + Ok(Self { + e_ident, + e_type, + e_machine, + e_version, + e_entry, + e_phoff, + e_shoff, + e_flags, + e_ehsize, + e_phentsize, + e_phnum, + e_shentsize, + e_shnum, + e_shstrndx, + }) + } +} + +#[derive(Debug)] +pub struct Elf64Phdr { + pub p_type: Elf64Word, + pub p_flags: Elf64PhdrFlags, + pub p_offset: Elf64Off, + pub p_vaddr: Elf64Addr, + pub p_paddr: Elf64Addr, + pub p_filesz: Elf64Xword, + pub p_memsz: Elf64Xword, + pub p_align: Elf64Xword, +} + +bitflags! { + pub struct Elf64PhdrFlags : Elf64Word { + const EXECUTE = 0x01; + const WRITE = 0x02; + const READ = 0x04; + } +} + +impl Elf64Phdr { + pub const PT_NULL: Elf64Word = 1; + pub const PT_LOAD: Elf64Word = 1; + pub const PT_DYNAMIC: Elf64Word = 2; + + fn read(phdr_buf: &[u8]) -> Self { + let p_type = Elf64Word::from_le_bytes(phdr_buf[0..4].try_into().unwrap()); + let p_flags = Elf64Word::from_le_bytes(phdr_buf[4..8].try_into().unwrap()); + let p_offset = Elf64Off::from_le_bytes(phdr_buf[8..16].try_into().unwrap()); + let p_vaddr = Elf64Addr::from_le_bytes(phdr_buf[16..24].try_into().unwrap()); + let p_paddr = Elf64Addr::from_le_bytes(phdr_buf[24..32].try_into().unwrap()); + let p_filesz = Elf64Xword::from_le_bytes(phdr_buf[32..40].try_into().unwrap()); + let p_memsz = Elf64Xword::from_le_bytes(phdr_buf[40..48].try_into().unwrap()); + let p_align = Elf64Xword::from_le_bytes(phdr_buf[48..56].try_into().unwrap()); + + let p_flags = Elf64PhdrFlags::from_bits_truncate(p_flags); + + Self { + p_type, + p_flags, + p_offset, + p_vaddr, + p_paddr, + p_filesz, + p_memsz, + p_align, + } + } + + fn verify(&self) -> Result<(), ElfError> { + if self.p_type == Self::PT_NULL { + return Ok(()); + } + + if self.p_type == Self::PT_LOAD && self.p_memsz < self.p_filesz { + return Err(ElfError::InvalidSegmentSize); + } + + if self.p_align != 0 { + if !self.p_align.is_power_of_two() { + return Err(ElfError::InvalidAddressAlignment); + } + if self.p_vaddr & (self.p_align - 1) != 0 { + return Err(ElfError::UnalignedSegmentAddress); + } + } + + if self.p_filesz != 0 { + Elf64FileRange::try_from((self.p_offset, self.p_filesz))?; + } + if self.p_memsz != 0 { + Elf64AddrRange::try_from((self.p_vaddr, self.p_memsz))?; + } + + Ok(()) + } + + fn file_range(&self) -> Elf64FileRange { + Elf64FileRange::try_from((self.p_offset, self.p_filesz)).unwrap() + } + + fn vaddr_range(&self) -> Elf64AddrRange { + Elf64AddrRange::try_from((self.p_vaddr, self.p_memsz)).unwrap() + } +} + +#[derive(Debug)] +pub struct Elf64Shdr { + pub sh_name: Elf64Word, + sh_type: Elf64Word, + sh_flags: Elf64ShdrFlags, + sh_addr: Elf64Addr, + sh_offset: Elf64Off, + sh_size: Elf64Xword, + sh_link: Elf64Word, + sh_info: Elf64Word, + sh_addralign: Elf64Xword, + #[allow(unused)] + sh_entsize: Elf64Xword, +} + +bitflags! { + pub struct Elf64ShdrFlags : Elf64Xword { + const WRITE = 0x001; + const ALLOC = 0x002; + const EXECINSTR = 0x004; + const MERGE = 0x010; + const STRINGS = 0x020; + const INFO_LINK = 0x040; + const LINK_ORDER = 0x080; + const OS_NONCONFORMING = 0x100; + const GROUP = 0x200; + const TLS = 0x400; + const COMPRESSED = 0x800; + } +} + +impl Elf64Shdr { + const SHN_UNDEF: Elf64Word = 0; + const SHN_ABS: Elf64Word = 0xfff1; + const SHN_XINDEX: Elf64Word = 0xffff; + + pub const SHT_NULL: Elf64Word = 0; + pub const SHT_STRTAB: Elf64Word = 3; + pub const SHT_NOBITS: Elf64Word = 8; + + fn read(shdr_buf: &'_ [u8]) -> Self { + let sh_name = Elf64Word::from_le_bytes(shdr_buf[0..4].try_into().unwrap()); + let sh_type = Elf64Word::from_le_bytes(shdr_buf[4..8].try_into().unwrap()); + let sh_flags = Elf64Xword::from_le_bytes(shdr_buf[8..16].try_into().unwrap()); + let sh_addr = Elf64Addr::from_le_bytes(shdr_buf[16..24].try_into().unwrap()); + let sh_offset = Elf64Off::from_le_bytes(shdr_buf[24..32].try_into().unwrap()); + let sh_size = Elf64Xword::from_le_bytes(shdr_buf[32..40].try_into().unwrap()); + let sh_link = Elf64Word::from_le_bytes(shdr_buf[40..44].try_into().unwrap()); + let sh_info = Elf64Word::from_le_bytes(shdr_buf[44..48].try_into().unwrap()); + let sh_addralign = Elf64Xword::from_le_bytes(shdr_buf[48..56].try_into().unwrap()); + let sh_entsize = Elf64Xword::from_le_bytes(shdr_buf[56..64].try_into().unwrap()); + + let sh_flags = Elf64ShdrFlags::from_bits_truncate(sh_flags); + + Self { + sh_name, + sh_type, + sh_flags, + sh_addr, + sh_offset, + sh_size, + sh_link, + sh_info, + sh_addralign, + sh_entsize, + } + } + + fn verify(&self) -> Result<(), ElfError> { + if self.sh_type == Self::SHT_NULL { + return Ok(()); + } + + if self.sh_type != Self::SHT_NOBITS { + Elf64FileRange::try_from((self.sh_offset, self.sh_size))?; + } else { + Elf64FileRange::try_from((self.sh_offset, 0))?; + } + + if self.sh_flags.contains(Elf64ShdrFlags::ALLOC) { + Elf64AddrRange::try_from((self.sh_addr, self.sh_size))?; + + if self.sh_addralign != 0 { + if self.sh_addralign != 0 && !self.sh_addralign.is_power_of_two() { + return Err(ElfError::InvalidAddressAlignment); + } + if self.sh_addr & (self.sh_addralign - 1) != 0 { + return Err(ElfError::InvalidAddressAlignment); + } + } + } else if self.sh_addr != 0 { + return Err(ElfError::InvalidAddressRange); + } + + Ok(()) + } + + fn file_range(&self) -> Elf64FileRange { + if self.sh_type != Self::SHT_NOBITS { + Elf64FileRange::try_from((self.sh_offset, self.sh_size)).unwrap() + } else { + Elf64FileRange::try_from((self.sh_offset, 0)).unwrap() + } + } +} + +#[derive(Debug)] +struct Elf64LoadSegments { + segments: Vec<(Elf64AddrRange, Elf64Half)>, +} + +impl Elf64LoadSegments { + fn new() -> Self { + Self { + segments: Vec::new(), + } + } + + fn find_first_not_before(&self, range: &Elf64AddrRange) -> Option<usize> { + let i = self.segments.partition_point(|segment| { + matches!(segment.0.partial_cmp(range), Some(cmp::Ordering::Less)) + }); + + if i != self.segments.len() { + Some(i) + } else { + None + } + } + + fn try_insert(&mut self, segment: Elf64AddrRange, phdr_index: Elf64Half) -> Result<(), ()> { + let i = self.find_first_not_before(&segment); + match i { + Some(i) => { + match segment.partial_cmp(&self.segments[i].0) { + Some(cmp::Ordering::Less) => { + // Ok, no overlap. + self.segments.insert(i, (segment, phdr_index)); + Ok(()) + } + _ => Err(()), + } + } + None => { + self.segments.push((segment, phdr_index)); + Ok(()) + } + } + } + + fn lookup_vaddr_range(&self, range: &Elf64AddrRange) -> Option<(Elf64Half, Elf64Xword)> { + let i = self.find_first_not_before(range); + let i = match i { + Some(i) => i, + None => return None, + }; + + let segment = &self.segments[i]; + if segment.0.vaddr_begin <= range.vaddr_begin && range.vaddr_end <= segment.0.vaddr_end { + let offset_in_segment = range.vaddr_begin - segment.0.vaddr_begin; + Some((segment.1, offset_in_segment)) + } else { + None + } + } + + fn total_vaddr_range(&self) -> Elf64AddrRange { + Elf64AddrRange { + vaddr_begin: self + .segments + .first() + .map(|first| first.0.vaddr_begin) + .unwrap_or(0), + vaddr_end: self + .segments + .last() + .map(|last| last.0.vaddr_end) + .unwrap_or(0), + } + } +} + +#[derive(Debug)] +struct Elf64DynamicRelocTable { + base_vaddr: Elf64Addr, // DT_RELA / DT_REL + size: Elf64Xword, // DT_RELASZ / DT_RELSZ + entsize: Elf64Xword, // DT_RELAENT / DT_RELENT +} + +impl Elf64DynamicRelocTable { + fn verify(&self) -> Result<(), ElfError> { + Elf64AddrRange::try_from((self.base_vaddr, self.size))?; + Ok(()) + } + + fn vaddr_range(&self) -> Elf64AddrRange { + Elf64AddrRange::try_from((self.base_vaddr, self.size)).unwrap() + } +} + +#[derive(Debug)] +struct Elf64DynamicSymtab { + base_vaddr: Elf64Addr, // DT_SYMTAB + entsize: Elf64Xword, // DT_SYMENT + #[allow(unused)] + shndx: Option<Elf64Addr>, // DT_SYMTAB_SHNDX +} + +impl Elf64DynamicSymtab { + fn verify(&self) -> Result<(), ElfError> { + Ok(()) + } +} + +#[derive(Debug)] +struct Elf64Dynamic { + // No DT_REL representation: "The AMD64 ABI architectures uses only + // Elf64_Rela relocation entries [...]". + rela: Option<Elf64DynamicRelocTable>, + symtab: Option<Elf64DynamicSymtab>, + flags_1: Elf64Xword, +} + +impl Elf64Dynamic { + const DT_NULL: Elf64Xword = 0; + const DT_HASH: Elf64Xword = 4; + const DT_STRTAB: Elf64Xword = 5; + const DT_SYMTAB: Elf64Xword = 6; + const DT_RELA: Elf64Xword = 7; + const DT_RELASZ: Elf64Xword = 8; + const DT_RELAENT: Elf64Xword = 9; + const DT_STRSZ: Elf64Xword = 10; + const DT_SYMENT: Elf64Xword = 11; + const DT_DEBUG: Elf64Xword = 21; + const DT_TEXTREL: Elf64Xword = 22; + const DT_FLAGS: Elf64Xword = 30; + const DT_SYMTAB_SHNDX: Elf64Xword = 34; + const DT_GNU_HASH: Elf64Xword = 0x6ffffef5; + const DT_RELACOUNT: Elf64Xword = 0x6ffffff9; + const DT_FLAGS_1: Elf64Xword = 0x6ffffffb; + + const DF_PIE_1: Elf64Xword = 0x08000000; + + fn read(buf: &[u8]) -> Result<Self, ElfError> { + let mut rela: Option<Elf64Addr> = None; + let mut relasz: Option<Elf64Xword> = None; + let mut relaent: Option<Elf64Xword> = None; + + let mut symtab: Option<Elf64Addr> = None; + let mut syment: Option<Elf64Xword> = None; + let mut symtab_shndx: Option<Elf64Addr> = None; + + let mut flags_1: Option<Elf64Xword> = None; + + let mut fields = [ + (Self::DT_RELA, &mut rela), + (Self::DT_RELASZ, &mut relasz), + (Self::DT_RELAENT, &mut relaent), + (Self::DT_SYMTAB, &mut symtab), + (Self::DT_SYMENT, &mut syment), + (Self::DT_SYMTAB_SHNDX, &mut symtab_shndx), + (Self::DT_FLAGS_1, &mut flags_1), + ]; + let ignored_fields = [ + Self::DT_HASH, + Self::DT_STRTAB, + Self::DT_STRSZ, + Self::DT_DEBUG, + Self::DT_TEXTREL, + Self::DT_FLAGS, + Self::DT_GNU_HASH, + Self::DT_RELACOUNT, + ]; + let mut null_seen = false; + let max_entries = buf.len() / 16; + for i in 0..max_entries { + let entry_buf = &buf[(i * 16)..((i + 1) * 16)]; + let d_tag = Elf64Xword::from_le_bytes(entry_buf[0..8].try_into().unwrap()); + + if d_tag == Self::DT_NULL { + null_seen = true; + break; + } + + if let Some(field) = fields.iter_mut().find(|f| f.0 == d_tag) { + if field.1.is_some() { + return Err(ElfError::DynamicFieldConflict); + } + + let d_val = Elf64Xword::from_le_bytes(entry_buf[8..16].try_into().unwrap()); + *field.1 = Some(d_val); + } else if ignored_fields.iter().all(|tag| *tag != d_tag) { + // For unhandled fields not on the ignore list, bail out: + // failing to take the associated, required fixup action from + // the dynamic loader, if any, would result in a broken image, + // respectively in hard to debug runtime breakages. + return Err(ElfError::UnrecognizedDynamicField); + } + } + if !null_seen { + return Err(ElfError::UnterminatedDynamicSection); + } + + let rela = if rela.is_some() || relasz.is_some() || relaent.is_some() { + let rela = rela.ok_or(ElfError::MissingDynamicField)?; + let relasz = relasz.ok_or(ElfError::MissingDynamicField)?; + let relaent = relaent.ok_or(ElfError::MissingDynamicField)?; + Some(Elf64DynamicRelocTable { + base_vaddr: rela, + size: relasz, + entsize: relaent, + }) + } else { + None + }; + + let symtab = if symtab.is_some() || syment.is_some() { + let symtab = symtab.ok_or(ElfError::MissingDynamicField)?; + let syment = syment.ok_or(ElfError::MissingDynamicField)?; + Some(Elf64DynamicSymtab { + base_vaddr: symtab, + entsize: syment, + shndx: symtab_shndx, + }) + } else { + None + }; + + let flags_1 = flags_1.unwrap_or(0); + + Ok(Elf64Dynamic { + rela, + symtab, + flags_1, + }) + } + + fn verify(&self) -> Result<(), ElfError> { + if let Some(rela) = &self.rela { + rela.verify()?; + } + if let Some(symtab) = &self.symtab { + symtab.verify()?; + } + Ok(()) + } + + fn is_pie(&self) -> bool { + self.flags_1 & Self::DF_PIE_1 != 0 + } +} + +pub struct Elf64ImageLoadVaddrAllocInfo { + pub range: Elf64AddrRange, // vaddr range to allocate + pub align: Option<Elf64Xword>, // Set for PIE executables so that a valid vaddr base can be allocated. +} + +pub struct Elf64ImageLoadSegment<'a> { + pub vaddr_range: Elf64AddrRange, + pub file_contents: &'a [u8], + pub flags: Elf64PhdrFlags, +} + +pub struct Elf64ImageLoadSegmentIterator<'a> { + elf_file: &'a Elf64File<'a>, + load_base: Elf64Xword, + + next: usize, +} + +impl<'a> Iterator for Elf64ImageLoadSegmentIterator<'a> { + type Item = Elf64ImageLoadSegment<'a>; + + fn next(&mut self) -> Option<Self::Item> { + let cur = self.next; + if cur == self.elf_file.load_segments.segments.len() { + return None; + } + self.next += 1; + + let phdr_index = self.elf_file.load_segments.segments[cur].1; + let phdr = self.elf_file.read_phdr(phdr_index); + + let mut vaddr_range = phdr.vaddr_range(); + vaddr_range.vaddr_begin = vaddr_range.vaddr_begin.wrapping_add(self.load_base); + vaddr_range.vaddr_end = vaddr_range.vaddr_end.wrapping_add(self.load_base); + + let file_range = phdr.file_range(); + let file_contents = + &self.elf_file.elf_file_buf[file_range.offset_begin..file_range.offset_end]; + + Some(Elf64ImageLoadSegment { + vaddr_range, + file_contents, + flags: phdr.p_flags, + }) + } +} + +struct Elf64Strtab<'a> { + strtab_buf: &'a [u8], +} + +impl<'a> Elf64Strtab<'a> { + fn new(strtab_buf: &'a [u8]) -> Self { + Self { strtab_buf } + } + + #[allow(unused)] + fn get_str(&self, index: Elf64Word) -> Result<&'a ffi::CStr, ElfError> { + let index = usize::try_from(index).unwrap(); + if index >= self.strtab_buf.len() { + return Err(ElfError::InvalidStrtabString); + } + + ffi::CStr::from_bytes_until_nul(&self.strtab_buf[index..]) + .map_err(|_| ElfError::InvalidStrtabString) + } +} + +#[derive(Debug)] +struct Elf64Sym { + #[allow(unused)] + st_name: Elf64Word, + #[allow(unused)] + st_info: Elf64char, + #[allow(unused)] + st_other: Elf64char, + st_shndx: Elf64Half, + st_value: Elf64Addr, + #[allow(unused)] + st_size: Elf64Xword, +} + +impl Elf64Sym { + fn read(buf: &[u8]) -> Self { + let st_name = Elf64Word::from_le_bytes(buf[0..4].try_into().unwrap()); + let st_info = Elf64char::from_le_bytes(buf[4..5].try_into().unwrap()); + let st_other = Elf64char::from_le_bytes(buf[5..6].try_into().unwrap()); + let st_shndx = Elf64Half::from_le_bytes(buf[6..8].try_into().unwrap()); + let st_value = Elf64Addr::from_le_bytes(buf[8..16].try_into().unwrap()); + let st_size = Elf64Xword::from_le_bytes(buf[16..24].try_into().unwrap()); + Self { + st_name, + st_info, + st_other, + st_shndx, + st_value, + st_size, + } + } +}
Have you considered using the [bytemuck](https://docs.rs/bytemuck/1.13.1/bytemuck/) crate? It can be used to cast bytes to a struct.
svsm
github_2023
others
21
coconut-svsm
Freax13
@@ -0,0 +1,1612 @@ +// SPDX-License-Identifier: (GPL-2.0-or-later OR MIT) +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Nicolai Stange <nstange@suse.de> +// +// vim: ts=4 sw=4 et + +extern crate alloc; + +use alloc::vec::Vec; +use bitflags::bitflags; +use core::cmp; +use core::convert; +use core::ffi; +use core::fmt; +use core::matches; +use core::mem; + +#[derive(Debug)] +pub enum ElfError { + FileTooShort, + + InvalidAddressRange, + InvalidAddressAlignment, + InvalidFileRange, + UnmappedVaddrRange, + UnbackedVaddrRange, + + UnrecognizedMagic, + UnsupportedClass, + UnsupportedEndianess, + UnsupportedOsAbi, + UnsupportedType, + UnsupportedMachine, + UnsupportedVersion, + InvalidPhdrSize, + InvalidShdrSize, + + InvalidSegmentSize, + UnalignedSegmentAddress, + LoadSegmentConflict, + DynamicPhdrConflict, + + UnterminatedDynamicSection, + DynamicFieldConflict, + UnrecognizedDynamicField, + MissingDynamicField, + + InvalidSectionIndex, + IncompatibleSectionType, + + InvalidStrtabString, + + InvalidSymbolEntrySize, + InvalidSymbolIndex, + + InvalidRelocationEntrySize, + UnrecognizedRelocationType, + InvalidRelocationOffset, + RelocationAgainstUndefSymbol, +} + +impl fmt::Display for ElfError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::FileTooShort => { + write!(f, "ELF file too short") + } + + Self::InvalidAddressRange => { + write!(f, "invalid ELF address range") + } + Self::InvalidAddressAlignment => { + write!(f, "invalid ELF address alignment") + } + Self::InvalidFileRange => { + write!(f, "invalid ELF file range") + } + Self::UnmappedVaddrRange => { + write!(f, "reference to unmapped ELF address range") + } + Self::UnbackedVaddrRange => { + write!(f, "reference ELF address range not backed by file") + } + + Self::UnrecognizedMagic => { + write!(f, "unrecognized ELF magic") + } + Self::UnsupportedClass => { + write!(f, "unsupported ELF class") + } + Self::UnsupportedEndianess => { + write!(f, "unsupported ELF endianess") + } + Self::UnsupportedOsAbi => { + write!(f, "unsupported ELF ABI") + } + Self::UnsupportedType => { + write!(f, "unsupported ELF file type") + } + Self::UnsupportedMachine => { + write!(f, "unsupported ELF machine") + } + Self::UnsupportedVersion => { + write!(f, "unsupported ELF version") + } + Self::InvalidPhdrSize => { + write!(f, "invalid ELF program header size") + } + Self::InvalidShdrSize => { + write!(f, "invalid ELF section header size") + } + + Self::InvalidSegmentSize => { + write!(f, "invalid ELF segment size") + } + Self::UnalignedSegmentAddress => { + write!(f, "unaligned ELF segment address") + } + Self::LoadSegmentConflict => { + write!(f, "ELF PT_LOAD segment conflict") + } + Self::DynamicPhdrConflict => { + write!(f, "multiple ELF PT_DYNAMIC program headers") + } + + Self::UnterminatedDynamicSection => { + write!(f, "unterminated ELF dynamic section") + } + Self::DynamicFieldConflict => { + write!(f, "conflicting fields in ELF dynamic section") + } + Self::UnrecognizedDynamicField => { + write!(f, "unrecognized field in ELF dynamic section") + } + Self::MissingDynamicField => { + write!(f, "missing field in ELF dynamic section") + } + + Self::InvalidSectionIndex => { + write!(f, "invalid ELF section index") + } + Self::IncompatibleSectionType => { + write!(f, "unexpected ELF section type") + } + + Self::InvalidStrtabString => { + write!(f, "invalid ELF strtab string") + } + + Self::InvalidSymbolEntrySize => { + write!(f, "invalid ELF symbol entry size") + } + Self::InvalidSymbolIndex => { + write!(f, "invalid ELF symbol index") + } + + Self::InvalidRelocationEntrySize => { + write!(f, "invalid ELF relocation entry size") + } + Self::UnrecognizedRelocationType => { + write!(f, "unrecognized ELF relocation type") + } + Self::InvalidRelocationOffset => { + write!(f, "ELF relocation offset out of bounds") + } + Self::RelocationAgainstUndefSymbol => { + write!(f, "ELF relocation against undefined symbol") + } + } + } +} + +pub type Elf64Addr = u64; +pub type Elf64Off = u64; +pub type Elf64Half = u16; +pub type Elf64Word = u32; +#[allow(unused)] +pub type Elf64Sword = i32; +pub type Elf64Xword = u64; +pub type Elf64Sxword = i64; +pub type Elf64char = u8; + +#[derive(PartialEq, Eq, Debug)] +pub struct Elf64AddrRange { + pub vaddr_begin: Elf64Addr, + pub vaddr_end: Elf64Addr, +} + +impl Elf64AddrRange { + pub fn len(&self) -> Elf64Xword { + self.vaddr_end - self.vaddr_begin + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +impl convert::TryFrom<(Elf64Addr, Elf64Xword)> for Elf64AddrRange { + type Error = ElfError; + + fn try_from(value: (Elf64Addr, Elf64Xword)) -> Result<Self, Self::Error> { + let vaddr_begin = value.0; + let size = value.1; + let vaddr_end = vaddr_begin + .checked_add(size) + .ok_or(ElfError::InvalidAddressRange)?; + Ok(Self { + vaddr_begin, + vaddr_end, + }) + } +} + +impl cmp::PartialOrd for Elf64AddrRange { + fn partial_cmp(&self, other: &Elf64AddrRange) -> Option<cmp::Ordering> { + if self.vaddr_end <= other.vaddr_begin { + Some(cmp::Ordering::Less) + } else if self.vaddr_begin >= other.vaddr_end { + Some(cmp::Ordering::Greater) + } else if self == other { + Some(cmp::Ordering::Equal) + } else { + None + } + } +} + +pub struct Elf64FileRange { + pub offset_begin: usize, + pub offset_end: usize, +} + +impl convert::TryFrom<(Elf64Off, Elf64Xword)> for Elf64FileRange { + type Error = ElfError; + + fn try_from(value: (Elf64Off, Elf64Xword)) -> Result<Self, Self::Error> { + let offset_begin = usize::try_from(value.0).map_err(|_| ElfError::InvalidFileRange)?; + let size = usize::try_from(value.1).map_err(|_| ElfError::InvalidFileRange)?; + let offset_end = offset_begin + .checked_add(size) + .ok_or(ElfError::InvalidFileRange)?; + Ok(Self { + offset_begin, + offset_end, + }) + } +} + +pub struct Elf64File<'a> { + elf_file_buf: &'a [u8], + elf_hdr: Elf64Hdr, + load_segments: Elf64LoadSegments, + max_load_segment_align: Elf64Xword, + #[allow(unused)] + sh_strtab: Option<Elf64Strtab<'a>>, + dynamic: Option<Elf64Dynamic>, +} + +impl<'a> Elf64File<'a> { + pub fn read(elf_file_buf: &'a [u8]) -> Result<Self, ElfError> { + let mut elf_hdr = Elf64Hdr::read(elf_file_buf)?; + + // Verify that the program header table is within the file bounds. + let phdrs_off = usize::try_from(elf_hdr.e_phoff).map_err(|_| ElfError::FileTooShort)?; + let phdr_size = usize::try_from(elf_hdr.e_phentsize).unwrap(); + if phdr_size < 56 { + return Err(ElfError::InvalidPhdrSize); + } + let phdrs_num = usize::try_from(elf_hdr.e_phnum).unwrap(); + let phdrs_size = phdrs_num + .checked_mul(phdr_size) + .ok_or(ElfError::FileTooShort)?; + let phdrs_end = phdrs_off + .checked_add(phdrs_size) + .ok_or(ElfError::FileTooShort)?; + if phdrs_end > elf_file_buf.len() { + return Err(ElfError::FileTooShort); + } + + // Verify that the section header table is within the file bounds. + let shdr_size = usize::try_from(elf_hdr.e_shentsize).unwrap(); + if shdr_size < 64 { + return Err(ElfError::InvalidShdrSize); + } + if elf_hdr.e_shnum == 0 && elf_hdr.e_shoff != 0 { + // The number of section headers is stored in the first section header's + // ->sh_size member. + elf_hdr.e_shnum = 1; + Self::check_section_header_table_bounds(&elf_hdr, elf_file_buf.len())?; + let shdr0 = Self::read_shdr_from_file(elf_file_buf, &elf_hdr, 0); + elf_hdr.e_shnum = match Elf64Word::try_from(shdr0.sh_size) { + Ok(shnum) => shnum, + Err(_) => return Err(ElfError::InvalidSectionIndex), + }; + } + Self::check_section_header_table_bounds(&elf_hdr, elf_file_buf.len())?; + + // Verify all headers once at load time, so that no error checking will + // be neeeded at each and every subsequent access. + let mut load_segments = Elf64LoadSegments::new(); + let mut max_load_segment_align = 0; + let mut dynamic_file_range: Option<Elf64FileRange> = None; + for i in 0..elf_hdr.e_phnum { + let phdr = Self::read_phdr_from_file(elf_file_buf, &elf_hdr, i); + Self::verify_phdr(&phdr, elf_file_buf.len())?; + if phdr.p_type == Elf64Phdr::PT_LOAD { + let vaddr_range = phdr.vaddr_range(); + if vaddr_range.vaddr_begin == vaddr_range.vaddr_end { + continue; + } + if load_segments.try_insert(vaddr_range, i).is_err() { + return Err(ElfError::LoadSegmentConflict); + } + max_load_segment_align = max_load_segment_align.max(phdr.p_align); + } else if phdr.p_type == Elf64Phdr::PT_DYNAMIC { + if dynamic_file_range.is_some() { + return Err(ElfError::DynamicPhdrConflict); + } + dynamic_file_range = Some(phdr.file_range()); + } + } + + // If ->e_shstrndx == SHN_XINDEX, the actual strndx is stored in first + // section header table's ->sh_link member. + if elf_hdr.e_shstrndx == Elf64Shdr::SHN_XINDEX { + if elf_hdr.e_shnum == 0 { + return Err(ElfError::InvalidSectionIndex); + } + let shdr0 = Self::read_shdr_from_file(elf_file_buf, &elf_hdr, 0); + elf_hdr.e_shstrndx = shdr0.sh_link; + } + if elf_hdr.e_shstrndx != Elf64Shdr::SHN_UNDEF && elf_hdr.e_shstrndx > elf_hdr.e_shnum { + return Err(ElfError::InvalidSectionIndex); + } + + let mut sh_strtab: Option<Elf64Strtab> = None; + for i in 0..elf_hdr.e_shnum { + let shdr = Self::read_shdr_from_file(elf_file_buf, &elf_hdr, i); + Self::verify_shdr(&shdr, elf_file_buf.len(), elf_hdr.e_shnum)?; + + if elf_hdr.e_shstrndx != Elf64Shdr::SHN_UNDEF && i == elf_hdr.e_shstrndx { + if shdr.sh_type != Elf64Shdr::SHT_STRTAB { + return Err(ElfError::IncompatibleSectionType); + } + + let sh_strtab_buf_range = shdr.file_range(); + let sh_strtab_buf = + &elf_file_buf[sh_strtab_buf_range.offset_begin..sh_strtab_buf_range.offset_end]; + sh_strtab = Some(Elf64Strtab::new(sh_strtab_buf)); + } + } + + let dynamic = if let Some(dynamic_file_range) = dynamic_file_range { + let dynamic_buf = + &elf_file_buf[dynamic_file_range.offset_begin..dynamic_file_range.offset_end]; + let dynamic = Elf64Dynamic::read(dynamic_buf)?; + Self::verify_dynamic(&dynamic)?; + Some(dynamic) + } else { + None + }; + + Ok(Self { + elf_file_buf, + elf_hdr, + load_segments, + max_load_segment_align, + sh_strtab, + dynamic, + }) + } + + fn read_phdr_from_file(elf_file_buf: &'a [u8], elf_hdr: &Elf64Hdr, i: Elf64Half) -> Elf64Phdr { + let phdrs_off = usize::try_from(elf_hdr.e_phoff).unwrap(); + let phdr_size = usize::try_from(elf_hdr.e_phentsize).unwrap(); + let i = usize::try_from(i).unwrap(); + let phdr_off = phdrs_off + i * phdr_size; + let phdr_buf = &elf_file_buf[phdr_off..(phdr_off + phdr_size)]; + Elf64Phdr::read(phdr_buf) + } + + fn verify_phdr(phdr: &Elf64Phdr, elf_file_buf_len: usize) -> Result<(), ElfError> { + if phdr.p_type == Elf64Phdr::PT_NULL { + return Ok(()); + } + + phdr.verify()?; + + if phdr.p_filesz != 0 { + let file_range = phdr.file_range(); + if file_range.offset_end > elf_file_buf_len { + return Err(ElfError::FileTooShort); + } + } + + Ok(()) + } + + fn read_phdr(&self, i: Elf64Half) -> Elf64Phdr { + Self::read_phdr_from_file(self.elf_file_buf, &self.elf_hdr, i) + } + + fn check_section_header_table_bounds( + elf_hdr: &Elf64Hdr, + elf_file_buf_len: usize, + ) -> Result<(), ElfError> { + // Verify that the section header table is within the file bounds. + let shdrs_off = usize::try_from(elf_hdr.e_shoff).map_err(|_| ElfError::FileTooShort)?; + let shdr_size = usize::try_from(elf_hdr.e_shentsize).unwrap(); + let shdrs_num = usize::try_from(elf_hdr.e_shnum).unwrap(); + let shdrs_size = shdrs_num + .checked_mul(shdr_size) + .ok_or(ElfError::FileTooShort)?; + let shdrs_end = shdrs_off + .checked_add(shdrs_size) + .ok_or(ElfError::FileTooShort)?; + if shdrs_end > elf_file_buf_len { + return Err(ElfError::FileTooShort); + } + Ok(()) + } + + fn read_shdr_from_file(elf_file_buf: &'a [u8], elf_hdr: &Elf64Hdr, i: Elf64Word) -> Elf64Shdr { + let shdrs_off = usize::try_from(elf_hdr.e_shoff).unwrap(); + let shdr_size = usize::try_from(elf_hdr.e_shentsize).unwrap(); + let i = usize::try_from(i).unwrap(); + let shdr_off = shdrs_off + i * shdr_size; + let shdr_buf = &elf_file_buf[shdr_off..(shdr_off + shdr_size)]; + Elf64Shdr::read(shdr_buf) + } + + fn verify_shdr( + shdr: &Elf64Shdr, + elf_file_buf_len: usize, + shnum: Elf64Word, + ) -> Result<(), ElfError> { + if shdr.sh_type == Elf64Shdr::SHT_NULL { + return Ok(()); + } + + shdr.verify()?; + + if shdr.sh_link > shnum + || shdr.sh_flags.contains(Elf64ShdrFlags::INFO_LINK) && shdr.sh_info > shnum + { + return Err(ElfError::InvalidSectionIndex); + } + + let file_range = shdr.file_range(); + if file_range.offset_end > elf_file_buf_len { + return Err(ElfError::FileTooShort); + } + + Ok(()) + } + + fn read_shdr(&self, i: Elf64Word) -> Elf64Shdr { + Self::read_shdr_from_file(self.elf_file_buf, &self.elf_hdr, i) + } + + pub fn shdrs_iter(&self) -> Elf64ShdrIterator { + Elf64ShdrIterator::new(self) + }
This function is unused.
svsm
github_2023
others
21
coconut-svsm
Freax13
@@ -105,151 +107,176 @@ fn setup_env() { sev_status_verify(); } -fn map_kernel_region(vaddr: VirtAddr, region: &MemoryRegion) -> Result<(), SvsmError> { +fn map_and_validate(vaddr: VirtAddr, paddr: PhysAddr, len: usize) { let flags = PTEntryFlags::PRESENT | PTEntryFlags::WRITABLE | PTEntryFlags::ACCESSED | PTEntryFlags::DIRTY; - let paddr = region.start as PhysAddr; - let size = (region.end - region.start) as usize; let mut pgtbl = get_init_pgtable_locked(); + pgtbl + .map_region(vaddr, vaddr + len, paddr, flags) + .expect("Error mapping kernel region"); - log::info!( - "Mapping kernel region {:#018x}-{:#018x} to {:#018x}", - vaddr, - vaddr + size, - paddr - ); - - pgtbl.map_region_2m(vaddr, vaddr + size, paddr, flags) + this_cpu_mut() + .ghcb() + .page_state_change(paddr, paddr + len, true, PageStateChangeOp::PscPrivate) + .expect("GHCB::PAGE_STATE_CHANGE call failed for kernel region"); + pvalidate_range(vaddr, vaddr + len, true).expect("PVALIDATE kernel region failed"); + valid_bitmap_set_valid_range(paddr, paddr + len); } -fn validate_kernel_region(vaddr: VirtAddr, region: &MemoryRegion) -> Result<(), ()> { - let pstart = region.start as PhysAddr; - let pend = region.end as PhysAddr; - let size: usize = pend - pstart; +#[no_mangle] +pub extern "C" fn stage2_main(kernel_elf_start: PhysAddr, kernel_elf_end: PhysAddr) { + setup_env(); - assert!(is_aligned(pstart, PAGE_SIZE_2M)); - assert!(is_aligned(pend, PAGE_SIZE_2M)); + // Find a suitable physical memory region to allocate to the SVSM kernel. + let fw_cfg = FwCfg::new(&CONSOLE_IO); + let r = fw_cfg + .find_kernel_region() + .expect("Failed to find memory region for SVSM kernel"); - this_cpu_mut() - .ghcb() - .page_state_change(pstart, pend, true, PageStateChangeOp::PscPrivate) - .expect("GHCB::PAGE_STATE_CHANGE call failed for kernel region"); + log::info!("COCONUT Secure Virtual Machine Service Module (SVSM) Stage 2 Loader"); - pvalidate_range(vaddr, vaddr + size, true).expect("PVALIDATE kernel region failed"); + let (kernel_region_phys_start, kernel_region_phys_end) = (r.start as usize, r.end as usize); + init_valid_bitmap_alloc(kernel_region_phys_start, kernel_region_phys_end) + .expect("Failed to allocate valid-bitmap"); - for paddr in (pstart..pend).step_by(PAGE_SIZE_2M) { - valid_bitmap_set_valid_2m(paddr); - } + // Read the SVSM kernel's ELF file metadata. + let kernel_elf_len = (kernel_elf_end - kernel_elf_start) as usize; + let kernel_elf_buf = + unsafe { slice::from_raw_parts(kernel_elf_start as *const u8, kernel_elf_len) }; + let kernel_elf = match elf::Elf64File::read(kernel_elf_buf) { + Ok(kernel_elf) => kernel_elf, + Err(e) => panic!("error reading kernel ELF: {}", e), + }; - Ok(()) -} + let kernel_vaddr_alloc_info = kernel_elf.image_load_vaddr_alloc_info(); + let kernel_vaddr_alloc_base = kernel_vaddr_alloc_info.range.vaddr_begin; + + // Map, validate and populate the SVSM kernel ELF's PT_LOAD segments. The + // segments' virtual address range might not necessarily be contiguous, + // track their total extent along the way. Physical memory is successively + // being taken from the physical memory region, the remaining space will be + // available as heap space for the SVSM kernel. Remember the end of all + // physical memory occupied by the loaded ELF image. + let mut loaded_kernel_virt_start: Option<VirtAddr> = None; + let mut loaded_kernel_virt_end: VirtAddr = 0; + let mut loaded_kernel_phys_end = kernel_region_phys_start as PhysAddr; + for segment in kernel_elf.image_load_segment_iter(kernel_vaddr_alloc_base) { + // All ELF segments should be aligned to the page size. If not, there's + // the risk of pvalidating a page twice, bail out if so. Note that the + // ELF reading code had already verified that the individual segments, + // with bounds specified as in the ELF file, are non-overlapping. + let vaddr_start = segment.vaddr_range.vaddr_begin as VirtAddr; + if !is_aligned(vaddr_start, PAGE_SIZE) { + panic!("kernel ELF segment not aligned to page boundary"); + } + + // Remember the mapping range's lower bound to pass it on the kernel + // later. Note that the segments are being iterated over here in + // increasing load order. + if loaded_kernel_virt_start.is_none() { + loaded_kernel_virt_start = Some(vaddr_start); + } + + let vaddr_end = segment.vaddr_range.vaddr_end as VirtAddr; + let aligned_vaddr_end = page_align_up(vaddr_end); + loaded_kernel_virt_end = aligned_vaddr_end; + + let segment_len = aligned_vaddr_end - vaddr_start; + let paddr_start = loaded_kernel_phys_end; + loaded_kernel_phys_end += segment_len; + + map_and_validate(vaddr_start, paddr_start, segment_len); + + let segment_buf = unsafe { slice::from_raw_parts_mut(vaddr_start as *mut u8, segment_len) }; + let segment_contents = segment.file_contents; + let contents_len = segment_contents.len(); + segment_buf[..contents_len].copy_from_slice(segment_contents); + segment_buf[contents_len..].fill(0); + } -#[repr(C, packed)] -struct KernelMetaData { - virt_addr: VirtAddr, - entry: VirtAddr, -} + let loaded_kernel_virt_start = match loaded_kernel_virt_start { + Some(loaded_kernel_virt_start) => loaded_kernel_virt_start, + None => { + panic!("no loadable segment found in kernel ELF"); + } + }; -struct KInfo { - k_image_start: PhysAddr, - k_image_end: PhysAddr, - phys_base: PhysAddr, - phys_end: PhysAddr, - virt_base: VirtAddr, - entry: VirtAddr, -} + // Apply relocations, if any. + let dyn_relocs = match kernel_elf + .apply_dyn_relas(elf::Elf64X86RelocProcessor::new(), kernel_vaddr_alloc_base) + { + Ok(dyn_relocs) => dyn_relocs, + Err(e) => { + panic!("failed to read ELF relocations : {}", e);
```suggestion panic!("failed to read ELF relocations : {e}"); ``` The same change can be applied in a few more places.
svsm
github_2023
others
21
coconut-svsm
Freax13
@@ -8,11 +8,24 @@ #[repr(C)] pub struct KernelLaunchInfo { /// Start of the kernel in physical memory. - pub kernel_start: u64, + pub kernel_region_phys_start: u64, /// Exclusive end of the kernel in physical memory. - pub kernel_end: u64, - pub virt_base: u64, + pub kernel_region_phys_end: u64, + pub heap_area_phys_start: u64, // Start of trailing heap area within the physical memory region. + pub kernel_region_virt_start: u64, + pub heap_area_virt_start: u64, // Start of virtual heap area mapping. + pub kernel_elf_stage2_virt_start: u64, // Virtual address of kernel ELF in Stage2 mapping.
Items are usually documented with triple slash comments before the item. That way the comments are recognized as public documentation and are displayed in rustdoc generated docs. Some IDEs also support such doc comments: ![image](https://user-images.githubusercontent.com/14952658/231872222-067a8bac-4231-4198-a9c9-9f5aa6b6b9a6.png)
svsm
github_2023
others
21
coconut-svsm
joergroedel
@@ -126,11 +136,14 @@ impl ValidBitmap { } pub fn clear_all(&mut self) { - let (i, _) = self.index(self.pend - 1); + let (mut i, bit) = self.index(self.pend); + if bit != 0 { + i += 1; + } let index: usize = i.try_into().unwrap(); unsafe { - ptr::write_bytes(self.bitmap, 0, index); + ptr::write_bytes(self.bitmap, 0, index * 8);
This causes a crash in debug builds for me. ptr::write_bytes() already writes count*size_of<T>() bytes, no need to multiply by 8.
rill-flow
github_2023
java
90
weibocom
qdaxb
@@ -0,0 +1,355 @@ +package com.weibo.rill.flow.service.strategies;
没有copyright
rill-flow
github_2023
others
90
weibocom
qdaxb
@@ -0,0 +1,31 @@ +package com.weibo.rill.flow.service.strategies
没有copyright
rill-flow
github_2023
others
90
weibocom
qdaxb
@@ -0,0 +1,73 @@ +package com.weibo.rill.flow.service.strategies
没有copyright
rill-flow
github_2023
others
90
weibocom
qdaxb
@@ -1,46 +1,46 @@ -package com.weibo.rill.flow.service.statistic - -import com.weibo.rill.flow.olympicene.core.switcher.SwitcherManager -import com.weibo.rill.flow.olympicene.storage.exception.StorageException -import com.weibo.rill.flow.service.dconfs.BizDConfs -import spock.lang.Specification - -class DAGSubmitCheckerTest extends Specification { - SwitcherManager switcherManager = Mock(SwitcherManager) - BizDConfs bizDConfs = Mock(BizDConfs) - DAGSubmitChecker dagSubmitChecker = new DAGSubmitChecker(switcherManagerImpl: switcherManager, bizDConfs: bizDConfs) - - def "test checkDAGInfoLength when switcher is off"() { - given: - switcherManager.getSwitcherState("ENABLE_DAG_INFO_LENGTH_CHECK") >> false - expect: - dagSubmitChecker.checkDAGInfoLength("testBusiness1:testFeatureName1_c_0dc48c1d-32a2", ["hello world".bytes]) - } - - def "test checkDAGInfoLength when switcher is on and be limited"() { - given: - switcherManager.getSwitcherState("ENABLE_DAG_INFO_LENGTH_CHECK") >> true - bizDConfs.getRedisBusinessIdToDAGInfoMaxLength() >> ["testBusiness1": 5] - when: - dagSubmitChecker.checkDAGInfoLength("testBusiness1:testFeatureName1_c_0dc48c1d-32a2", ["hello world".bytes]) - then: - thrown StorageException - } - - def "test checkDAGInfoLength when switcher is on"() { - given: - switcherManager.getSwitcherState("ENABLE_DAG_INFO_LENGTH_CHECK") >> true - bizDConfs.getRedisBusinessIdToDAGInfoMaxLength() >> ["testBusiness1": 5] - expect: - dagSubmitChecker.checkDAGInfoLength("testBusiness1:testFeatureName1_c_0dc48c1d-32a2", null) - dagSubmitChecker.checkDAGInfoLength("testBusiness2:testFeatureName1_c_0dc48c1d-32a2", ["hello world".bytes]) - } - - def "test checkDAGInfoLength when switcher is on and dconfs return null"() { - given: - switcherManager.getSwitcherState("ENABLE_DAG_INFO_LENGTH_CHECK") >> true - bizDConfs.getRedisBusinessIdToDAGInfoMaxLength() >> null - expect: - dagSubmitChecker.checkDAGInfoLength("testBusiness2:testFeatureName1_c_0dc48c1d-32a2", ["hello world".bytes]) - } -} +package com.weibo.rill.flow.service.statistic
没有copyright
rill-flow
github_2023
others
90
weibocom
qdaxb
@@ -1,21 +1,21 @@ -package com.weibo.rill.flow.service.statistic - -import com.alibaba.fastjson.JSONObject -import spock.lang.Specification -import spock.lang.Unroll - -class DAGResourceStatisticTest extends Specification { - DAGResourceStatistic statistic = new DAGResourceStatistic() - - @Unroll - def "test getRetryIntervalSeconds"() { - when: - JSONObject urlRet1 = new JSONObject(Map.of("data", "message")) - JSONObject urlRet2 = new JSONObject(Map.of("data", Map.of("sys_info", Map.of("retry_interval_seconds", 100)))) - JSONObject urlRet3 = new JSONObject(Map.of("error_detail", Map.of("retry_interval_seconds", 100))) - then: - statistic.getRetryIntervalSeconds(urlRet1) == 0 - statistic.getRetryIntervalSeconds(urlRet2) == 100 - statistic.getRetryIntervalSeconds(urlRet3) == 100 - } -} +package com.weibo.rill.flow.service.statistic
没有copyright
rill-flow
github_2023
java
90
weibocom
qdaxb
@@ -0,0 +1,52 @@ +/* + * Copyright 2021-2023 Weibo, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.weibo.rill.flow.service.strategies; + +import com.weibo.rill.flow.olympicene.core.model.dag.DAG; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.Map; + +@Slf4j +@Component("dagProcessStrategyContext") +public class DAGProcessStrategyContext {
没有注释,看不懂这个类是做什么的
rill-flow
github_2023
java
90
weibocom
qdaxb
@@ -0,0 +1,35 @@ +/* + * Copyright 2021-2023 Weibo, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.weibo.rill.flow.service.strategies; + +import com.weibo.rill.flow.olympicene.core.model.dag.DAG; + +public interface DAGProcessStrategy {
类名是Strategy,但方法看更像是listener
rill-flow
github_2023
java
90
weibocom
qdaxb
@@ -0,0 +1,52 @@ +/* + * Copyright 2021-2023 Weibo, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.weibo.rill.flow.service.strategies; + +import com.weibo.rill.flow.olympicene.core.model.dag.DAG; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.Map; + +@Slf4j +@Component("dagProcessStrategyContext") +public class DAGProcessStrategyContext { + @Resource + private Map<String, DAGProcessStrategy> strategies; + + public static final String DEFAULT_STRATEGY = "defaultDAGProcessStrategy"; + public static final String CUSTOM_STRATEGY = "customDAGProcessStrategy"; + + public DAG onStorage(DAG dag, String strategyName) {
看不懂`context.onXXX`的语义
rill-flow
github_2023
java
90
weibocom
qdaxb
@@ -0,0 +1,52 @@ +/* + * Copyright 2021-2023 Weibo, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.weibo.rill.flow.service.strategies; + +import com.weibo.rill.flow.olympicene.core.model.dag.DAG; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.Map; + +@Slf4j +@Component("dagProcessStrategyContext") +public class DAGProcessStrategyContext { + @Resource + private Map<String, DAGProcessStrategy> strategies; + + public static final String DEFAULT_STRATEGY = "defaultDAGProcessStrategy"; + public static final String CUSTOM_STRATEGY = "customDAGProcessStrategy";
没有注释,看不懂`CUSTOM_STRATEGY`是做什么的
rill-flow
github_2023
java
90
weibocom
qdaxb
@@ -152,7 +156,13 @@ public class DescriptorManager { public String getDagDescriptor(Long uid, Map<String, Object> input, String dagDescriptorId) { // 调用量比较小 useCache为false 实时取最新的yaml保证更新会立即生效 - return getDagDescriptorWithCache(uid, input, dagDescriptorId, false); + String descriptor = getDagDescriptorWithCache(uid, input, dagDescriptorId, false); + return dagProcessStrategyContext.onRetrieval(descriptor, DAGProcessStrategyContext.DEFAULT_STRATEGY); + } + + public String getDagDescriptorForClient(Long uid, Map<String, Object> input, String dagDescriptorId) {
`getDagDescriptor`和`getDagDescriptorForClient`返回的`DagDescripter`有什么区别,如果是两种`DagDescriptor`,是否能区分不同的`DagDescriptor`类?
rill-flow
github_2023
java
90
weibocom
qdaxb
@@ -201,26 +201,74 @@ public Map<String, Object> setValue(Map<String, Object> map, Object value, Strin while (matcher.find()) { if (matcher.group(1) != null) { jsonPathParts.add(matcher.group(1)); - } else if (matcher.group(2) != null) { - jsonPathParts.add(matcher.group(2)); } } - jsonPathParts.remove(jsonPathParts.size() - 1); - Object current = map; - for (String part: jsonPathParts) { + for (int i = 0; i < jsonPathParts.size() - 1; i++) { + String part = jsonPathParts.get(i); + if (part.startsWith("\"") || part.startsWith("'")) { + part = part.substring(1, part.length() - 1); + } if (current instanceof Map) { - Map<String, Object> mapCurrent = (Map<String, Object>) current; - current = mapCurrent.computeIfAbsent(part, k -> new HashMap<>()); - } else { - break; + current = processMapJsonPathPart(current, part, jsonPathParts, i); + } else if (current instanceof List) { + current = processListJsonPathPart(current, part, jsonPathParts, i); } } return JsonPath.using(conf).parse(map).set(path, value).json(); } + /** + * 处理 List 类型的 jsonPath 元素 + */ + private Object processListJsonPathPart(Object current, String part, List<String> jsonPathParts, int i) {
注释没有比函数名提供更多信息
rill-flow
github_2023
java
90
weibocom
qdaxb
@@ -201,26 +201,74 @@ public Map<String, Object> setValue(Map<String, Object> map, Object value, Strin while (matcher.find()) { if (matcher.group(1) != null) { jsonPathParts.add(matcher.group(1)); - } else if (matcher.group(2) != null) { - jsonPathParts.add(matcher.group(2)); } } - jsonPathParts.remove(jsonPathParts.size() - 1); - Object current = map; - for (String part: jsonPathParts) { + for (int i = 0; i < jsonPathParts.size() - 1; i++) { + String part = jsonPathParts.get(i); + if (part.startsWith("\"") || part.startsWith("'")) { + part = part.substring(1, part.length() - 1); + } if (current instanceof Map) { - Map<String, Object> mapCurrent = (Map<String, Object>) current; - current = mapCurrent.computeIfAbsent(part, k -> new HashMap<>()); - } else { - break; + current = processMapJsonPathPart(current, part, jsonPathParts, i); + } else if (current instanceof List) { + current = processListJsonPathPart(current, part, jsonPathParts, i); } } return JsonPath.using(conf).parse(map).set(path, value).json(); } + /** + * 处理 List 类型的 jsonPath 元素 + */ + private Object processListJsonPathPart(Object current, String part, List<String> jsonPathParts, int i) { + List<Object> listCurrent = (List<Object>) current; + int index = Integer.parseInt(part); + Object insertPosition = listCurrent.get(index); + if (insertPosition != null) { + return insertPosition; + } + if (jsonPathParts.get(i + 1).matches("\\d+")) { + List<Object> nextArray = createAndFillNextArrayPart(jsonPathParts, i); + listCurrent.set(index, nextArray); + } else if (i + 1 < jsonPathParts.size() ) { + listCurrent.set(index, new HashMap<>()); + } + return listCurrent.get(index); + } + + /** + * 处理 Map 类型的 jsonPath 元素 + */ + private Object processMapJsonPathPart(Object current, String part, List<String> jsonPathParts, int i) {
注释没有比函数名提供更多信息
rill-flow
github_2023
java
86
weibocom
github-advanced-security[bot]
@@ -0,0 +1,139 @@ +/* + * Copyright 2021-2023 Weibo, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.weibo.api.flow.executors.service; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.weibo.api.flow.executors.model.enums.DAGStatus; +import com.weibo.api.flow.executors.model.enums.TaskStatus; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.client.utils.URIBuilder; +import org.jetbrains.annotations.Nullable; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.*; +import org.springframework.stereotype.Service; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Service +@Slf4j +public class RillFlowService { + @Value("${rill.flow.task.check.uri:/flow/get.json}") + private String rillFlowExecutionInfoGetUri; + @Value("${rill.flow.task.check.uri:/flow/submit.json}") + private String rillFlowSubmitUri; + @Value("${rill.flow.get.context.uri:/flow/get_context.json}") + private String rillFlowGetContextUri; + + @Resource + private RestTemplate rillFlowHttpTemplate; + + + public TaskStatus getTaskStatus(String rillFlowHost, String executionId, String taskName) { + JSONObject responseJson = getExecutionInfo(rillFlowHost, executionId); + if (responseJson == null) + return null; + String dagStatus = Optional.of(responseJson).map(it -> it.getJSONObject("ret")).map(it -> it.getString("dag_status")).orElse(null); + if ("FAILED".equalsIgnoreCase(dagStatus)) { + return TaskStatus.FAILED; + } + String status = Optional.of(responseJson).map(it -> it.getJSONObject("ret")) + .map(it -> it.getJSONObject("tasks")).map(it -> it.getJSONObject(taskName)) + .map(it -> it.getString("status")).orElse(null); + if (status == null) { + throw new IllegalArgumentException("task not exist"); + } + return TaskStatus.valueOf(status); + } + + @Nullable + private JSONObject getExecutionInfo(String rillFlowHost, String executionId) { + JSONObject responseJson; + try { + MultiValueMap<String, String> header = new LinkedMultiValueMap<>(); + URIBuilder uriBuilder = new URIBuilder(rillFlowHost + rillFlowExecutionInfoGetUri); + uriBuilder.addParameter("execution_id", executionId); + header.put(HttpHeaders.CONTENT_TYPE, List.of(MediaType.APPLICATION_JSON_VALUE)); + HttpEntity<Object> requestEntity = new HttpEntity<>(null, header); + ResponseEntity<String> response = rillFlowHttpTemplate.exchange(uriBuilder.build().toString(), HttpMethod.GET, requestEntity, String.class); + responseJson = JSON.parseObject(response.getBody()); + } catch (Exception e) { + log.error("getTaskStatus error, execution_id: {}, error: ", executionId, e); + return null; + } + return responseJson; + } + + public JSONObject getContext(String rillFlowHost, String executionId) { + try { + MultiValueMap<String, String> header = new LinkedMultiValueMap<>(); + header.put(HttpHeaders.CONTENT_TYPE, List.of(MediaType.APPLICATION_JSON_VALUE)); + URIBuilder uriBuilder = new URIBuilder(rillFlowHost + rillFlowGetContextUri); + uriBuilder.addParameter("execution_id", executionId); + HttpEntity<Object> requestEntity = new HttpEntity<>(null, header); + ResponseEntity<String> response = rillFlowHttpTemplate.exchange(uriBuilder.build().toString(), HttpMethod.GET, requestEntity, String.class); + return JSON.parseObject(response.getBody()); + } catch (Exception e) { + log.error("getContext error, execution_id: {}, error: ", executionId, e); + return null; + } + } + + public void callbackResult(JSONObject callbackInfo, boolean success, List<String> result) { + if (callbackInfo == null || callbackInfo.getString("trigger_url") == null) { + return; + } + String callbackUrl = String.format("%s&status=%s", callbackInfo.getString("trigger_url"), success ? "success": "failed"); + MultiValueMap<String, String> header = new LinkedMultiValueMap<>(); + header.put(HttpHeaders.CONTENT_TYPE, List.of(MediaType.APPLICATION_JSON_VALUE)); + JSONObject body = new JSONObject(Map.of("data", result)); + HttpEntity<Object> requestEntity = new HttpEntity<>(body, header); + rillFlowHttpTemplate.exchange(callbackUrl, HttpMethod.GET, requestEntity, String.class); + } + + public String submitFlow(String rillFlowHost, String descriptorId, JSONObject context) { + String submitUrl = rillFlowHost + rillFlowSubmitUri + "?descriptor_id=" + descriptorId; + MultiValueMap<String, String> header = new LinkedMultiValueMap<>(); + header.put(HttpHeaders.CONTENT_TYPE, List.of(MediaType.APPLICATION_JSON_VALUE)); + HttpEntity<Object> requestEntity = new HttpEntity<>(context, header); + ResponseEntity<String> response = rillFlowHttpTemplate.exchange(submitUrl, HttpMethod.GET, requestEntity, String.class);
## Server-side requests should not be vulnerable to forging attacks <!--SONAR_ISSUE_KEY:AZIjIfKadMY2tUEHm0UQ-->Change this code to not construct the URL from user-controlled data. <p>See more on <a href="https://sonarcloud.io/project/issues?id=weibocom_rill-flow&issues=AZIjIfKadMY2tUEHm0UQ&open=AZIjIfKadMY2tUEHm0UQ&pullRequest=86">SonarCloud</a></p> [Show more details](https://github.com/weibocom/rill-flow/security/code-scanning/1)
rill-flow
github_2023
java
86
weibocom
github-advanced-security[bot]
@@ -0,0 +1,148 @@ +/* + * Copyright 2021-2023 Weibo, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.weibo.api.flow.executors.service; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.weibo.api.flow.executors.model.enums.DAGStatus; +import com.weibo.api.flow.executors.model.enums.TaskStatus; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.client.utils.URIBuilder; +import org.jetbrains.annotations.Nullable; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.*; +import org.springframework.stereotype.Service; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +@Service +@Slf4j +public class RillFlowService { + @Value("${rill.flow.task.check.uri:/flow/get.json}") + private String rillFlowExecutionInfoGetUri; + @Value("${rill.flow.task.check.uri:/flow/submit.json}") + private String rillFlowSubmitUri; + @Value("${rill.flow.get.context.uri:/flow/get_context.json}") + private String rillFlowGetContextUri; + + @Resource + private RestTemplate rillFlowHttpTemplate; + + + public TaskStatus getTaskStatus(String rillFlowHost, String executionId, String taskName) { + JSONObject responseJson = getExecutionInfo(rillFlowHost, executionId); + if (responseJson == null) + return null; + String dagStatus = Optional.of(responseJson).map(it -> it.getJSONObject("ret")).map(it -> it.getString("dag_status")).orElse(null); + if ("FAILED".equalsIgnoreCase(dagStatus)) { + return TaskStatus.FAILED; + } + String status = Optional.of(responseJson).map(it -> it.getJSONObject("ret")) + .map(it -> it.getJSONObject("tasks")).map(it -> it.getJSONObject(taskName)) + .map(it -> it.getString("status")).orElse(null); + if (status == null) { + throw new IllegalArgumentException("task not exist"); + } + return TaskStatus.valueOf(status); + } + + @Nullable + private JSONObject getExecutionInfo(String rillFlowHost, String executionId) { + JSONObject responseJson; + try { + MultiValueMap<String, String> header = new LinkedMultiValueMap<>(); + URIBuilder uriBuilder = new URIBuilder(rillFlowHost + rillFlowExecutionInfoGetUri); + uriBuilder.addParameter("execution_id", executionId); + header.put(HttpHeaders.CONTENT_TYPE, List.of(MediaType.APPLICATION_JSON_VALUE)); + HttpEntity<Object> requestEntity = new HttpEntity<>(null, header); + ResponseEntity<String> response = rillFlowHttpTemplate.exchange(uriBuilder.build().toString(), HttpMethod.GET, requestEntity, String.class); + responseJson = JSON.parseObject(response.getBody()); + } catch (Exception e) { + log.error("getTaskStatus error, execution_id: {}, error: ", executionId, e); + return null; + } + return responseJson; + } + + public JSONObject getContext(String rillFlowHost, String executionId) { + try { + MultiValueMap<String, String> header = new LinkedMultiValueMap<>(); + header.put(HttpHeaders.CONTENT_TYPE, List.of(MediaType.APPLICATION_JSON_VALUE)); + URIBuilder uriBuilder = new URIBuilder(rillFlowHost + rillFlowGetContextUri); + uriBuilder.addParameter("execution_id", executionId); + HttpEntity<Object> requestEntity = new HttpEntity<>(null, header); + ResponseEntity<String> response = rillFlowHttpTemplate.exchange(uriBuilder.build().toString(), HttpMethod.GET, requestEntity, String.class); + return JSON.parseObject(response.getBody()); + } catch (Exception e) { + log.error("getContext error, execution_id: {}, error: ", executionId, e); + return null; + } + } + + public void callbackResult(JSONObject callbackInfo, boolean success, List<String> result) { + if (callbackInfo == null || callbackInfo.getString("trigger_url") == null) { + return; + } + String callbackUrl = String.format("%s&status=%s", callbackInfo.getString("trigger_url"), success ? "success": "failed"); + MultiValueMap<String, String> header = new LinkedMultiValueMap<>(); + header.put(HttpHeaders.CONTENT_TYPE, List.of(MediaType.APPLICATION_JSON_VALUE)); + JSONObject body = new JSONObject(Map.of("data", result)); + HttpEntity<Object> requestEntity = new HttpEntity<>(body, header); + rillFlowHttpTemplate.exchange(callbackUrl, HttpMethod.GET, requestEntity, String.class); + } + + public String submitFlow(String rillFlowHost, String descriptorId, JSONObject context) { + String submitUrl = rillFlowHost + rillFlowSubmitUri + "?descriptor_id=" + descriptorId; + MultiValueMap<String, String> header = new LinkedMultiValueMap<>(); + header.put(HttpHeaders.CONTENT_TYPE, List.of(MediaType.APPLICATION_JSON_VALUE)); + // Adding a CSRF token to the header to prevent CSRF attacks + String csrfToken = generateCsrfToken(); + header.put("X-CSRF-Token", List.of(csrfToken)); + HttpEntity<Object> requestEntity = new HttpEntity<>(context, header); + ResponseEntity<String> response = rillFlowHttpTemplate.exchange(submitUrl, HttpMethod.POST, requestEntity, String.class);
## Server-side requests should not be vulnerable to forging attacks <!--SONAR_ISSUE_KEY:AZIjKFHQyEi49Sr8X5_U-->Change this code to not construct the URL from user-controlled data. <p>See more on <a href="https://sonarcloud.io/project/issues?id=weibocom_rill-flow&issues=AZIjKFHQyEi49Sr8X5_U&open=AZIjKFHQyEi49Sr8X5_U&pullRequest=86">SonarCloud</a></p> [Show more details](https://github.com/weibocom/rill-flow/security/code-scanning/2)
rill-flow
github_2023
java
73
weibocom
qdaxb
@@ -177,19 +182,37 @@ public Map<String, Object> setValue(Map<String, Object> map, Object value, Strin return null; } - List<String> intermediateRoute = Lists.newArrayList(); - for (int i = 0; i < path.length(); i++) { - if (path.charAt(i) == '.') { - intermediateRoute.add(path.substring(0, i)); + String jsonPath = JsonPath.compile(path).getPath(); + String patternString = "\\[\"(.*?)\"]|\\['(.*?)']"; + + // 创建 Pattern 对象 + Pattern pattern = Pattern.compile(patternString);
提取到成员变量
rill-flow
github_2023
others
34
weibocom
qdaxb
@@ -0,0 +1,23 @@ +CREATE DATABASE IF NOT EXISTS rill_flow; +USE rill_flow; +CREATE TABLE IF NOT EXISTS `task_template` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `name` varchar(64) NOT NULL DEFAULT '' COMMENT '模板名称',
comment改英文
rill-flow
github_2023
java
34
weibocom
qdaxb
@@ -0,0 +1,250 @@ +/* + * Copyright 2021-2023 Weibo, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.weibo.rill.flow.impl.service; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.weibo.rill.flow.task.template.dao.mapper.TaskTemplateDAO; +import com.weibo.rill.flow.task.template.dao.model.TaskTemplateDO; +import com.weibo.rill.flow.task.template.model.TaskTemplateParams; +import com.weibo.rill.flow.task.template.model.TaskTemplateTypeEnum; +import com.weibo.rill.flow.olympicene.traversal.runners.AbstractTaskRunner; +import com.weibo.rill.flow.task.template.model.MetaData; +import com.weibo.rill.flow.task.template.model.TaskTemplate; +import com.weibo.rill.flow.task.template.service.TaskTemplateService; +import lombok.extern.slf4j.Slf4j; +import org.jetbrains.annotations.NotNull; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@Service +@Slf4j +public class TaskTemplateServiceImpl implements TaskTemplateService { + @Autowired + private Map<String, AbstractTaskRunner> taskRunnerMap; + @Autowired + private TaskTemplateDAO taskTemplateDAO; + + private final static int minPage = 1; + private final static int minPageSize = 10; + private final static int maxPageSize = 50; + + public JSONArray getTaskMetaDataList() { + JSONArray metaDataList = new JSONArray(); + for (Map.Entry<String, AbstractTaskRunner> taskRunnerEntry: taskRunnerMap.entrySet()) { + JSONObject metaData = new JSONObject(); + AbstractTaskRunner taskRunner = taskRunnerEntry.getValue(); + if (!taskRunner.isEnable()) { + continue; + } + metaData.put("category", taskRunner.getCategory()); + metaData.put("icon", taskRunner.getIcon()); + metaData.put("fields", taskRunner.getFields()); + metaDataList.add(metaData); + } + return metaDataList; + } + + public List<TaskTemplate> getTaskTemplates(TaskTemplateParams params, int page, int pageSize) { + if (page < minPage) { + page = minPage; + } + if (pageSize < minPageSize || pageSize > maxPageSize) { + pageSize = minPageSize; + } + + // 已展示元素数量 + int preSize = pageSize * (page - 1); + List<TaskTemplate> taskTemplateList = new ArrayList<>(); + List<AbstractTaskRunner> metaDataList = new ArrayList<>(); + if ((params.getNodeType() == null || params.getNodeType().equals("meta")) && (params.getEnable() == null || params.getEnable() == 1)) { + metaDataList = getTaskRunners(params); + } + + // 已展示元素数量小于元数据列表数量,说明需要用元数据填充列表 + if (preSize < metaDataList.size()) { + for (; preSize < metaDataList.size() && taskTemplateList.size() < pageSize; preSize++) { + taskTemplateList.add(turnMetaDataToTaskTemplate(metaDataList.get(preSize))); + } + pageSize -= taskTemplateList.size(); + } + + // 将 preSize 转化为数据库偏移量 + preSize -= metaDataList.size(); + if (pageSize <= 0) { + return taskTemplateList; + } + + // 查询数据库,填充列表 + List<TaskTemplate> taskTemplatesFromDB = getTaskTemplatesFromDB(params, pageSize, preSize); + taskTemplateList.addAll(taskTemplatesFromDB); + + return taskTemplateList; + } + + private List<TaskTemplate> getTaskTemplatesFromDB(TaskTemplateParams params, int pageSize, int preSize) { + List<TaskTemplate> taskTemplateList = new ArrayList<>(); + if (params.getNodeType() != null && !"template".equals(params.getNodeType())) { + return taskTemplateList; + } + params.setOffset(preSize); + params.setLimit(pageSize); + List<TaskTemplateDO> taskTemplateDOList = taskTemplateDAO.getTaskTemplateList(params); + if (taskTemplateDOList == null) { + return taskTemplateList; + } + for (TaskTemplateDO taskTemplateDO : taskTemplateDOList) { + taskTemplateList.add(turnTaskTemplateDOToTaskTemplate(taskTemplateDO)); + } + return taskTemplateList; + } + + @NotNull + private List<AbstractTaskRunner> getTaskRunners(TaskTemplateParams params) { + List<AbstractTaskRunner> metaDataList = new ArrayList<>(); + for (Map.Entry<String, AbstractTaskRunner> taskRunnerEntry: taskRunnerMap.entrySet()) { + AbstractTaskRunner taskRunner = taskRunnerEntry.getValue(); + if (!taskRunner.isEnable() || params.getId() != null + || params.getName() != null && !taskRunner.getCategory().contains(params.getName()) + || params.getCategory() != null && !taskRunner.getCategory().equals(params.getCategory()) + || params.getType() != null && params.getType() == 1
magic number
rill-flow
github_2023
java
34
weibocom
qdaxb
@@ -0,0 +1,250 @@ +/* + * Copyright 2021-2023 Weibo, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.weibo.rill.flow.impl.service; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.weibo.rill.flow.task.template.dao.mapper.TaskTemplateDAO; +import com.weibo.rill.flow.task.template.dao.model.TaskTemplateDO; +import com.weibo.rill.flow.task.template.model.TaskTemplateParams; +import com.weibo.rill.flow.task.template.model.TaskTemplateTypeEnum; +import com.weibo.rill.flow.olympicene.traversal.runners.AbstractTaskRunner; +import com.weibo.rill.flow.task.template.model.MetaData; +import com.weibo.rill.flow.task.template.model.TaskTemplate; +import com.weibo.rill.flow.task.template.service.TaskTemplateService; +import lombok.extern.slf4j.Slf4j; +import org.jetbrains.annotations.NotNull; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@Service +@Slf4j +public class TaskTemplateServiceImpl implements TaskTemplateService { + @Autowired + private Map<String, AbstractTaskRunner> taskRunnerMap; + @Autowired + private TaskTemplateDAO taskTemplateDAO; + + private final static int minPage = 1; + private final static int minPageSize = 10; + private final static int maxPageSize = 50; + + public JSONArray getTaskMetaDataList() { + JSONArray metaDataList = new JSONArray(); + for (Map.Entry<String, AbstractTaskRunner> taskRunnerEntry: taskRunnerMap.entrySet()) { + JSONObject metaData = new JSONObject(); + AbstractTaskRunner taskRunner = taskRunnerEntry.getValue(); + if (!taskRunner.isEnable()) { + continue; + } + metaData.put("category", taskRunner.getCategory()); + metaData.put("icon", taskRunner.getIcon()); + metaData.put("fields", taskRunner.getFields()); + metaDataList.add(metaData); + } + return metaDataList; + } + + public List<TaskTemplate> getTaskTemplates(TaskTemplateParams params, int page, int pageSize) { + if (page < minPage) { + page = minPage; + } + if (pageSize < minPageSize || pageSize > maxPageSize) { + pageSize = minPageSize; + } + + // 已展示元素数量 + int preSize = pageSize * (page - 1); + List<TaskTemplate> taskTemplateList = new ArrayList<>(); + List<AbstractTaskRunner> metaDataList = new ArrayList<>(); + if ((params.getNodeType() == null || params.getNodeType().equals("meta")) && (params.getEnable() == null || params.getEnable() == 1)) { + metaDataList = getTaskRunners(params); + } + + // 已展示元素数量小于元数据列表数量,说明需要用元数据填充列表 + if (preSize < metaDataList.size()) { + for (; preSize < metaDataList.size() && taskTemplateList.size() < pageSize; preSize++) { + taskTemplateList.add(turnMetaDataToTaskTemplate(metaDataList.get(preSize))); + } + pageSize -= taskTemplateList.size(); + } + + // 将 preSize 转化为数据库偏移量 + preSize -= metaDataList.size(); + if (pageSize <= 0) { + return taskTemplateList; + } + + // 查询数据库,填充列表 + List<TaskTemplate> taskTemplatesFromDB = getTaskTemplatesFromDB(params, pageSize, preSize); + taskTemplateList.addAll(taskTemplatesFromDB); + + return taskTemplateList; + } + + private List<TaskTemplate> getTaskTemplatesFromDB(TaskTemplateParams params, int pageSize, int preSize) { + List<TaskTemplate> taskTemplateList = new ArrayList<>(); + if (params.getNodeType() != null && !"template".equals(params.getNodeType())) { + return taskTemplateList; + } + params.setOffset(preSize); + params.setLimit(pageSize); + List<TaskTemplateDO> taskTemplateDOList = taskTemplateDAO.getTaskTemplateList(params); + if (taskTemplateDOList == null) { + return taskTemplateList; + } + for (TaskTemplateDO taskTemplateDO : taskTemplateDOList) { + taskTemplateList.add(turnTaskTemplateDOToTaskTemplate(taskTemplateDO)); + } + return taskTemplateList; + } + + @NotNull + private List<AbstractTaskRunner> getTaskRunners(TaskTemplateParams params) { + List<AbstractTaskRunner> metaDataList = new ArrayList<>(); + for (Map.Entry<String, AbstractTaskRunner> taskRunnerEntry: taskRunnerMap.entrySet()) { + AbstractTaskRunner taskRunner = taskRunnerEntry.getValue(); + if (!taskRunner.isEnable() || params.getId() != null + || params.getName() != null && !taskRunner.getCategory().contains(params.getName()) + || params.getCategory() != null && !taskRunner.getCategory().equals(params.getCategory()) + || params.getType() != null && params.getType() == 1 + || params.getType() != null && params.getType() == 0 && !"function".equals(taskRunner.getCategory()) + || params.getType() != null && params.getType() == 2 && "function".equals(taskRunner.getCategory()) + ) { + continue; + } + metaDataList.add(taskRunner); + } + return metaDataList; + } + + private TaskTemplate turnTaskTemplateDOToTaskTemplate(TaskTemplateDO taskTemplateDO) { + TaskTemplate result = new TaskTemplate(); + result.setId(taskTemplateDO.getId()); + result.setCategory(taskTemplateDO.getCategory()); + result.setIcon(taskTemplateDO.getIcon()); + result.setTaskYaml(taskTemplateDO.getTaskYaml()); + result.setName(taskTemplateDO.getName()); + result.setOutput(taskTemplateDO.getOutput()); + result.setSchema(taskTemplateDO.getSchema()); + result.setType(taskTemplateDO.getType()); + result.setEnable(taskTemplateDO.getEnable()); + result.setTypeStr(TaskTemplateTypeEnum.getEnumByType(taskTemplateDO.getType()).getDesc()); + result.setNodeType("template"); + AbstractTaskRunner taskRunner = taskRunnerMap.get(taskTemplateDO.getCategory() + "TaskRunner"); + MetaData metaData = MetaData.builder().icon(taskRunner.getIcon()).fields(taskRunner.getFields()).build(); + result.setMetaData(metaData); + return result; + } + + private TaskTemplate turnMetaDataToTaskTemplate(AbstractTaskRunner taskRunner) { + TaskTemplate result = new TaskTemplate(); + result.setId(null); + result.setCategory(taskRunner.getCategory()); + result.setIcon(taskRunner.getIcon()); + result.setTaskYaml(""); + result.setName(taskRunner.getCategory()); + result.setOutput("{}"); + result.setSchema("{}"); + result.setEnable(1); + result.setType("function".equals(taskRunner.getCategory())? 0: 2);
magic number
rill-flow
github_2023
java
34
weibocom
qdaxb
@@ -0,0 +1,33 @@ +/* + * Copyright 2021-2023 Weibo, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.weibo.rill.flow.task.template.service; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.weibo.rill.flow.task.template.model.TaskTemplateParams; +import com.weibo.rill.flow.task.template.model.TaskTemplate; + +import java.util.List; + +public interface TaskTemplateService { + JSONArray getTaskMetaDataList();
没有注释
rill-flow
github_2023
others
27
weibocom
qdaxb
@@ -0,0 +1,174 @@ +name: Deploy and Test +on: + push: + branches: + - main + pull_request: + types: [ opened, synchronize, reopened ] +jobs: + test: + name: Deploy and Test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: Set up Maven + run: | + sudo apt-get update + sudo apt-get install -y maven + - name: Set up JDK 17 + uses: actions/setup-java@v3 + with: + java-version: 17 + distribution: 'temurin' + + - name: Build and package + run: mvn clean package -am && echo "Maven Build and package succeeded" || { echo "Maven Build and package failed."; exit 1; } + + - name: Run Internal Test + run: mvn test && echo "Maven Run Internal Test succeeded"|| { echo "Run Internal Test failed."; exit 1; } + + - name: Install Docker Compose + run: | + sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose + sudo chmod +x /usr/local/bin/docker-compose + + - name: Deploy with Docker Compose + run: | + cd docker + docker-compose up -d + + - name: Wait for service to start + run: sleep 2s + + - name: Run API Test + run: | + set response $(curl --location 'http://localhost:8080/flow/bg/manage/descriptor/add_descriptor.json?business_id=rillFlowSample&feature_name=choiceSample&alias=release' \
应该用测试框架执行测试。
rill-flow
github_2023
others
27
weibocom
qdaxb
@@ -0,0 +1,174 @@ +name: Deploy and Test +on: + push: + branches: + - main + pull_request: + types: [ opened, synchronize, reopened ] +jobs: + test: + name: Deploy and Test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: Set up Maven + run: | + sudo apt-get update + sudo apt-get install -y maven
setupjdk里包含maven
rill-flow
github_2023
others
27
weibocom
qdaxb
@@ -0,0 +1,174 @@ +name: Deploy and Test +on: + push: + branches: + - main + pull_request: + types: [ opened, synchronize, reopened ] +jobs: + test: + name: Deploy and Test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: Set up Maven + run: | + sudo apt-get update + sudo apt-get install -y maven + - name: Set up JDK 17 + uses: actions/setup-java@v3 + with: + java-version: 17 + distribution: 'temurin' + + - name: Build and package + run: mvn clean package -am && echo "Maven Build and package succeeded" || { echo "Maven Build and package failed."; exit 1; } + + - name: Run Internal Test + run: mvn test && echo "Maven Run Internal Test succeeded"|| { echo "Run Internal Test failed."; exit 1; }
package包含test
rill-flow
github_2023
others
27
weibocom
qdaxb
@@ -33,13 +33,13 @@ jobs: - name: Build and analyze env: SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: mvn -B clean javadoc:javadoc clean verify -P coverage -DskipITs=false -Dmaven.test.skip=false + run: mvn -B clean javadoc:javadoc clean verify -P coverage -DskipITs=false -Dmaven.test.skip=false -pl '!rill-flow-test'
应该默认不运行rill-flow-test,而不是显式指定不运行
rill-flow
github_2023
others
27
weibocom
qdaxb
@@ -0,0 +1,170 @@ +package com.weibo.rill.flow.sample + +import org.apache.http.HttpEntity +import org.apache.http.HttpResponse +import org.apache.http.client.HttpClient +import org.apache.http.client.methods.HttpPost +import org.apache.http.entity.ContentType +import org.apache.http.entity.StringEntity +import org.apache.http.impl.client.HttpClientBuilder +import org.apache.http.util.EntityUtils +import org.junit.jupiter.api.MethodOrderer +import org.junit.jupiter.api.Order +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.TestInstance +import org.junit.jupiter.api.TestMethodOrder +import spock.lang.Specification + +import java.nio.file.Files +import java.nio.file.Paths + +import static org.junit.jupiter.api.Assertions.assertEquals + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
应该使用spock的`Stepwise`来顺序执行测试
rill-flow
github_2023
others
27
weibocom
qdaxb
@@ -0,0 +1,170 @@ +package com.weibo.rill.flow.sample + +import org.apache.http.HttpEntity +import org.apache.http.HttpResponse +import org.apache.http.client.HttpClient +import org.apache.http.client.methods.HttpPost +import org.apache.http.entity.ContentType +import org.apache.http.entity.StringEntity +import org.apache.http.impl.client.HttpClientBuilder +import org.apache.http.util.EntityUtils +import org.junit.jupiter.api.MethodOrderer +import org.junit.jupiter.api.Order +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.TestInstance +import org.junit.jupiter.api.TestMethodOrder +import spock.lang.Specification + +import java.nio.file.Files +import java.nio.file.Paths + +import static org.junit.jupiter.api.Assertions.assertEquals + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SampleApiTest extends Specification { + class ApiResponse { + int statusCode; + String responseContent; + + ApiResponse(int statusCode, String responseContent) { + this.statusCode = statusCode; + this.responseContent = responseContent; + } + + int getStatusCode() { + return statusCode + } + + void setStatusCode(int statusCode) { + this.statusCode = statusCode + } + + String getResponseContent() { + return responseContent + } + + void setResponseContent(String responseContent) { + this.responseContent = responseContent + } + } + + + @Test + @Order(1) + public void testChoiceSampleAddDescriptor() {
这里没有使用spock的基本测试格式
rill-flow
github_2023
others
27
weibocom
qdaxb
@@ -0,0 +1,170 @@ +package com.weibo.rill.flow.sample + +import org.apache.http.HttpEntity +import org.apache.http.HttpResponse +import org.apache.http.client.HttpClient +import org.apache.http.client.methods.HttpPost +import org.apache.http.entity.ContentType +import org.apache.http.entity.StringEntity +import org.apache.http.impl.client.HttpClientBuilder +import org.apache.http.util.EntityUtils +import org.junit.jupiter.api.MethodOrderer +import org.junit.jupiter.api.Order +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.TestInstance +import org.junit.jupiter.api.TestMethodOrder +import spock.lang.Specification + +import java.nio.file.Files +import java.nio.file.Paths + +import static org.junit.jupiter.api.Assertions.assertEquals + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SampleApiTest extends Specification { + class ApiResponse { + int statusCode; + String responseContent; + + ApiResponse(int statusCode, String responseContent) { + this.statusCode = statusCode; + this.responseContent = responseContent; + } + + int getStatusCode() { + return statusCode + } + + void setStatusCode(int statusCode) { + this.statusCode = statusCode + } + + String getResponseContent() { + return responseContent + } + + void setResponseContent(String responseContent) { + this.responseContent = responseContent + } + } + + + @Test + @Order(1) + public void testChoiceSampleAddDescriptor() { + String url = "http://localhost:8080/flow/bg/manage/descriptor/add_descriptor.json?business_id=rillFlowSample&feature_name=choiceSample&alias=release"; + String contentType = "text/plain"; + String requestData = readFileContent("../docs/samples/choice-sample.yaml"); + // 执行 API 请求并获取响应 + ApiResponse response = sendApiRequest(url, contentType, requestData); + // 使用测试断言来验证测试结果 + assertEquals(200, response.getStatusCode(), response.getResponseContent());
这里没有使用spock风格的assert
rill-flow
github_2023
others
27
weibocom
qdaxb
@@ -0,0 +1,170 @@ +package com.weibo.rill.flow.sample + +import org.apache.http.HttpEntity +import org.apache.http.HttpResponse +import org.apache.http.client.HttpClient +import org.apache.http.client.methods.HttpPost +import org.apache.http.entity.ContentType +import org.apache.http.entity.StringEntity +import org.apache.http.impl.client.HttpClientBuilder +import org.apache.http.util.EntityUtils +import org.junit.jupiter.api.MethodOrderer +import org.junit.jupiter.api.Order +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.TestInstance +import org.junit.jupiter.api.TestMethodOrder +import spock.lang.Specification + +import java.nio.file.Files +import java.nio.file.Paths + +import static org.junit.jupiter.api.Assertions.assertEquals + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SampleApiTest extends Specification { + class ApiResponse {
可以直接用map,不需要单独定义类
rill-flow
github_2023
others
27
weibocom
qdaxb
@@ -0,0 +1,170 @@ +package com.weibo.rill.flow.sample + +import org.apache.http.HttpEntity +import org.apache.http.HttpResponse +import org.apache.http.client.HttpClient +import org.apache.http.client.methods.HttpPost +import org.apache.http.entity.ContentType +import org.apache.http.entity.StringEntity +import org.apache.http.impl.client.HttpClientBuilder +import org.apache.http.util.EntityUtils +import org.junit.jupiter.api.MethodOrderer +import org.junit.jupiter.api.Order +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.TestInstance +import org.junit.jupiter.api.TestMethodOrder +import spock.lang.Specification + +import java.nio.file.Files +import java.nio.file.Paths + +import static org.junit.jupiter.api.Assertions.assertEquals + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SampleApiTest extends Specification { + class ApiResponse { + int statusCode; + String responseContent; + + ApiResponse(int statusCode, String responseContent) { + this.statusCode = statusCode; + this.responseContent = responseContent; + } + + int getStatusCode() { + return statusCode + } + + void setStatusCode(int statusCode) { + this.statusCode = statusCode + } + + String getResponseContent() { + return responseContent + } + + void setResponseContent(String responseContent) { + this.responseContent = responseContent + } + } + + + @Test + @Order(1) + public void testChoiceSampleAddDescriptor() { + String url = "http://localhost:8080/flow/bg/manage/descriptor/add_descriptor.json?business_id=rillFlowSample&feature_name=choiceSample&alias=release"; + String contentType = "text/plain"; + String requestData = readFileContent("../docs/samples/choice-sample.yaml"); + // 执行 API 请求并获取响应 + ApiResponse response = sendApiRequest(url, contentType, requestData); + // 使用测试断言来验证测试结果 + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + @Test + @Order(2) + public void testChoiceSampleSubmit() { + String url = "http://localhost:8080/flow/submit.json?descriptor_id=rillFlowSample:choiceSample"; + String contentType = "application/json"; + String requestData = "{\"input_num\":10}"; + ApiResponse response = sendApiRequest(url, contentType, requestData); + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + @Test + @Order(3) + public void testCallApiSampleAddDescriptor() { + String url = "http://localhost:8080/flow/bg/manage/descriptor/add_descriptor.json?business_id=rillFlowSample&feature_name=callApiSample&alias=release"; + String contentType = "text/plain"; + String requestData = readFileContent("../docs/samples/call-api-sample.yaml"); + ApiResponse response = sendApiRequest(url, contentType, requestData); + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + @Test + @Order(4) + public void testCallApiSampleSubmit() { + String url = "http://localhost:8080/flow/submit.json?descriptor_id=rillFlowSample:callApiSample"; + String contentType = "application/json"; + String requestData = "{\"input_num\":10}"; + ApiResponse response = sendApiRequest(url, contentType, requestData); + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + @Test + @Order(5) + public void testParallelAsyncTaskAddDescriptor() { + String url = "http://localhost:8080/flow/bg/manage/descriptor/add_descriptor.json?business_id=rillFlowSample&feature_name=parallelAsyncTask&alias=release"; + String contentType = "text/plain"; + String requestData = readFileContent("../docs/samples/parallel-async-dag.yaml"); + ApiResponse response = sendApiRequest(url, contentType, requestData); + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + @Test + @Order(6) + public void testParallelAsyncTaskSubmit() { + String url = "http://localhost:8080/flow/submit.json?descriptor_id=rillFlowSample:parallelAsyncTask"; + String contentType = "application/json"; + String requestData = "{\"rand_num\":20}"; + ApiResponse response = sendApiRequest(url, contentType, requestData); + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + @Test + @Order(7) + public void testSubDagTaskAddDescriptor() { + String url = "http://localhost:8080/flow/bg/manage/descriptor/add_descriptor.json?business_id=rillFlowSample&feature_name=subdagTask&alias=release"; + String contentType = "text/plain"; + String requestData = readFileContent("../docs/samples/ref-dag.yaml"); + ApiResponse response = sendApiRequest(url, contentType, requestData); + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + @Test + @Order(8) + public void testSubDagTaskSubmit() { + String url = "http://localhost:8080/flow/submit.json?descriptor_id=rillFlowSample:subdagTask"; + String contentType = "application/json"; + String requestData = "{\"parent_rand_num\":20}"; + ApiResponse response = sendApiRequest(url, contentType, requestData); + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + + + + private String readFileContent(String filePath) { + try { + // 读取文件内容并返回 + return new String(Files.readAllBytes(Paths.get(filePath))); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + private ApiResponse sendApiRequest(String url, String contentType, String requestData) { + HttpClient httpClient = HttpClientBuilder.create().build(); + try { + HttpPost httpPost = new HttpPost(url); + httpPost.addHeader("Content-Type", contentType); + + // 设置请求体 + httpPost.setEntity(new StringEntity(requestData, ContentType.create(contentType))); + + HttpResponse response = httpClient.execute(httpPost); + HttpEntity entity = response.getEntity(); + + // 获取响应状态码和内容 + int statusCode = response.getStatusLine().getStatusCode(); + String responseContent = EntityUtils.toString(entity); + + return new ApiResponse(statusCode, responseContent);
可以直接用`jsonslurper`解析
rill-flow
github_2023
others
27
weibocom
qdaxb
@@ -0,0 +1,170 @@ +package com.weibo.rill.flow.sample + +import org.apache.http.HttpEntity +import org.apache.http.HttpResponse +import org.apache.http.client.HttpClient +import org.apache.http.client.methods.HttpPost +import org.apache.http.entity.ContentType +import org.apache.http.entity.StringEntity +import org.apache.http.impl.client.HttpClientBuilder +import org.apache.http.util.EntityUtils +import org.junit.jupiter.api.MethodOrderer +import org.junit.jupiter.api.Order +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.TestInstance +import org.junit.jupiter.api.TestMethodOrder +import spock.lang.Specification + +import java.nio.file.Files +import java.nio.file.Paths + +import static org.junit.jupiter.api.Assertions.assertEquals + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SampleApiTest extends Specification { + class ApiResponse { + int statusCode; + String responseContent; + + ApiResponse(int statusCode, String responseContent) { + this.statusCode = statusCode; + this.responseContent = responseContent; + } + + int getStatusCode() { + return statusCode + } + + void setStatusCode(int statusCode) { + this.statusCode = statusCode + } + + String getResponseContent() { + return responseContent + } + + void setResponseContent(String responseContent) { + this.responseContent = responseContent + } + } + + + @Test + @Order(1) + public void testChoiceSampleAddDescriptor() { + String url = "http://localhost:8080/flow/bg/manage/descriptor/add_descriptor.json?business_id=rillFlowSample&feature_name=choiceSample&alias=release"; + String contentType = "text/plain"; + String requestData = readFileContent("../docs/samples/choice-sample.yaml"); + // 执行 API 请求并获取响应 + ApiResponse response = sendApiRequest(url, contentType, requestData); + // 使用测试断言来验证测试结果 + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + @Test + @Order(2) + public void testChoiceSampleSubmit() { + String url = "http://localhost:8080/flow/submit.json?descriptor_id=rillFlowSample:choiceSample"; + String contentType = "application/json"; + String requestData = "{\"input_num\":10}"; + ApiResponse response = sendApiRequest(url, contentType, requestData); + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + @Test + @Order(3) + public void testCallApiSampleAddDescriptor() { + String url = "http://localhost:8080/flow/bg/manage/descriptor/add_descriptor.json?business_id=rillFlowSample&feature_name=callApiSample&alias=release"; + String contentType = "text/plain"; + String requestData = readFileContent("../docs/samples/call-api-sample.yaml"); + ApiResponse response = sendApiRequest(url, contentType, requestData); + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + @Test + @Order(4) + public void testCallApiSampleSubmit() { + String url = "http://localhost:8080/flow/submit.json?descriptor_id=rillFlowSample:callApiSample"; + String contentType = "application/json"; + String requestData = "{\"input_num\":10}"; + ApiResponse response = sendApiRequest(url, contentType, requestData); + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + @Test + @Order(5) + public void testParallelAsyncTaskAddDescriptor() { + String url = "http://localhost:8080/flow/bg/manage/descriptor/add_descriptor.json?business_id=rillFlowSample&feature_name=parallelAsyncTask&alias=release"; + String contentType = "text/plain"; + String requestData = readFileContent("../docs/samples/parallel-async-dag.yaml"); + ApiResponse response = sendApiRequest(url, contentType, requestData); + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + @Test + @Order(6) + public void testParallelAsyncTaskSubmit() { + String url = "http://localhost:8080/flow/submit.json?descriptor_id=rillFlowSample:parallelAsyncTask"; + String contentType = "application/json"; + String requestData = "{\"rand_num\":20}"; + ApiResponse response = sendApiRequest(url, contentType, requestData); + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + @Test + @Order(7) + public void testSubDagTaskAddDescriptor() { + String url = "http://localhost:8080/flow/bg/manage/descriptor/add_descriptor.json?business_id=rillFlowSample&feature_name=subdagTask&alias=release"; + String contentType = "text/plain"; + String requestData = readFileContent("../docs/samples/ref-dag.yaml"); + ApiResponse response = sendApiRequest(url, contentType, requestData); + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + @Test + @Order(8) + public void testSubDagTaskSubmit() { + String url = "http://localhost:8080/flow/submit.json?descriptor_id=rillFlowSample:subdagTask"; + String contentType = "application/json"; + String requestData = "{\"parent_rand_num\":20}"; + ApiResponse response = sendApiRequest(url, contentType, requestData); + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + + + + private String readFileContent(String filePath) { + try { + // 读取文件内容并返回 + return new String(Files.readAllBytes(Paths.get(filePath)));
```return new File('/path/to/file').text```
rill-flow
github_2023
others
27
weibocom
qdaxb
@@ -0,0 +1,170 @@ +package com.weibo.rill.flow.sample + +import org.apache.http.HttpEntity +import org.apache.http.HttpResponse +import org.apache.http.client.HttpClient +import org.apache.http.client.methods.HttpPost +import org.apache.http.entity.ContentType +import org.apache.http.entity.StringEntity +import org.apache.http.impl.client.HttpClientBuilder +import org.apache.http.util.EntityUtils +import org.junit.jupiter.api.MethodOrderer +import org.junit.jupiter.api.Order +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.TestInstance +import org.junit.jupiter.api.TestMethodOrder +import spock.lang.Specification + +import java.nio.file.Files +import java.nio.file.Paths + +import static org.junit.jupiter.api.Assertions.assertEquals + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SampleApiTest extends Specification { + class ApiResponse { + int statusCode; + String responseContent; + + ApiResponse(int statusCode, String responseContent) { + this.statusCode = statusCode; + this.responseContent = responseContent; + } + + int getStatusCode() { + return statusCode + } + + void setStatusCode(int statusCode) { + this.statusCode = statusCode + } + + String getResponseContent() { + return responseContent + } + + void setResponseContent(String responseContent) { + this.responseContent = responseContent + } + } + + + @Test + @Order(1) + public void testChoiceSampleAddDescriptor() { + String url = "http://localhost:8080/flow/bg/manage/descriptor/add_descriptor.json?business_id=rillFlowSample&feature_name=choiceSample&alias=release"; + String contentType = "text/plain"; + String requestData = readFileContent("../docs/samples/choice-sample.yaml"); + // 执行 API 请求并获取响应 + ApiResponse response = sendApiRequest(url, contentType, requestData); + // 使用测试断言来验证测试结果 + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + @Test + @Order(2) + public void testChoiceSampleSubmit() { + String url = "http://localhost:8080/flow/submit.json?descriptor_id=rillFlowSample:choiceSample"; + String contentType = "application/json"; + String requestData = "{\"input_num\":10}"; + ApiResponse response = sendApiRequest(url, contentType, requestData); + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + @Test + @Order(3) + public void testCallApiSampleAddDescriptor() { + String url = "http://localhost:8080/flow/bg/manage/descriptor/add_descriptor.json?business_id=rillFlowSample&feature_name=callApiSample&alias=release"; + String contentType = "text/plain"; + String requestData = readFileContent("../docs/samples/call-api-sample.yaml"); + ApiResponse response = sendApiRequest(url, contentType, requestData); + assertEquals(200, response.getStatusCode(), response.getResponseContent()); + } + + @Test + @Order(4) + public void testCallApiSampleSubmit() { + String url = "http://localhost:8080/flow/submit.json?descriptor_id=rillFlowSample:callApiSample"; + String contentType = "application/json"; + String requestData = "{\"input_num\":10}"; + ApiResponse response = sendApiRequest(url, contentType, requestData); + assertEquals(200, response.getStatusCode(), response.getResponseContent());
只验证了状态码,没有验证返回内容和图的业务结果
rill-flow
github_2023
others
17
weibocom
qdaxb
@@ -0,0 +1,50 @@ +version: '3' +services: + rill-flow-textGatherer: + image: <repository>/rill-flow-textgatherer:0.0.1 + ports: + - "9000:9000" + volumes: + - "/tmp:/tmp" + environment: + - PROXY_RILL_FLOW_DOMAIN="<rill-flow-ip>"
应该是`RILL_FLOW_HOST`
rill-flow
github_2023
others
17
weibocom
qdaxb
@@ -0,0 +1,50 @@ +version: '3' +services: + rill-flow-textGatherer: + image: <repository>/rill-flow-textgatherer:0.0.1 + ports: + - "9000:9000" + volumes: + - "/tmp:/tmp" + environment: + - PROXY_RILL_FLOW_DOMAIN="<rill-flow-ip>" + - PROXY_RILL_FLOW_PORT=8080
应该是`RILL_FLOW_PORT`
rill-flow
github_2023
others
17
weibocom
qdaxb
@@ -0,0 +1,60 @@ +version: 0.0.1 +type: flow +workspace: rillFlow +dagName: digitalHuman +tasks: + - category: function + name: textGatherer + pattern: task_async + resourceName: http://<rill-flow-textGatherer-ip>:9000/scrape
应该是`textGatherer-executor-host`
rill-flow
github_2023
others
17
weibocom
qdaxb
@@ -0,0 +1,60 @@ +version: 0.0.1 +type: flow +workspace: rillFlow +dagName: digitalHuman +tasks: + - category: function + name: textGatherer + pattern: task_async + resourceName: http://<rill-flow-textGatherer-ip>:9000/scrape + inputMappings: + - target: $.input.paragraph_limit + source: $.context.paragraph_limit + outputMappings: + - target: $.context.txt_array + source: $.output.txt_array + next: generate + - category: foreach + name: generate + iterationMapping: + collection: $.input.txt_array + item: txt + inputMappings: + - target: $.input.txt_array + source: $.context.txt_array + outputMappings: + - target: $.context.segments + source: $.output.sub_context.[*].segment + next: processor + tasks: + - category: function + name: bark + pattern: task_async + resourceName: http://<rill-flow-bark-ip>:9001/bark/generate
`bark-executor-host`
rill-flow
github_2023
others
17
weibocom
qdaxb
@@ -0,0 +1,60 @@ +version: 0.0.1 +type: flow +workspace: rillFlow +dagName: digitalHuman +tasks: + - category: function + name: textGatherer + pattern: task_async + resourceName: http://<rill-flow-textGatherer-ip>:9000/scrape + inputMappings: + - target: $.input.paragraph_limit + source: $.context.paragraph_limit + outputMappings: + - target: $.context.txt_array + source: $.output.txt_array + next: generate + - category: foreach + name: generate + iterationMapping: + collection: $.input.txt_array + item: txt + inputMappings: + - target: $.input.txt_array + source: $.context.txt_array + outputMappings: + - target: $.context.segments + source: $.output.sub_context.[*].segment + next: processor + tasks: + - category: function + name: bark + pattern: task_async + resourceName: http://<rill-flow-bark-ip>:9001/bark/generate + inputMappings: + - source: $.context.txt + target: $.input.txt + outputMappings: + - source: $.output.audio_path + target: $.context.audio_path + next: digital + - category: function + name: digital + pattern: task_async + resourceName: http://<rill-flow-wav2lip-ip>:9002/wav2lip/generate
`wav2lip-executor-host`
rill-flow
github_2023
others
17
weibocom
qdaxb
@@ -0,0 +1,60 @@ +version: 0.0.1 +type: flow +workspace: rillFlow +dagName: digitalHuman +tasks: + - category: function + name: textGatherer + pattern: task_async + resourceName: http://<rill-flow-textGatherer-ip>:9000/scrape + inputMappings: + - target: $.input.paragraph_limit + source: $.context.paragraph_limit + outputMappings: + - target: $.context.txt_array + source: $.output.txt_array + next: generate + - category: foreach + name: generate + iterationMapping: + collection: $.input.txt_array + item: txt + inputMappings: + - target: $.input.txt_array + source: $.context.txt_array + outputMappings: + - target: $.context.segments + source: $.output.sub_context.[*].segment + next: processor + tasks: + - category: function + name: bark + pattern: task_async + resourceName: http://<rill-flow-bark-ip>:9001/bark/generate + inputMappings: + - source: $.context.txt + target: $.input.txt + outputMappings: + - source: $.output.audio_path + target: $.context.audio_path + next: digital + - category: function + name: digital + pattern: task_async + resourceName: http://<rill-flow-wav2lip-ip>:9002/wav2lip/generate + inputMappings: + - source: $.context.audio_path + target: $.input.audio_path + outputMappings: + - source: $.output.segment + target: $.context.segment + - category: function + name: processor + pattern: task_async + resourceName: http://<rill-flow-media-processor-ip>:9003/moviepy/generate
`mergevideo-executor-host`
rill-flow
github_2023
others
17
weibocom
qdaxb
@@ -0,0 +1,23 @@ +FROM continuumio/miniconda3 +RUN conda create --name moviepy python=3.10 +RUN echo "conda activate moviepy" >> ~/.bashrc +ENV PATH /opt/conda/envs/moviepy/bin:$PATH + +# install dependency +RUN sed -i 's/deb.debian.org/mirrors.tencent.com/g' /etc/apt/sources.list +RUN apt-get update && apt-get install -y imagemagick vim + +# create project +WORKDIR /media-processor +COPY main.py main.py +COPY subtitles.srt subtitles.srt
这个应该动态生成
rill-flow
github_2023
java
15
weibocom
qdaxb
@@ -152,11 +156,23 @@ public Map<String, Object> getExecution( ) { Map<String, Object> result = dagRuntimeFacade.getBasicDAGInfo(executionId, false); - String traceId = redisClient.get(TRACE_ID_PREFIX + executionId); - result.put("trace_uri", "/trace/" + traceId); + appendTraceInfo(executionId, result); return result; } + private void appendTraceInfo(String executionId, Map<String, Object> result) {
应该是result.put("trace_url",`buildTraceInfo`)
rill-flow
github_2023
java
15
weibocom
qdaxb
@@ -43,6 +44,9 @@ public class BgController { private static final String BUSINESS_IDS = "business_ids"; private static final String TRACE_ID_PREFIX = "trace_id_"; + @Value("${rill_flow_trace_query_url}")
应该是`rill_flow_trace_query_host`
rill-flow
github_2023
others
9
weibocom
qdaxb
@@ -98,6 +98,11 @@ <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-autoconfigure</artifactId> + <version>2.7.18</version>
remove version
rill-flow
github_2023
others
9
weibocom
qdaxb
@@ -21,7 +21,5 @@ rill_flow_auth_secret_key=a819796893fad1350e6bc17548e8f02e rill_flow_dag_redo_url=http://127.0.0.1:8080/flow/redo.json spring.kafka.producer.bootstrap-servers=127.0.0.1:9092
remove it
zig-objc
github_2023
others
3
mitchellh
mitchellh
@@ -0,0 +1,316 @@ +const std = @import("std"); +const objc = @import("main.zig"); + +const NSConcreteStackBlock = @extern(*anyopaque, .{ .name = "_NSConcreteStackBlock" }); +extern "C" fn _Block_object_assign(dst: *anyopaque, src: *const anyopaque, flag: c_int) void; +extern "C" fn _Block_object_dispose(src: *const anyopaque, flag: c_int) void; + +/// captures is either a struct type or a struct literal +// whose fields will be added to the block +// captures should not be a tuple +// blockFn is either a function type or an actual function +pub fn Block(comptime captures: anytype, comptime blockFn: anytype) type { + const Captures = @TypeOf(captures); + const BlockFn = @TypeOf(blockFn); + const captures_info = @typeInfo(Captures); + const blockfn_info = @typeInfo(BlockFn); + const real_captures_info = switch (captures_info) { + .Type => @typeInfo(captures).Struct, + .Struct => |s| s, + else => @compileError("captures should be a struct type or struct literal"), + }; + const real_blockfn_info = switch (blockfn_info) { + .Type => @typeInfo(blockFn).Fn, + .Fn => |f| f, + .Pointer => |p| @typeInfo(p.child).Fn, + else => @compileError("blockFn should be a function type or a function"), + }; + const Return = real_blockfn_info.return_type.?; + const params = real_blockfn_info.params; + // an invoke function takes at least one argument: a block. + std.debug.assert(params.len > 0); + // an invoke function's first argument, a block, must be *anyopaque. + std.debug.assert(params[0].type == *anyopaque); + const fields: []std.builtin.Type.StructField = fields: { + var acc: [real_captures_info.fields.len + 5]std.builtin.Type.StructField = undefined; + acc[0] = .{ + .name = "isa", + .type = ?*anyopaque, + .default_value = null, + .is_comptime = false, + .alignment = @alignOf(*anyopaque), + }; + acc[1] = .{ + .name = "flags", + .type = c_int, + .default_value = null, + .is_comptime = false, + .alignment = @alignOf(c_int), + }; + acc[2] = .{ + .name = "reserved", + .type = c_int, + .default_value = null, + .is_comptime = false, + .alignment = @alignOf(c_int), + }; + acc[3] = .{ + .name = "invoke", + .type = *const @Type(.{ + .Fn = .{ + .calling_convention = .C, + .alignment = @typeInfo(fn () callconv(.C) void).Fn.alignment, + .is_generic = false, + .is_var_args = false, + .return_type = Return, + .params = params, + }, + }), + .default_value = null, + .is_comptime = false, + .alignment = @typeInfo(*const fn () callconv(.C) void).Pointer.alignment, + }; + acc[4] = .{ + .name = "descriptor", + .type = *Descriptor, + .default_value = null, + .is_comptime = false, + .alignment = @alignOf(*Descriptor), + }; + std.debug.assert(!real_captures_info.is_tuple); + for (real_captures_info.fields, 0..) |capture, i| { + switch (capture.type) { + comptime_int => @compileError("capture should not be a comptime_int! try using @as"), + comptime_float => @compileError("capture should not be a comptime_float! try using @as"), + else => {}, + } + acc[5 + i] = .{ + .name = capture.name, + .type = capture.type, + .default_value = null, + .is_comptime = false, + .alignment = capture.alignment, + }; + } + break :fields &acc; + }; + return @Type(.{ + .Struct = .{ + .layout = .Extern, + .fields = fields, + .decls = &.{}, + .is_tuple = false, + }, + }); +} + +/// creates a block (on the heap, using malloc) of type T, +// which should be the output of Block, +// assigns the given captures +// (which should be a struct literal with correct names) +// and assigns the given function +// (which should have the correct signature and C calling convention) +// to the block. +// Objective-C will free block pointers itself, +// otherwise you can call free on it yourself. +pub fn initBlock(comptime T: type, captures: anytype, blockFn: anytype) *T { + const allocator = std.heap.raw_c_allocator;
Just want to confirm: I don't see a reason this has to be hardcoded to the c allocator, is there? Is there any reason we can't take an `Allocator` param?
libxev
github_2023
others
147
mitchellh
unexge
@@ -1,10 +1,29 @@ const std = @import("std"); +const builtin = @import("builtin"); const assert = std.debug.assert; const linux = std.os.linux; const posix = std.posix; const queue = @import("../queue.zig"); const xev = @import("../main.zig").IO_Uring; +/// True if this backend is available on this platform. +pub fn available() bool { + if (comptime builtin.os.tag != .linux) return true;
Shouldn't this return false? Though probably doesn't matter as `Backend.candidates()` only returns this on Linux
libxev
github_2023
others
119
mitchellh
mitchellh
@@ -744,6 +744,7 @@ pub const Completion = struct { @intCast(res) else switch (@as(posix.E, @enumFromInt(-res))) { .CANCELED => error.Canceled, + .INTR => error.SignalInterrupt,
Hm. I'm thinking there's no downside to rearming here and we should do that. Any thoughts?
libxev
github_2023
others
95
mitchellh
fallenwood
@@ -208,7 +208,7 @@ And in your `build.zig`: ```zig const xev = b.dependency("libxev", .{ .target = target, .optimize = optimize }); -exe.addModule("xev", xev.module("xev")); +exe.root_module.addImport("xev", libxev_dep.module("xev"));
it should be `exe.root_module.addImport("xev", xev.module("xev"));`, right? the variable `libxev_dep` is not defined
libxev
github_2023
others
16
mitchellh
mitchellh
@@ -75,6 +76,7 @@ fn asyncCallback( } fn threadMain(loop: *xev.Loop) !void { - while (state == .running) try notifier.notify(loop); + while (state == .running) try notifier.notify(); state = .stopped; + _ = loop; }
We can just not pass the loop into the thread anymore.
3d-ascii-viewer
github_2023
c
13
autopawn
autopawn
@@ -454,3 +454,127 @@ struct model *model_load_from_obj(const char *fname, bool color_support) model_validate_idxs(model); return model; } + +struct model *model_load_from_stl(const char *fname) +{ + FILE *fp = fopen(fname, "rb"); + if (!fp) + { + fprintf(stderr, "ERROR: failed to load file \"%s\".\n", fname); + return NULL; + } + + // Create a new model + struct model *model = model_init(); + + // Read each line of the file + char buffer[256]; + + int current_material = -1; + + // Check this is an ASCII STL file + // As the header of a binary STL could start with solid + // we must also check the second line starts with facet + bool isASCII = false; + + // Check first line starts with "solid" + fgets(buffer, sizeof(buffer), fp); + + char *bufferp = buffer; + char *instr = str_chop_skip_empty(&bufferp, " "); + + if (strcmp(instr, "solid") == 0) + { + // Check second line starts with "facet" + fgets(buffer, sizeof(buffer), fp); + + char *bufferp = buffer; + char *instr = str_chop_skip_empty(&bufferp, " "); + + if (strcmp(instr, "facet") == 0) + { + isASCII = true; + } + } + + if (isASCII) + { + while (fgets(buffer, sizeof(buffer), fp)) + { + string_strip(buffer); + + char *bufferp = buffer; + char *instr = str_chop_skip_empty(&bufferp, " "); + + // As we ignore normals only vertex definitions are required + if (strcmp(instr, "vertex") == 0) + { + float f1, f2, f3; + + if (!parse_float(&bufferp, &f1) || !parse_float(&bufferp, &f2) || !parse_float(&bufferp, &f3)) + { + fprintf(stderr, "ERROR: invalid \"vertex\" instruction.\n"); + fclose(fp); + model_free(model); + return NULL; + } + + vec3 vec; + vec.x = f1; + vec.y = f2; + vec.z = f3; + + model_add_vertex(model, vec); + } + } + } + else + { + // ASCII check will have moved the read pointer beyond the first block of data, + // reset to byte 80, after the 80 byte header + fseek(fp, 80, SEEK_SET); + + int facetCountExpected; + int facetCountActual = 0; + + char facetCount[4]; + fread(facetCount, sizeof(int), 1, fp); + memcpy(&facetCountExpected, facetCount, sizeof facetCountExpected);
If I am not mistaken, this assumes that the processor is little-endian, which I think is pretty reasonable these days. Still, it would be good to add a comment: ``` // NOTE: Assuming little-endian hardware. ```
3d-ascii-viewer
github_2023
c
13
autopawn
autopawn
@@ -454,3 +454,127 @@ struct model *model_load_from_obj(const char *fname, bool color_support) model_validate_idxs(model); return model; } + +struct model *model_load_from_stl(const char *fname) +{ + FILE *fp = fopen(fname, "rb"); + if (!fp) + { + fprintf(stderr, "ERROR: failed to load file \"%s\".\n", fname); + return NULL; + } + + // Create a new model + struct model *model = model_init(); + + // Read each line of the file + char buffer[256]; + + int current_material = -1; + + // Check this is an ASCII STL file + // As the header of a binary STL could start with solid + // we must also check the second line starts with facet + bool isASCII = false; + + // Check first line starts with "solid" + fgets(buffer, sizeof(buffer), fp); + + char *bufferp = buffer; + char *instr = str_chop_skip_empty(&bufferp, " "); + + if (strcmp(instr, "solid") == 0) + { + // Check second line starts with "facet" + fgets(buffer, sizeof(buffer), fp); + + char *bufferp = buffer; + char *instr = str_chop_skip_empty(&bufferp, " "); + + if (strcmp(instr, "facet") == 0) + { + isASCII = true; + } + } + + if (isASCII) + { + while (fgets(buffer, sizeof(buffer), fp)) + { + string_strip(buffer); + + char *bufferp = buffer; + char *instr = str_chop_skip_empty(&bufferp, " "); + + // As we ignore normals only vertex definitions are required + if (strcmp(instr, "vertex") == 0) + { + float f1, f2, f3; + + if (!parse_float(&bufferp, &f1) || !parse_float(&bufferp, &f2) || !parse_float(&bufferp, &f3)) + { + fprintf(stderr, "ERROR: invalid \"vertex\" instruction.\n"); + fclose(fp); + model_free(model); + return NULL; + } + + vec3 vec; + vec.x = f1; + vec.y = f2; + vec.z = f3; + + model_add_vertex(model, vec); + } + } + } + else + { + // ASCII check will have moved the read pointer beyond the first block of data, + // reset to byte 80, after the 80 byte header + fseek(fp, 80, SEEK_SET); + + int facetCountExpected; + int facetCountActual = 0; + + char facetCount[4]; + fread(facetCount, sizeof(int), 1, fp); + memcpy(&facetCountExpected, facetCount, sizeof facetCountExpected); + + // Read facet definitions, 50 bytes each, facet normal, 3 vertices, and a 2 byte spacer + char buffer[50]; + while(fread(buffer, sizeof(char), 50, fp))
Should we make sure that this call to `fread` returns 50?
3d-ascii-viewer
github_2023
c
13
autopawn
autopawn
@@ -495,9 +502,28 @@ int main(int argc, char *argv[]) struct model *model; - if (!(model = model_load_from_obj(args.input_file, args.color_support))) - return 1; - model_invert_z(model); // Required by the OBJ format. + const char *fileExt = get_file_extension(args.input_file); + if (fileExt == NULL) + { + fprintf(stderr, "ERROR: Input file has no extension.\n"); + exit(1); + } + else if (strcmp(fileExt, "obj") == 0) + { + if (!(model = model_load_from_obj(args.input_file, args.color_support))) + return 1; + model_invert_z(model); // Required by the OBJ format. + } + else if (strcmp(fileExt, "stl") == 0) + { + if (!(model = model_load_from_stl(args.input_file))) + return 1;
In case `args.color_support` is true, it may be good to print a warning indicating that stl doesn't have material data.
3d-ascii-viewer
github_2023
c
13
autopawn
autopawn
@@ -570,7 +570,7 @@ struct model *model_load_from_stl(const char *fname) // For every 3 vertices create a face for (int i = 0; i < model->vertex_count; i += 3) { - model_add_face(model, i, i+1, i+2, current_material); + model_add_face(model, i, i+2, i+1, current_material);
I would squash this patch with the previous one, since this flipping of the face directions is required exactly when the axes are swapped.
Awesome-Dev-Portfolios
github_2023
others
199
Kiran1689
Kiran1689
@@ -1,7 +1,7 @@ { "username": "jasmeetsinghbhatia", "name": "Jasmeet Singh", - "image": "https://github.com/Kiran1689/Awesome-Dev-Portfolios/assets/5153163/f2b5a30a-60ff-4523-a951-aa8e3c6d0b96", + "image": "https://github.com/Kiran1689/Awesome-Dev-Portfolios/assets/75929997/a28debcf-df61-4498-aef8-63486f36d649"
Please add , at the end
Awesome-Dev-Portfolios
github_2023
others
135
Kiran1689
Kiran1689
@@ -0,0 +1,12 @@ +{ + "username": "Matt-code-d", + "name": "Matteo Santoro D", + "image": "https://i.imgur.com/r0KKbj3.png", + "technologiesUsed": "HTML · CSS · JavaScript · WebGL · Construct3",
This won't work. Add comma separated values for **technologiesUsed** Make sure that your portfolio image is **1900x900**.
Awesome-Dev-Portfolios
github_2023
others
122
Kiran1689
Kiran1689
@@ -0,0 +1,10 @@ +{ + "username": "LuisJimenez19", + "name": "Luis Ángel Jimenez", + "image": "https://github.com/Kiran1689/Awesome-Dev-Portfolios/assets/102745510/5e94fd47-c62f-42c1-8fa3-91072d5a1437",
Resize your image, the image resolution should be **1900 x 900 (Width x Height)**
Awesome-Dev-Portfolios
github_2023
others
20
Kiran1689
Kiran1689
@@ -0,0 +1,10 @@ +{ + "username": "Nailheart", + "name": "Yaroslav Lebedenko", + "image": "https://private-user-images.githubusercontent.com/48065097/292616139-4bf4225f-8472-4d90-be7d-0c5738940371.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTEiLCJleHAiOjE3MDMzMTkwOTgsIm5iZiI6MTcwMzMxODc5OCwicGF0aCI6Ii80ODA2NTA5Ny8yOTI2MTYxMzktNGJmNDIyNWYtODQ3Mi00ZDkwLWJlN2QtMGM1NzM4OTQwMzcxLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFJV05KWUFYNENTVkVINTNBJTJGMjAyMzEyMjMlMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjMxMjIzVDA4MDYzOFomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPWNlM2FmNWVlYzcwMzNjYTFiOWEwNDUxZmE5ZmU4NmM1MzkyY2MzMzg5MzJhZTdkYzA3MzdkMTk2OTkyZjJmZjEmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0JmFjdG9yX2lkPTAma2V5X2lkPTAmcmVwb19pZD0wIn0.HHS8ZK8aaYXeyMwsOu0rXcU9gbrfz583F7CpvYj7En8",
Hi @Nailheart Please change the image URL to : https://user-images.githubusercontent.com/48065097/292616139-4bf4225f-8472-4d90-be7d-0c5738940371.png
Awesome-Dev-Portfolios
github_2023
others
13
Kiran1689
Kiran1689
@@ -0,0 +1,10 @@ +{ + "username": "mrepol742", + "name": "Melvin Jones Repol", + "image": "https://github-production-user-asset-6210df.s3.amazonaws.com/62317165/292488473-10556d1c-e8e5-4884-af75-781e7df4498e.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20231222%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20231222T123824Z&X-Amz-Expires=300&X-Amz-Signature=62d3bfac127ce858d430087d63da9e5ed7471c08df1d083f1178d5dd3a81e3fb&X-Amz-SignedHeaders=host&actor_id=62317165&key_id=0&repo_id=731031630",
Remove the credentials from the image URL. Make it as: "image": "https://github-production-user-asset-6210df.s3.amazonaws.com/62317165/292488473-10556d1c-e8e5-4884-af75-781e7df4498e.png"
Awesome-Dev-Portfolios
github_2023
others
9
Kiran1689
Kiran1689
@@ -0,0 +1,10 @@ +{ + "username": "vishwasnavadak", + "name": "Vishwasa Navada K", + "image": "https://github-production-user-asset-6210df.s3.amazonaws.com/13111030/291629578-a8d255a5-d5f9-4efd-afc4-f3db1402dabc.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20231219%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20231219T152228Z&X-Amz-Expires=300&X-Amz-Signature=a6b7281aee582069c6fcb23465472274f070f8d7e932966005558b73dd33881f&X-Amz-SignedHeaders=host&actor_id=13111030&key_id=0&repo_id=731031630",
This image URL will not work. Please change the image URL as per contribution guidelines. Refer here: https://github.com/Kiran1689/Awesome-Dev-Portfolios/blob/main/CONTRIBUTING.md
Awesome-Dev-Portfolios
github_2023
others
9
Kiran1689
Kiran1689
@@ -0,0 +1,10 @@ +{ + "username": "vishwasnavadak", + "name": "Vishwasa Navada K", + "image": "https://github-production-user-asset-6210df.s3.amazonaws.com/13111030/291629578-a8d255a5-d5f9-4efd-afc4-f3db1402dabc.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20231219%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20231219T152228Z&X-Amz-Expires=300&X-Amz-Signature=a6b7281aee582069c6fcb23465472274f070f8d7e932966005558b73dd33881f&X-Amz-SignedHeaders=host&actor_id=13111030&key_id=0&repo_id=731031630", + "technologiesUsed": "AWS, Serverless, NodeJS, JavaScript", + "livePortfolioLink": "https://vishwas.tech", + "githubRepoLink": "",
Please add "-" "githubRepoLink": " - "
Attend-and-Excite
github_2023
python
11
yuval-alaluf
patrickvonplaten
@@ -1,224 +0,0 @@ -import inspect
Let's please not delete this pipeline ;-)
Attend-and-Excite
github_2023
python
11
yuval-alaluf
patrickvonplaten
@@ -1,262 +1,584 @@ -from typing import List, Optional, Union, Tuple -
Could you move this pipeline into the following folder: https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines/stable_diffusion
Attend-and-Excite
github_2023
python
11
yuval-alaluf
AttendAndExcite
@@ -0,0 +1,108 @@ +import os
I am not sure we need to push this file, correct?
Attend-and-Excite
github_2023
others
11
yuval-alaluf
AttendAndExcite
@@ -0,0 +1,166 @@ +name: sd
I am not sure the changes to the environment are needed. If I am not mistaken, the code should work with the original `environment.yaml` file and if the code is compatible with `diffusers 0.12.1`, then the only change that should be needed is in the `requirements.txt` with updating the diffusers version. We should also add `accelerate`.
Attend-and-Excite
github_2023
python
11
yuval-alaluf
AttendAndExcite
@@ -1,262 +1,584 @@ -from typing import List, Optional, Union, Tuple - -import numpy as np -import torch -from diffusers.schedulers import LMSDiscreteScheduler -from torch.nn import functional as F - -from pipeline_stable_diffusion import StableDiffusionPipeline -from utils.gaussian_smoothing import GaussianSmoothing -from utils.ptp_utils import AttentionStore, aggregate_attention - - -class AttendAndExcitePipeline(StableDiffusionPipeline): - - @staticmethod - def _compute_max_attention_per_index(attention_maps: torch.Tensor, - indices_to_alter: List[int], - smooth_attentions: bool = False, - sigma: float = 0.5, - kernel_size: int = 3) -> List[torch.Tensor]: - """ Computes the maximum attention value for each of the tokens we wish to alter. """ - attention_for_text = attention_maps[:, :, 1:-1] - attention_for_text *= 100 - attention_for_text = torch.nn.functional.softmax(attention_for_text, dim=-1) - - # Shift indices since we removed the first token - indices_to_alter = [index - 1 for index in indices_to_alter] - - # Extract the maximum values - max_indices_list = [] - for i in indices_to_alter: - image = attention_for_text[:, :, i] - if smooth_attentions: - smoothing = GaussianSmoothing(channels=1, kernel_size=kernel_size, sigma=sigma, dim=2).cuda() - input = F.pad(image.unsqueeze(0).unsqueeze(0), (1, 1, 1, 1), mode='reflect') - image = smoothing(input).squeeze(0).squeeze(0) - max_indices_list.append(image.max()) - return max_indices_list - - def _aggregate_and_get_max_attention_per_token(self, attention_store: AttentionStore, - indices_to_alter: List[int], - attention_res: int = 16, - smooth_attentions: bool = False, - sigma: float = 0.5, - kernel_size: int = 3): - """ Aggregates the attention for each token and computes the max activation value for each token to alter. """ - attention_maps = aggregate_attention( - attention_store=attention_store, - res=attention_res, - from_where=("up", "down", "mid"), - is_cross=True, - select=0) - max_attention_per_index = self._compute_max_attention_per_index( - attention_maps=attention_maps, - indices_to_alter=indices_to_alter, - smooth_attentions=smooth_attentions, - sigma=sigma, - kernel_size=kernel_size) - return max_attention_per_index - - @staticmethod - def _compute_loss(max_attention_per_index: List[torch.Tensor], return_losses: bool = False) -> torch.Tensor: - """ Computes the attend-and-excite loss using the maximum attention value for each token. """ - losses = [max(0, 1. - curr_max) for curr_max in max_attention_per_index] - loss = max(losses) - if return_losses: - return loss, losses - else: - return loss - - @staticmethod - def _update_latent(latents: torch.Tensor, loss: torch.Tensor, step_size: float) -> torch.Tensor: - """ Update the latent according to the computed loss. """ - grad_cond = torch.autograd.grad(loss.requires_grad_(True), [latents], retain_graph=True)[0] - latents = latents - step_size * grad_cond - return latents - - def _perform_iterative_refinement_step(self, - latents: torch.Tensor, - indices_to_alter: List[int], - loss: torch.Tensor, - threshold: float, - text_embeddings: torch.Tensor, - text_input, - attention_store: AttentionStore, - step_size: float, - t: int, - attention_res: int = 16, - smooth_attentions: bool = True, - sigma: float = 0.5, - kernel_size: int = 3, - max_refinement_steps: int = 20): - """ - Performs the iterative latent refinement introduced in the paper. Here, we continuously update the latent - code according to our loss objective until the given threshold is reached for all tokens. - """ - iteration = 0 - target_loss = max(0, 1. - threshold) - while loss > target_loss: - iteration += 1 - - latents = latents.clone().detach().requires_grad_(True) - noise_pred_text = self.unet(latents, t, encoder_hidden_states=text_embeddings[1].unsqueeze(0)).sample - self.unet.zero_grad() - - # Get max activation value for each subject token - max_attention_per_index = self._aggregate_and_get_max_attention_per_token( - attention_store=attention_store, - indices_to_alter=indices_to_alter, - attention_res=attention_res, - smooth_attentions=smooth_attentions, - sigma=sigma, - kernel_size=kernel_size) - - loss, losses = self._compute_loss(max_attention_per_index, return_losses=True) - - if loss != 0: - latents = self._update_latent(latents, loss, step_size) - - with torch.no_grad(): - noise_pred_uncond = self.unet(latents, t, encoder_hidden_states=text_embeddings[0].unsqueeze(0)).sample - noise_pred_text = self.unet(latents, t, encoder_hidden_states=text_embeddings[1].unsqueeze(0)).sample - - try: - low_token = np.argmax([l.item() if type(l) != int else l for l in losses]) - except Exception as e: - print(e) # catch edge case :) - low_token = np.argmax(losses) - - low_word = self.tokenizer.decode(text_input.input_ids[0][indices_to_alter[low_token]]) - print(f'\t Try {iteration}. {low_word} has a max attention of {max_attention_per_index[low_token]}') - - if iteration >= max_refinement_steps: - print(f'\t Exceeded max number of iterations ({max_refinement_steps})! ' - f'Finished with a max attention of {max_attention_per_index[low_token]}') - break - - # Run one more time but don't compute gradients and update the latents. - # We just need to compute the new loss - the grad update will occur below - latents = latents.clone().detach().requires_grad_(True) - noise_pred_text = self.unet(latents, t, encoder_hidden_states=text_embeddings[1].unsqueeze(0)).sample - self.unet.zero_grad() - - # Get max activation value for each subject token - max_attention_per_index = self._aggregate_and_get_max_attention_per_token( - attention_store=attention_store, - indices_to_alter=indices_to_alter, - attention_res=attention_res, - smooth_attentions=smooth_attentions, - sigma=sigma, - kernel_size=kernel_size) - loss, losses = self._compute_loss(max_attention_per_index, return_losses=True) - print(f"\t Finished with loss of: {loss}") - return loss, latents, max_attention_per_index - - @torch.no_grad() - def __call__( - self, - prompt: Union[str, List[str]], - attention_store: AttentionStore, - indices_to_alter: List[int], - attention_res: int = 16, - height: Optional[int] = 512, - width: Optional[int] = 512, - num_inference_steps: Optional[int] = 50, - guidance_scale: Optional[float] = 7.5, - eta: Optional[float] = 0.0, - generator: Optional[torch.Generator] = None, - latents: Optional[torch.FloatTensor] = None, - output_type: Optional[str] = "pil", - return_dict: bool = True, - max_iter_to_alter: Optional[int] = 25, - run_standard_sd: bool = False, - thresholds: Optional[dict] = {0: 0.05, 10: 0.5, 20: 0.8}, - scale_factor: int = 20, - scale_range: Tuple[float, float] = (1., 0.5), - smooth_attentions: bool = True, - sigma: float = 0.5, - kernel_size: int = 3, - **kwargs): - - text_embeddings, text_input, latents, do_classifier_free_guidance, extra_step_kwargs = self._setup_inference( - prompt=prompt, - height=height, - width=width, - num_inference_steps=num_inference_steps, - guidance_scale=guidance_scale, - eta=eta, - generator=generator, - latents=latents, **kwargs - ) - - scale_range = np.linspace(scale_range[0], scale_range[1], len(self.scheduler.timesteps)) - - if max_iter_to_alter is None: - max_iter_to_alter = len(self.scheduler.timesteps) + 1 - - for i, t in enumerate(self.progress_bar(self.scheduler.timesteps)): - - with torch.enable_grad(): - - latents = latents.clone().detach().requires_grad_(True) - - # Forward pass of denoising with text conditioning - noise_pred_text = self.unet(latents, t, encoder_hidden_states=text_embeddings[1].unsqueeze(0)).sample - self.unet.zero_grad() - - # Get max activation value for each subject token - max_attention_per_index = self._aggregate_and_get_max_attention_per_token( - attention_store=attention_store, - indices_to_alter=indices_to_alter, - attention_res=attention_res, - smooth_attentions=smooth_attentions, - sigma=sigma, - kernel_size=kernel_size) - - if not run_standard_sd: - - loss = self._compute_loss(max_attention_per_index=max_attention_per_index) - - # If this is an iterative refinement step, verify we have reached the desired threshold for all - if i in thresholds.keys() and loss > 1. - thresholds[i]: - del noise_pred_text - torch.cuda.empty_cache() - loss, latents, max_attention_per_index = self._perform_iterative_refinement_step( - latents=latents, - indices_to_alter=indices_to_alter, - loss=loss, - threshold=thresholds[i], - text_embeddings=text_embeddings, - text_input=text_input, - attention_store=attention_store, - step_size=scale_factor * np.sqrt(scale_range[i]), - t=t, - attention_res=attention_res, - smooth_attentions=smooth_attentions, - sigma=sigma, - kernel_size=kernel_size) - - # Perform gradient update - if i < max_iter_to_alter: - loss = self._compute_loss(max_attention_per_index=max_attention_per_index) - if loss != 0: - latents = self._update_latent(latents=latents, loss=loss, - step_size=scale_factor * np.sqrt(scale_range[i])) - print(f'Iteration {i} | Loss: {loss:0.4f}') - - noise_pred_uncond = self.unet(latents, t, encoder_hidden_states=text_embeddings[0].unsqueeze(0)).sample - noise_pred_text = self.unet(latents, t, encoder_hidden_states=text_embeddings[1].unsqueeze(0)).sample - - # Perform guidance - if do_classifier_free_guidance: - noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) - - # Compute the previous noisy sample x_t -> x_t-1 - if isinstance(self.scheduler, LMSDiscreteScheduler): - latents = self.scheduler.step(noise_pred, i, latents, **extra_step_kwargs).prev_sample - else: - latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample - - outputs = self._prepare_output(latents, output_type, return_dict) - return outputs + +import inspect +from typing import Any, Callable, Dict, List, Optional, Union, Tuple + +import numpy as np +import torch +from torch.nn import functional as F + +from packaging import version +from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer + +from diffusers.configuration_utils import FrozenDict +from diffusers.models import AutoencoderKL, UNet2DConditionModel +from diffusers.schedulers import KarrasDiffusionSchedulers +from diffusers.utils import deprecate, is_accelerate_available, logging, randn_tensor, replace_example_docstring +from diffusers.pipelines.pipeline_utils import DiffusionPipeline +from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput +from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker + +#from pipeline_sd import StableDiffusionPipeline
Can remove the commented out code :)
Attend-and-Excite
github_2023
python
11
yuval-alaluf
AttendAndExcite
@@ -1,262 +1,584 @@ -from typing import List, Optional, Union, Tuple - -import numpy as np -import torch -from diffusers.schedulers import LMSDiscreteScheduler -from torch.nn import functional as F - -from pipeline_stable_diffusion import StableDiffusionPipeline -from utils.gaussian_smoothing import GaussianSmoothing -from utils.ptp_utils import AttentionStore, aggregate_attention - - -class AttendAndExcitePipeline(StableDiffusionPipeline): - - @staticmethod - def _compute_max_attention_per_index(attention_maps: torch.Tensor, - indices_to_alter: List[int], - smooth_attentions: bool = False, - sigma: float = 0.5, - kernel_size: int = 3) -> List[torch.Tensor]: - """ Computes the maximum attention value for each of the tokens we wish to alter. """ - attention_for_text = attention_maps[:, :, 1:-1] - attention_for_text *= 100 - attention_for_text = torch.nn.functional.softmax(attention_for_text, dim=-1) - - # Shift indices since we removed the first token - indices_to_alter = [index - 1 for index in indices_to_alter] - - # Extract the maximum values - max_indices_list = [] - for i in indices_to_alter: - image = attention_for_text[:, :, i] - if smooth_attentions: - smoothing = GaussianSmoothing(channels=1, kernel_size=kernel_size, sigma=sigma, dim=2).cuda() - input = F.pad(image.unsqueeze(0).unsqueeze(0), (1, 1, 1, 1), mode='reflect') - image = smoothing(input).squeeze(0).squeeze(0) - max_indices_list.append(image.max()) - return max_indices_list - - def _aggregate_and_get_max_attention_per_token(self, attention_store: AttentionStore, - indices_to_alter: List[int], - attention_res: int = 16, - smooth_attentions: bool = False, - sigma: float = 0.5, - kernel_size: int = 3): - """ Aggregates the attention for each token and computes the max activation value for each token to alter. """ - attention_maps = aggregate_attention( - attention_store=attention_store, - res=attention_res, - from_where=("up", "down", "mid"), - is_cross=True, - select=0) - max_attention_per_index = self._compute_max_attention_per_index( - attention_maps=attention_maps, - indices_to_alter=indices_to_alter, - smooth_attentions=smooth_attentions, - sigma=sigma, - kernel_size=kernel_size) - return max_attention_per_index - - @staticmethod - def _compute_loss(max_attention_per_index: List[torch.Tensor], return_losses: bool = False) -> torch.Tensor: - """ Computes the attend-and-excite loss using the maximum attention value for each token. """ - losses = [max(0, 1. - curr_max) for curr_max in max_attention_per_index] - loss = max(losses) - if return_losses: - return loss, losses - else: - return loss - - @staticmethod - def _update_latent(latents: torch.Tensor, loss: torch.Tensor, step_size: float) -> torch.Tensor: - """ Update the latent according to the computed loss. """ - grad_cond = torch.autograd.grad(loss.requires_grad_(True), [latents], retain_graph=True)[0] - latents = latents - step_size * grad_cond - return latents - - def _perform_iterative_refinement_step(self, - latents: torch.Tensor, - indices_to_alter: List[int], - loss: torch.Tensor, - threshold: float, - text_embeddings: torch.Tensor, - text_input, - attention_store: AttentionStore, - step_size: float, - t: int, - attention_res: int = 16, - smooth_attentions: bool = True, - sigma: float = 0.5, - kernel_size: int = 3, - max_refinement_steps: int = 20): - """ - Performs the iterative latent refinement introduced in the paper. Here, we continuously update the latent - code according to our loss objective until the given threshold is reached for all tokens. - """ - iteration = 0 - target_loss = max(0, 1. - threshold) - while loss > target_loss: - iteration += 1 - - latents = latents.clone().detach().requires_grad_(True) - noise_pred_text = self.unet(latents, t, encoder_hidden_states=text_embeddings[1].unsqueeze(0)).sample - self.unet.zero_grad() - - # Get max activation value for each subject token - max_attention_per_index = self._aggregate_and_get_max_attention_per_token( - attention_store=attention_store, - indices_to_alter=indices_to_alter, - attention_res=attention_res, - smooth_attentions=smooth_attentions, - sigma=sigma, - kernel_size=kernel_size) - - loss, losses = self._compute_loss(max_attention_per_index, return_losses=True) - - if loss != 0: - latents = self._update_latent(latents, loss, step_size) - - with torch.no_grad(): - noise_pred_uncond = self.unet(latents, t, encoder_hidden_states=text_embeddings[0].unsqueeze(0)).sample - noise_pred_text = self.unet(latents, t, encoder_hidden_states=text_embeddings[1].unsqueeze(0)).sample - - try: - low_token = np.argmax([l.item() if type(l) != int else l for l in losses]) - except Exception as e: - print(e) # catch edge case :) - low_token = np.argmax(losses) - - low_word = self.tokenizer.decode(text_input.input_ids[0][indices_to_alter[low_token]]) - print(f'\t Try {iteration}. {low_word} has a max attention of {max_attention_per_index[low_token]}') - - if iteration >= max_refinement_steps: - print(f'\t Exceeded max number of iterations ({max_refinement_steps})! ' - f'Finished with a max attention of {max_attention_per_index[low_token]}') - break - - # Run one more time but don't compute gradients and update the latents. - # We just need to compute the new loss - the grad update will occur below - latents = latents.clone().detach().requires_grad_(True) - noise_pred_text = self.unet(latents, t, encoder_hidden_states=text_embeddings[1].unsqueeze(0)).sample - self.unet.zero_grad() - - # Get max activation value for each subject token - max_attention_per_index = self._aggregate_and_get_max_attention_per_token( - attention_store=attention_store, - indices_to_alter=indices_to_alter, - attention_res=attention_res, - smooth_attentions=smooth_attentions, - sigma=sigma, - kernel_size=kernel_size) - loss, losses = self._compute_loss(max_attention_per_index, return_losses=True) - print(f"\t Finished with loss of: {loss}") - return loss, latents, max_attention_per_index - - @torch.no_grad() - def __call__( - self, - prompt: Union[str, List[str]], - attention_store: AttentionStore, - indices_to_alter: List[int], - attention_res: int = 16, - height: Optional[int] = 512, - width: Optional[int] = 512, - num_inference_steps: Optional[int] = 50, - guidance_scale: Optional[float] = 7.5, - eta: Optional[float] = 0.0, - generator: Optional[torch.Generator] = None, - latents: Optional[torch.FloatTensor] = None, - output_type: Optional[str] = "pil", - return_dict: bool = True, - max_iter_to_alter: Optional[int] = 25, - run_standard_sd: bool = False, - thresholds: Optional[dict] = {0: 0.05, 10: 0.5, 20: 0.8}, - scale_factor: int = 20, - scale_range: Tuple[float, float] = (1., 0.5), - smooth_attentions: bool = True, - sigma: float = 0.5, - kernel_size: int = 3, - **kwargs): - - text_embeddings, text_input, latents, do_classifier_free_guidance, extra_step_kwargs = self._setup_inference( - prompt=prompt, - height=height, - width=width, - num_inference_steps=num_inference_steps, - guidance_scale=guidance_scale, - eta=eta, - generator=generator, - latents=latents, **kwargs - ) - - scale_range = np.linspace(scale_range[0], scale_range[1], len(self.scheduler.timesteps)) - - if max_iter_to_alter is None: - max_iter_to_alter = len(self.scheduler.timesteps) + 1 - - for i, t in enumerate(self.progress_bar(self.scheduler.timesteps)): - - with torch.enable_grad(): - - latents = latents.clone().detach().requires_grad_(True) - - # Forward pass of denoising with text conditioning - noise_pred_text = self.unet(latents, t, encoder_hidden_states=text_embeddings[1].unsqueeze(0)).sample - self.unet.zero_grad() - - # Get max activation value for each subject token - max_attention_per_index = self._aggregate_and_get_max_attention_per_token( - attention_store=attention_store, - indices_to_alter=indices_to_alter, - attention_res=attention_res, - smooth_attentions=smooth_attentions, - sigma=sigma, - kernel_size=kernel_size) - - if not run_standard_sd: - - loss = self._compute_loss(max_attention_per_index=max_attention_per_index) - - # If this is an iterative refinement step, verify we have reached the desired threshold for all - if i in thresholds.keys() and loss > 1. - thresholds[i]: - del noise_pred_text - torch.cuda.empty_cache() - loss, latents, max_attention_per_index = self._perform_iterative_refinement_step( - latents=latents, - indices_to_alter=indices_to_alter, - loss=loss, - threshold=thresholds[i], - text_embeddings=text_embeddings, - text_input=text_input, - attention_store=attention_store, - step_size=scale_factor * np.sqrt(scale_range[i]), - t=t, - attention_res=attention_res, - smooth_attentions=smooth_attentions, - sigma=sigma, - kernel_size=kernel_size) - - # Perform gradient update - if i < max_iter_to_alter: - loss = self._compute_loss(max_attention_per_index=max_attention_per_index) - if loss != 0: - latents = self._update_latent(latents=latents, loss=loss, - step_size=scale_factor * np.sqrt(scale_range[i])) - print(f'Iteration {i} | Loss: {loss:0.4f}') - - noise_pred_uncond = self.unet(latents, t, encoder_hidden_states=text_embeddings[0].unsqueeze(0)).sample - noise_pred_text = self.unet(latents, t, encoder_hidden_states=text_embeddings[1].unsqueeze(0)).sample - - # Perform guidance - if do_classifier_free_guidance: - noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) - - # Compute the previous noisy sample x_t -> x_t-1 - if isinstance(self.scheduler, LMSDiscreteScheduler): - latents = self.scheduler.step(noise_pred, i, latents, **extra_step_kwargs).prev_sample - else: - latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample - - outputs = self._prepare_output(latents, output_type, return_dict) - return outputs + +import inspect +from typing import Any, Callable, Dict, List, Optional, Union, Tuple + +import numpy as np +import torch +from torch.nn import functional as F + +from packaging import version +from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer + +from diffusers.configuration_utils import FrozenDict +from diffusers.models import AutoencoderKL, UNet2DConditionModel +from diffusers.schedulers import KarrasDiffusionSchedulers +from diffusers.utils import deprecate, is_accelerate_available, logging, randn_tensor, replace_example_docstring +from diffusers.pipelines.pipeline_utils import DiffusionPipeline +from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput +from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker + +#from pipeline_sd import StableDiffusionPipeline +from diffusers.pipelines.stable_diffusion import StableDiffusionPipeline + +from utils.gaussian_smoothing import GaussianSmoothing +from utils.ptp_utils import AttentionStore, aggregate_attention + +logger = logging.get_logger(__name__) + +class AttendAndExcitePipeline(StableDiffusionPipeline): + r""" + Pipeline for text-to-image generation using Stable Diffusion. + This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the + library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.) + Args: + vae ([`AutoencoderKL`]): + Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. + text_encoder ([`CLIPTextModel`]): + Frozen text-encoder. Stable Diffusion uses the text portion of + [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically + the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant. + tokenizer (`CLIPTokenizer`): + Tokenizer of class + [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer). + unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents. + scheduler ([`SchedulerMixin`]): + A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of + [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`]. + safety_checker ([`StableDiffusionSafetyChecker`]): + Classification module that estimates whether generated images could be considered offensive or harmful. + Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details. + feature_extractor ([`CLIPFeatureExtractor`]): + Model that extracts features from generated images to be used as inputs for the `safety_checker`. + """ + _optional_components = ["safety_checker", "feature_extractor"] + + def _encode_prompt( + self, + prompt, + device, + num_images_per_prompt, + do_classifier_free_guidance, + negative_prompt=None, + prompt_embeds: Optional[torch.FloatTensor] = None, + negative_prompt_embeds: Optional[torch.FloatTensor] = None, + ): + r""" + Encodes the prompt into text encoder hidden states. + Args: + prompt (`str` or `List[str]`, *optional*): + prompt to be encoded + device: (`torch.device`): + torch device + num_images_per_prompt (`int`): + number of images that should be generated per prompt + do_classifier_free_guidance (`bool`): + whether to use classifier free guidance or not + negative_ prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead. + Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). + prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + """ + if prompt is not None and isinstance(prompt, str): + batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + if prompt_embeds is None: + text_inputs = self.tokenizer( + prompt, + padding="max_length", + max_length=self.tokenizer.model_max_length, + truncation=True, + return_tensors="pt", + ) + text_input_ids = text_inputs.input_ids + untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids + + if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal( + text_input_ids, untruncated_ids + ): + removed_text = self.tokenizer.batch_decode( + untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] + ) + logger.warning( + "The following part of your input was truncated because CLIP can only handle sequences up to" + f" {self.tokenizer.model_max_length} tokens: {removed_text}" + ) + + if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: + attention_mask = text_inputs.attention_mask.to(device) + else: + attention_mask = None + + prompt_embeds = self.text_encoder( + text_input_ids.to(device), + attention_mask=attention_mask, + ) + prompt_embeds = prompt_embeds[0] + + prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device) + + bs_embed, seq_len, _ = prompt_embeds.shape + # duplicate text embeddings for each generation per prompt, using mps friendly method + prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) + prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1) + + # get unconditional embeddings for classifier free guidance + if do_classifier_free_guidance and negative_prompt_embeds is None: + uncond_tokens: List[str] + if negative_prompt is None: + uncond_tokens = [""] * batch_size + elif type(prompt) is not type(negative_prompt): + raise TypeError( + f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" + f" {type(prompt)}." + ) + elif isinstance(negative_prompt, str): + uncond_tokens = [negative_prompt] + elif batch_size != len(negative_prompt): + raise ValueError( + f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" + f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" + " the batch size of `prompt`." + ) + else: + uncond_tokens = negative_prompt + + max_length = prompt_embeds.shape[1] + uncond_input = self.tokenizer( + uncond_tokens, + padding="max_length", + max_length=max_length, + truncation=True, + return_tensors="pt", + ) + + if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: + attention_mask = uncond_input.attention_mask.to(device) + else: + attention_mask = None + + negative_prompt_embeds = self.text_encoder( + uncond_input.input_ids.to(device), + attention_mask=attention_mask, + ) + negative_prompt_embeds = negative_prompt_embeds[0] + + if do_classifier_free_guidance: + # duplicate unconditional embeddings for each generation per prompt, using mps friendly method + seq_len = negative_prompt_embeds.shape[1] + + negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device) + + negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1) + negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1) + + # For classifier free guidance, we need to do two forward passes. + # Here we concatenate the unconditional and text embeddings into a single batch + # to avoid doing two forward passes + prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds]) + + return text_inputs, prompt_embeds + + @staticmethod + def _compute_max_attention_per_index(attention_maps: torch.Tensor, + indices_to_alter: List[int], + smooth_attentions: bool = False, + sigma: float = 0.5, + kernel_size: int = 3) -> List[torch.Tensor]: + """ Computes the maximum attention value for each of the tokens we wish to alter. """ + attention_for_text = attention_maps[:, :, 1:-1] + attention_for_text *= 100 + attention_for_text = torch.nn.functional.softmax(attention_for_text, dim=-1) + + # Shift indices since we removed the first token + indices_to_alter = [index - 1 for index in indices_to_alter] + + # Extract the maximum values + max_indices_list = [] + for i in indices_to_alter: + image = attention_for_text[:, :, i] + if smooth_attentions: + smoothing = GaussianSmoothing(channels=1, kernel_size=kernel_size, sigma=sigma, dim=2).half().cuda()
I ran the code and got an exception here: ``` RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.cuda.HalfTensor) should be the same ``` This was done when running `run.py` as follows: ``` python run.py --prompt "a cat and a dog" --seeds [0] --token_indices [2,5] ``` Are there any other adjustments you made in order to get this to work? I see that you added `.half()` to the `smoothing` module, but the input should still be a `FloatTensor`, if I'm not mistaken.