Skip to content

Commit ecca78f

Browse files
refactor(profiling): make ErrnoBackup::new safe and document safety invariants
1 parent 9a4063c commit ecca78f

2 files changed

Lines changed: 9 additions & 6 deletions

File tree

profiling/src/io/got_macho.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -550,8 +550,9 @@ unsafe fn rebind_symbols_in_section(
550550
fn seg_name(seg: &libc::segment_command_64) -> &str {
551551
let bytes = &seg.segname;
552552
let len = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
553-
// SAFETY: segment names are always ASCII; cast from &[i8] to &[u8] is safe
554-
// because i8 and u8 have the same size and alignment.
553+
// SAFETY: `seg.segname` is a fixed 16-byte array that outlives the returned reference.
554+
// Casting from `*const c_char` (`*const i8`) to `*const u8` is safe because `i8` and `u8`
555+
// have identical size (1 byte) and alignment, and `len` is bounded by the array length.
555556
let bytes: &[u8] = unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const u8, len) };
556557
std::str::from_utf8(bytes).unwrap_or("")
557558
}

profiling/src/io/mod.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,15 @@ struct ErrnoBackup {
3131
impl ErrnoBackup {
3232
/// Snapshots the current `errno` value.
3333
#[inline]
34-
unsafe fn new() -> Self {
34+
fn new() -> Self {
35+
// SAFETY: libc::__errno_location() (Linux) / libc::__error() (macOS) returns a valid,
36+
// non-null pointer to the calling thread's errno lvalue, safe for reading.
3537
#[cfg(target_os = "linux")]
36-
let location = libc::__errno_location();
38+
let location = unsafe { libc::__errno_location() };
3739
#[cfg(target_os = "macos")]
38-
let location = libc::__error();
40+
let location = unsafe { libc::__error() };
3941
Self {
40-
errno: *location,
42+
errno: unsafe { *location },
4143
location,
4244
}
4345
}

0 commit comments

Comments
 (0)