Skip to content

Commit 6f15b39

Browse files
committed
Add safety comments to unsafe blocks
This commit adds a safety comment to every unsafe block in the `unix.rs` file, explaining why I blieve the call is justified.
1 parent f8dc3ee commit 6f15b39

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

samply-markers/src/provider/unix.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,9 @@ impl TimestampNowProvider for TimestampNowImpl {
6767

6868
let nanos_per_tick = NANOS_PER_TICK.get_or_init(|| {
6969
let mut info = mach_time::mach_timebase_info::default();
70+
// SAFETY: mach_timebase_info is an FFI call on macOS. We pass a valid mutable reference
71+
// to a properly initialized mach_timebase_info struct.
72+
// See https://developer.apple.com/documentation/driverkit/3433733-mach_timebase_info
7073
let errno = unsafe { mach_time::mach_timebase_info(&raw mut info) };
7174
if errno != 0 || info.denom == 0 {
7275
info.numer = 1;
@@ -75,6 +78,9 @@ impl TimestampNowProvider for TimestampNowImpl {
7578
info
7679
});
7780

81+
// SAFETY: mach_absolute_time is an FFI call on macOS that returns the current
82+
// absolute time value in tick units.
83+
// See https://developer.apple.com/documentation/kernel/1462446-mach_absolute_time
7884
let time = unsafe { mach_time::mach_absolute_time() };
7985
let nanos = time * u64::from(nanos_per_tick.numer) / u64::from(nanos_per_tick.denom);
8086

@@ -138,6 +144,9 @@ fn get_thread_id() -> u32 {
138144
// See https://github.com/mstange/samply/blob/2041b956f650bb92d912990052967d03fef66b75/samply/src/mac/thread_profiler.rs#L209-L229
139145
let mut tid: u64 = 0;
140146

147+
// SAFETY: pthread_threadid_np is an FFI call. We pass pthread_self() provided by libc,
148+
// along with a valid mutable reference to our tid variable.
149+
// See https://docs.rs/libc/latest/x86_64-apple-darwin/libc/fn.pthread_threadid_np.html
141150
unsafe {
142151
libc::pthread_threadid_np(libc::pthread_self(), &raw mut tid);
143152
}
@@ -183,6 +192,12 @@ fn create_marker_file() -> Option<File> {
183192
// so it is not necessary to map it with any particular protection or
184193
// flags, so we use PROT_READ because that offers the fewest ways to
185194
// screw up.
195+
//
196+
// SAFETY: This call to mmap is safe because:
197+
// - We're mapping a valid file descriptor that we just opened
198+
// - The size (4096) is a valid, non-zero size
199+
// - The offset is 0 which is valid for any file
200+
// See https://docs.rs/nix/latest/nix/sys/mman/fn.mmap.html
186201
unsafe {
187202
nix::sys::mman::mmap(
188203
None,

0 commit comments

Comments
 (0)