summaryrefslogtreecommitdiffstats
path: root/vendor/rustix/src/io/kqueue.rs
blob: 09fa0a4e22ea8c9bbe46775ec9c9ddbc3d9cd519 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! An API for interfacing with `kqueue`.

use crate::fd::{AsFd, AsRawFd, OwnedFd, RawFd};
use crate::{backend, io};

use backend::c::{self, kevent as kevent_t, uintptr_t};
use backend::io::syscalls;

#[cfg(any(apple, freebsdlike))]
use backend::c::intptr_t;

use alloc::vec::Vec;
use core::ptr::slice_from_raw_parts_mut;
use core::time::Duration;

/// A `kqueue` event.
#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct Event {
    // The layout varies between BSDs and macOS.
    inner: kevent_t,
}

impl Event {
    /// Create a new `Event`.
    #[allow(clippy::needless_update)]
    pub fn new(filter: EventFilter, flags: EventFlags, udata: isize) -> Event {
        let (ident, filter, fflags) = match filter {
            EventFilter::Read(fd) => (fd.as_raw_fd() as uintptr_t, c::EVFILT_READ, 0),
            EventFilter::Write(fd) => (fd.as_raw_fd() as _, c::EVFILT_WRITE, 0),
            #[cfg(target_os = "freebsd")]
            EventFilter::Empty(fd) => (fd.as_raw_fd() as _, c::EVFILT_EMPTY, 0),
            EventFilter::Vnode { vnode, flags } => {
                (vnode.as_raw_fd() as _, c::EVFILT_VNODE, flags.bits())
            }
            #[cfg(feature = "process")]
            EventFilter::Proc { pid, flags } => (
                crate::process::Pid::as_raw(Some(pid)) as _,
                c::EVFILT_PROC,
                flags.bits(),
            ),
            #[cfg(feature = "process")]
            EventFilter::Signal { signal, times: _ } => (signal as _, c::EVFILT_SIGNAL, 0),
            EventFilter::Timer(timer) => {
                #[cfg(any(apple, target_os = "freebsd", target_os = "netbsd"))]
                let (data, fflags) = match timer {
                    Some(timer) => {
                        if timer.subsec_millis() == 0 {
                            (timer.as_secs() as _, c::NOTE_SECONDS)
                        } else if timer.subsec_nanos() == 0 {
                            (timer.as_micros() as _, c::NOTE_USECONDS)
                        } else {
                            (timer.as_nanos() as _, c::NOTE_NSECONDS)
                        }
                    }
                    None => (uintptr_t::MAX, c::NOTE_SECONDS),
                };
                #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))]
                let (data, fflags) = match timer {
                    Some(timer) => (timer.as_millis() as _, 0),
                    None => (uintptr_t::MAX, 0),
                };

                (data, c::EVFILT_TIMER, fflags)
            }
            #[cfg(any(apple, freebsdlike))]
            EventFilter::User {
                ident,
                flags,
                user_flags,
            } => (ident as _, c::EVFILT_USER, flags.bits() | user_flags.0),
            EventFilter::Unknown => panic!("unknown filter"),
        };

        Event {
            inner: kevent_t {
                ident,
                filter: filter as _,
                flags: flags.bits() as _,
                fflags,
                data: 0,
                udata: {
                    // On netbsd, udata is an isize and not a pointer.
                    // TODO: Strict provenance, prevent int-to-ptr cast.
                    udata as _
                },
                ..unsafe { core::mem::zeroed() }
            },
        }
    }

    /// Get the event flags for this event.
    pub fn flags(&self) -> EventFlags {
        EventFlags::from_bits_truncate(self.inner.flags as _)
    }

    /// Get the user data for this event.
    pub fn udata(&self) -> isize {
        // On netbsd, udata is an isize and not a pointer.
        // TODO: Strict provenance, prevent ptr-to-int cast.

        self.inner.udata as _
    }

    /// Get the filter of this event.
    pub fn filter(&self) -> EventFilter {
        match self.inner.filter as _ {
            c::EVFILT_READ => EventFilter::Read(self.inner.ident as _),
            c::EVFILT_WRITE => EventFilter::Write(self.inner.ident as _),
            #[cfg(target_os = "freebsd")]
            c::EVFILT_EMPTY => EventFilter::Empty(self.inner.ident as _),
            c::EVFILT_VNODE => EventFilter::Vnode {
                vnode: self.inner.ident as _,
                flags: VnodeEvents::from_bits_truncate(self.inner.fflags),
            },
            #[cfg(feature = "process")]
            c::EVFILT_PROC => EventFilter::Proc {
                pid: unsafe { crate::process::Pid::from_raw(self.inner.ident as _) }.unwrap(),
                flags: ProcessEvents::from_bits_truncate(self.inner.fflags),
            },
            #[cfg(feature = "process")]
            c::EVFILT_SIGNAL => EventFilter::Signal {
                signal: crate::process::Signal::from_raw(self.inner.ident as _).unwrap(),
                times: self.inner.data as _,
            },
            c::EVFILT_TIMER => EventFilter::Timer({
                let (data, fflags) = (self.inner.data, self.inner.fflags);
                #[cfg(any(apple, target_os = "freebsd", target_os = "netbsd"))]
                match fflags as _ {
                    c::NOTE_SECONDS => Some(Duration::from_secs(data as _)),
                    c::NOTE_USECONDS => Some(Duration::from_micros(data as _)),
                    c::NOTE_NSECONDS => Some(Duration::from_nanos(data as _)),
                    _ => {
                        // Unknown timer flags.
                        None
                    }
                }
                #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))]
                Some(Duration::from_millis(data as _))
            }),
            #[cfg(any(apple, freebsdlike))]
            c::EVFILT_USER => EventFilter::User {
                ident: self.inner.ident as _,
                flags: UserFlags::from_bits_truncate(self.inner.fflags),
                user_flags: UserDefinedFlags(self.inner.fflags & EVFILT_USER_FLAGS),
            },
            _ => EventFilter::Unknown,
        }
    }
}

/// Bottom 24 bits of a u32.
#[cfg(any(apple, freebsdlike))]
const EVFILT_USER_FLAGS: u32 = 0x00ff_ffff;

/// The possible filters for a `kqueue`.
#[repr(i16)]
#[non_exhaustive]
pub enum EventFilter {
    /// A read filter.
    Read(RawFd),

    /// A write filter.
    Write(RawFd),

    /// An empty filter.
    #[cfg(target_os = "freebsd")]
    Empty(RawFd),

    /// A VNode filter.
    Vnode {
        /// The file descriptor we looked for events in.
        vnode: RawFd,

        /// The flags for this event.
        flags: VnodeEvents,
    },

    /// A process filter.
    #[cfg(feature = "process")]
    Proc {
        /// The process ID we waited on.
        pid: crate::process::Pid,

        /// The flags for this event.
        flags: ProcessEvents,
    },

    /// A signal filter.
    #[cfg(feature = "process")]
    Signal {
        /// The signal number we waited on.
        signal: crate::process::Signal,

        /// The number of times the signal has been
        /// received since the last call to kevent.
        times: usize,
    },

    /// A timer filter.
    Timer(Option<Duration>),

    /// A user filter.
    #[cfg(any(apple, freebsdlike))]
    User {
        /// The identifier for this event.
        ident: intptr_t,

        /// The flags for this event.
        flags: UserFlags,

        /// The user-defined flags for this event.
        user_flags: UserDefinedFlags,
    },

    /// This filter is unknown.
    ///
    /// # Panics
    ///
    /// Passing this into `Event::new()` will result in a panic.
    Unknown,
}

bitflags::bitflags! {
    /// The flags for a `kqueue` event.
    pub struct EventFlags: u16 {
        /// Add the event to the `kqueue`.
        const ADD = c::EV_ADD as _;

        /// Enable the event.
        const ENABLE = c::EV_ENABLE as _;

        /// Disable the event.
        const DISABLE = c::EV_DISABLE as _;

        /// Delete the event from the `kqueue`.
        const DELETE = c::EV_DELETE as _;

        /// TODO
        const RECEIPT = c::EV_RECEIPT as _;

        /// Clear the event after it is triggered.
        const ONESHOT = c::EV_ONESHOT as _;

        /// TODO
        const CLEAR = c::EV_CLEAR as _;

        /// TODO
        const EOF = c::EV_EOF as _;

        /// TODO
        const ERROR = c::EV_ERROR as _;
    }
}

bitflags::bitflags! {
    /// The flags for a virtual node event.
    pub struct VnodeEvents: u32 {
        /// The file was deleted.
        const DELETE = c::NOTE_DELETE;

        /// The file was written to.
        const WRITE = c::NOTE_WRITE;

        /// The file was extended.
        const EXTEND = c::NOTE_EXTEND;

        /// The file had its attributes changed.
        const ATTRIBUTES = c::NOTE_ATTRIB;

        /// The file was renamed.
        const RENAME = c::NOTE_RENAME;

        /// Access to the file was revoked.
        const REVOKE = c::NOTE_REVOKE;

        /// The link count of the file has changed.
        const LINK = c::NOTE_LINK;
    }
}

#[cfg(feature = "process")]
bitflags::bitflags! {
    /// The flags for a process event.
    pub struct ProcessEvents: u32 {
        /// The process exited.
        const EXIT = c::NOTE_EXIT;

        /// The process forked itself.
        const FORK = c::NOTE_FORK;

        /// The process executed a new process.
        const EXEC = c::NOTE_EXEC;

        /// Follow the process through fork() calls (write only).
        const TRACK = c::NOTE_TRACK;

        /// An error has occurred with following the process.
        const TRACKERR = c::NOTE_TRACKERR;
    }
}

#[cfg(any(apple, freebsdlike))]
bitflags::bitflags! {
    /// The flags for a user event.
    pub struct UserFlags: u32 {
        /// Ignore the user input flags.
        const NOINPUT = c::NOTE_FFNOP;

        /// Bitwise AND fflags.
        const AND = c::NOTE_FFAND;

        /// Bitwise OR fflags.
        const OR = c::NOTE_FFOR;

        /// Copy fflags.
        const COPY = c::NOTE_FFCOPY;

        /// Control mask for operations.
        const CTRLMASK = c::NOTE_FFCTRLMASK;

        /// User defined flags for masks.
        const UDFMASK = c::NOTE_FFLAGSMASK;

        /// Trigger the event.
        const TRIGGER = c::NOTE_TRIGGER;
    }
}

/// User-defined flags.
///
/// Only the lower 24 bits are used in this struct.
#[repr(transparent)]
#[cfg(any(apple, freebsdlike))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct UserDefinedFlags(u32);

#[cfg(any(apple, freebsdlike))]
impl UserDefinedFlags {
    /// Create a new `UserDefinedFlags` from a `u32`.
    pub fn new(flags: u32) -> Self {
        Self(flags & EVFILT_USER_FLAGS)
    }

    /// Get the underlying `u32`.
    pub fn get(self) -> u32 {
        self.0
    }
}

/// `kqueue()`—Create a new `kqueue` file descriptor.
///
/// # References
///  - [Apple]
///  - [FreeBSD]
///  - [OpenBSD]
///  - [NetBSD]
///  - [DragonflyBSD]
///
/// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/kqueue.2.html
/// [FreeBSD]: https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
/// [OpenBSD]: https://man.openbsd.org/kqueue.2
/// [NetBSD]: https://man.netbsd.org/kqueue.2
/// [DragonflyBSD]: https://www.dragonflybsd.org/cgi/web-man/?command=kqueue
pub fn kqueue() -> io::Result<OwnedFd> {
    syscalls::kqueue()
}

/// `kevent(kqueue, changelist, eventlist, timeout)`—Wait for events on a
/// `kqueue`.
///
/// Note: in order to receive events, make sure to allocate capacity in the
/// eventlist! Otherwise, the function will return immediately.
///
/// # Safety
///
/// The file descriptors referred to by the `Event` structs must be valid for
/// the lifetime of the `kqueue` file descriptor.
///
/// # References
///  - [Apple]
///  - [FreeBSD]
///  - [OpenBSD]
///  - [NetBSD]
///  - [DragonflyBSD]
///
/// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/kevent.2.html
/// [FreeBSD]: https://www.freebsd.org/cgi/man.cgi?query=kevent&sektion=2
/// [OpenBSD]: https://man.openbsd.org/kevent.2
/// [NetBSD]: https://man.netbsd.org/kevent.2
/// [DragonflyBSD]: https://www.dragonflybsd.org/cgi/web-man/?command=kevent
pub unsafe fn kevent(
    kqueue: impl AsFd,
    changelist: &[Event],
    eventlist: &mut Vec<Event>,
    timeout: Option<Duration>,
) -> io::Result<usize> {
    let timeout = timeout.map(|timeout| crate::backend::c::timespec {
        tv_sec: timeout.as_secs() as _,
        tv_nsec: timeout.subsec_nanos() as _,
    });

    // Populate the event list with events.
    eventlist.set_len(0);
    let out_slice =
        slice_from_raw_parts_mut(eventlist.as_mut_ptr() as *mut _, eventlist.capacity());
    let res = syscalls::kevent(
        kqueue.as_fd(),
        changelist,
        &mut *out_slice,
        timeout.as_ref(),
    )
    .map(|res| res as _);

    // Update the event list.
    if let Ok(len) = res {
        eventlist.set_len(len);
    }

    res
}