Skip to content

Commit 4413384

Browse files
committed
common: Move string manipulation functions to common.rs
We can have `ascii_strip` use entirely safe code by `unwrap()`ing the result of `from_utf8` instead of using `from_utf8_unchecked`. We also add a helper function to convert a C-string pointer into a byte slice. Signed-off-by: Joe Richey <joerichey@google.com>
1 parent c87a9bc commit 4413384

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

src/common.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,24 @@ macro_rules! container_of_mut {
3333
}};
3434
}
3535

36+
// SAFETY: Requires that addr point to a static, null-terminated C-string.
37+
// The returned slice does not include the null-terminator.
38+
pub unsafe fn from_cstring(addr: u64) -> &'static [u8] {
39+
if addr == 0 {
40+
return &[];
41+
}
42+
let start = addr as *const u8;
43+
let mut size: usize = 0;
44+
while start.offset(size as _).read() != 0 {
45+
size += 1;
46+
}
47+
core::slice::from_raw_parts(start, size)
48+
}
49+
50+
pub fn ascii_strip(s: &[u8]) -> &str {
51+
core::str::from_utf8(s).unwrap().trim_matches(char::from(0))
52+
}
53+
3654
pub fn ucs2_as_ascii_length(input: *const u16) -> usize {
3755
let mut len = 0;
3856
loop {

src/loader.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
use crate::{
1616
bzimage,
17+
common::ascii_strip,
1718
fat::{self, Read},
1819
};
1920

@@ -104,10 +105,6 @@ fn parse_entry(f: &mut fat::File) -> Result<LoaderConfig, fat::Error> {
104105
Ok(loader_config)
105106
}
106107

107-
fn ascii_strip(s: &[u8]) -> &str {
108-
unsafe { core::str::from_utf8_unchecked(&s) }.trim_matches(char::from(0))
109-
}
110-
111108
const ENTRY_DIRECTORY: &str = "/loader/entries/";
112109

113110
fn default_entry_path(fs: &fat::Filesystem) -> Result<[u8; 260], fat::Error> {

0 commit comments

Comments
 (0)