2023-02-12 04:31:08 +08:00
|
|
|
//! Functions for handling event triggers
|
|
|
|
//!
|
|
|
|
//! Because most of these functions can be called by signal handler, it is important to make it well
|
|
|
|
//! defined when these functions produce output or perform memory allocations, since such functions
|
|
|
|
//! may not be safely called by signal handlers.
|
|
|
|
|
|
|
|
use libc::pid_t;
|
|
|
|
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
|
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
|
2023-10-09 05:22:27 +08:00
|
|
|
use crate::common::{escape, scoped_push_replacer, ScopeGuard};
|
2023-02-12 04:31:08 +08:00
|
|
|
use crate::flog::FLOG;
|
2023-10-09 05:22:27 +08:00
|
|
|
use crate::io::{IoChain, IoStreams};
|
2024-01-02 04:29:05 +08:00
|
|
|
use crate::job_group::MaybeJobId;
|
2023-10-09 05:22:27 +08:00
|
|
|
use crate::parser::{Block, Parser};
|
2023-05-01 06:40:06 +08:00
|
|
|
use crate::signal::{signal_check_cancel, signal_handle, Signal};
|
2023-03-20 06:50:33 +08:00
|
|
|
use crate::termsize;
|
2023-08-09 06:16:04 +08:00
|
|
|
use crate::wchar::prelude::*;
|
2023-02-12 04:31:08 +08:00
|
|
|
|
2024-01-02 04:29:05 +08:00
|
|
|
pub enum event_type_t {
|
|
|
|
any,
|
|
|
|
signal,
|
|
|
|
variable,
|
|
|
|
process_exit,
|
|
|
|
job_exit,
|
|
|
|
caller_exit,
|
|
|
|
generic,
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
|
|
|
|
2023-05-15 02:40:18 +08:00
|
|
|
pub const ANY_PID: pid_t = 0;
|
2023-02-12 04:31:08 +08:00
|
|
|
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
2023-07-16 02:59:08 +08:00
|
|
|
pub enum EventDescription {
|
2023-02-12 04:31:08 +08:00
|
|
|
/// Matches any event type (not always any event, as the function name may limit the choice as
|
|
|
|
/// well).
|
|
|
|
Any,
|
|
|
|
/// An event triggered by a signal.
|
2023-03-21 04:30:18 +08:00
|
|
|
Signal { signal: Signal },
|
2023-02-12 04:31:08 +08:00
|
|
|
/// An event triggered by a variable update.
|
|
|
|
Variable { name: WString },
|
|
|
|
/// An event triggered by a process exit.
|
|
|
|
ProcessExit {
|
|
|
|
/// Process ID. Use [`ANY_PID`] to match any pid.
|
|
|
|
pid: pid_t,
|
|
|
|
},
|
|
|
|
/// An event triggered by a job exit.
|
|
|
|
JobExit {
|
|
|
|
/// pid requested by the event, or [`ANY_PID`] for all.
|
|
|
|
pid: pid_t,
|
|
|
|
/// `internal_job_id` of the job to match.
|
|
|
|
/// If this is 0, we match either all jobs (`pid == ANY_PID`) or no jobs (otherwise).
|
|
|
|
internal_job_id: u64,
|
|
|
|
},
|
|
|
|
/// An event triggered by a job exit, triggering the 'caller'-style events only.
|
|
|
|
CallerExit {
|
|
|
|
/// Internal job ID.
|
|
|
|
caller_id: u64,
|
|
|
|
},
|
|
|
|
/// A generic event.
|
|
|
|
Generic {
|
|
|
|
/// The parameter describing this generic event.
|
|
|
|
param: WString,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2023-07-16 02:59:08 +08:00
|
|
|
impl EventDescription {
|
2023-02-12 04:31:08 +08:00
|
|
|
fn str_param1(&self) -> Option<&wstr> {
|
|
|
|
match self {
|
2023-07-16 02:59:08 +08:00
|
|
|
EventDescription::Any
|
|
|
|
| EventDescription::Signal { .. }
|
|
|
|
| EventDescription::ProcessExit { .. }
|
|
|
|
| EventDescription::JobExit { .. }
|
|
|
|
| EventDescription::CallerExit { .. } => None,
|
|
|
|
EventDescription::Variable { name } => Some(name),
|
|
|
|
EventDescription::Generic { param } => Some(param),
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn name(&self) -> &'static wstr {
|
|
|
|
match self {
|
2024-01-13 02:10:56 +08:00
|
|
|
EventDescription::Any => L!("any"),
|
|
|
|
EventDescription::Signal { .. } => L!("signal"),
|
|
|
|
EventDescription::Variable { .. } => L!("variable"),
|
|
|
|
EventDescription::ProcessExit { .. } => L!("process-exit"),
|
|
|
|
EventDescription::JobExit { .. } => L!("job-exit"),
|
|
|
|
EventDescription::CallerExit { .. } => L!("caller-exit"),
|
|
|
|
EventDescription::Generic { .. } => L!("generic"),
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn matches_filter(&self, filter: &wstr) -> bool {
|
|
|
|
if filter.is_empty() {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
match self {
|
2023-07-16 02:59:08 +08:00
|
|
|
EventDescription::Any => false,
|
|
|
|
EventDescription::ProcessExit { .. }
|
|
|
|
| EventDescription::JobExit { .. }
|
|
|
|
| EventDescription::CallerExit { .. }
|
2024-01-13 15:25:12 +08:00
|
|
|
if filter == "exit" =>
|
2023-03-13 05:01:59 +08:00
|
|
|
{
|
|
|
|
true
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
2023-03-13 05:01:59 +08:00
|
|
|
_ => filter == self.name(),
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-16 02:59:08 +08:00
|
|
|
impl From<&EventDescription> for event_type_t {
|
|
|
|
fn from(desc: &EventDescription) -> Self {
|
|
|
|
match desc {
|
|
|
|
EventDescription::Any => event_type_t::any,
|
|
|
|
EventDescription::Signal { .. } => event_type_t::signal,
|
|
|
|
EventDescription::Variable { .. } => event_type_t::variable,
|
|
|
|
EventDescription::ProcessExit { .. } => event_type_t::process_exit,
|
|
|
|
EventDescription::JobExit { .. } => event_type_t::job_exit,
|
|
|
|
EventDescription::CallerExit { .. } => event_type_t::caller_exit,
|
|
|
|
EventDescription::Generic { .. } => event_type_t::generic,
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct EventHandler {
|
|
|
|
/// Properties of the event to match.
|
2023-04-22 06:50:36 +08:00
|
|
|
pub desc: EventDescription,
|
2023-02-12 04:31:08 +08:00
|
|
|
/// Name of the function to invoke.
|
2023-04-22 06:50:36 +08:00
|
|
|
pub function_name: WString,
|
2023-02-12 04:31:08 +08:00
|
|
|
/// A flag set when an event handler is removed from the global list.
|
|
|
|
/// Once set, this is never cleared.
|
2023-04-22 06:50:36 +08:00
|
|
|
pub removed: AtomicBool,
|
2023-02-12 04:31:08 +08:00
|
|
|
/// A flag set when an event handler is first fired.
|
2023-04-22 06:50:36 +08:00
|
|
|
pub fired: AtomicBool,
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
impl EventHandler {
|
|
|
|
pub fn new(desc: EventDescription, name: Option<WString>) -> Self {
|
|
|
|
Self {
|
|
|
|
desc,
|
2023-10-06 22:52:57 +08:00
|
|
|
function_name: name.unwrap_or_default(),
|
2023-02-12 04:31:08 +08:00
|
|
|
removed: AtomicBool::new(false),
|
|
|
|
fired: AtomicBool::new(false),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// \return true if a handler is "one shot": it fires at most once.
|
|
|
|
fn is_one_shot(&self) -> bool {
|
2023-07-16 02:59:08 +08:00
|
|
|
match self.desc {
|
|
|
|
EventDescription::ProcessExit { pid } => pid != ANY_PID,
|
|
|
|
EventDescription::JobExit { pid, .. } => pid != ANY_PID,
|
|
|
|
EventDescription::CallerExit { .. } => true,
|
|
|
|
EventDescription::Signal { .. }
|
|
|
|
| EventDescription::Variable { .. }
|
|
|
|
| EventDescription::Generic { .. }
|
|
|
|
| EventDescription::Any => false,
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Tests if this event handler matches an event that has occurred.
|
|
|
|
fn matches(&self, event: &Event) -> bool {
|
2023-07-16 02:59:08 +08:00
|
|
|
match (&self.desc, &event.desc) {
|
|
|
|
(EventDescription::Any, _) => true,
|
|
|
|
(
|
|
|
|
EventDescription::Signal { signal },
|
|
|
|
EventDescription::Signal { signal: ev_signal },
|
|
|
|
) => signal == ev_signal,
|
|
|
|
(EventDescription::Variable { name }, EventDescription::Variable { name: ev_name }) => {
|
2023-02-12 04:31:08 +08:00
|
|
|
name == ev_name
|
|
|
|
}
|
|
|
|
(
|
2023-07-16 02:59:08 +08:00
|
|
|
EventDescription::ProcessExit { pid },
|
|
|
|
EventDescription::ProcessExit { pid: ev_pid },
|
|
|
|
) => *pid == ANY_PID || pid == ev_pid,
|
|
|
|
(
|
|
|
|
EventDescription::JobExit {
|
2023-02-12 04:31:08 +08:00
|
|
|
pid,
|
|
|
|
internal_job_id,
|
|
|
|
},
|
2023-07-16 02:59:08 +08:00
|
|
|
EventDescription::JobExit {
|
2023-02-12 04:31:08 +08:00
|
|
|
internal_job_id: ev_internal_job_id,
|
|
|
|
..
|
|
|
|
},
|
|
|
|
) => *pid == ANY_PID || internal_job_id == ev_internal_job_id,
|
|
|
|
(
|
2023-07-16 02:59:08 +08:00
|
|
|
EventDescription::CallerExit { caller_id },
|
|
|
|
EventDescription::CallerExit {
|
2023-02-12 04:31:08 +08:00
|
|
|
caller_id: ev_caller_id,
|
|
|
|
},
|
|
|
|
) => caller_id == ev_caller_id,
|
2023-07-16 02:59:08 +08:00
|
|
|
(
|
|
|
|
EventDescription::Generic { param },
|
|
|
|
EventDescription::Generic { param: ev_param },
|
|
|
|
) => param == ev_param,
|
2023-02-12 04:31:08 +08:00
|
|
|
(_, _) => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
type EventHandlerList = Vec<Arc<EventHandler>>;
|
|
|
|
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
|
|
pub struct Event {
|
|
|
|
desc: EventDescription,
|
|
|
|
arguments: Vec<WString>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Event {
|
|
|
|
pub fn generic(desc: WString) -> Self {
|
|
|
|
Self {
|
2023-07-16 02:59:08 +08:00
|
|
|
desc: EventDescription::Generic { param: desc },
|
2023-02-12 04:31:08 +08:00
|
|
|
arguments: vec![],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn variable_erase(name: WString) -> Self {
|
|
|
|
Self {
|
2023-07-16 02:59:08 +08:00
|
|
|
desc: EventDescription::Variable { name: name.clone() },
|
2023-02-12 04:31:08 +08:00
|
|
|
arguments: vec!["VARIABLE".into(), "ERASE".into(), name],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn variable_set(name: WString) -> Self {
|
|
|
|
Self {
|
2023-07-16 02:59:08 +08:00
|
|
|
desc: EventDescription::Variable { name: name.clone() },
|
2023-02-12 04:31:08 +08:00
|
|
|
arguments: vec!["VARIABLE".into(), "SET".into(), name],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn process_exit(pid: pid_t, status: i32) -> Self {
|
|
|
|
Self {
|
2023-07-16 02:59:08 +08:00
|
|
|
desc: EventDescription::ProcessExit { pid },
|
2023-02-12 04:31:08 +08:00
|
|
|
arguments: vec![
|
|
|
|
"PROCESS_EXIT".into(),
|
|
|
|
pid.to_string().into(),
|
|
|
|
status.to_string().into(),
|
|
|
|
],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn job_exit(pgid: pid_t, jid: u64) -> Self {
|
|
|
|
Self {
|
2023-07-16 02:59:08 +08:00
|
|
|
desc: EventDescription::JobExit {
|
|
|
|
pid: pgid,
|
|
|
|
internal_job_id: jid,
|
2023-02-12 04:31:08 +08:00
|
|
|
},
|
|
|
|
arguments: vec![
|
|
|
|
"JOB_EXIT".into(),
|
|
|
|
pgid.to_string().into(),
|
|
|
|
"0".into(), // historical
|
|
|
|
],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-09 20:29:43 +08:00
|
|
|
pub fn caller_exit(internal_job_id: u64, job_id: MaybeJobId) -> Self {
|
2023-02-12 04:31:08 +08:00
|
|
|
Self {
|
2023-07-16 02:59:08 +08:00
|
|
|
desc: EventDescription::CallerExit {
|
|
|
|
caller_id: internal_job_id,
|
2023-02-12 04:31:08 +08:00
|
|
|
},
|
|
|
|
arguments: vec![
|
|
|
|
"JOB_EXIT".into(),
|
2023-04-09 20:29:43 +08:00
|
|
|
job_id.to_wstring(),
|
2023-02-12 04:31:08 +08:00
|
|
|
"0".into(), // historical
|
|
|
|
],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Test if specified event is blocked.
|
2023-10-09 05:22:27 +08:00
|
|
|
fn is_blocked(&self, parser: &Parser) -> bool {
|
|
|
|
for block in parser.blocks().iter().rev() {
|
|
|
|
if block.event_blocks != 0 {
|
2023-02-12 04:31:08 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-09 05:22:27 +08:00
|
|
|
parser.global_event_blocks.load(Ordering::Relaxed) != 0
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-10 10:24:59 +08:00
|
|
|
/// All the signals we are interested in are in the 1-32 range (with 32 being the typical SIGRTMAX),
|
|
|
|
/// but we can expand it to 64 just to be safe. All code checks if a signal value is within bounds
|
|
|
|
/// before handling it.
|
|
|
|
const SIGNAL_COUNT: usize = 64;
|
2023-02-12 04:31:08 +08:00
|
|
|
|
|
|
|
struct PendingSignals {
|
|
|
|
/// A counter that is incremented each time a pending signal is received.
|
|
|
|
counter: AtomicU32,
|
|
|
|
/// List of pending signals.
|
|
|
|
received: [AtomicBool; SIGNAL_COUNT],
|
|
|
|
/// The last counter visible in `acquire_pending()`.
|
|
|
|
/// This is not accessed from a signal handler.
|
|
|
|
last_counter: Mutex<u32>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl PendingSignals {
|
|
|
|
/// Mark a signal as pending. This may be called from a signal handler. We expect only one
|
|
|
|
/// signal handler to execute at once. Also note that these may be coalesced.
|
2023-04-09 20:27:25 +08:00
|
|
|
pub fn mark(&self, sig: libc::c_int) {
|
|
|
|
if let Some(received) = self.received.get(usize::try_from(sig).unwrap()) {
|
2023-02-12 04:31:08 +08:00
|
|
|
received.store(true, Ordering::Relaxed);
|
2023-03-13 07:58:22 +08:00
|
|
|
self.counter.fetch_add(1, Ordering::Relaxed);
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-13 07:58:22 +08:00
|
|
|
/// Return the list of signals that were set as the bits in a u64, clearing them.
|
|
|
|
pub fn acquire_pending(&self) -> u64 {
|
2023-02-12 04:31:08 +08:00
|
|
|
let mut current = self
|
|
|
|
.last_counter
|
|
|
|
.lock()
|
|
|
|
.expect("mutex should not be poisoned");
|
|
|
|
|
|
|
|
// Check the counter first. If it hasn't changed, no signals have been received.
|
|
|
|
let count = self.counter.load(Ordering::Acquire);
|
|
|
|
if count == *current {
|
2023-03-13 07:58:22 +08:00
|
|
|
return 0;
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// The signal count has changed. Store the new counter and fetch all set signals.
|
|
|
|
*current = count;
|
2023-03-13 07:58:22 +08:00
|
|
|
let mut result = 0;
|
2023-02-12 04:31:08 +08:00
|
|
|
for (i, received) in self.received.iter().enumerate() {
|
|
|
|
if received.load(Ordering::Relaxed) {
|
2023-03-13 07:58:22 +08:00
|
|
|
result |= 1_u64 << i;
|
2023-02-12 04:31:08 +08:00
|
|
|
received.store(false, Ordering::Relaxed);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
result
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Required until inline const is stabilized.
|
|
|
|
#[allow(clippy::declare_interior_mutable_const)]
|
|
|
|
const ATOMIC_BOOL_FALSE: AtomicBool = AtomicBool::new(false);
|
|
|
|
#[allow(clippy::declare_interior_mutable_const)]
|
|
|
|
const ATOMIC_U32_0: AtomicU32 = AtomicU32::new(0);
|
|
|
|
|
|
|
|
static PENDING_SIGNALS: PendingSignals = PendingSignals {
|
|
|
|
counter: AtomicU32::new(0),
|
|
|
|
received: [ATOMIC_BOOL_FALSE; SIGNAL_COUNT],
|
|
|
|
last_counter: Mutex::new(0),
|
|
|
|
};
|
|
|
|
|
|
|
|
/// List of event handlers. **While this is locked to allow safely accessing/modifying the vector,
|
|
|
|
/// note that it does NOT provide exclusive access to the [`EventHandler`] objects which are shared
|
|
|
|
/// references (in an `Arc<T>`).**
|
|
|
|
static EVENT_HANDLERS: Mutex<EventHandlerList> = Mutex::new(Vec::new());
|
|
|
|
|
|
|
|
/// Tracks the number of registered event handlers for each signal.
|
|
|
|
/// This is inspected by a signal handler. We assume no values in here overflow.
|
|
|
|
static OBSERVED_SIGNALS: [AtomicU32; SIGNAL_COUNT] = [ATOMIC_U32_0; SIGNAL_COUNT];
|
|
|
|
|
|
|
|
/// List of events that have been sent but have not yet been delivered because they are blocked.
|
|
|
|
///
|
|
|
|
/// This was part of profile_item_t accessed as parser.libdata().blocked_events and has been
|
|
|
|
/// temporarily moved here. There was no mutex around this in the cpp code. TODO: Move it back.
|
|
|
|
static BLOCKED_EVENTS: Mutex<Vec<Event>> = Mutex::new(Vec::new());
|
|
|
|
|
2023-03-21 04:30:18 +08:00
|
|
|
fn inc_signal_observed(sig: Signal) {
|
2023-04-09 20:27:25 +08:00
|
|
|
if let Some(sig) = OBSERVED_SIGNALS.get(usize::from(sig)) {
|
2023-03-21 04:30:18 +08:00
|
|
|
sig.fetch_add(1, Ordering::Relaxed);
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-21 04:30:18 +08:00
|
|
|
fn dec_signal_observed(sig: Signal) {
|
2023-04-09 20:27:25 +08:00
|
|
|
if let Some(sig) = OBSERVED_SIGNALS.get(usize::from(sig)) {
|
2023-03-21 04:30:18 +08:00
|
|
|
sig.fetch_sub(1, Ordering::Relaxed);
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns whether an event listener is registered for the given signal. This is safe to call from
|
|
|
|
/// a signal handler.
|
2023-04-09 20:27:25 +08:00
|
|
|
pub fn is_signal_observed(sig: libc::c_int) -> bool {
|
2023-02-12 04:31:08 +08:00
|
|
|
// We are in a signal handler!
|
|
|
|
OBSERVED_SIGNALS
|
2023-04-09 20:27:25 +08:00
|
|
|
.get(usize::try_from(sig).unwrap())
|
2023-02-12 04:31:08 +08:00
|
|
|
.map_or(false, |s| s.load(Ordering::Relaxed) > 0)
|
|
|
|
}
|
|
|
|
|
2023-10-09 05:10:05 +08:00
|
|
|
pub fn get_desc(parser: &Parser, evt: &Event) -> WString {
|
2023-07-16 02:59:08 +08:00
|
|
|
let s = match &evt.desc {
|
|
|
|
EventDescription::Signal { signal } => {
|
2023-03-21 04:30:18 +08:00
|
|
|
format!("signal handler for {} ({})", signal.name(), signal.desc(),)
|
|
|
|
}
|
2023-07-16 02:59:08 +08:00
|
|
|
EventDescription::Variable { name } => format!("handler for variable '{name}'"),
|
|
|
|
EventDescription::ProcessExit { pid } => format!("exit handler for process {pid}"),
|
|
|
|
EventDescription::JobExit { pid, .. } => {
|
2023-02-12 04:31:08 +08:00
|
|
|
if let Some(job) = parser.job_get_from_pid(*pid) {
|
2023-10-09 05:22:27 +08:00
|
|
|
format!("exit handler for job {}, '{}'", job.job_id(), job.command())
|
2023-02-12 04:31:08 +08:00
|
|
|
} else {
|
|
|
|
format!("exit handler for job with pid {pid}")
|
|
|
|
}
|
|
|
|
}
|
2023-07-16 02:59:08 +08:00
|
|
|
EventDescription::CallerExit { .. } => {
|
|
|
|
"exit handler for command substitution caller".to_string()
|
|
|
|
}
|
|
|
|
EventDescription::Generic { param } => format!("handler for generic event '{param}'"),
|
|
|
|
EventDescription::Any => unreachable!(),
|
2023-02-12 04:31:08 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
WString::from_str(&s)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Add an event handler.
|
|
|
|
pub fn add_handler(eh: EventHandler) {
|
2023-07-16 02:59:08 +08:00
|
|
|
if let EventDescription::Signal { signal } = eh.desc {
|
2023-05-01 06:40:06 +08:00
|
|
|
signal_handle(signal);
|
2023-02-12 04:31:08 +08:00
|
|
|
inc_signal_observed(signal);
|
|
|
|
}
|
|
|
|
|
|
|
|
EVENT_HANDLERS
|
|
|
|
.lock()
|
|
|
|
.expect("event handler list should not be poisoned")
|
|
|
|
.push(Arc::new(eh));
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Remove handlers where `pred` returns true. Simultaneously update our `signal_observed` array.
|
|
|
|
fn remove_handlers_if(pred: impl Fn(&EventHandler) -> bool) -> usize {
|
|
|
|
let mut handlers = EVENT_HANDLERS
|
|
|
|
.lock()
|
|
|
|
.expect("event handler list should not be poisoned");
|
|
|
|
|
|
|
|
let mut removed = 0;
|
|
|
|
for i in (0..handlers.len()).rev() {
|
|
|
|
let handler = &handlers[i];
|
|
|
|
if pred(handler) {
|
|
|
|
handler.removed.store(true, Ordering::Relaxed);
|
2023-07-16 02:59:08 +08:00
|
|
|
if let EventDescription::Signal { signal } = handler.desc {
|
2023-02-12 04:31:08 +08:00
|
|
|
dec_signal_observed(signal);
|
|
|
|
}
|
|
|
|
handlers.remove(i);
|
|
|
|
removed += 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
removed
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Remove all events for the given function name.
|
|
|
|
pub fn remove_function_handlers(name: &wstr) -> usize {
|
|
|
|
remove_handlers_if(|h| h.function_name == name)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return all event handlers for the given function.
|
|
|
|
pub fn get_function_handlers(name: &wstr) -> EventHandlerList {
|
|
|
|
EVENT_HANDLERS
|
|
|
|
.lock()
|
|
|
|
.expect("event handler list should not be poisoned")
|
|
|
|
.iter()
|
|
|
|
.filter(|h| h.function_name == name)
|
|
|
|
.cloned()
|
|
|
|
.collect()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Perform the specified event. Since almost all event firings will not be matched by even a single
|
|
|
|
/// event handler, we make sure to optimize the 'no matches' path. This means that nothing is
|
|
|
|
/// allocated/initialized unless needed.
|
2023-10-09 05:22:27 +08:00
|
|
|
fn fire_internal(parser: &Parser, event: &Event) {
|
2023-02-12 04:31:08 +08:00
|
|
|
assert!(
|
2023-10-09 05:22:27 +08:00
|
|
|
parser.libdata().pods.is_event >= 0,
|
2023-02-12 04:31:08 +08:00
|
|
|
"is_event should not be negative"
|
|
|
|
);
|
|
|
|
|
|
|
|
// Suppress fish_trace during events.
|
2023-10-09 05:22:27 +08:00
|
|
|
let is_event = parser.libdata().pods.is_event;
|
|
|
|
let _inc_event = scoped_push_replacer(
|
|
|
|
|new_value| std::mem::replace(&mut parser.libdata_mut().pods.is_event, new_value),
|
2023-04-09 19:58:47 +08:00
|
|
|
is_event + 1,
|
|
|
|
);
|
2023-10-09 05:22:27 +08:00
|
|
|
let _suppress_trace = scoped_push_replacer(
|
|
|
|
|new_value| {
|
|
|
|
std::mem::replace(
|
|
|
|
&mut parser.libdata_mut().pods.suppress_fish_trace,
|
|
|
|
new_value,
|
|
|
|
)
|
|
|
|
},
|
2023-04-09 19:58:47 +08:00
|
|
|
true,
|
|
|
|
);
|
2023-02-12 04:31:08 +08:00
|
|
|
|
|
|
|
// Capture the event handlers that match this event.
|
|
|
|
let fire: Vec<_> = EVENT_HANDLERS
|
|
|
|
.lock()
|
|
|
|
.expect("event handler list should not be poisoned")
|
|
|
|
.iter()
|
|
|
|
.filter(|h| h.matches(event))
|
|
|
|
.cloned()
|
|
|
|
.collect();
|
|
|
|
|
|
|
|
// Iterate over our list of matching events. Fire the ones that are still present.
|
|
|
|
let mut fired_one_shot = false;
|
|
|
|
for handler in fire {
|
|
|
|
// A previous handler may have erased this one.
|
|
|
|
if handler.removed.load(Ordering::Relaxed) {
|
|
|
|
continue;
|
|
|
|
};
|
|
|
|
|
|
|
|
// Construct a buffer to evaluate, starting with the function name and then all the
|
|
|
|
// arguments.
|
|
|
|
let mut buffer = handler.function_name.clone();
|
|
|
|
for arg in &event.arguments {
|
|
|
|
buffer.push(' ');
|
2023-10-09 05:22:27 +08:00
|
|
|
buffer.push_utfstr(&escape(arg));
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Event handlers are not part of the main flow of code, so they are marked as
|
|
|
|
// non-interactive.
|
2023-03-13 04:26:19 +08:00
|
|
|
let saved_is_interactive =
|
2023-10-09 05:22:27 +08:00
|
|
|
std::mem::replace(&mut parser.libdata_mut().pods.is_interactive, false);
|
|
|
|
let saved_statuses = parser.get_last_statuses();
|
|
|
|
let _cleanup = ScopeGuard::new((), |()| {
|
|
|
|
parser.set_last_statuses(saved_statuses);
|
|
|
|
parser.libdata_mut().pods.is_interactive = saved_is_interactive;
|
2023-03-13 04:26:19 +08:00
|
|
|
});
|
2023-02-12 04:31:08 +08:00
|
|
|
|
|
|
|
FLOG!(
|
|
|
|
event,
|
|
|
|
"Firing event '",
|
2023-07-16 02:59:08 +08:00
|
|
|
event.desc.str_param1().unwrap_or(L!("")),
|
2023-02-12 04:31:08 +08:00
|
|
|
"' to handler '",
|
|
|
|
handler.function_name,
|
|
|
|
"'"
|
|
|
|
);
|
|
|
|
|
2023-10-09 05:22:27 +08:00
|
|
|
let b = parser.push_block(Block::event_block(event.clone()));
|
|
|
|
parser.eval(&buffer, &IoChain::new());
|
|
|
|
parser.pop_block(b);
|
2023-02-12 04:31:08 +08:00
|
|
|
|
|
|
|
handler.fired.store(true, Ordering::Relaxed);
|
|
|
|
fired_one_shot |= handler.is_one_shot();
|
|
|
|
}
|
|
|
|
|
|
|
|
if fired_one_shot {
|
|
|
|
remove_handlers_if(|h| h.fired.load(Ordering::Relaxed) && h.is_one_shot());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Fire all delayed events attached to the given parser.
|
2023-10-09 05:22:27 +08:00
|
|
|
pub fn fire_delayed(parser: &Parser) {
|
|
|
|
{
|
|
|
|
let ld = &parser.libdata().pods;
|
|
|
|
|
|
|
|
// Do not invoke new event handlers from within event handlers.
|
|
|
|
if ld.is_event != 0 {
|
|
|
|
return;
|
|
|
|
};
|
|
|
|
}
|
2023-02-12 04:31:08 +08:00
|
|
|
|
|
|
|
// Do not invoke new event handlers if we are unwinding (#6649).
|
2023-05-01 06:40:06 +08:00
|
|
|
if signal_check_cancel() != 0 {
|
2023-02-12 04:31:08 +08:00
|
|
|
return;
|
|
|
|
};
|
|
|
|
|
|
|
|
// We unfortunately can't keep this locked until we're done with it because the SIGWINCH handler
|
|
|
|
// code might call back into here and we would delay processing of the events, leading to a test
|
2023-10-09 05:22:27 +08:00
|
|
|
// failure under CI.
|
2023-02-12 04:31:08 +08:00
|
|
|
let mut to_send = std::mem::take(&mut *BLOCKED_EVENTS.lock().expect("Mutex poisoned!"));
|
|
|
|
|
|
|
|
// Append all signal events to to_send.
|
2023-03-13 07:58:22 +08:00
|
|
|
// 'signals' contains a bit set for each signal that has been received.
|
|
|
|
let mut signals: u64 = PENDING_SIGNALS.acquire_pending();
|
|
|
|
while signals != 0 {
|
2023-03-21 04:30:18 +08:00
|
|
|
let sig = signals.trailing_zeros() as i32;
|
2023-03-13 07:58:22 +08:00
|
|
|
signals &= !(1_u64 << sig);
|
2023-03-21 04:30:18 +08:00
|
|
|
let sig = Signal::new(sig);
|
2023-03-13 07:58:22 +08:00
|
|
|
|
2023-02-12 04:31:08 +08:00
|
|
|
// HACK: The only variables we change in response to a *signal* are $COLUMNS and $LINES.
|
|
|
|
// Do that now.
|
2023-05-01 03:38:06 +08:00
|
|
|
if sig == libc::SIGWINCH {
|
2023-03-20 06:50:33 +08:00
|
|
|
termsize::SHARED_CONTAINER.updating(parser);
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
|
|
|
let event = Event {
|
2023-07-16 02:59:08 +08:00
|
|
|
desc: EventDescription::Signal { signal: sig },
|
2023-03-21 04:30:18 +08:00
|
|
|
arguments: vec![sig.name().into()],
|
2023-02-12 04:31:08 +08:00
|
|
|
};
|
|
|
|
to_send.push(event);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Fire or re-block all events. Don't obtain BLOCKED_EVENTS until we know that we have at least
|
|
|
|
// one event that is blocked.
|
|
|
|
let mut blocked_events = None;
|
|
|
|
for event in to_send {
|
|
|
|
if event.is_blocked(parser) {
|
|
|
|
if blocked_events.is_none() {
|
2023-11-19 00:51:52 +08:00
|
|
|
blocked_events = Some(BLOCKED_EVENTS.lock().expect("Mutex poisoned"));
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
|
|
|
blocked_events.as_mut().unwrap().push(event);
|
|
|
|
} else {
|
|
|
|
// fire_internal() does not access BLOCKED_EVENTS so this call can't deadlock.
|
|
|
|
fire_internal(parser, &event);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Enqueue a signal event. Invoked from a signal handler.
|
2023-04-09 20:27:25 +08:00
|
|
|
pub fn enqueue_signal(signal: libc::c_int) {
|
2023-02-12 04:31:08 +08:00
|
|
|
// Beware, we are in a signal handler
|
|
|
|
PENDING_SIGNALS.mark(signal);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Fire the specified event event, executing it on `parser`.
|
2023-10-09 05:22:27 +08:00
|
|
|
pub fn fire(parser: &Parser, event: Event) {
|
2023-02-12 04:31:08 +08:00
|
|
|
// Fire events triggered by signals.
|
|
|
|
fire_delayed(parser);
|
|
|
|
|
|
|
|
if event.is_blocked(parser) {
|
|
|
|
BLOCKED_EVENTS.lock().expect("Mutex poisoned!").push(event);
|
|
|
|
} else {
|
|
|
|
fire_internal(parser, &event);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-09 23:13:19 +08:00
|
|
|
pub const EVENT_FILTER_NAMES: [&wstr; 7] = [
|
2024-01-13 02:10:56 +08:00
|
|
|
L!("signal"),
|
|
|
|
L!("variable"),
|
|
|
|
L!("exit"),
|
|
|
|
L!("process-exit"),
|
|
|
|
L!("job-exit"),
|
|
|
|
L!("caller-exit"),
|
|
|
|
L!("generic"),
|
2023-02-12 04:31:08 +08:00
|
|
|
];
|
|
|
|
|
|
|
|
/// Print all events. If type_filter is not empty, only output events with that type.
|
2023-10-09 05:10:05 +08:00
|
|
|
pub fn print(streams: &mut IoStreams, type_filter: &wstr) {
|
2023-02-12 04:31:08 +08:00
|
|
|
let mut tmp = EVENT_HANDLERS
|
|
|
|
.lock()
|
|
|
|
.expect("event handler list should not be poisoned")
|
|
|
|
.clone();
|
|
|
|
|
2023-07-16 02:59:08 +08:00
|
|
|
tmp.sort_by(|e1, e2| e1.desc.cmp(&e2.desc));
|
2023-02-12 04:31:08 +08:00
|
|
|
|
2023-08-11 00:42:11 +08:00
|
|
|
let mut last_type = std::mem::discriminant(&EventDescription::Any);
|
2023-02-12 04:31:08 +08:00
|
|
|
for evt in tmp {
|
|
|
|
// If we have a filter, skip events that don't match.
|
2023-07-16 02:59:08 +08:00
|
|
|
if !evt.desc.matches_filter(type_filter) {
|
2023-02-12 04:31:08 +08:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2023-08-11 00:42:11 +08:00
|
|
|
// Print a "Event $TYPE" header for each event type.
|
|
|
|
// This compares only the event *type*, not the entire event,
|
|
|
|
// so we don't compare variable events for different variables as different.
|
|
|
|
//
|
|
|
|
// This assumes EventDescription::Any is not a valid value for an event to have
|
|
|
|
// - it's marked "unreachable!()" below!
|
|
|
|
if last_type != std::mem::discriminant(&evt.desc) {
|
|
|
|
if last_type != std::mem::discriminant(&EventDescription::Any) {
|
2023-02-12 04:31:08 +08:00
|
|
|
streams.out.append(L!("\n"));
|
|
|
|
}
|
|
|
|
|
2023-08-11 00:42:11 +08:00
|
|
|
last_type = std::mem::discriminant(&evt.desc);
|
2024-01-07 08:49:58 +08:00
|
|
|
streams.out.append(sprintf!("Event %ls\n", evt.desc.name()));
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
|
|
|
|
2023-07-16 02:59:08 +08:00
|
|
|
match &evt.desc {
|
|
|
|
EventDescription::Signal { signal } => {
|
2023-03-21 04:30:18 +08:00
|
|
|
let name: WString = signal.name().into();
|
|
|
|
streams
|
|
|
|
.out
|
2024-01-07 08:49:58 +08:00
|
|
|
.append(sprintf!("%ls %ls\n", name, evt.function_name));
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
2023-07-16 02:59:08 +08:00
|
|
|
EventDescription::ProcessExit { .. } | EventDescription::JobExit { .. } => {}
|
|
|
|
EventDescription::CallerExit { .. } => {
|
2023-02-12 04:31:08 +08:00
|
|
|
streams
|
|
|
|
.out
|
2024-01-07 08:49:58 +08:00
|
|
|
.append(sprintf!("caller-exit %ls\n", evt.function_name));
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
2023-07-16 02:59:08 +08:00
|
|
|
EventDescription::Variable { name: param } | EventDescription::Generic { param } => {
|
2023-02-12 04:31:08 +08:00
|
|
|
streams
|
|
|
|
.out
|
2024-01-07 08:49:58 +08:00
|
|
|
.append(sprintf!("%ls %ls\n", param, evt.function_name));
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
2023-07-16 02:59:08 +08:00
|
|
|
EventDescription::Any => unreachable!(),
|
2023-02-12 04:31:08 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Fire a generic event with the specified name.
|
2023-10-09 05:22:27 +08:00
|
|
|
pub fn fire_generic(parser: &Parser, name: WString, arguments: Vec<WString>) {
|
2023-02-12 04:31:08 +08:00
|
|
|
fire(
|
|
|
|
parser,
|
|
|
|
Event {
|
2023-07-16 02:59:08 +08:00
|
|
|
desc: EventDescription::Generic { param: name },
|
2023-02-12 04:31:08 +08:00
|
|
|
arguments,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
}
|