Debian Codegraph @

debian/rust-vendor/nix/src/sys/event.rs

raw
1 //! Kernel event notification mechanism
2 //!
3 //! # See Also
4 //! [kqueue(2)](https://www.freebsd.org/cgi/man.cgi?query=kqueue)
5
6 use crate::{Errno, Result};
7 #[cfg(not(target_os = "netbsd"))]
8 use libc::{c_int, c_long, intptr_t, time_t, timespec, uintptr_t};
9 #[cfg(target_os = "netbsd")]
10 use libc::{c_long, intptr_t, size_t, time_t, timespec, uintptr_t};
11 use std::convert::TryInto;
12 use std::mem;
13 use std::os::fd::{AsFd, BorrowedFd};
14 use std::os::unix::io::{AsRawFd, FromRawFd, OwnedFd};
15 use std::ptr;
16
17 /// An event for use with [`Kqueue::kevent`].
18 #[repr(C)]
19 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
20 pub struct KEvent {
21 kevent: libc::kevent,
22 }
23
24 /// An event for use with [`Kqueue::kevent64`].
25 #[cfg(apple_targets)]
26 #[repr(transparent)]
27 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
28 pub struct KEvent64 {
29 kevent: libc::kevent64_s,
30 }
31
32 /// A kernel event queue.
33 ///
34 /// Used by the kernel to notify the process of various types of asynchronous
35 /// events.
36 #[repr(transparent)]
37 #[derive(Debug)]
38 pub struct Kqueue(OwnedFd);
39
40 impl AsFd for Kqueue {
41 fn as_fd(&self) -> BorrowedFd<'_> {
42 self.0.as_fd()
43 }
44 }
45
46 impl From<Kqueue> for OwnedFd {
47 fn from(value: Kqueue) -> Self {
48 value.0
49 }
50 }
51
52 impl Kqueue {
53 /// Create a new kernel event queue.
54 pub fn new() -> Result<Self> {
55 let res = unsafe { libc::kqueue() };
56
57 Errno::result(res).map(|fd| unsafe { Self(OwnedFd::from_raw_fd(fd)) })
58 }
59
60 /// Register new events with the kqueue, and return any pending events to
61 /// the user.
62 ///
63 /// This method will block until either the timeout expires, or a registered
64 /// event triggers a notification.
65 ///
66 /// # Arguments
67 /// - `changelist` - Any new kevents to register for notifications.
68 /// - `eventlist` - Storage space for the kernel to return notifications.
69 /// - `timeout` - An optional timeout.
70 ///
71 /// # Returns
72 /// Returns the number of events placed in the `eventlist`. If an error
73 /// occurs while processing an element of the `changelist` and there is
74 /// enough room in the `eventlist`, then the event will be placed in the
75 /// `eventlist` with `EV_ERROR` set in `flags` and the system error in
76 /// `data`.
77 pub fn kevent(
78 &self,
79 changelist: &[KEvent],
80 eventlist: &mut [KEvent],
81 timeout_opt: Option<timespec>,
82 ) -> Result<usize> {
83 let res = unsafe {
84 libc::kevent(
85 self.0.as_raw_fd(),
86 changelist.as_ptr().cast(),
87 changelist.len() as type_of_nchanges,
88 eventlist.as_mut_ptr().cast(),
89 eventlist.len() as type_of_nchanges,
90 if let Some(ref timeout) = timeout_opt {
91 timeout as *const timespec
92 } else {
93 ptr::null()
94 },
95 )
96 };
97 Errno::result(res).map(|r| r as usize)
98 }
99
100 /// Like [`kevent`](Kqueue::kevent), but uses [`KEvent64`].
101 #[cfg(apple_targets)]
102 pub fn kevent64(
103 &self,
104 changelist: &[KEvent64],
105 eventlist: &mut [KEvent64],
106 flags: Kevent64Flags,
107 timeout_opt: Option<timespec>,
108 ) -> Result<usize> {
109 let res = unsafe {
110 libc::kevent64(
111 self.0.as_raw_fd(),
112 changelist.as_ptr().cast(),
113 changelist.len() as c_int,
114 eventlist.as_mut_ptr().cast(),
115 eventlist.len() as c_int,
116 flags.bits(),
117 if let Some(ref timeout) = timeout_opt {
118 timeout as *const timespec
119 } else {
120 ptr::null()
121 },
122 )
123 };
124 Errno::result(res).map(|r| r as usize)
125 }
126 }
127
128 #[cfg(target_os = "netbsd")]
129 type type_of_event_filter = u32;
130 #[cfg(not(target_os = "netbsd"))]
131 type type_of_event_filter = i16;
132 libc_enum! {
133 #[cfg_attr(target_os = "netbsd", repr(u32))]
134 #[cfg_attr(not(target_os = "netbsd"), repr(i16))]
135 #[non_exhaustive]
136 /// Kqueue filter types. These are all the different types of event that a
137 /// kqueue can notify for.
138 pub enum EventFilter {
139 /// Notifies on the completion of a POSIX AIO operation.
140 EVFILT_AIO,
141 #[cfg(target_os = "freebsd")]
142 /// Returns whenever there is no remaining data in the write buffer
143 EVFILT_EMPTY,
144 #[cfg(target_os = "dragonfly")]
145 /// Takes a descriptor as the identifier, and returns whenever one of
146 /// the specified exceptional conditions has occurred on the descriptor.
147 EVFILT_EXCEPT,
148 #[cfg(any(freebsdlike, apple_targets))]
149 /// Establishes a file system monitor.
150 EVFILT_FS,
151 #[cfg(target_os = "freebsd")]
152 /// Notify for completion of a list of POSIX AIO operations.
153 /// # See Also
154 /// [lio_listio(2)](https://www.freebsd.org/cgi/man.cgi?query=lio_listio)
155 EVFILT_LIO,
156 #[cfg(apple_targets)]
157 /// Mach portsets
158 EVFILT_MACHPORT,
159 /// Notifies when a process performs one or more of the requested
160 /// events.
161 EVFILT_PROC,
162 /// Returns events associated with the process referenced by a given
163 /// process descriptor, created by `pdfork()`. The events to monitor are:
164 ///
165 /// - NOTE_EXIT: the process has exited. The exit status will be stored in data.
166 #[cfg(target_os = "freebsd")]
167 EVFILT_PROCDESC,
168 /// Takes a file descriptor as the identifier, and notifies whenever
169 /// there is data available to read.
170 EVFILT_READ,
171 #[cfg(target_os = "freebsd")]
172 #[doc(hidden)]
173 #[deprecated(since = "0.27.0", note = "Never fully implemented by the OS")]
174 EVFILT_SENDFILE,
175 /// Takes a signal number to monitor as the identifier and notifies when
176 /// the given signal is delivered to the process.
177 EVFILT_SIGNAL,
178 /// Establishes a timer and notifies when the timer expires.
179 EVFILT_TIMER,
180 #[cfg(any(freebsdlike, apple_targets))]
181 /// Notifies only when explicitly requested by the user.
182 EVFILT_USER,
183 #[cfg(apple_targets)]
184 /// Virtual memory events
185 EVFILT_VM,
186 /// Notifies when a requested event happens on a specified file.
187 EVFILT_VNODE,
188 /// Takes a file descriptor as the identifier, and notifies whenever
189 /// it is possible to write to the file without blocking.
190 EVFILT_WRITE,
191 }
192 impl TryFrom<type_of_event_filter>
193 }
194
195 #[cfg(any(freebsdlike, apple_targets, target_os = "openbsd"))]
196 #[doc(hidden)]
197 pub type type_of_event_flag = u16;
198 #[cfg(target_os = "netbsd")]
199 #[doc(hidden)]
200 pub type type_of_event_flag = u32;
201 libc_bitflags! {
202 /// Event flags. See the man page for details.
203 // There's no useful documentation we can write for the individual flags
204 // that wouldn't simply be repeating the man page.
205 pub struct EvFlags: type_of_event_flag {
206 #[allow(missing_docs)]
207 EV_ADD;
208 #[allow(missing_docs)]
209 EV_CLEAR;
210 #[allow(missing_docs)]
211 EV_DELETE;
212 #[allow(missing_docs)]
213 EV_DISABLE;
214 #[cfg(bsd)]
215 #[allow(missing_docs)]
216 EV_DISPATCH;
217 #[cfg(target_os = "freebsd")]
218 #[allow(missing_docs)]
219 EV_DROP;
220 #[allow(missing_docs)]
221 EV_ENABLE;
222 #[allow(missing_docs)]
223 EV_EOF;
224 #[allow(missing_docs)]
225 EV_ERROR;
226 #[cfg(apple_targets)]
227 #[allow(missing_docs)]
228 EV_FLAG0;
229 #[allow(missing_docs)]
230 EV_FLAG1;
231 #[cfg(target_os = "dragonfly")]
232 #[allow(missing_docs)]
233 EV_NODATA;
234 #[allow(missing_docs)]
235 EV_ONESHOT;
236 #[cfg(apple_targets)]
237 #[allow(missing_docs)]
238 EV_OOBAND;
239 #[cfg(apple_targets)]
240 #[allow(missing_docs)]
241 EV_POLL;
242 #[cfg(bsd)]
243 #[allow(missing_docs)]
244 EV_RECEIPT;
245 }
246 }
247
248 #[deprecated(since = "0.30.0", note = "Use `EvFlags instead`")]
249 /// The deprecated EventFlag type alias
250 pub type EventFlag = EvFlags;
251
252 libc_bitflags!(
253 /// Filter-specific flags. See the man page for details.
254 // There's no useful documentation we can write for the individual flags
255 // that wouldn't simply be repeating the man page.
256 #[allow(missing_docs)]
257 pub struct FilterFlag: u32 {
258 #[cfg(apple_targets)]
259 #[allow(missing_docs)]
260 NOTE_ABSOLUTE;
261 #[allow(missing_docs)]
262 NOTE_ATTRIB;
263 #[allow(missing_docs)]
264 NOTE_CHILD;
265 #[allow(missing_docs)]
266 NOTE_DELETE;
267 #[cfg(target_os = "openbsd")]
268 #[allow(missing_docs)]
269 NOTE_EOF;
270 #[allow(missing_docs)]
271 NOTE_EXEC;
272 #[allow(missing_docs)]
273 NOTE_EXIT;
274 #[cfg(apple_targets)]
275 #[allow(missing_docs)]
276 NOTE_EXITSTATUS;
277 #[allow(missing_docs)]
278 NOTE_EXTEND;
279 #[cfg(any(apple_targets, freebsdlike))]
280 #[allow(missing_docs)]
281 NOTE_FFAND;
282 #[cfg(any(apple_targets, freebsdlike))]
283 #[allow(missing_docs)]
284 NOTE_FFCOPY;
285 #[cfg(any(apple_targets, freebsdlike))]
286 #[allow(missing_docs)]
287 NOTE_FFCTRLMASK;
288 #[cfg(any(apple_targets, freebsdlike))]
289 #[allow(missing_docs)]
290 NOTE_FFLAGSMASK;
291 #[cfg(any(apple_targets, freebsdlike))]
292 #[allow(missing_docs)]
293 NOTE_FFNOP;
294 #[cfg(any(apple_targets, freebsdlike))]
295 #[allow(missing_docs)]
296 NOTE_FFOR;
297 #[allow(missing_docs)]
298 NOTE_FORK;
299 #[allow(missing_docs)]
300 NOTE_LINK;
301 #[allow(missing_docs)]
302 NOTE_LOWAT;
303 #[cfg(target_os = "freebsd")]
304 #[allow(missing_docs)]
305 NOTE_MSECONDS;
306 #[cfg(apple_targets)]
307 #[allow(missing_docs)]
308 NOTE_NONE;
309 #[cfg(any(
310 apple_targets,
311 target_os = "freebsd"))]
312 #[allow(missing_docs)]
313 NOTE_NSECONDS;
314 #[cfg(target_os = "dragonfly")]
315 #[allow(missing_docs)]
316 NOTE_OOB;
317 #[allow(missing_docs)]
318 NOTE_PCTRLMASK;
319 #[allow(missing_docs)]
320 NOTE_PDATAMASK;
321 #[allow(missing_docs)]
322 NOTE_RENAME;
323 #[allow(missing_docs)]
324 NOTE_REVOKE;
325 #[cfg(any(
326 apple_targets,
327 target_os = "freebsd"))]
328 #[allow(missing_docs)]
329 NOTE_SECONDS;
330 #[cfg(apple_targets)]
331 #[allow(missing_docs)]
332 NOTE_SIGNAL;
333 #[allow(missing_docs)]
334 NOTE_TRACK;
335 #[allow(missing_docs)]
336 NOTE_TRACKERR;
337 #[cfg(any(apple_targets, freebsdlike))]
338 #[allow(missing_docs)]
339 NOTE_TRIGGER;
340 #[cfg(target_os = "openbsd")]
341 #[allow(missing_docs)]
342 NOTE_TRUNCATE;
343 #[cfg(any(
344 apple_targets,
345 target_os = "freebsd"))]
346 #[allow(missing_docs)]
347 NOTE_USECONDS;
348 #[cfg(apple_targets)]
349 #[allow(missing_docs)]
350 NOTE_VM_ERROR;
351 #[cfg(apple_targets)]
352 #[allow(missing_docs)]
353 NOTE_VM_PRESSURE;
354 #[cfg(apple_targets)]
355 #[allow(missing_docs)]
356 NOTE_VM_PRESSURE_SUDDEN_TERMINATE;
357 #[cfg(apple_targets)]
358 #[allow(missing_docs)]
359 NOTE_VM_PRESSURE_TERMINATE;
360 #[allow(missing_docs)]
361 NOTE_WRITE;
362 }
363 );
364
365 #[cfg(apple_targets)]
366 libc_bitflags! {
367 /// Flags for [`Kqueue::kevent64`].
368 pub struct Kevent64Flags: libc::c_uint {
369 /// Return immediately even if there are no events to return.
370 KEVENT_FLAG_IMMEDIATE;
371 /// Only return error events from the changelist.
372 KEVENT_FLAG_ERROR_EVENTS;
373 }
374 }
375
376 #[allow(missing_docs)]
377 #[deprecated(since = "0.27.0", note = "Use KEvent::new instead")]
378 pub fn kqueue() -> Result<Kqueue> {
379 Kqueue::new()
380 }
381
382 // KEvent can't derive Send because on some operating systems, udata is defined
383 // as a void*. However, KEvent's public API always treats udata as an intptr_t,
384 // which is safe to Send.
385 unsafe impl Send for KEvent {}
386
387 impl KEvent {
388 #[allow(clippy::needless_update)] // Not needless on all platforms.
389 /// Construct a new `KEvent` suitable for submission to the kernel via the
390 /// `changelist` argument of [`Kqueue::kevent`].
391 pub fn new(
392 ident: uintptr_t,
393 filter: EventFilter,
394 flags: EvFlags,
395 fflags: FilterFlag,
396 data: intptr_t,
397 udata: intptr_t,
398 ) -> KEvent {
399 KEvent {
400 kevent: libc::kevent {
401 ident,
402 filter: filter as type_of_event_filter,
403 flags: flags.bits(),
404 fflags: fflags.bits(),
405 // data can be either i64 or intptr_t, depending on platform
406 data: data as _,
407 udata: udata as *mut libc::c_void,
408 ..unsafe { mem::zeroed() }
409 },
410 }
411 }
412
413 /// Value used to identify this event. The exact interpretation is
414 /// determined by the attached filter, but often is a raw file descriptor.
415 pub fn ident(&self) -> uintptr_t {
416 self.kevent.ident
417 }
418
419 /// Identifies the kernel filter used to process this event.
420 ///
421 /// Will only return an error if the kernel reports an event via a filter
422 /// that is unknown to Nix.
423 pub fn filter(&self) -> Result<EventFilter> {
424 self.kevent.filter.try_into()
425 }
426
427 /// Flags control what the kernel will do when this event is added with
428 /// [`Kqueue::kevent`].
429 pub fn flags(&self) -> EvFlags {
430 EvFlags::from_bits_retain(self.kevent.flags)
431 }
432
433 /// Filter-specific flags.
434 pub fn fflags(&self) -> FilterFlag {
435 FilterFlag::from_bits_retain(self.kevent.fflags)
436 }
437
438 /// Filter-specific data value.
439 pub fn data(&self) -> intptr_t {
440 self.kevent.data as intptr_t
441 }
442
443 /// Opaque user-defined value passed through the kernel unchanged.
444 pub fn udata(&self) -> intptr_t {
445 self.kevent.udata as intptr_t
446 }
447 }
448
449 #[cfg(apple_targets)]
450 const _: () = {
451 fn _assert_send<T: Send>() {}
452 fn _assert() {
453 _assert_send::<KEvent64>();
454 }
455 };
456
457 #[cfg(apple_targets)]
458 impl KEvent64 {
459 /// Construct a new `KEvent64`.
460 pub fn new(
461 ident: u64,
462 filter: EventFilter,
463 flags: EvFlags,
464 fflags: FilterFlag,
465 data: i64,
466 udata: u64,
467 ext: [u64; 2],
468 ) -> KEvent64 {
469 KEvent64 {
470 kevent: libc::kevent64_s {
471 ident,
472 filter: filter as type_of_event_filter,
473 flags: flags.bits(),
474 fflags: fflags.bits(),
475 data,
476 udata,
477 ext,
478 },
479 }
480 }
481
482 /// Value used to identify this event.
483 pub fn ident(&self) -> u64 {
484 self.kevent.ident
485 }
486
487 /// Identifies the kernel filter used to process this event.
488 pub fn filter(&self) -> Result<EventFilter> {
489 self.kevent.filter.try_into()
490 }
491
492 /// Event flags.
493 pub fn flags(&self) -> EvFlags {
494 EvFlags::from_bits_retain(self.kevent.flags)
495 }
496
497 /// Filter-specific flags.
498 pub fn fflags(&self) -> FilterFlag {
499 FilterFlag::from_bits_retain(self.kevent.fflags)
500 }
501
502 /// Filter-specific data value.
503 pub fn data(&self) -> i64 {
504 self.kevent.data
505 }
506
507 /// Opaque user-defined value passed through the kernel unchanged.
508 pub fn udata(&self) -> u64 {
509 self.kevent.udata
510 }
511
512 /// Filter-specific extension data.
513 pub fn ext(&self) -> [u64; 2] {
514 self.kevent.ext
515 }
516 }
517
518 #[allow(missing_docs)]
519 #[deprecated(since = "0.27.0", note = "Use Kqueue::kevent instead")]
520 pub fn kevent(
521 kq: &Kqueue,
522 changelist: &[KEvent],
523 eventlist: &mut [KEvent],
524 timeout_ms: usize,
525 ) -> Result<usize> {
526 // Convert ms to timespec
527 let timeout = timespec {
528 tv_sec: (timeout_ms / 1000) as time_t,
529 tv_nsec: ((timeout_ms % 1000) * 1_000_000) as c_long,
530 };
531
532 kq.kevent(changelist, eventlist, Some(timeout))
533 }
534
535 #[cfg(any(apple_targets, freebsdlike, target_os = "openbsd"))]
536 type type_of_nchanges = c_int;
537 #[cfg(target_os = "netbsd")]
538 type type_of_nchanges = size_t;
539
540 #[allow(missing_docs)]
541 #[deprecated(since = "0.27.0", note = "Use Kqueue::kevent instead")]
542 pub fn kevent_ts(
543 kq: &Kqueue,
544 changelist: &[KEvent],
545 eventlist: &mut [KEvent],
546 timeout_opt: Option<timespec>,
547 ) -> Result<usize> {
548 kq.kevent(changelist, eventlist, timeout_opt)
549 }
550
551 /// Modify an existing [`KEvent`].
552 // Probably should deprecate. Would anybody ever use it over `KEvent::new`?
553 #[deprecated(since = "0.27.0", note = "Use Kqueue::kevent instead")]
554 #[inline]
555 pub fn ev_set(
556 ev: &mut KEvent,
557 ident: usize,
558 filter: EventFilter,
559 flags: EvFlags,
560 fflags: FilterFlag,
561 udata: intptr_t,
562 ) {
563 ev.kevent.ident = ident as uintptr_t;
564 ev.kevent.filter = filter as type_of_event_filter;
565 ev.kevent.flags = flags.bits();
566 ev.kevent.fflags = fflags.bits();
567 ev.kevent.data = 0;
568 ev.kevent.udata = udata as *mut libc::c_void;
569 }