use core::{
convert::TryInto,
ffi::{CStr, c_void},
mem::ManuallyDrop,
ptr::{self, NonNull},
time::Duration,
};
use std::{
io,
os::fd::{AsRawFd, FromRawFd, OwnedFd},
};
use super::super::retry_on_eintr;
pub(super) struct MemMapping {
start_addr: NonNull<c_void>,
only_for_pid: u32,
}
unsafe impl Send for MemMapping {}
impl super::HeaderMemoryHolder for MemMapping {
fn new() -> io::Result<Self> {
Self::new()
}
fn as_ptr(&self) -> Option<NonNull<super::MappingHeader>> {
if self.only_for_pid != std::process::id() {
None
} else {
Some(self.start_addr.cast())
}
}
fn make_discoverable(&mut self) {
let _ = self.set_name();
}
fn unpublish_and_release(self) -> io::Result<()> {
self.free()
}
}
pub(super) struct MonotonicClock;
impl super::MonotonicTime for MonotonicClock {
fn monotonic_time_ns() -> io::Result<u64> {
since_boottime_ns().ok_or_else(|| {
io::Error::other("failed to get current time for process context publication")
})
}
}
impl MemMapping {
fn new() -> io::Result<Self> {
let size = super::mapping_size();
let mapping = try_memfd(crate::otel_process_ctx::linux::MAPPING_NAME, libc::MFD_CLOEXEC | libc::MFD_NOEXEC_SEAL | libc::MFD_ALLOW_SEALING)
.or_else(|_| try_memfd(crate::otel_process_ctx::linux::MAPPING_NAME, libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING))
.and_then(|fd| {
retry_on_eintr(|| {
check_syscall_retval(
unsafe {
libc::ftruncate(fd.as_raw_fd(), super::mapping_size() as libc::off_t)
},
"ftruncate failed",
)
})?;
let start_addr = retry_on_eintr(|| {
check_mapping_addr(
unsafe {
libc::mmap(
ptr::null_mut(),
size,
libc::PROT_WRITE | libc::PROT_READ,
libc::MAP_PRIVATE,
fd.as_raw_fd(),
0,
)
},
"mmap failed",
)
})?;
Ok(MemMapping {
start_addr,
only_for_pid: std::process::id(),
})
})
.or_else(|_| {
let start_addr = retry_on_eintr(|| {
check_mapping_addr(
unsafe {
libc::mmap(
ptr::null_mut(),
size,
libc::PROT_WRITE | libc::PROT_READ,
libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
-1,
0,
)
},
"mmap failed: couldn't create a memfd or anonymous mmapped region for process context publication",
)
})?;
Ok::<_, io::Error>(MemMapping {
start_addr,
only_for_pid: std::process::id(),
})
})?;
retry_on_eintr(|| {
check_syscall_retval(
unsafe {
libc::madvise(
mapping.start_addr.as_ptr(),
super::mapping_size(),
libc::MADV_DONTFORK,
)
},
"madvise MADV_DONTFORK failed",
)
})?;
Ok(mapping)
}
fn set_name(&mut self) -> io::Result<()> {
retry_on_eintr(|| {
check_syscall_retval(
unsafe {
libc::prctl(
libc::PR_SET_VMA,
libc::PR_SET_VMA_ANON_NAME as libc::c_ulong,
TryInto::<libc::c_ulong>::try_into(self.start_addr.as_ptr() as usize)
.expect("start addr overflowed"),
TryInto::<libc::c_ulong>::try_into(super::mapping_size())
.expect("mapping size overflowed"),
crate::otel_process_ctx::linux::MAPPING_NAME.as_ptr(),
)
},
"prctl PR_SET_VMA_ANON_NAME failed",
)
})?;
Ok(())
}
fn free(mut self) -> io::Result<()> {
unsafe {
self.unmap()?;
}
let _ = ManuallyDrop::new(self);
Ok(())
}
unsafe fn unmap(&mut self) -> io::Result<()> {
if self.only_for_pid != std::process::id() {
return Ok(());
}
retry_on_eintr(|| {
check_syscall_retval(
unsafe { libc::munmap(self.start_addr.as_ptr(), super::mapping_size()) },
"munmap failed when freeing the process context",
)
})?;
Ok(())
}
}
impl Drop for MemMapping {
fn drop(&mut self) {
let _ = unsafe { self.unmap() };
}
}
fn check_syscall_retval(ret: libc::c_int, msg: &'static str) -> io::Result<libc::c_int> {
if ret < 0 {
let e = io::Error::last_os_error();
Err(io::Error::new(e.kind(), format!("{msg}: {e}")))
} else {
Ok(ret)
}
}
fn check_mapping_addr(addr: *mut c_void, msg: &'static str) -> io::Result<NonNull<c_void>> {
if addr == libc::MAP_FAILED {
let e = io::Error::last_os_error();
Err(io::Error::new(e.kind(), format!("{msg}: {e}")))
} else {
Ok(unsafe { NonNull::new_unchecked(addr) })
}
}
fn try_memfd(name: &CStr, flags: libc::c_uint) -> io::Result<OwnedFd> {
check_syscall_retval(
unsafe {
libc::syscall(libc::SYS_memfd_create, name.as_ptr(), flags as libc::c_long)
as libc::c_int
},
"memfd_create failed",
)
.map(|fd| unsafe { OwnedFd::from_raw_fd(fd) })
}
fn since_boottime_ns() -> Option<u64> {
let mut ts = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
let ret = unsafe { libc::clock_gettime(libc::CLOCK_BOOTTIME, &mut ts) };
if ret != 0 {
return None;
}
let secs: u64 = ts.tv_sec.try_into().ok()?;
let nanos: u32 = ts.tv_nsec.try_into().ok()?;
let duration = Duration::new(secs, nanos);
u64::try_from(duration.as_nanos()).ok()
}