use std::sync::Arc;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{kind} at offset {pos}")]
pub struct QuoteError {
pub pos: usize,
pub kind: QuoteErrorKind,
}
impl QuoteError {
pub(crate) fn new(pos: usize, kind: QuoteErrorKind) -> Self {
QuoteError { pos, kind }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum QuoteErrorKind {
#[error("unterminated single quote")]
UnterminatedSingleQuote,
#[error("unterminated double quote")]
UnterminatedDoubleQuote,
#[error("trailing backslash")]
TrailingBackslash,
#[error("not valid UTF-8")]
NonUtf8,
#[error("character cannot be represented in this grammar")]
UnrepresentableChar,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ElevationErrorKind {
#[error("no usable elevation backend is available")]
BackendUnavailable,
#[error("elevation authentication failed")]
AuthFailed,
#[error("elevation prompt was declined")]
AuthDeclined,
#[error("no controlling terminal for interactive elevation")]
NoTty,
#[error("could not signal or stop an elevated child")]
Unkillable,
#[error("elevated child launched but could not be tracked")]
Untracked,
#[error("the elevation command is too long for this host")]
CommandTooLong,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum RecordErrorKind {
#[error("unknown record format version")]
UnknownVersion,
#[error("the record was written on a different platform")]
ForeignPlatform,
#[error("the record's pid cannot name a single process")]
InvalidPid,
#[error("the record was written in a different boot session")]
ForeignBootSession,
#[error("the record carries no boot session identifier")]
MissingBootSession,
#[error("the record was written in a different pid namespace")]
ForeignPidNamespace,
#[error("the record carries no pid namespace identifier")]
MissingPidNamespace,
#[error("the record's token is of another kind than this host's")]
ForeignTokenKind,
#[error("the record carries no kind of token")]
MissingTokenKind,
#[error("this host's boot session could not be read")]
ScopeUnreadable,
}
#[derive(Debug, Clone)]
pub struct Failures {
members: Box<[Arc<Error>]>,
}
impl Failures {
pub(crate) fn new(first: Arc<Error>, rest: impl IntoIterator<Item = Arc<Error>>) -> Failures {
Failures {
members: std::iter::once(first).chain(rest).collect(),
}
}
pub(crate) fn collect(members: impl IntoIterator<Item = Arc<Error>>) -> Option<Failures> {
let mut members = members.into_iter();
let first = members.next()?;
Some(Failures::new(first, members))
}
pub fn first(&self) -> &Arc<Error> {
&self.members[0]
}
pub fn iter(&self) -> std::slice::Iter<'_, Arc<Error>> {
self.members.iter()
}
pub(crate) fn merged(first: Option<Failures>, second: Option<Failures>) -> Option<Failures> {
match (first, second) {
(Some(first), Some(second)) => Some(first.extended(second.members.into_vec())),
(first, None) => first,
(None, second) => second,
}
}
fn extended(self, more: impl IntoIterator<Item = Arc<Error>>) -> Failures {
Failures {
members: self.members.into_vec().into_iter().chain(more).collect(),
}
}
pub(crate) fn into_cause(self) -> Arc<Error> {
if self.members.len() == 1 {
return self.members.into_vec().remove(0);
}
Arc::new(Error::Several(self))
}
}
#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
Quote(QuoteError),
Io(std::io::Error),
Unsupported {
op: String,
platform: &'static str,
detail: String,
source: Option<Arc<Error>>,
},
Containment {
detail: String,
source: Option<Arc<Error>>,
},
NoConsole {
detail: String,
},
Elevation {
kind: ElevationErrorKind,
detail: String,
source: Option<Arc<Error>>,
},
Unassessable {
detail: String,
source: Option<Arc<Error>>,
},
MembersLeft {
members: Failures,
others: Option<Arc<Error>>,
},
MemberNotKilled {
pid: u32,
source: Arc<Error>,
},
Several(Failures),
NotThreadGroupLeader {
pid: u32,
detail: String,
source: Arc<Error>,
},
IdentityRecord {
kind: RecordErrorKind,
detail: String,
source: Option<Arc<Error>>,
},
MayHaveStarted {
fate: ChildFate,
wrapper_elevated: bool,
detail: Option<String>,
source: Arc<Error>,
unreaped: Option<Box<crate::Unreaped>>,
cleanup: Option<Failures>,
},
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::Quote(_) => f.write_str("argument parsing failed"),
Error::Io(_) => f.write_str("an I/O operation failed"),
Error::Unsupported {
op, platform, detail, ..
} => write!(f, "{op} is not supported on {platform}: {detail}"),
Error::Containment { detail, .. } => write!(f, "process containment failed: {detail}"),
Error::NoConsole { detail } => {
write!(f, "no attached console for the graceful console-group signal: {detail}")
}
Error::Elevation { kind, detail, .. } => write!(f, "elevation failed ({kind}): {detail}"),
Error::Unassessable { detail, .. } => {
write!(f, "could not determine the target process's state: {detail}")
}
Error::MembersLeft { members, .. } => match members.iter().len() {
1 => f.write_str("1 member of the tree was left running"),
n => write!(f, "{n} members of the tree were left running"),
},
Error::MemberNotKilled { pid, .. } => write!(f, "pid {pid} was not killed"),
Error::Several(failures) => write!(f, "{} failures", failures.iter().len()),
Error::NotThreadGroupLeader { pid, detail, .. } => {
write!(f, "pid {pid} names a live thread, not a thread-group leader; {detail}")
}
Error::IdentityRecord { kind, detail, .. } => {
write!(f, "persisted process identity is not usable here ({kind}): {detail}")
}
Error::MayHaveStarted {
fate,
wrapper_elevated,
detail,
cleanup,
..
} => {
write!(
f,
"the program may have started, and {fate}{}",
elevated_note(fate, *wrapper_elevated)
)?;
if let Some(detail) = detail {
write!(f, "; {detail}")?;
}
match cleanup.as_ref().map(|failures| failures.iter().len()) {
None => Ok(()),
Some(1) => f.write_str("; its teardown failed too (1 failure, in `cleanup`)"),
Some(n) => write!(f, "; its teardown failed too ({n} failures, in `cleanup`)"),
}
}
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Quote(e) => Some(e),
Error::Io(e) => Some(e),
Error::Unsupported { source, .. }
| Error::Containment { source, .. }
| Error::Elevation { source, .. }
| Error::Unassessable { source, .. }
| Error::IdentityRecord { source, .. } => source.as_deref().map(|source| source as _),
Error::NoConsole { .. } => None,
Error::MemberNotKilled { source, .. }
| Error::NotThreadGroupLeader { source, .. }
| Error::MayHaveStarted { source, .. } => Some(&**source),
Error::MembersLeft { members: failures, .. } | Error::Several(failures) => Some(&**failures.first()),
}
}
}
impl From<QuoteError> for Error {
fn from(e: QuoteError) -> Error {
Error::Quote(e)
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Error {
Error::Io(e)
}
}
impl Error {
pub(crate) fn failures(&self) -> Option<&Failures> {
match self {
Error::Several(failures) | Error::MembersLeft { members: failures, .. } => Some(failures),
Error::MayHaveStarted { cleanup, .. } => cleanup.as_ref(),
_ => None,
}
}
pub(crate) fn members_left(members: Failures, others: Option<Arc<Error>>) -> Error {
debug_assert!(
members
.iter()
.all(|member| matches!(**member, Error::MemberNotKilled { .. })),
"every member of a MembersLeft is a MemberNotKilled: {members:?}"
);
Error::MembersLeft { members, others }
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChildFate {
Reaped,
Killed,
Running { id: Option<crate::identity::ProcessId> },
Gone,
Unknown,
}
impl ChildFate {
pub(crate) fn not_running(&self) -> bool {
matches!(self, ChildFate::Reaped | ChildFate::Killed | ChildFate::Gone)
}
}
impl std::fmt::Display for ChildFate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ChildFate::Reaped => f.write_str("its child was reaped"),
ChildFate::Killed => f.write_str("its child was killed, its exit not collected"),
ChildFate::Running { id: Some(id) } => write!(f, "its child, pid {}, may still be running", id.pid()),
ChildFate::Running { id: None } => f.write_str("its child may still be running"),
ChildFate::Gone => f.write_str("its child had been reaped by someone else"),
ChildFate::Unknown => f.write_str("what became of its child is unknown"),
}
}
}
fn elevated_note(fate: &ChildFate, wrapper_elevated: bool) -> &'static str {
match fate {
ChildFate::Reaped | ChildFate::Killed | ChildFate::Gone if wrapper_elevated => {
" (an elevated program behind it may still run)"
}
_ => "",
}
}
pub(crate) fn io_context(context: impl Into<String>, source: std::io::Error) -> std::io::Error {
std::io::Error::new(
source.kind(),
IoContext {
context: context.into(),
source: IoContextSource::Io(source),
},
)
}
#[cfg(target_os = "linux")]
pub(crate) fn io_context_over(context: impl Into<String>, cause: Error) -> std::io::Error {
match cause {
Error::Io(source) => io_context(context, source),
cause => std::io::Error::other(IoContext {
context: context.into(),
source: IoContextSource::Cosca(cause),
}),
}
}
#[cfg(target_os = "linux")]
pub(crate) fn io_context_or_other(context: impl Into<String>, cause: Option<std::io::Error>) -> std::io::Error {
match cause {
Some(cause) => io_context(context, cause),
None => std::io::Error::other(context.into()),
}
}
#[cfg(windows)]
pub(crate) fn win32_io_error(e: windows::core::Error) -> std::io::Error {
let code = e.code().0 as u32;
if code & 0xFFFF_0000 == 0x8007_0000 {
std::io::Error::from_raw_os_error((code & 0xFFFF) as i32)
} else {
std::io::Error::from_raw_os_error(code as i32)
}
}
#[cfg(windows)]
pub(crate) fn nt_io_error(status: windows::Win32::Foundation::NTSTATUS) -> std::io::Error {
let code = unsafe { windows::Win32::Foundation::RtlNtStatusToDosError(status) };
if code == windows::Win32::Foundation::ERROR_MR_MID_NOT_FOUND.0 {
log::debug!("NTSTATUS {:#010x} has no Win32 code", status.0 as u32);
}
std::io::Error::from_raw_os_error(code as i32)
}
pub(crate) fn chain<'a>(
error: &'a (dyn std::error::Error + 'static),
) -> impl Iterator<Item = &'a (dyn std::error::Error + 'static)> {
std::iter::successors(Some(error), |e| e.source())
}
#[cfg(any(target_os = "macos", target_os = "linux", test))]
pub(crate) fn first_os_code(error: &(dyn std::error::Error + 'static)) -> Option<i32> {
chain(error)
.filter_map(|layer| layer.downcast_ref::<std::io::Error>())
.find_map(std::io::Error::raw_os_error)
}
fn cosca_error<'a>(layer: &'a (dyn std::error::Error + 'static)) -> Option<&'a Error> {
layer
.downcast_ref::<Error>()
.or_else(|| layer.downcast_ref::<Arc<Error>>().map(|held| &**held))
}
#[derive(Debug)]
pub struct Report<'a>(pub(crate) &'a (dyn std::error::Error + 'static));
impl<'a> Report<'a> {
pub fn new(error: &'a (dyn std::error::Error + 'static)) -> Self {
Report(error)
}
fn write(
error: &(dyn std::error::Error + 'static),
nested: bool,
f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
for (i, layer) in chain(error).enumerate() {
if i > 0 {
f.write_str(": ")?;
}
write!(f, "{layer}")?;
let own = cosca_error(layer);
if let Some(Error::MayHaveStarted {
source,
cleanup: Some(cleanup),
..
}) = own
{
f.write_str(if nested { ": [" } else { ": " })?;
Report::write(&**source, true, f)?;
f.write_str("; cleanup: [")?;
Report::write_members(cleanup, f)?;
return f.write_str(if nested { "]]" } else { "]" });
}
let Some(failures) = own.and_then(Error::failures) else {
continue;
};
f.write_str(if nested { ": [" } else { ": " })?;
Report::write_members(failures, f)?;
if let Some(Error::MembersLeft {
others: Some(others), ..
}) = own
{
f.write_str("; others: ")?;
Report::write(&**others, true, f)?;
}
return f.write_str(if nested { "]" } else { "" });
}
Ok(())
}
fn write_members(failures: &Failures, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for (n, member) in failures.iter().enumerate() {
if n > 0 {
f.write_str("; ")?;
}
write!(f, "({}) ", n + 1)?;
Report::write(&**member, true, f)?;
}
Ok(())
}
}
impl std::fmt::Display for Report<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Report::write(self.0, false, f)
}
}
#[cfg(test)]
pub(crate) fn said(error: &(dyn std::error::Error + 'static)) -> String {
Report::new(error).to_string()
}
#[cfg(all(test, target_os = "linux"))]
pub(crate) fn several_in<'a>(error: &'a (dyn std::error::Error + 'static)) -> Option<Vec<&'a Error>> {
chain(error).find_map(|layer| match cosca_error(layer)? {
Error::Several(list) => Some(list.iter().map(|member| &**member).collect()),
_ => None,
})
}
#[cfg(test)]
pub(crate) fn io_said(cause: impl std::fmt::Display) -> String {
said(&Error::Io(std::io::Error::other(cause.to_string())))
}
#[derive(Debug)]
struct IoContext {
context: String,
source: IoContextSource,
}
#[derive(Debug)]
enum IoContextSource {
Io(std::io::Error),
#[cfg(target_os = "linux")]
Cosca(Error),
}
impl std::fmt::Display for IoContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.context)
}
}
impl std::error::Error for IoContext {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(match &self.source {
IoContextSource::Io(source) => source as &(dyn std::error::Error + 'static),
#[cfg(target_os = "linux")]
IoContextSource::Cosca(source) => source,
})
}
}
pub(crate) fn shared_io(e: &Arc<std::io::Error>) -> std::io::Error {
match e.raw_os_error() {
Some(code) => std::io::Error::from_raw_os_error(code),
None => std::io::Error::new(e.kind(), Arc::clone(e)),
}
}
#[cfg(unix)]
pub(crate) fn shared_io_cause(e: &Arc<std::io::Error>) -> Arc<Error> {
Error::io_cause(shared_io(e))
}
impl Error {
#[cfg(unix)]
pub(crate) fn of_member(pid: u32, words: &str, cause: Error, unassessed: bool) -> Error {
let (detail, source) = (format!("pid {pid}: {words}"), Some(Arc::new(cause)));
if unassessed {
Error::Unassessable { detail, source }
} else {
Error::Containment { detail, source }
}
}
#[cfg(windows)]
pub(crate) fn terminate_unsupported() -> Error {
Error::Unsupported {
op: "graceful terminate (SIGTERM-equivalent)".into(),
platform: "windows",
detail: "Windows has no per-process graceful-termination signal; for a contained \
child use graceful_shutdown_tree (CTRL_BREAK to the group)"
.into(),
source: None,
}
}
pub(crate) fn io_cause(e: std::io::Error) -> Arc<Error> {
Arc::new(Error::Io(e))
}
pub(crate) fn in_step(self, step: &str) -> Error {
match self {
Error::Io(e) => Error::Io(io_context(step, e)),
other => other,
}
}
pub fn fate(&self) -> Option<ChildFate> {
match self {
Error::MayHaveStarted { fate, .. } => Some(*fate),
_ => None,
}
}
#[cfg(test)]
pub(crate) fn left_members(&self) -> Vec<&Error> {
match self {
Error::MembersLeft { members, others } => members
.iter()
.map(|member| &**member)
.chain(others.as_deref())
.collect(),
other => vec![other],
}
}
#[cfg(test)]
pub(crate) fn failures_below(&self) -> Vec<&Error> {
match std::error::Error::source(self).and_then(cosca_error) {
Some(Error::Several(list)) => list.iter().map(|member| &**member).collect(),
Some(cause) => vec![cause],
None => Vec::new(),
}
}
pub(crate) fn joined_cause(own: Option<Arc<Error>>, peers: impl IntoIterator<Item = Arc<Error>>) -> Arc<Error> {
Failures::collect(own.into_iter().chain(peers).flat_map(Error::spliced))
.expect("a cause or a peer")
.into_cause()
}
fn spliced(error: Arc<Error>) -> Vec<Arc<Error>> {
match &*error {
Error::Several(list) => list.iter().cloned().collect(),
_ => vec![error],
}
}
pub(crate) fn with_peers(self, peers: impl IntoIterator<Item = Arc<Error>>) -> Error {
let mut peers = peers.into_iter().peekable();
if peers.peek().is_none() {
return self;
}
let joined = Error::joined_cause;
match self {
Error::Unsupported {
op,
platform,
detail,
source,
} => Error::Unsupported {
op,
platform,
detail,
source: Some(joined(source, peers)),
},
Error::Containment { detail, source } => Error::Containment {
detail,
source: Some(joined(source, peers)),
},
Error::Elevation { kind, detail, source } => Error::Elevation {
kind,
detail,
source: Some(joined(source, peers)),
},
Error::Unassessable { detail, source } => Error::Unassessable {
detail,
source: Some(joined(source, peers)),
},
Error::IdentityRecord { kind, detail, source } => Error::IdentityRecord {
kind,
detail,
source: Some(joined(source, peers)),
},
Error::MemberNotKilled { pid, source } => Error::MemberNotKilled {
pid,
source: joined(Some(source), peers),
},
Error::NotThreadGroupLeader { pid, detail, source } => Error::NotThreadGroupLeader {
pid,
detail,
source: joined(Some(source), peers),
},
Error::MayHaveStarted {
fate,
wrapper_elevated,
detail,
source,
unreaped,
cleanup,
} => Error::MayHaveStarted {
fate,
wrapper_elevated,
detail,
source: joined(Some(source), peers),
unreaped,
cleanup,
},
Error::Several(list) => Error::Several(list.extended(peers.flat_map(Error::spliced))),
Error::MembersLeft { members, others } => {
let own = match others {
None => Vec::new(),
Some(one) => match &*one {
Error::Several(list) => list.iter().cloned().collect(),
_ => vec![one],
},
};
Error::MembersLeft {
members,
others: Some(
Failures::collect(peers.flat_map(Error::spliced).chain(own))
.expect("a peer")
.into_cause(),
),
}
}
leaf @ (Error::Io(_) | Error::Quote(_) | Error::NoConsole { .. }) => {
debug_assert!(
false,
"a leaf has no cause to hold peers, so a site that can have them returns a variant that has \
one: {}",
Report(&leaf)
);
leaf
}
}
}
pub(crate) fn with_peers_or_unassessable(
self,
detail: impl FnOnce() -> String,
own: Option<Arc<Error>>,
peers: impl IntoIterator<Item = Arc<Error>>,
) -> Error {
match self {
io @ Error::Io(_) => Error::Unassessable {
detail: detail(),
source: own,
}
.with_peers(std::iter::once(Arc::new(io)).chain(peers)),
other => other.with_peers(peers.into_iter().chain(own)),
}
}
fn has_slot(&self) -> bool {
!matches!(self, Error::Io(_) | Error::Quote(_) | Error::NoConsole { .. })
}
pub(crate) fn with_peers_or_warn(self, call: &str, peers: impl IntoIterator<Item = Error>) -> Error {
let peers = peers.into_iter();
if self.has_slot() {
return self.with_peers(peers.map(Arc::new));
}
for peer in peers {
log::warn!(
"{call}: another failure of the call is not in its error, which has no place for it: {report}",
report = Report(&peer)
);
}
self
}
pub(crate) fn into_io(self) -> std::io::Error {
match self {
Error::Io(e) => e,
other => std::io::Error::other(other),
}
}
#[cfg(target_os = "linux")]
pub(crate) fn into_io_over(self, context: &str) -> std::io::Error {
match self {
Error::Io(e) => e,
other => io_context_over(context, other),
}
}
#[cfg(test)]
pub(crate) fn io_errors(&self) -> impl Iterator<Item = &std::io::Error> {
chain(self).filter_map(|s| s.downcast_ref::<std::io::Error>())
}
pub(crate) fn with_note(self, note: &str) -> Error {
let append = |detail: String| format!("{detail}; {note}");
match self {
Error::Io(source) => Error::Io(io_context(note, source)),
Error::Unsupported {
op,
platform,
detail,
source,
} => Error::Unsupported {
op,
platform,
detail: append(detail),
source,
},
Error::Containment { detail, source } => Error::Containment {
detail: append(detail),
source,
},
Error::NoConsole { detail } => Error::NoConsole { detail: append(detail) },
Error::Elevation { kind, detail, source } => Error::Elevation {
kind,
detail: append(detail),
source,
},
Error::Unassessable { detail, source } => Error::Unassessable {
detail: append(detail),
source,
},
compound @ (Error::MemberNotKilled { .. } | Error::MembersLeft { .. } | Error::Several(_)) => {
debug_assert!(
false,
"a note goes in the site's own variant, never to a compound error: {}",
Report(&compound)
);
compound
}
Error::NotThreadGroupLeader { pid, detail, source } => Error::NotThreadGroupLeader {
pid,
detail: append(detail),
source,
},
Error::IdentityRecord { kind, detail, source } => Error::IdentityRecord {
kind,
detail: append(detail),
source,
},
Error::MayHaveStarted {
fate,
wrapper_elevated,
detail,
source,
unreaped,
cleanup,
} => Error::MayHaveStarted {
fate,
wrapper_elevated,
detail: Some(detail.map_or_else(|| note.to_owned(), append)),
source,
unreaped,
cleanup,
},
Error::Quote(e) => {
debug_assert!(
false,
"a note is added only to a spawn's error, never a quoting one: {}",
Report(&e)
);
Error::Quote(e)
}
}
}
}
#[cfg(all(test, windows))]
pub(crate) fn assert_detail_is_not_hard_wrapped(detail: &str) {
assert!(
!detail.contains(" "),
"a run of two or more spaces means a hard-wrapped literal lost its `\\` continuation: {detail:?}"
);
}
#[cfg(test)]
#[path = "error_tests.rs"]
mod error_tests;