Skip to content

Commit

Permalink
default FDs to CLOEXEC
Browse files Browse the repository at this point in the history
Note: this is a behavior change.

Currently, this crate opens FDs without CLOEXEC, which means they
persist across exec. This is not the convention throughout the Rust
ecosystem, which is to do the opposite:

rust-lang/rust#24237

This patch setting CLOEXEC :)

Note that doing that after-the-fact on the resulting FD isn't quite good
enough: if your process is forking a lot, that's racy.
  • Loading branch information
krallin committed Mar 10, 2023
1 parent c866cc5 commit f15d5fa
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion perf-event/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ pub struct Builder<'a> {
who: EventPid<'a>,
cpu: Option<usize>,
group: Option<&'a mut Group>,
cloexec: bool,
}

#[derive(Debug)]
Expand Down Expand Up @@ -470,6 +471,7 @@ impl<'a> Default for Builder<'a> {
who: EventPid::ThisProcess,
cpu: None,
group: None,
cloexec: true,
}
}
}
Expand Down Expand Up @@ -618,6 +620,12 @@ impl<'a> Builder<'a> {
self
}

/// By default, perf event FDs are open with PERF_FLAG_FD_CLOEXEC, so the FD you get back has
/// CLOEXEC set. Call this to not do so.
pub fn unset_cloexec(mut self) {
self.cloexec = false;
}

/// Place the counter in the given [`Group`]. Groups allow a set of counters
/// to be enabled, disabled, or read as a single atomic operation, so that
/// the counts can be usefully compared.
Expand Down Expand Up @@ -656,7 +664,7 @@ impl<'a> Builder<'a> {
Some(cpu) => cpu as c_int,
None => -1,
};
let (pid, flags) = self.who.as_args();
let (pid, mut flags) = self.who.as_args();
let group_fd = match self.group {
Some(ref mut g) => {
g.max_members += 1;
Expand All @@ -665,6 +673,10 @@ impl<'a> Builder<'a> {
None => -1,
};

if self.cloexec {
flags |= perf_event_open_sys::bindings::PERF_FLAG_FD_CLOEXEC;
}

let file = unsafe {
File::from_raw_fd(check_errno_syscall(|| {
sys::perf_event_open(&mut self.attrs, pid, cpu, group_fd, flags as c_ulong)
Expand Down

0 comments on commit f15d5fa

Please sign in to comment.