diff --git a/src/tools/clippy/clippy_lints/src/disallowed_macros.rs b/src/tools/clippy/clippy_lints/src/disallowed_macros.rs index fc6af204a74a0..fa33fef230622 100644 --- a/src/tools/clippy/clippy_lints/src/disallowed_macros.rs +++ b/src/tools/clippy/clippy_lints/src/disallowed_macros.rs @@ -1,4 +1,3 @@ - use clippy_config::Conf; use clippy_config::types::{DisallowedPath, create_disallowed_map}; use clippy_utils::diagnostics::{span_lint_and_then, span_lint_hir_and_then}; diff --git a/src/tools/miri/cargo-miri/src/arg.rs b/src/tools/miri/cargo-miri/src/arg.rs index d7216060358cb..2f9723e87c9f5 100644 --- a/src/tools/miri/cargo-miri/src/arg.rs +++ b/src/tools/miri/cargo-miri/src/arg.rs @@ -45,7 +45,7 @@ impl<'s, I: Iterator>> Iterator for ArgSplitFlagValue<'_, I> } // These branches cannot be merged if we want to avoid the allocation in the `Borrowed` branch. match &arg { - Cow::Borrowed(arg) => + Cow::Borrowed(arg) => { if let Some(suffix) = arg.strip_prefix(self.name) { // Strip leading `name`. if suffix.is_empty() { @@ -55,8 +55,9 @@ impl<'s, I: Iterator>> Iterator for ArgSplitFlagValue<'_, I> // This argument is `name=value`; get the value. return Some(Ok(Cow::Borrowed(suffix))); } - }, - Cow::Owned(arg) => + } + } + Cow::Owned(arg) => { if let Some(suffix) = arg.strip_prefix(self.name) { // Strip leading `name`. if suffix.is_empty() { @@ -67,7 +68,8 @@ impl<'s, I: Iterator>> Iterator for ArgSplitFlagValue<'_, I> // here as a `String` cannot be subsliced (what would the lifetime be?). return Some(Ok(Cow::Owned(suffix.to_owned()))); } - }, + } + } } Some(Err(arg)) } @@ -78,11 +80,9 @@ impl<'a, I: Iterator + 'a> ArgSplitFlagValue<'a, I> { args: I, name: &'a str, ) -> impl Iterator> + 'a { - ArgSplitFlagValue::new(args.map(Cow::Owned), name).map(|x| { - match x { - Ok(s) => Ok(s.into_owned()), - Err(s) => Err(s.into_owned()), - } + ArgSplitFlagValue::new(args.map(Cow::Owned), name).map(|x| match x { + Ok(s) => Ok(s.into_owned()), + Err(s) => Err(s.into_owned()), }) } } @@ -92,12 +92,10 @@ impl<'x: 'a, 'a, I: Iterator + 'a> ArgSplitFlagValue<'a, I> { args: I, name: &'a str, ) -> impl Iterator> + 'a { - ArgSplitFlagValue::new(args.map(Cow::Borrowed), name).map(|x| { - match x { - Ok(Cow::Borrowed(s)) => Ok(s), - Err(Cow::Borrowed(s)) => Err(s), - _ => panic!("iterator converted borrowed to owned"), - } + ArgSplitFlagValue::new(args.map(Cow::Borrowed), name).map(|x| match x { + Ok(Cow::Borrowed(s)) => Ok(s), + Err(Cow::Borrowed(s)) => Err(s), + _ => panic!("iterator converted borrowed to owned"), }) } } diff --git a/src/tools/miri/cargo-miri/src/phases.rs b/src/tools/miri/cargo-miri/src/phases.rs index cb62e12413c84..79f49f4965599 100644 --- a/src/tools/miri/cargo-miri/src/phases.rs +++ b/src/tools/miri/cargo-miri/src/phases.rs @@ -85,10 +85,9 @@ pub fn phase_cargo_miri(mut args: impl Iterator) { "setup" => MiriCommand::Setup, "test" | "t" | "run" | "r" | "nextest" => MiriCommand::Forward(subcommand), "clean" => MiriCommand::Clean, - _ => - show_error!( - "`cargo miri` supports the following subcommands: `run`, `test`, `nextest`, `clean`, and `setup`." - ), + _ => show_error!( + "`cargo miri` supports the following subcommands: `run`, `test`, `nextest`, `clean`, and `setup`." + ), }; let verbose = num_arg_flag("-v"); let quiet = has_arg_flag("-q") || has_arg_flag("--quiet"); diff --git a/src/tools/miri/cargo-miri/src/setup.rs b/src/tools/miri/cargo-miri/src/setup.rs index 7afc8481009cb..deb525f0ae43d 100644 --- a/src/tools/miri/cargo-miri/src/setup.rs +++ b/src/tools/miri/cargo-miri/src/setup.rs @@ -75,10 +75,12 @@ pub fn setup( None => // No-std heuristic taken from rust/src/bootstrap/config.rs // (https://github.com/rust-lang/rust/blob/25b5af1b3a0b9e2c0c57b223b2d0e3e203869b2c/src/bootstrap/config.rs#L549-L555). + { target.contains("-none") || target.contains("nvptx") || target.contains("switch") - || target.contains("-uefi"), + || target.contains("-uefi") + } Some(val) => val != "0", }; let sysroot_config = if no_std { @@ -170,13 +172,14 @@ pub fn setup( .when_build_required(notify) .build_from_source(&rust_src); match status { - Ok(SysrootStatus::AlreadyCached) => + Ok(SysrootStatus::AlreadyCached) => { if !quiet && show_setup { eprintln!( "A sysroot for Miri is already available in `{}`.", sysroot_dir.display() ); - }, + } + } Ok(SysrootStatus::SysrootBuilt) => { // Print what `notify` prepared. eprint!("{after_build_output}"); diff --git a/src/tools/miri/src/bin/miri.rs b/src/tools/miri/src/bin/miri.rs index 8ff1c9d6ff022..7625cd5d00a83 100644 --- a/src/tools/miri/src/bin/miri.rs +++ b/src/tools/miri/src/bin/miri.rs @@ -555,12 +555,12 @@ fn main() { "abort" => miri::IsolatedOp::Reject(miri::RejectOpWith::Abort), "hide" => miri::IsolatedOp::Reject(miri::RejectOpWith::NoWarning), "warn" => miri::IsolatedOp::Reject(miri::RejectOpWith::Warning), - "warn-nobacktrace" => - miri::IsolatedOp::Reject(miri::RejectOpWith::WarningWithoutBacktrace), - _ => - show_error!( - "-Zmiri-isolation-error must be `abort`, `hide`, `warn`, or `warn-nobacktrace`" - ), + "warn-nobacktrace" => { + miri::IsolatedOp::Reject(miri::RejectOpWith::WarningWithoutBacktrace) + } + _ => show_error!( + "-Zmiri-isolation-error must be `abort`, `hide`, `warn`, or `warn-nobacktrace`" + ), }; } else if arg == "-Zmiri-ignore-leaks" { miri_config.ignore_leaks = true; diff --git a/src/tools/miri/src/borrow_tracker/mod.rs b/src/tools/miri/src/borrow_tracker/mod.rs index 9808102f4ba66..538fedc71416f 100644 --- a/src/tools/miri/src/borrow_tracker/mod.rs +++ b/src/tools/miri/src/borrow_tracker/mod.rs @@ -253,14 +253,12 @@ impl GlobalStateInner { machine: &MiriMachine<'_>, ) -> AllocState { match self.borrow_tracker_method { - BorrowTrackerMethod::StackedBorrows => - AllocState::StackedBorrows(Box::new(RefCell::new(Stacks::new_allocation( - id, alloc_size, self, kind, machine, - )))), - BorrowTrackerMethod::TreeBorrows => - AllocState::TreeBorrows(Box::new(RefCell::new(Tree::new_allocation( - id, alloc_size, self, kind, machine, - )))), + BorrowTrackerMethod::StackedBorrows => AllocState::StackedBorrows(Box::new( + RefCell::new(Stacks::new_allocation(id, alloc_size, self, kind, machine)), + )), + BorrowTrackerMethod::TreeBorrows => AllocState::TreeBorrows(Box::new(RefCell::new( + Tree::new_allocation(id, alloc_size, self, kind, machine), + ))), } } } @@ -324,8 +322,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.tcx.tcx.dcx().warn("Stacked Borrows does not support named pointers; `miri_pointer_name` is a no-op"); interp_ok(()) } - BorrowTrackerMethod::TreeBorrows => - this.tb_give_pointer_debug_name(ptr, nth_parent, name), + BorrowTrackerMethod::TreeBorrows => { + this.tb_give_pointer_debug_name(ptr, nth_parent, name) + } } } @@ -424,16 +423,16 @@ impl AllocState { machine: &MiriMachine<'tcx>, ) -> InterpResult<'tcx> { match self { - AllocState::StackedBorrows(sb) => - sb.borrow_mut().before_memory_read(alloc_id, prov_extra, range, machine), - AllocState::TreeBorrows(tb) => - tb.borrow_mut().before_memory_access( - AccessKind::Read, - alloc_id, - prov_extra, - range, - machine, - ), + AllocState::StackedBorrows(sb) => { + sb.borrow_mut().before_memory_read(alloc_id, prov_extra, range, machine) + } + AllocState::TreeBorrows(tb) => tb.borrow_mut().before_memory_access( + AccessKind::Read, + alloc_id, + prov_extra, + range, + machine, + ), } } @@ -445,16 +444,16 @@ impl AllocState { machine: &MiriMachine<'tcx>, ) -> InterpResult<'tcx> { match self { - AllocState::StackedBorrows(sb) => - sb.get_mut().before_memory_write(alloc_id, prov_extra, range, machine), - AllocState::TreeBorrows(tb) => - tb.get_mut().before_memory_access( - AccessKind::Write, - alloc_id, - prov_extra, - range, - machine, - ), + AllocState::StackedBorrows(sb) => { + sb.get_mut().before_memory_write(alloc_id, prov_extra, range, machine) + } + AllocState::TreeBorrows(tb) => tb.get_mut().before_memory_access( + AccessKind::Write, + alloc_id, + prov_extra, + range, + machine, + ), } } @@ -466,10 +465,12 @@ impl AllocState { machine: &MiriMachine<'tcx>, ) -> InterpResult<'tcx> { match self { - AllocState::StackedBorrows(sb) => - sb.get_mut().before_memory_deallocation(alloc_id, prov_extra, size, machine), - AllocState::TreeBorrows(tb) => - tb.get_mut().before_memory_deallocation(alloc_id, prov_extra, size, machine), + AllocState::StackedBorrows(sb) => { + sb.get_mut().before_memory_deallocation(alloc_id, prov_extra, size, machine) + } + AllocState::TreeBorrows(tb) => { + tb.get_mut().before_memory_deallocation(alloc_id, prov_extra, size, machine) + } } } @@ -490,8 +491,9 @@ impl AllocState { ) -> InterpResult<'tcx> { match self { AllocState::StackedBorrows(_sb) => interp_ok(()), - AllocState::TreeBorrows(tb) => - tb.borrow_mut().release_protector(machine, global, tag, alloc_id), + AllocState::TreeBorrows(tb) => { + tb.borrow_mut().release_protector(machine, global, tag, alloc_id) + } } } } diff --git a/src/tools/miri/src/borrow_tracker/stacked_borrows/diagnostics.rs b/src/tools/miri/src/borrow_tracker/stacked_borrows/diagnostics.rs index 63b18028a5b9d..fed98dfeca7d2 100644 --- a/src/tools/miri/src/borrow_tracker/stacked_borrows/diagnostics.rs +++ b/src/tools/miri/src/borrow_tracker/stacked_borrows/diagnostics.rs @@ -96,8 +96,9 @@ impl fmt::Display for InvalidationCause { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { InvalidationCause::Access(kind) => write!(f, "{kind}"), - InvalidationCause::Retag(perm, info) => - write!(f, "{perm:?} {retag}", retag = info.summary()), + InvalidationCause::Retag(perm, info) => { + write!(f, "{perm:?} {retag}", retag = info.summary()) + } } } } @@ -250,7 +251,7 @@ impl<'history, 'ecx, 'tcx> DiagnosticCx<'history, 'ecx, 'tcx> { None => { last_creation.retag.permission = Some(perm); } - Some(previous) => + Some(previous) => { if previous != perm { // 'Split up' the creation event. let previous_range = last_creation.retag.range; @@ -259,7 +260,8 @@ impl<'history, 'ecx, 'tcx> DiagnosticCx<'history, 'ecx, 'tcx> { new_event.retag.range = alloc_range(self.offset, previous_range.end()); new_event.retag.permission = Some(perm); self.history.creations.push(new_event); - }, + } + } } } @@ -281,8 +283,9 @@ impl<'history, 'ecx, 'tcx> DiagnosticCx<'history, 'ecx, 'tcx> { } (*range, InvalidationCause::Retag(permission.unwrap(), *info)) } - Operation::Access(AccessOp { kind, range, .. }) => - (*range, InvalidationCause::Access(*kind)), + Operation::Access(AccessOp { kind, range, .. }) => { + (*range, InvalidationCause::Access(*kind)) + } Operation::Dealloc(_) => { // This can be reached, but never be relevant later since the entire allocation is // gone now. @@ -434,17 +437,17 @@ impl<'history, 'ecx, 'tcx> DiagnosticCx<'history, 'ecx, 'tcx> { ProtectorKind::StrongProtector => "strongly protected", }; match self.operation { - Operation::Dealloc(_) => - err_sb_ub(format!("deallocating while item {item:?} is {protected}",), vec![], None), + Operation::Dealloc(_) => { + err_sb_ub(format!("deallocating while item {item:?} is {protected}",), vec![], None) + } Operation::Retag(RetagOp { orig_tag: tag, .. }) - | Operation::Access(AccessOp { tag, .. }) => - err_sb_ub( - format!( - "not granting access to tag {tag:?} because that would remove {item:?} which is {protected}", - ), - vec![], - tag.and_then(|tag| self.get_logs_relevant_to(tag, Some(item.tag()))), + | Operation::Access(AccessOp { tag, .. }) => err_sb_ub( + format!( + "not granting access to tag {tag:?} because that would remove {item:?} which is {protected}", ), + vec![], + tag.and_then(|tag| self.get_logs_relevant_to(tag, Some(item.tag()))), + ), } } @@ -472,8 +475,9 @@ impl<'history, 'ecx, 'tcx> DiagnosticCx<'history, 'ecx, 'tcx> { } let cause = match self.operation { Operation::Dealloc(_) => format!(" due to deallocation"), - Operation::Access(AccessOp { kind, tag, .. }) => - format!(" due to {kind:?} access for {tag:?}"), + Operation::Access(AccessOp { kind, tag, .. }) => { + format!(" due to {kind:?} access for {tag:?}") + } Operation::Retag(RetagOp { orig_tag, permission, new_tag, .. }) => { let permission = permission .expect("start_grant should set the current permission before popping a tag"); diff --git a/src/tools/miri/src/borrow_tracker/stacked_borrows/stack.rs b/src/tools/miri/src/borrow_tracker/stacked_borrows/stack.rs index dc3370f125104..9dfdcd7fbe243 100644 --- a/src/tools/miri/src/borrow_tracker/stacked_borrows/stack.rs +++ b/src/tools/miri/src/borrow_tracker/stacked_borrows/stack.rs @@ -64,8 +64,9 @@ impl Stack { Permission::Disabled => left.perm() == Permission::SharedReadWrite, // Unique and SharedReadOnly can terminate a SharedReadWrite block, so only remove // them if they are both unreachable and not directly after a SharedReadWrite. - Permission::Unique | Permission::SharedReadOnly => - left.perm() == Permission::SharedReadWrite || tags.contains(&this.tag()), + Permission::Unique | Permission::SharedReadOnly => { + left.perm() == Permission::SharedReadWrite || tags.contains(&this.tag()) + } }; if should_keep { diff --git a/src/tools/miri/src/borrow_tracker/tree_borrows/diagnostics.rs b/src/tools/miri/src/borrow_tracker/tree_borrows/diagnostics.rs index b2fd9b2bf054a..eb3cac2d62151 100644 --- a/src/tools/miri/src/borrow_tracker/tree_borrows/diagnostics.rs +++ b/src/tools/miri/src/borrow_tracker/tree_borrows/diagnostics.rs @@ -526,11 +526,9 @@ impl DisplayFmt { /// Print extra text if the tag has a protector. fn print_protector(&self, protector: Option<&ProtectorKind>) -> &'static str { protector - .map(|p| { - match *p { - ProtectorKind::WeakProtector => " Weakly protected", - ProtectorKind::StrongProtector => " Strongly protected", - } + .map(|p| match *p { + ProtectorKind::WeakProtector => " Weakly protected", + ProtectorKind::StrongProtector => " Strongly protected", }) .unwrap_or("") } diff --git a/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs b/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs index 65042f2668081..47cf85566b3ee 100644 --- a/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs +++ b/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs @@ -336,10 +336,10 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // - if the pointer is not reborrowed (raw pointer) or if `zero_size` is set // then we override the size to do a zero-length reborrow. let reborrow_size = match new_perm { - NewPermission { zero_size: false, .. } => - this.size_and_align_of_mplace(place)? - .map(|(size, _)| size) - .unwrap_or(place.layout.size), + NewPermission { zero_size: false, .. } => this + .size_and_align_of_mplace(place)? + .map(|(size, _)| size) + .unwrap_or(place.layout.size), _ => Size::from_bytes(0), }; trace!("Creating new permission: {:?} with size {:?}", new_perm, reborrow_size); @@ -385,8 +385,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ) -> InterpResult<'tcx, ImmTy<'tcx>> { let this = self.eval_context_mut(); let new_perm = match val.layout.ty.kind() { - &ty::Ref(_, pointee, mutability) => - NewPermission::from_ref_ty(pointee, mutability, kind, this), + &ty::Ref(_, pointee, mutability) => { + NewPermission::from_ref_ty(pointee, mutability, kind, this) + } _ => None, }; if let Some(new_perm) = new_perm { diff --git a/src/tools/miri/src/borrow_tracker/tree_borrows/perms.rs b/src/tools/miri/src/borrow_tracker/tree_borrows/perms.rs index 5c12ce39d10da..79dd018cd56fb 100644 --- a/src/tools/miri/src/borrow_tracker/tree_borrows/perms.rs +++ b/src/tools/miri/src/borrow_tracker/tree_borrows/perms.rs @@ -150,7 +150,7 @@ mod transition { assert!(!protected); res } - Active => + Active => { if protected { // We wrote, someone else reads -- that's bad. // (Since Active is always initialized, this move-to-protected will mean insta-UB.) @@ -159,7 +159,8 @@ mod transition { // We don't want to disable here to allow read-read reordering: it is crucial // that the foreign read does not invalidate future reads through this tag. Frozen - }, + } + } }) } @@ -432,12 +433,14 @@ pub mod diagnostics { match (self.from, self.to) { (_, Active) => "the first write to a 2-phase borrowed mutable reference", (_, Frozen) => "a loss of write permissions", - (ReservedFrz { conflicted: false }, ReservedFrz { conflicted: true }) => - "a temporary loss of write permissions until function exit", + (ReservedFrz { conflicted: false }, ReservedFrz { conflicted: true }) => { + "a temporary loss of write permissions until function exit" + } (Frozen, Disabled) => "a loss of read permissions", (_, Disabled) => "a loss of read and write permissions", - (old, new) => - unreachable!("Transition from {old:?} to {new:?} should never be possible"), + (old, new) => { + unreachable!("Transition from {old:?} to {new:?} should never be possible") + } } } @@ -494,12 +497,14 @@ pub mod diagnostics { // `Active` and `Reserved` have all permissions, so a // `ChildAccessForbidden(Reserved | Active)` can never exist. - (_, Active) | (_, ReservedFrz { conflicted: false }) => - unreachable!("this permission cannot cause an error"), + (_, Active) | (_, ReservedFrz { conflicted: false }) => { + unreachable!("this permission cannot cause an error") + } // No transition has `Reserved { conflicted: false }` or `ReservedIM` // as its `.to` unless it's a noop. - (ReservedFrz { conflicted: false } | ReservedIM, _) => - unreachable!("self is a noop transition"), + (ReservedFrz { conflicted: false } | ReservedIM, _) => { + unreachable!("self is a noop transition") + } // All transitions produced in normal executions (using `apply_access`) // change permissions in the order `Reserved -> Active -> Frozen -> Disabled`. // We assume that the error was triggered on the same location that @@ -507,8 +512,9 @@ pub mod diagnostics { // in the order `self.from < self.to <= insufficient.inner` (Active | Frozen | Disabled, ReservedFrz { .. } | ReservedIM) | (Disabled, Frozen) - | (ReservedFrz { .. }, ReservedIM) => - unreachable!("permissions between self and err must be increasing"), + | (ReservedFrz { .. }, ReservedIM) => { + unreachable!("permissions between self and err must be increasing") + } } } TransitionError::ProtectedDisabled(before_disabled) => { @@ -539,22 +545,23 @@ pub mod diagnostics { (Active, Frozen) => false, (ReservedFrz { conflicted: true }, _) => false, - (_, Disabled) => - unreachable!( - "permission that results in Disabled should not itself be Disabled in the first place" - ), + (_, Disabled) => unreachable!( + "permission that results in Disabled should not itself be Disabled in the first place" + ), // No transition has `Reserved { conflicted: false }` or `ReservedIM` as its `.to` // unless it's a noop. - (ReservedFrz { conflicted: false } | ReservedIM, _) => - unreachable!("self is a noop transition"), + (ReservedFrz { conflicted: false } | ReservedIM, _) => { + unreachable!("self is a noop transition") + } // Permissions only evolve in the order `Reserved -> Active -> Frozen -> Disabled`, // so permissions found must be increasing in the order // `self.from < self.to <= forbidden.from < forbidden.to`. (Disabled, ReservedFrz { .. } | ReservedIM | Active | Frozen) | (Frozen, ReservedFrz { .. } | ReservedIM | Active) - | (Active, ReservedFrz { .. } | ReservedIM) => - unreachable!("permissions between self and err must be increasing"), + | (Active, ReservedFrz { .. } | ReservedIM) => { + unreachable!("permissions between self and err must be increasing") + } } } // We don't care because protectors evolve independently from diff --git a/src/tools/miri/src/borrow_tracker/tree_borrows/tree/tests.rs b/src/tools/miri/src/borrow_tracker/tree_borrows/tree/tests.rs index dbfa9807e3b5a..271f0b8872493 100644 --- a/src/tools/miri/src/borrow_tracker/tree_borrows/tree/tests.rs +++ b/src/tools/miri/src/borrow_tracker/tree_borrows/tree/tests.rs @@ -9,12 +9,10 @@ use crate::borrow_tracker::tree_borrows::exhaustive::{Exhaustive, precondition}; impl Exhaustive for LocationState { fn exhaustive() -> Box> { // We keep `latest_foreign_access` at `None` as that's just a cache. - Box::new(<(Permission, bool)>::exhaustive().map(|(permission, initialized)| { - Self { - permission, - initialized, - idempotent_foreign_access: IdempotentForeignAccess::default(), - } + Box::new(<(Permission, bool)>::exhaustive().map(|(permission, initialized)| Self { + permission, + initialized, + idempotent_foreign_access: IdempotentForeignAccess::default(), })) } } @@ -261,18 +259,16 @@ mod spurious_read { fn rel_pair(self, xy_rel: RelPosXY) -> (AccessRelatedness, AccessRelatedness) { use AccessRelatedness::*; match xy_rel { - RelPosXY::MutuallyForeign => - match self { - PtrSelector::X => (This, CousinAccess), - PtrSelector::Y => (CousinAccess, This), - PtrSelector::Other => (CousinAccess, CousinAccess), - }, - RelPosXY::XChildY => - match self { - PtrSelector::X => (This, StrictChildAccess), - PtrSelector::Y => (AncestorAccess, This), - PtrSelector::Other => (CousinAccess, CousinAccess), - }, + RelPosXY::MutuallyForeign => match self { + PtrSelector::X => (This, CousinAccess), + PtrSelector::Y => (CousinAccess, This), + PtrSelector::Other => (CousinAccess, CousinAccess), + }, + RelPosXY::XChildY => match self { + PtrSelector::X => (This, StrictChildAccess), + PtrSelector::Y => (AncestorAccess, This), + PtrSelector::Other => (CousinAccess, CousinAccess), + }, } } } @@ -442,10 +438,9 @@ mod spurious_read { let initialized = match ptr { PtrSelector::X => self.x.state.initialized, PtrSelector::Y => self.y.state.initialized, - PtrSelector::Other => - panic!( - "the `initialized` status of `PtrSelector::Other` is unknown, do not pass it to `read_if_initialized`" - ), + PtrSelector::Other => panic!( + "the `initialized` status of `PtrSelector::Other` is unknown, do not pass it to `read_if_initialized`" + ), }; if initialized { self.perform_test_access(&TestAccess { ptr, kind: AccessKind::Read }) @@ -492,8 +487,11 @@ mod spurious_read { impl Exhaustive for LocStateProtPair { fn exhaustive() -> Box> { Box::new(<[LocStateProt; 2]>::exhaustive().flat_map(|[x, y]| { - RelPosXY::exhaustive() - .map(move |xy_rel| Self { x: x.clone(), y: y.clone(), xy_rel }) + RelPosXY::exhaustive().map(move |xy_rel| Self { + x: x.clone(), + y: y.clone(), + xy_rel, + }) })) } } diff --git a/src/tools/miri/src/clock.rs b/src/tools/miri/src/clock.rs index 34465e9cac60d..4e6f867013079 100644 --- a/src/tools/miri/src/clock.rs +++ b/src/tools/miri/src/clock.rs @@ -39,8 +39,9 @@ impl Instant { pub fn duration_since(&self, earlier: Instant) -> Duration { match (&self.kind, earlier.kind) { - (InstantKind::Host(instant), InstantKind::Host(earlier)) => - instant.duration_since(earlier), + (InstantKind::Host(instant), InstantKind::Host(earlier)) => { + instant.duration_since(earlier) + } ( InstantKind::Virtual { nanoseconds }, InstantKind::Virtual { nanoseconds: earlier }, @@ -122,17 +123,20 @@ impl MonotonicClock { pub fn epoch(&self) -> Instant { match &self.kind { MonotonicClockKind::Host { epoch } => Instant { kind: InstantKind::Host(*epoch) }, - MonotonicClockKind::Virtual { .. } => - Instant { kind: InstantKind::Virtual { nanoseconds: 0 } }, + MonotonicClockKind::Virtual { .. } => { + Instant { kind: InstantKind::Virtual { nanoseconds: 0 } } + } } } pub fn now(&self) -> Instant { match &self.kind { - MonotonicClockKind::Host { .. } => - Instant { kind: InstantKind::Host(StdInstant::now()) }, - MonotonicClockKind::Virtual { nanoseconds } => - Instant { kind: InstantKind::Virtual { nanoseconds: nanoseconds.get() } }, + MonotonicClockKind::Host { .. } => { + Instant { kind: InstantKind::Host(StdInstant::now()) } + } + MonotonicClockKind::Virtual { nanoseconds } => { + Instant { kind: InstantKind::Virtual { nanoseconds: nanoseconds.get() } } + } } } } diff --git a/src/tools/miri/src/concurrency/data_race.rs b/src/tools/miri/src/concurrency/data_race.rs index 847c682347592..c0bc8e8356c73 100644 --- a/src/tools/miri/src/concurrency/data_race.rs +++ b/src/tools/miri/src/concurrency/data_race.rs @@ -984,8 +984,9 @@ impl VClockAlloc { | MiriMemoryKind::ExternStatic | MiriMemoryKind::Tls, ) - | MemoryKind::CallerLocation => - (VTimestamp::ZERO, global.thread_index(ThreadId::MAIN_THREAD)), + | MemoryKind::CallerLocation => { + (VTimestamp::ZERO, global.thread_index(ThreadId::MAIN_THREAD)) + } }; VClockAlloc { alloc_ranges: RefCell::new(RangeMap::new( diff --git a/src/tools/miri/src/concurrency/range_object_map.rs b/src/tools/miri/src/concurrency/range_object_map.rs index 4c9cf3dc6351b..eab768af13dc3 100644 --- a/src/tools/miri/src/concurrency/range_object_map.rs +++ b/src/tools/miri/src/concurrency/range_object_map.rs @@ -83,14 +83,15 @@ impl RangeObjectMap { // Start of the range doesn't belong to an existing object match self.find_offset(range.end() - Size::from_bytes(1)) { // Neither does the end - Err(end_pos) => + Err(end_pos) => { if pos == end_pos { // There's nothing between the start and the end, so the range thing is empty AccessType::Empty(pos) } else { // Otherwise we have entirely covered an existing object AccessType::ImperfectlyOverlapping(pos..end_pos) - }, + } + } // Otherwise at least part of it overlaps with something else Ok(end_pos) => AccessType::ImperfectlyOverlapping(pos..end_pos + 1), } diff --git a/src/tools/miri/src/concurrency/thread.rs b/src/tools/miri/src/concurrency/thread.rs index 72fa918e8e511..d1525924c3c9a 100644 --- a/src/tools/miri/src/concurrency/thread.rs +++ b/src/tools/miri/src/concurrency/thread.rs @@ -126,8 +126,9 @@ impl<'tcx> std::fmt::Debug for ThreadState<'tcx> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Enabled => write!(f, "Enabled"), - Self::Blocked { reason, timeout, .. } => - f.debug_struct("Blocked").field("reason", reason).field("timeout", timeout).finish(), + Self::Blocked { reason, timeout, .. } => { + f.debug_struct("Blocked").field("reason", reason).field("timeout", timeout).finish() + } Self::Terminated => write!(f, "Terminated"), } } @@ -350,8 +351,9 @@ impl Timeout { fn get_wait_time(&self, clock: &MonotonicClock) -> Duration { match self { Timeout::Monotonic(instant) => instant.duration_since(clock.now()), - Timeout::RealTime(time) => - time.duration_since(SystemTime::now()).unwrap_or(Duration::ZERO), + Timeout::RealTime(time) => { + time.duration_since(SystemTime::now()).unwrap_or(Duration::ZERO) + } } } @@ -686,12 +688,11 @@ impl<'tcx> ThreadManager<'tcx> { fn next_callback_wait_time(&self, clock: &MonotonicClock) -> Option { self.threads .iter() - .filter_map(|t| { - match &t.state { - ThreadState::Blocked { timeout: Some(timeout), .. } => - Some(timeout.get_wait_time(clock)), - _ => None, + .filter_map(|t| match &t.state { + ThreadState::Blocked { timeout: Some(timeout), .. } => { + Some(timeout.get_wait_time(clock)) } + _ => None, }) .min() } @@ -954,16 +955,18 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Now free the TLS statics. for ptr in free_tls_statics { match tls_alloc_action { - TlsAllocAction::Deallocate => - this.deallocate_ptr(ptr.into(), None, MiriMemoryKind::Tls.into())?, - TlsAllocAction::Leak => + TlsAllocAction::Deallocate => { + this.deallocate_ptr(ptr.into(), None, MiriMemoryKind::Tls.into())? + } + TlsAllocAction::Leak => { if let Some(alloc) = ptr.provenance.get_alloc_id() { trace!( "Thread-local static leaked and stored as static root: {:?}", alloc ); this.machine.static_roots.push(alloc); - }, + } + } } } } @@ -1004,11 +1007,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { TimeoutAnchor::Relative => SystemTime::now(), }) } - TimeoutClock::Monotonic => - Timeout::Monotonic(match anchor { - TimeoutAnchor::Absolute => this.machine.monotonic_clock.epoch(), - TimeoutAnchor::Relative => this.machine.monotonic_clock.now(), - }), + TimeoutClock::Monotonic => Timeout::Monotonic(match anchor { + TimeoutAnchor::Absolute => this.machine.monotonic_clock.epoch(), + TimeoutAnchor::Relative => this.machine.monotonic_clock.now(), + }), }; anchor.add_lossy(duration) }); @@ -1158,8 +1160,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // See if this thread can do something else. match this.run_on_stack_empty()? { Poll::Pending => {} // keep going - Poll::Ready(()) => - this.terminate_active_thread(TlsAllocAction::Deallocate)?, + Poll::Ready(()) => { + this.terminate_active_thread(TlsAllocAction::Deallocate)? + } } } } diff --git a/src/tools/miri/src/concurrency/vector_clock.rs b/src/tools/miri/src/concurrency/vector_clock.rs index 345726634299b..0fe1788d407e7 100644 --- a/src/tools/miri/src/concurrency/vector_clock.rs +++ b/src/tools/miri/src/concurrency/vector_clock.rs @@ -269,14 +269,16 @@ impl PartialOrd for VClock { for (l, r) in iter { match order { Ordering::Equal => order = l.cmp(r), - Ordering::Less => + Ordering::Less => { if l > r { return None; - }, - Ordering::Greater => + } + } + Ordering::Greater => { if l < r { return None; - }, + } + } } } @@ -291,18 +293,16 @@ impl PartialOrd for VClock { Ordering::Equal => Some(order), // Right has at least 1 element > than the implicit 0, // so the only valid values are Ordering::Less or None. - Ordering::Less => - match order { - Ordering::Less | Ordering::Equal => Some(Ordering::Less), - Ordering::Greater => None, - }, + Ordering::Less => match order { + Ordering::Less | Ordering::Equal => Some(Ordering::Less), + Ordering::Greater => None, + }, // Left has at least 1 element > than the implicit 0, // so the only valid values are Ordering::Greater or None. - Ordering::Greater => - match order { - Ordering::Greater | Ordering::Equal => Some(Ordering::Greater), - Ordering::Less => None, - }, + Ordering::Greater => match order { + Ordering::Greater | Ordering::Equal => Some(Ordering::Greater), + Ordering::Less => None, + }, } } diff --git a/src/tools/miri/src/diagnostics.rs b/src/tools/miri/src/diagnostics.rs index 014b1299f2dd0..e0e0b58394703 100644 --- a/src/tools/miri/src/diagnostics.rs +++ b/src/tools/miri/src/diagnostics.rs @@ -67,28 +67,28 @@ impl fmt::Display for TerminationInfo { Abort(msg) => write!(f, "{msg}"), Interrupted => write!(f, "interpretation was interrupted"), UnsupportedInIsolation(msg) => write!(f, "{msg}"), - Int2PtrWithStrictProvenance => - write!( - f, - "integer-to-pointer casts and `ptr::with_exposed_provenance` are not supported with `-Zmiri-strict-provenance`" - ), + Int2PtrWithStrictProvenance => write!( + f, + "integer-to-pointer casts and `ptr::with_exposed_provenance` are not supported with `-Zmiri-strict-provenance`" + ), StackedBorrowsUb { msg, .. } => write!(f, "{msg}"), TreeBorrowsUb { title, .. } => write!(f, "{title}"), Deadlock => write!(f, "the evaluated program deadlocked"), - MultipleSymbolDefinitions { link_name, .. } => - write!(f, "multiple definitions of symbol `{link_name}`"), - SymbolShimClashing { link_name, .. } => - write!(f, "found `{link_name}` symbol definition that clashes with a built-in shim",), - DataRace { involves_non_atomic, ptr, op1, op2, .. } => - write!( - f, - "{} detected between (1) {} on {} and (2) {} on {} at {ptr:?}. (2) just happened here", - if *involves_non_atomic { "Data race" } else { "Race condition" }, - op1.action, - op1.thread_info, - op2.action, - op2.thread_info - ), + MultipleSymbolDefinitions { link_name, .. } => { + write!(f, "multiple definitions of symbol `{link_name}`") + } + SymbolShimClashing { link_name, .. } => { + write!(f, "found `{link_name}` symbol definition that clashes with a built-in shim",) + } + DataRace { involves_non_atomic, ptr, op1, op2, .. } => write!( + f, + "{} detected between (1) {} on {} and (2) {} on {} at {ptr:?}. (2) just happened here", + if *involves_non_atomic { "Data race" } else { "Race condition" }, + op1.action, + op1.thread_info, + op2.action, + op2.thread_info + ), UnsupportedForeignItem(msg) => write!(f, "{msg}"), } } @@ -230,10 +230,12 @@ pub fn report_error<'tcx>( &Exit { code, leak_check } => return Some((code, leak_check)), Abort(_) => Some("abnormal termination"), Interrupted => None, - UnsupportedInIsolation(_) | Int2PtrWithStrictProvenance | UnsupportedForeignItem(_) => - Some("unsupported operation"), - StackedBorrowsUb { .. } | TreeBorrowsUb { .. } | DataRace { .. } => - Some("Undefined Behavior"), + UnsupportedInIsolation(_) | Int2PtrWithStrictProvenance | UnsupportedForeignItem(_) => { + Some("unsupported operation") + } + StackedBorrowsUb { .. } | TreeBorrowsUb { .. } | DataRace { .. } => { + Some("Undefined Behavior") + } Deadlock => Some("deadlock"), MultipleSymbolDefinitions { .. } | SymbolShimClashing { .. } => None, }; @@ -604,51 +606,59 @@ impl<'tcx> MiriMachine<'tcx> { let (stacktrace, _was_pruned) = prune_stacktrace(stacktrace, self); let (title, diag_level) = match &e { - RejectedIsolatedOp(_) => - ("operation rejected by isolation".to_string(), DiagLevel::Warning), + RejectedIsolatedOp(_) => { + ("operation rejected by isolation".to_string(), DiagLevel::Warning) + } Int2Ptr { .. } => ("integer-to-pointer cast".to_string(), DiagLevel::Warning), - NativeCallSharedMem => - ("sharing memory with a native function".to_string(), DiagLevel::Warning), - ExternTypeReborrow => - ("reborrow of reference to `extern type`".to_string(), DiagLevel::Warning), + NativeCallSharedMem => { + ("sharing memory with a native function".to_string(), DiagLevel::Warning) + } + ExternTypeReborrow => { + ("reborrow of reference to `extern type`".to_string(), DiagLevel::Warning) + } CreatedPointerTag(..) | PoppedPointerTag(..) | CreatedAlloc(..) | AccessedAlloc(..) | FreedAlloc(..) | ProgressReport { .. } - | WeakMemoryOutdatedLoad { .. } => - ("tracking was triggered".to_string(), DiagLevel::Note), + | WeakMemoryOutdatedLoad { .. } => { + ("tracking was triggered".to_string(), DiagLevel::Note) + } }; let msg = match &e { CreatedPointerTag(tag, None, _) => format!("created base tag {tag:?}"), - CreatedPointerTag(tag, Some(perm), None) => - format!("created {tag:?} with {perm} derived from unknown tag"), - CreatedPointerTag(tag, Some(perm), Some((alloc_id, range, orig_tag))) => - format!( - "created tag {tag:?} with {perm} at {alloc_id:?}{range:?} derived from {orig_tag:?}" - ), + CreatedPointerTag(tag, Some(perm), None) => { + format!("created {tag:?} with {perm} derived from unknown tag") + } + CreatedPointerTag(tag, Some(perm), Some((alloc_id, range, orig_tag))) => format!( + "created tag {tag:?} with {perm} at {alloc_id:?}{range:?} derived from {orig_tag:?}" + ), PoppedPointerTag(item, cause) => format!("popped tracked tag for item {item:?}{cause}"), - CreatedAlloc(AllocId(id), size, align, kind) => - format!( - "created {kind} allocation of {size} bytes (alignment {align} bytes) with id {id}", - size = size.bytes(), - align = align.bytes(), - ), - AccessedAlloc(AllocId(id), access_kind) => - format!("{access_kind} to allocation with id {id}"), + CreatedAlloc(AllocId(id), size, align, kind) => format!( + "created {kind} allocation of {size} bytes (alignment {align} bytes) with id {id}", + size = size.bytes(), + align = align.bytes(), + ), + AccessedAlloc(AllocId(id), access_kind) => { + format!("{access_kind} to allocation with id {id}") + } FreedAlloc(AllocId(id)) => format!("freed allocation with id {id}"), - RejectedIsolatedOp(ref op) => - format!("{op} was made to return an error due to isolation"), - ProgressReport { .. } => - format!("progress report: current operation being executed is here"), + RejectedIsolatedOp(ref op) => { + format!("{op} was made to return an error due to isolation") + } + ProgressReport { .. } => { + format!("progress report: current operation being executed is here") + } Int2Ptr { .. } => format!("integer-to-pointer cast"), NativeCallSharedMem => format!("sharing memory with a native function called via FFI"), - WeakMemoryOutdatedLoad { ptr } => - format!("weak memory emulation: outdated value returned from load at {ptr}"), - ExternTypeReborrow => - format!("reborrow of a reference to `extern type` is not properly supported"), + WeakMemoryOutdatedLoad { ptr } => { + format!("weak memory emulation: outdated value returned from load at {ptr}") + } + ExternTypeReborrow => { + format!("reborrow of a reference to `extern type` is not properly supported") + } }; let notes = match &e { diff --git a/src/tools/miri/src/eval.rs b/src/tools/miri/src/eval.rs index 7586b5efd4b2b..9df58116ab13a 100644 --- a/src/tools/miri/src/eval.rs +++ b/src/tools/miri/src/eval.rs @@ -226,31 +226,29 @@ impl<'tcx> MainThreadState<'tcx> { Running => { *self = TlsDtors(Default::default()); } - TlsDtors(state) => - match state.on_stack_empty(this)? { - Poll::Pending => {} // just keep going - Poll::Ready(()) => { - // Give background threads a chance to finish by yielding the main thread a - // couple of times -- but only if we would also preempt threads randomly. - if this.machine.preemption_rate > 0.0 { - // There is a non-zero chance they will yield back to us often enough to - // make Miri terminate eventually. - *self = Yield { remaining: MAIN_THREAD_YIELDS_AT_SHUTDOWN }; - } else { - // The other threads did not get preempted, so no need to yield back to - // them. - *self = Done; - } + TlsDtors(state) => match state.on_stack_empty(this)? { + Poll::Pending => {} // just keep going + Poll::Ready(()) => { + // Give background threads a chance to finish by yielding the main thread a + // couple of times -- but only if we would also preempt threads randomly. + if this.machine.preemption_rate > 0.0 { + // There is a non-zero chance they will yield back to us often enough to + // make Miri terminate eventually. + *self = Yield { remaining: MAIN_THREAD_YIELDS_AT_SHUTDOWN }; + } else { + // The other threads did not get preempted, so no need to yield back to + // them. + *self = Done; } - }, - Yield { remaining } => - match remaining.checked_sub(1) { - None => *self = Done, - Some(new_remaining) => { - *remaining = new_remaining; - this.yield_active_thread(); - } - }, + } + }, + Yield { remaining } => match remaining.checked_sub(1) { + None => *self = Done, + Some(new_remaining) => { + *remaining = new_remaining; + this.yield_active_thread(); + } + }, Done => { // Figure out exit code. let ret_place = this.machine.main_fn_ret_place.clone().unwrap(); diff --git a/src/tools/miri/src/helpers.rs b/src/tools/miri/src/helpers.rs index a3aa8bbbfb32d..b04b9c2efe06f 100644 --- a/src/tools/miri/src/helpers.rs +++ b/src/tools/miri/src/helpers.rs @@ -581,8 +581,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { fn visit_value(&mut self, v: &MPlaceTy<'tcx>) -> InterpResult<'tcx> { trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty); let is_unsafe_cell = match v.layout.ty.kind() { - ty::Adt(adt, _) => - Some(adt.did()) == self.ecx.tcx.lang_items().unsafe_cell_type(), + ty::Adt(adt, _) => { + Some(adt.did()) == self.ecx.tcx.lang_items().unsafe_cell_type() + } _ => false, }; if is_unsafe_cell { @@ -1160,12 +1161,11 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (Scalar::from_int(res.value, int_size), res.status) } // Nothing else - _ => - span_bug!( - ecx.cur_span(), - "attempted float-to-int conversion with non-int output type {}", - cast_to.ty, - ), + _ => span_bug!( + ecx.cur_span(), + "attempted float-to-int conversion with non-int output type {}", + cast_to.ty, + ), } } @@ -1174,14 +1174,18 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }; let (val, status) = match fty { - FloatTy::F16 => - float_to_int_inner::(this, src.to_scalar().to_f16()?, cast_to, round), - FloatTy::F32 => - float_to_int_inner::(this, src.to_scalar().to_f32()?, cast_to, round), - FloatTy::F64 => - float_to_int_inner::(this, src.to_scalar().to_f64()?, cast_to, round), - FloatTy::F128 => - float_to_int_inner::(this, src.to_scalar().to_f128()?, cast_to, round), + FloatTy::F16 => { + float_to_int_inner::(this, src.to_scalar().to_f16()?, cast_to, round) + } + FloatTy::F32 => { + float_to_int_inner::(this, src.to_scalar().to_f32()?, cast_to, round) + } + FloatTy::F64 => { + float_to_int_inner::(this, src.to_scalar().to_f64()?, cast_to, round) + } + FloatTy::F128 => { + float_to_int_inner::(this, src.to_scalar().to_f128()?, cast_to, round) + } }; if status.intersects( diff --git a/src/tools/miri/src/intrinsics/atomic.rs b/src/tools/miri/src/intrinsics/atomic.rs index dcafa7b6cabe5..2456c0e3497e3 100644 --- a/src/tools/miri/src/intrinsics/atomic.rs +++ b/src/tools/miri/src/intrinsics/atomic.rs @@ -73,23 +73,31 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ["singlethreadfence", ord] => this.compiler_fence_intrinsic(args, fence_ord(ord))?, ["xchg", ord] => this.atomic_exchange(args, dest, rw_ord(ord))?, - ["cxchg", ord1, ord2] => - this.atomic_compare_exchange(args, dest, rw_ord(ord1), read_ord(ord2))?, - ["cxchgweak", ord1, ord2] => - this.atomic_compare_exchange_weak(args, dest, rw_ord(ord1), read_ord(ord2))?, - - ["or", ord] => - this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::BitOr, false), rw_ord(ord))?, - ["xor", ord] => - this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::BitXor, false), rw_ord(ord))?, - ["and", ord] => - this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::BitAnd, false), rw_ord(ord))?, - ["nand", ord] => - this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::BitAnd, true), rw_ord(ord))?, - ["xadd", ord] => - this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::Add, false), rw_ord(ord))?, - ["xsub", ord] => - this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::Sub, false), rw_ord(ord))?, + ["cxchg", ord1, ord2] => { + this.atomic_compare_exchange(args, dest, rw_ord(ord1), read_ord(ord2))? + } + ["cxchgweak", ord1, ord2] => { + this.atomic_compare_exchange_weak(args, dest, rw_ord(ord1), read_ord(ord2))? + } + + ["or", ord] => { + this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::BitOr, false), rw_ord(ord))? + } + ["xor", ord] => { + this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::BitXor, false), rw_ord(ord))? + } + ["and", ord] => { + this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::BitAnd, false), rw_ord(ord))? + } + ["nand", ord] => { + this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::BitAnd, true), rw_ord(ord))? + } + ["xadd", ord] => { + this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::Add, false), rw_ord(ord))? + } + ["xsub", ord] => { + this.atomic_rmw_op(args, dest, AtomicOp::MirOp(BinOp::Sub, false), rw_ord(ord))? + } ["min", ord] => { // Later we will use the type to indicate signed vs unsigned, // so make sure it matches the intrinsic name. diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index 55aa3d6fa6873..96444e0360a18 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -1203,9 +1203,7 @@ impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> { ecx: &mut InterpCx<'tcx, Self>, val: ImmTy<'tcx>, ) -> InterpResult<'tcx, ImmTy<'tcx>> { - crate::math::apply_random_float_error_to_imm( - ecx, val, 2 /* log2(4) */ - ) + crate::math::apply_random_float_error_to_imm(ecx, val, 2 /* log2(4) */) } #[inline(always)] diff --git a/src/tools/miri/src/math.rs b/src/tools/miri/src/math.rs index 2ff29c7ac1aad..0f8ba3bc7a5e4 100644 --- a/src/tools/miri/src/math.rs +++ b/src/tools/miri/src/math.rs @@ -55,14 +55,18 @@ pub(crate) fn apply_random_float_error_to_imm<'tcx>( ) -> InterpResult<'tcx, ImmTy<'tcx>> { let scalar = val.to_scalar_int()?; let res: ScalarInt = match val.layout.ty.kind() { - ty::Float(FloatTy::F16) => - apply_random_float_error_ulp(ecx, scalar.to_f16(), ulp_exponent).into(), - ty::Float(FloatTy::F32) => - apply_random_float_error_ulp(ecx, scalar.to_f32(), ulp_exponent).into(), - ty::Float(FloatTy::F64) => - apply_random_float_error_ulp(ecx, scalar.to_f64(), ulp_exponent).into(), - ty::Float(FloatTy::F128) => - apply_random_float_error_ulp(ecx, scalar.to_f128(), ulp_exponent).into(), + ty::Float(FloatTy::F16) => { + apply_random_float_error_ulp(ecx, scalar.to_f16(), ulp_exponent).into() + } + ty::Float(FloatTy::F32) => { + apply_random_float_error_ulp(ecx, scalar.to_f32(), ulp_exponent).into() + } + ty::Float(FloatTy::F64) => { + apply_random_float_error_ulp(ecx, scalar.to_f64(), ulp_exponent).into() + } + ty::Float(FloatTy::F128) => { + apply_random_float_error_ulp(ecx, scalar.to_f128(), ulp_exponent).into() + } _ => bug!("intrinsic called with non-float input type"), }; diff --git a/src/tools/miri/src/shims/alloc.rs b/src/tools/miri/src/shims/alloc.rs index 323b95d5f5f23..60425c0c29ac6 100644 --- a/src/tools/miri/src/shims/alloc.rs +++ b/src/tools/miri/src/shims/alloc.rs @@ -17,8 +17,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // be kept in sync. let max_fundamental_align = match this.tcx.sess.target.arch.as_ref() { "x86" | "arm" | "mips" | "mips32r6" | "powerpc" | "powerpc64" | "wasm32" => 8, - "x86_64" | "aarch64" | "mips64" | "mips64r6" | "s390x" | "sparc64" | "loongarch64" => - 16, + "x86_64" | "aarch64" | "mips64" | "mips64r6" | "s390x" | "sparc64" | "loongarch64" => { + 16 + } arch => bug!("unsupported target architecture for malloc: `{}`", arch), }; // The C standard only requires sufficient alignment for any *type* with size less than or diff --git a/src/tools/miri/src/shims/backtrace.rs b/src/tools/miri/src/shims/backtrace.rs index 7e667e70a1721..65ed26da36492 100644 --- a/src/tools/miri/src/shims/backtrace.rs +++ b/src/tools/miri/src/shims/backtrace.rs @@ -68,14 +68,15 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { 0 => { throw_unsup_format!("miri_get_backtrace: v0 is not supported any more"); } - 1 => + 1 => { for (i, ptr) in ptrs.into_iter().enumerate() { let offset = ptr_layout.size.checked_mul(i.try_into().unwrap(), this).unwrap(); let op_place = buf_place.offset(offset, ptr_layout, this)?; this.write_pointer(ptr, &op_place)?; - }, + } + } _ => throw_unsup_format!("unknown `miri_get_backtrace` flags {}", flags), }; diff --git a/src/tools/miri/src/shims/foreign_items.rs b/src/tools/miri/src/shims/foreign_items.rs index 52c16a0c2e2dc..621577296a378 100644 --- a/src/tools/miri/src/shims/foreign_items.rs +++ b/src/tools/miri/src/shims/foreign_items.rs @@ -1015,22 +1015,26 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { } // Platform-specific shims - _ => + _ => { return match this.tcx.sess.target.os.as_ref() { - _ if this.target_os_is_unix() => + _ if this.target_os_is_unix() => { shims::unix::foreign_items::EvalContextExt::emulate_foreign_item_inner( this, link_name, abi, args, dest, - ), - "wasi" => + ) + } + "wasi" => { shims::wasi::foreign_items::EvalContextExt::emulate_foreign_item_inner( this, link_name, abi, args, dest, - ), - "windows" => + ) + } + "windows" => { shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_inner( this, link_name, abi, args, dest, - ), + ) + } _ => interp_ok(EmulateItemResult::NotSupported), - }, + }; + } }; // We only fall through to here if we did *not* hit the `_` arm above, // i.e., if we actually emulated the function with one of the shims. diff --git a/src/tools/miri/src/shims/native_lib.rs b/src/tools/miri/src/shims/native_lib.rs index 0258a76c3e703..c5789a154436e 100644 --- a/src/tools/miri/src/shims/native_lib.rs +++ b/src/tools/miri/src/shims/native_lib.rs @@ -255,15 +255,17 @@ fn imm_to_carg<'tcx>(v: &ImmTy<'tcx>, cx: &impl HasDataLayout) -> InterpResult<' ty::Int(IntTy::I16) => CArg::Int16(v.to_scalar().to_i16()?), ty::Int(IntTy::I32) => CArg::Int32(v.to_scalar().to_i32()?), ty::Int(IntTy::I64) => CArg::Int64(v.to_scalar().to_i64()?), - ty::Int(IntTy::Isize) => - CArg::ISize(v.to_scalar().to_target_isize(cx)?.try_into().unwrap()), + ty::Int(IntTy::Isize) => { + CArg::ISize(v.to_scalar().to_target_isize(cx)?.try_into().unwrap()) + } // the uints ty::Uint(UintTy::U8) => CArg::UInt8(v.to_scalar().to_u8()?), ty::Uint(UintTy::U16) => CArg::UInt16(v.to_scalar().to_u16()?), ty::Uint(UintTy::U32) => CArg::UInt32(v.to_scalar().to_u32()?), ty::Uint(UintTy::U64) => CArg::UInt64(v.to_scalar().to_u64()?), - ty::Uint(UintTy::Usize) => - CArg::USize(v.to_scalar().to_target_usize(cx)?.try_into().unwrap()), + ty::Uint(UintTy::Usize) => { + CArg::USize(v.to_scalar().to_target_usize(cx)?.try_into().unwrap()) + } ty::RawPtr(..) => { let s = v.to_scalar().to_pointer(cx)?.addr(); // This relies on the `expose_provenance` in `prepare_for_native_call`. diff --git a/src/tools/miri/src/shims/unix/foreign_items.rs b/src/tools/miri/src/shims/unix/foreign_items.rs index 026aa1f950399..12df8485fd379 100644 --- a/src/tools/miri/src/shims/unix/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/foreign_items.rs @@ -27,15 +27,14 @@ pub fn is_dyn_sym(name: &str, target_os: &str) -> bool { // needed at least on macOS to avoid file-based fallback in getrandom "getentropy" | "getrandom" => true, // Give specific OSes a chance to allow their symbols. - _ => - match target_os { - "android" => android::is_dyn_sym(name), - "freebsd" => freebsd::is_dyn_sym(name), - "linux" => linux::is_dyn_sym(name), - "macos" => macos::is_dyn_sym(name), - "solaris" | "illumos" => solarish::is_dyn_sym(name), - _ => false, - }, + _ => match target_os { + "android" => android::is_dyn_sym(name), + "freebsd" => freebsd::is_dyn_sym(name), + "linux" => linux::is_dyn_sym(name), + "macos" => macos::is_dyn_sym(name), + "solaris" | "illumos" => solarish::is_dyn_sym(name), + _ => false, + }, } } @@ -979,10 +978,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // TODO: when https://github.com/rust-lang/miri/issues/3730 is fixed this should use its notion of tid/pid let thread_id = match pid { 0 => this.active_thread(), - _ => - throw_unsup_format!( - "`sched_getaffinity` is only supported with a pid of 0 (indicating the current thread)" - ), + _ => throw_unsup_format!( + "`sched_getaffinity` is only supported with a pid of 0 (indicating the current thread)" + ), }; // The mask is stored in chunks, and the size must be a whole number of chunks. @@ -1016,10 +1014,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // TODO: when https://github.com/rust-lang/miri/issues/3730 is fixed this should use its notion of tid/pid let thread_id = match pid { 0 => this.active_thread(), - _ => - throw_unsup_format!( - "`sched_setaffinity` is only supported with a pid of 0 (indicating the current thread)" - ), + _ => throw_unsup_format!( + "`sched_setaffinity` is only supported with a pid of 0 (indicating the current thread)" + ), }; if this.ptr_is_null(mask)? { @@ -1240,26 +1237,21 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { _ => { let target_os = &*this.tcx.sess.target.os; return match target_os { - "android" => - android::EvalContextExt::emulate_foreign_item_inner( - this, link_name, abi, args, dest, - ), - "freebsd" => - freebsd::EvalContextExt::emulate_foreign_item_inner( - this, link_name, abi, args, dest, - ), - "linux" => - linux::EvalContextExt::emulate_foreign_item_inner( - this, link_name, abi, args, dest, - ), - "macos" => - macos::EvalContextExt::emulate_foreign_item_inner( - this, link_name, abi, args, dest, - ), - "solaris" | "illumos" => - solarish::EvalContextExt::emulate_foreign_item_inner( - this, link_name, abi, args, dest, - ), + "android" => android::EvalContextExt::emulate_foreign_item_inner( + this, link_name, abi, args, dest, + ), + "freebsd" => freebsd::EvalContextExt::emulate_foreign_item_inner( + this, link_name, abi, args, dest, + ), + "linux" => linux::EvalContextExt::emulate_foreign_item_inner( + this, link_name, abi, args, dest, + ), + "macos" => macos::EvalContextExt::emulate_foreign_item_inner( + this, link_name, abi, args, dest, + ), + "solaris" | "illumos" => solarish::EvalContextExt::emulate_foreign_item_inner( + this, link_name, abi, args, dest, + ), _ => interp_ok(EmulateItemResult::NotSupported), }; } diff --git a/src/tools/miri/src/shims/unix/fs.rs b/src/tools/miri/src/shims/unix/fs.rs index 1f6acff0787a6..43a2da43052f1 100644 --- a/src/tools/miri/src/shims/unix/fs.rs +++ b/src/tools/miri/src/shims/unix/fs.rs @@ -250,21 +250,26 @@ trait EvalContextExtPrivate<'tcx>: crate::MiriInterpCxExt<'tcx> { match () { _ if file_type.is_dir() => interp_ok(this.eval_libc("DT_DIR").to_u8()?.into()), _ if file_type.is_file() => interp_ok(this.eval_libc("DT_REG").to_u8()?.into()), - _ if file_type.is_symlink() => - interp_ok(this.eval_libc("DT_LNK").to_u8()?.into()), + _ if file_type.is_symlink() => { + interp_ok(this.eval_libc("DT_LNK").to_u8()?.into()) + } // Certain file types are only supported when the host is a Unix system. #[cfg(unix)] - _ if file_type.is_block_device() => - interp_ok(this.eval_libc("DT_BLK").to_u8()?.into()), + _ if file_type.is_block_device() => { + interp_ok(this.eval_libc("DT_BLK").to_u8()?.into()) + } #[cfg(unix)] - _ if file_type.is_char_device() => - interp_ok(this.eval_libc("DT_CHR").to_u8()?.into()), + _ if file_type.is_char_device() => { + interp_ok(this.eval_libc("DT_CHR").to_u8()?.into()) + } #[cfg(unix)] - _ if file_type.is_fifo() => - interp_ok(this.eval_libc("DT_FIFO").to_u8()?.into()), + _ if file_type.is_fifo() => { + interp_ok(this.eval_libc("DT_FIFO").to_u8()?.into()) + } #[cfg(unix)] - _ if file_type.is_socket() => - interp_ok(this.eval_libc("DT_SOCK").to_u8()?.into()), + _ if file_type.is_socket() => { + interp_ok(this.eval_libc("DT_SOCK").to_u8()?.into()) + } // Fallback _ => interp_ok(this.eval_libc("DT_UNKNOWN").to_u8()?.into()), } @@ -1566,17 +1571,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let fd = this.machine.fds.insert_new(FileHandle { file: f, writable: true }); return interp_ok(Scalar::from_i32(fd)); } - Err(e) => - match e.kind() { - // If the random file already exists, keep trying. - ErrorKind::AlreadyExists => continue, - // Any other errors are returned to the caller. - _ => { - // "On error, -1 is returned, and errno is set to - // indicate the error" - return this.set_last_error_and_return_i32(e); - } - }, + Err(e) => match e.kind() { + // If the random file already exists, keep trying. + ErrorKind::AlreadyExists => continue, + // Any other errors are returned to the caller. + _ => { + // "On error, -1 is returned, and errno is set to + // indicate the error" + return this.set_last_error_and_return_i32(e); + } + }, } } diff --git a/src/tools/miri/src/shims/unix/macos/sync.rs b/src/tools/miri/src/shims/unix/macos/sync.rs index 6ba52f2f57e40..7dc58797abfad 100644 --- a/src/tools/miri/src/shims/unix/macos/sync.rs +++ b/src/tools/miri/src/shims/unix/macos/sync.rs @@ -148,12 +148,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { .to_bits(Size::from_bytes(size))?; let futex = this - .get_sync_or_init(ptr, |_| { - MacOsFutex { - futex: Default::default(), - size: Cell::new(size), - shared: Cell::new(is_shared), - } + .get_sync_or_init(ptr, |_| MacOsFutex { + futex: Default::default(), + size: Cell::new(size), + shared: Cell::new(is_shared), }) .unwrap(); @@ -233,12 +231,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let is_shared = flags == shared; - let Some(futex) = this.get_sync_or_init(ptr, |_| { - MacOsFutex { - futex: Default::default(), - size: Cell::new(size), - shared: Cell::new(is_shared), - } + let Some(futex) = this.get_sync_or_init(ptr, |_| MacOsFutex { + futex: Default::default(), + size: Cell::new(size), + shared: Cell::new(is_shared), }) else { // No AllocId, or no live allocation at that AllocId. Return an // error code. (That seems nicer than silently doing something diff --git a/src/tools/miri/src/shims/unix/sync.rs b/src/tools/miri/src/shims/unix/sync.rs index 9f1fabfbf6494..40a78fcb64f95 100644 --- a/src/tools/miri/src/shims/unix/sync.rs +++ b/src/tools/miri/src/shims/unix/sync.rs @@ -214,12 +214,13 @@ fn mutex_kind_from_static_initializer<'tcx>( } // Support additional platform-specific initializers. match &*ecx.tcx.sess.target.os { - "linux" => + "linux" => { if is_initializer("PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP")? { return interp_ok(MutexKind::Recursive); } else if is_initializer("PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP")? { return interp_ok(MutexKind::ErrorCheck); - }, + } + } _ => {} } throw_unsup_format!("unsupported static initializer used for `pthread_mutex_t`"); @@ -515,10 +516,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } else { // Trying to acquire the same mutex again. match mutex.kind { - MutexKind::Default => - throw_ub_format!( - "trying to acquire default mutex already locked by the current thread" - ), + MutexKind::Default => throw_ub_format!( + "trying to acquire default mutex already locked by the current thread" + ), MutexKind::Normal => throw_machine_stop!(TerminationInfo::Deadlock), MutexKind::ErrorCheck => this.eval_libc_i32("EDEADLK"), MutexKind::Recursive => { @@ -547,8 +547,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.eval_libc_i32("EBUSY") } else { match mutex.kind { - MutexKind::Default | MutexKind::Normal | MutexKind::ErrorCheck => - this.eval_libc_i32("EBUSY"), + MutexKind::Default | MutexKind::Normal | MutexKind::ErrorCheck => { + this.eval_libc_i32("EBUSY") + } MutexKind::Recursive => { this.mutex_lock(&mutex.mutex_ref); 0 @@ -575,16 +576,15 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // the “Unlock When Not Owner” column in // https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_unlock.html. match mutex.kind { - MutexKind::Default => - throw_ub_format!( - "unlocked a default mutex that was not locked by the current thread" - ), - MutexKind::Normal => - throw_ub_format!( - "unlocked a PTHREAD_MUTEX_NORMAL mutex that was not locked by the current thread" - ), - MutexKind::ErrorCheck | MutexKind::Recursive => - interp_ok(Scalar::from_i32(this.eval_libc_i32("EPERM"))), + MutexKind::Default => throw_ub_format!( + "unlocked a default mutex that was not locked by the current thread" + ), + MutexKind::Normal => throw_ub_format!( + "unlocked a PTHREAD_MUTEX_NORMAL mutex that was not locked by the current thread" + ), + MutexKind::ErrorCheck | MutexKind::Recursive => { + interp_ok(Scalar::from_i32(this.eval_libc_i32("EPERM"))) + } } } } diff --git a/src/tools/miri/src/shims/windows/handle.rs b/src/tools/miri/src/shims/windows/handle.rs index eec6c62bebc73..2ada26c5f2a70 100644 --- a/src/tools/miri/src/shims/windows/handle.rs +++ b/src/tools/miri/src/shims/windows/handle.rs @@ -205,16 +205,18 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let handle = this.read_scalar(handle)?; match Handle::try_from_scalar(handle, this)? { Ok(handle) => interp_ok(handle), - Err(HandleError::InvalidHandle) => + Err(HandleError::InvalidHandle) => { throw_machine_stop!(TerminationInfo::Abort(format!( "invalid handle {} passed to {function_name}", handle.to_target_isize(this)?, - ))), - Err(HandleError::ThreadNotFound(_)) => + ))) + } + Err(HandleError::ThreadNotFound(_)) => { throw_machine_stop!(TerminationInfo::Abort(format!( "invalid thread ID {} passed to {function_name}", handle.to_target_isize(this)?, - ))), + ))) + } } } @@ -233,7 +235,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.detach_thread(thread, /*allow_terminated_joined*/ true)?; this.eval_windows("c", "TRUE") } - Handle::File(fd_num) => + Handle::File(fd_num) => { if let Some(fd) = this.machine.fds.remove(fd_num) { let err = fd.close_ref(this.machine.communicate(), this)?; if let Err(e) = err { @@ -244,7 +246,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } } else { this.invalid_handle("CloseHandle")? - }, + } + } _ => this.invalid_handle("CloseHandle")?, }; diff --git a/src/tools/miri/src/shims/x86/avx.rs b/src/tools/miri/src/shims/x86/avx.rs index 3aeb2b429dad5..727bbd6172d80 100644 --- a/src/tools/miri/src/shims/x86/avx.rs +++ b/src/tools/miri/src/shims/x86/avx.rs @@ -317,8 +317,9 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let res = match unprefixed_name { "vtestz.pd.256" | "vtestz.pd" | "vtestz.ps.256" | "vtestz.ps" => direct, "vtestc.pd.256" | "vtestc.pd" | "vtestc.ps.256" | "vtestc.ps" => negated, - "vtestnzc.pd.256" | "vtestnzc.pd" | "vtestnzc.ps.256" | "vtestnzc.ps" => - !direct && !negated, + "vtestnzc.pd.256" | "vtestnzc.pd" | "vtestnzc.ps.256" | "vtestnzc.ps" => { + !direct && !negated + } _ => unreachable!(), }; diff --git a/tests/assembly/nvptx-c-abi-arg-v7.rs b/tests/assembly/nvptx-c-abi-arg-v7.rs index 27b64b58f04cc..d7d2885f931eb 100644 --- a/tests/assembly/nvptx-c-abi-arg-v7.rs +++ b/tests/assembly/nvptx-c-abi-arg-v7.rs @@ -1,3 +1,4 @@ +//@ add-core-stubs //@ assembly-output: ptx-linker //@ compile-flags: --crate-type cdylib -C target-cpu=sm_86 -Z unstable-options -Clinker-flavor=llbc //@ only-nvptx64 @@ -10,10 +11,8 @@ #![feature(abi_ptx, lang_items, no_core)] #![no_core] -#[lang = "sized"] -trait Sized {} -#[lang = "copy"] -trait Copy {} +extern crate minicore; +use minicore::*; #[repr(C)] pub struct SingleU8 { diff --git a/tests/assembly/nvptx-c-abi-ret-v7.rs b/tests/assembly/nvptx-c-abi-ret-v7.rs index 56ab182fcce22..085debe8b3cb5 100644 --- a/tests/assembly/nvptx-c-abi-ret-v7.rs +++ b/tests/assembly/nvptx-c-abi-ret-v7.rs @@ -1,3 +1,4 @@ +//@ add-core-stubs //@ assembly-output: ptx-linker //@ compile-flags: --crate-type cdylib -C target-cpu=sm_86 -Z unstable-options -Clinker-flavor=llbc //@ only-nvptx64 @@ -10,10 +11,8 @@ #![feature(abi_ptx, lang_items, no_core)] #![no_core] -#[lang = "sized"] -trait Sized {} -#[lang = "copy"] -trait Copy {} +extern crate minicore; +use minicore::*; #[repr(C)] pub struct SingleU8 { diff --git a/tests/assembly/nvptx-kernel-abi/nvptx-kernel-args-abi-v7.rs b/tests/assembly/nvptx-kernel-abi/nvptx-kernel-args-abi-v7.rs index b3bfc66a5a570..cd8d52a41033c 100644 --- a/tests/assembly/nvptx-kernel-abi/nvptx-kernel-args-abi-v7.rs +++ b/tests/assembly/nvptx-kernel-abi/nvptx-kernel-args-abi-v7.rs @@ -1,3 +1,4 @@ +//@ add-core-stubs //@ assembly-output: ptx-linker //@ compile-flags: --crate-type cdylib -C target-cpu=sm_86 -Z unstable-options -Clinker-flavor=llbc //@ only-nvptx64 @@ -20,10 +21,8 @@ #![feature(abi_ptx, lang_items, no_core)] #![no_core] -#[lang = "sized"] -trait Sized {} -#[lang = "copy"] -trait Copy {} +extern crate minicore; +use minicore::*; #[repr(C)] pub struct SingleU8 { diff --git a/tests/assembly/simd-intrinsic-gather.rs b/tests/assembly/simd-intrinsic-gather.rs index bcab0ba1cc09b..665858eb14747 100644 --- a/tests/assembly/simd-intrinsic-gather.rs +++ b/tests/assembly/simd-intrinsic-gather.rs @@ -22,9 +22,6 @@ pub struct m64x4([i64; 4]); #[repr(simd)] pub struct pf64x4([*const f64; 4]); -#[rustc_intrinsic] -unsafe fn simd_gather(values: V, mask: M, pointer: P) -> V; - // CHECK-LABEL: gather_f64x4 #[no_mangle] pub unsafe extern "C" fn gather_f64x4(mask: m64x4, ptrs: pf64x4) -> f64x4 { diff --git a/tests/assembly/simd-intrinsic-mask-load.rs b/tests/assembly/simd-intrinsic-mask-load.rs index d3f3453a780a4..1994928a0b1b7 100644 --- a/tests/assembly/simd-intrinsic-mask-load.rs +++ b/tests/assembly/simd-intrinsic-mask-load.rs @@ -34,9 +34,6 @@ pub struct f64x4([f64; 4]); #[repr(simd)] pub struct m64x4([i64; 4]); -#[rustc_intrinsic] -unsafe fn simd_masked_load(mask: M, pointer: P, values: T) -> T; - // CHECK-LABEL: load_i8x16 #[no_mangle] pub unsafe extern "C" fn load_i8x16(mask: m8x16, pointer: *const i8) -> i8x16 { diff --git a/tests/assembly/small_data_threshold.rs b/tests/assembly/small_data_threshold.rs index bed515915b85d..929610f358810 100644 --- a/tests/assembly/small_data_threshold.rs +++ b/tests/assembly/small_data_threshold.rs @@ -1,4 +1,5 @@ // Test for -Z small_data_threshold=... +//@ add-core-stubs //@ revisions: RISCV MIPS HEXAGON M68K //@ assembly-output: emit-asm //@ compile-flags: -Z small_data_threshold=4 @@ -19,11 +20,8 @@ #![no_core] #![crate_type = "lib"] -#[lang = "sized"] -trait Sized {} - -#[lang = "drop_in_place"] -fn drop_in_place(_: *mut T) {} +extern crate minicore; +use minicore::*; #[used] #[no_mangle] diff --git a/tests/auxiliary/minicore.rs b/tests/auxiliary/minicore.rs index 941c4abed4679..a31875b4e65f2 100644 --- a/tests/auxiliary/minicore.rs +++ b/tests/auxiliary/minicore.rs @@ -25,11 +25,13 @@ f16, f128, asm_experimental_arch, - unboxed_closures + unboxed_closures, + intrinsics )] #![allow(unused, improper_ctypes_definitions, internal_features)] #![no_std] #![no_core] +#![rustc_coherence_is_core] // `core` has some exotic `marker_impls!` macro for handling the with-generics cases, but for our // purposes, just use a simple macro_rules macro. @@ -190,3 +192,82 @@ impl<'a, 'b: 'a, T: ?Sized + Unsize, U: ?Sized> CoerceUnsized<&'a U> for &'b trait Drop { fn drop(&mut self); } + +#[lang = "neg"] +trait Neg: Sized { + type Output; + + fn neg(self) -> Self::Output; +} + +// Macro to implement Neg for a list of primitive numeric types +// macro_rules! impl_neg_trait { +// ( $($ty:ty),* $(,)? ) => { +// $( +// impl Neg for $ty { +// type Output = $ty; +// +// fn neg(self) -> Self::Output { +// -self +// } +// } +// )* +// } +// } +// +// impl_neg_trait!(isize, i8, i16, i32, i64, i128,); + +#[lang = "Ordering"] +#[repr(i8)] +pub enum Ordering { + Less = 0, + Equal = 1, + Greater = 2, +} + +#[rustc_intrinsic] +pub fn three_way_compare(lhs: T, rhs: T) -> Ordering; + +#[rustc_intrinsic] +pub unsafe fn simd_gather(values: V, mask: M, pointer: P) -> V; + +#[rustc_intrinsic] +pub unsafe fn simd_masked_load(mask: M, pointer: P, values: T) -> T; + +// Cannot use `std::intrinsics::copy_nonoverlapping` as that is a wrapper function +#[rustc_nounwind] +#[rustc_intrinsic] +unsafe fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize); + +#[lang = "panic_location"] +struct Location<'a> { + _file: &'a str, + _line: u32, + _col: u32, +} + +#[lang = "panic_const_div_by_zero"] +#[inline] +#[track_caller] +fn panic_div_zero() -> ! { + loop {} +} + +#[lang = "panic_const_div_overflow"] +#[inline] +#[track_caller] +pub fn panic_div_overflow() -> ! { + loop {} +} + +#[rustc_intrinsic] +pub fn size_of() -> usize { + loop {} +} + +#[rustc_intrinsic] +pub unsafe fn catch_unwind( + try_fn: fn(_: *mut u8), + data: *mut u8, + catch_fn: fn(_: *mut u8, _: *mut u8), +) -> i32; diff --git a/tests/codegen-units/item-collection/implicit-panic-call.rs b/tests/codegen-units/item-collection/implicit-panic-call.rs index b348b4acc2486..516043cbd64ee 100644 --- a/tests/codegen-units/item-collection/implicit-panic-call.rs +++ b/tests/codegen-units/item-collection/implicit-panic-call.rs @@ -1,4 +1,5 @@ -//@ compile-flags:-Zprint-mono-items=lazy +//@ add-core-stubs +// @ compile-flags:-Zprint-mono-items=lazy // rust-lang/rust#90405 // Ensure implicit panic calls are collected @@ -9,35 +10,8 @@ #![no_core] #![no_std] -#[lang = "panic_location"] -struct Location<'a> { - _file: &'a str, - _line: u32, - _col: u32, -} - -#[lang = "panic_const_div_by_zero"] -#[inline] -#[track_caller] -fn panic_div_zero() -> ! { - loop {} -} - -#[lang = "panic_const_div_overflow"] -#[inline] -#[track_caller] -fn panic_div_overflow() -> ! { - loop {} -} - -#[lang = "sized"] -trait Sized {} - -#[lang = "copy"] -trait Copy {} - -#[lang = "freeze"] -trait Freeze {} +extern crate minicore; +use minicore::*; impl Copy for i32 {} diff --git a/tests/codegen/abi-x86-sse.rs b/tests/codegen/abi-x86-sse.rs index 837bf6134b01c..79170b81439ff 100644 --- a/tests/codegen/abi-x86-sse.rs +++ b/tests/codegen/abi-x86-sse.rs @@ -1,4 +1,5 @@ -//@ compile-flags: -Z merge-functions=disabled +//@ add-core-stubs +// @ compile-flags: -Z merge-functions=disabled //@ revisions: x86-64 //@[x86-64] compile-flags: --target x86_64-unknown-linux-gnu @@ -16,11 +17,8 @@ #![no_core] #![crate_type = "lib"] -#[lang = "sized"] -trait Sized {} - -#[lang = "copy"] -trait Copy {} +extern crate minicore; +use minicore::*; // Ensure this type is passed without ptr indirection on targets that // require SSE2. diff --git a/tests/codegen/emscripten-catch-unwind-js-eh.rs b/tests/codegen/emscripten-catch-unwind-js-eh.rs index 3ab4b5c9c6312..f6a837e7a3778 100644 --- a/tests/codegen/emscripten-catch-unwind-js-eh.rs +++ b/tests/codegen/emscripten-catch-unwind-js-eh.rs @@ -1,3 +1,4 @@ +//@ add-core-stubs //@ compile-flags: -Copt-level=3 --target wasm32-unknown-emscripten //@ needs-llvm-components: webassembly @@ -9,26 +10,8 @@ #![no_std] #![no_core] -#[lang = "sized"] -trait Sized {} -#[lang = "freeze"] -trait Freeze {} -#[lang = "copy"] -trait Copy {} - -impl Copy for *mut T {} - -#[rustc_intrinsic] -fn size_of() -> usize { - loop {} -} - -#[rustc_intrinsic] -unsafe fn catch_unwind( - try_fn: fn(_: *mut u8), - data: *mut u8, - catch_fn: fn(_: *mut u8, _: *mut u8), -) -> i32; +extern crate minicore; +use minicore::*; // CHECK-LABEL: @ptr_size #[no_mangle] diff --git a/tests/codegen/emscripten-catch-unwind-wasm-eh.rs b/tests/codegen/emscripten-catch-unwind-wasm-eh.rs index d0571e4df0816..da140961ffd38 100644 --- a/tests/codegen/emscripten-catch-unwind-wasm-eh.rs +++ b/tests/codegen/emscripten-catch-unwind-wasm-eh.rs @@ -1,3 +1,4 @@ +//@ add-core-stubs //@ compile-flags: -Copt-level=3 --target wasm32-unknown-emscripten -Z emscripten-wasm-eh //@ needs-llvm-components: webassembly @@ -8,25 +9,10 @@ #![no_std] #![no_core] -#[lang = "sized"] -trait Sized {} -#[lang = "freeze"] -trait Freeze {} -#[lang = "copy"] -trait Copy {} +extern crate minicore; +use minicore::*; -impl Copy for *mut T {} -#[rustc_intrinsic] -fn size_of() -> usize { - loop {} -} -#[rustc_intrinsic] -unsafe fn catch_unwind( - try_fn: fn(_: *mut u8), - data: *mut u8, - catch_fn: fn(_: *mut u8, _: *mut u8), -) -> i32; // CHECK-LABEL: @ptr_size #[no_mangle] diff --git a/tests/codegen/terminating-catchpad.rs b/tests/codegen/terminating-catchpad.rs index 17d8879630094..f9e95c2145b83 100644 --- a/tests/codegen/terminating-catchpad.rs +++ b/tests/codegen/terminating-catchpad.rs @@ -1,3 +1,4 @@ +//@ add-core-stubs //@ revisions: emscripten wasi seh //@[emscripten] compile-flags: --target wasm32-unknown-emscripten -Z emscripten-wasm-eh //@[wasi] compile-flags: --target wasm32-wasip1 -C panic=unwind @@ -15,8 +16,8 @@ #![no_std] #![no_core] -#[lang = "sized"] -trait Sized {} +extern crate minicore; +use minicore::*; unsafe extern "C-unwind" { safe fn unwinds(); diff --git a/tests/codegen/unwind-abis/aapcs-unwind-abi.rs b/tests/codegen/unwind-abis/aapcs-unwind-abi.rs index 0d9c7757883f7..54221c4e0a45a 100644 --- a/tests/codegen/unwind-abis/aapcs-unwind-abi.rs +++ b/tests/codegen/unwind-abis/aapcs-unwind-abi.rs @@ -1,9 +1,11 @@ +//@ add-core-stubs //@ needs-llvm-components: arm //@ compile-flags: --target=armv7-unknown-linux-gnueabihf --crate-type=rlib -Cno-prepopulate-passes #![no_core] #![feature(no_core, lang_items)] -#[lang = "sized"] -trait Sized {} + +extern crate minicore; +use minicore::*; // Test that `nounwind` attributes are correctly applied to exported `aapcs` and // `aapcs-unwind` extern functions. `aapcs-unwind` functions MUST NOT have this attribute. We diff --git a/tests/codegen/unwind-abis/fastcall-unwind-abi.rs b/tests/codegen/unwind-abis/fastcall-unwind-abi.rs index 4c7b2856e2e45..52f249adb3b35 100644 --- a/tests/codegen/unwind-abis/fastcall-unwind-abi.rs +++ b/tests/codegen/unwind-abis/fastcall-unwind-abi.rs @@ -1,9 +1,11 @@ +//@ add-core-stubs //@ needs-llvm-components: x86 //@ compile-flags: --target=i686-pc-windows-msvc --crate-type=rlib -Cno-prepopulate-passes #![no_core] #![feature(no_core, lang_items)] -#[lang = "sized"] -trait Sized {} + +extern crate minicore; +use minicore::*; // Test that `nounwind` attributes are correctly applied to exported `fastcall` and // `fastcall-unwind` extern functions. `fastcall-unwind` functions MUST NOT have this attribute. We diff --git a/tests/codegen/unwind-abis/stdcall-unwind-abi.rs b/tests/codegen/unwind-abis/stdcall-unwind-abi.rs index ffc11d1faef8c..6d8a29f513dc9 100644 --- a/tests/codegen/unwind-abis/stdcall-unwind-abi.rs +++ b/tests/codegen/unwind-abis/stdcall-unwind-abi.rs @@ -1,9 +1,11 @@ +//@ add-core-stubs //@ needs-llvm-components: x86 //@ compile-flags: --target=i686-pc-windows-msvc --crate-type=rlib -Cno-prepopulate-passes #![no_core] #![feature(no_core, lang_items)] -#[lang = "sized"] -trait Sized {} + +extern crate minicore; +use minicore::*; // Test that `nounwind` attributes are correctly applied to exported `stdcall` and `stdcall-unwind` // extern functions. `stdcall-unwind` functions MUST NOT have this attribute. We disable diff --git a/tests/codegen/unwind-abis/sysv64-unwind-abi.rs b/tests/codegen/unwind-abis/sysv64-unwind-abi.rs index c869ca7e2b825..f4f0df15d995a 100644 --- a/tests/codegen/unwind-abis/sysv64-unwind-abi.rs +++ b/tests/codegen/unwind-abis/sysv64-unwind-abi.rs @@ -1,9 +1,11 @@ +//@ add-core-stubs //@ needs-llvm-components: x86 //@ compile-flags: --target=x86_64-unknown-linux-gnu --crate-type=rlib -Cno-prepopulate-passes #![no_core] #![feature(no_core, lang_items)] -#[lang = "sized"] -trait Sized {} + +extern crate minicore; +use minicore::*; // Test that `nounwind` attributes are correctly applied to exported `sysv64` and // `sysv64-unwind` extern functions. `sysv64-unwind` functions MUST NOT have this attribute. We diff --git a/tests/codegen/unwind-abis/thiscall-unwind-abi.rs b/tests/codegen/unwind-abis/thiscall-unwind-abi.rs index 19b23ee47ba84..c611af12983b2 100644 --- a/tests/codegen/unwind-abis/thiscall-unwind-abi.rs +++ b/tests/codegen/unwind-abis/thiscall-unwind-abi.rs @@ -1,9 +1,11 @@ +//@ add-core-stubs //@ needs-llvm-components: x86 //@ compile-flags: --target=i686-pc-windows-msvc --crate-type=rlib -Cno-prepopulate-passes #![no_core] #![feature(no_core, lang_items)] -#[lang = "sized"] -trait Sized {} + +extern crate minicore; +use minicore::*; // Test that `nounwind` attributes are correctly applied to exported `thiscall` and // `thiscall-unwind` extern functions. `thiscall-unwind` functions MUST NOT have this attribute. We diff --git a/tests/codegen/unwind-abis/vectorcall-unwind-abi.rs b/tests/codegen/unwind-abis/vectorcall-unwind-abi.rs index b420f67ca9b70..872a47f90f785 100644 --- a/tests/codegen/unwind-abis/vectorcall-unwind-abi.rs +++ b/tests/codegen/unwind-abis/vectorcall-unwind-abi.rs @@ -1,9 +1,11 @@ +//@ add-core-stubs //@ needs-llvm-components: x86 //@ compile-flags: --target=i686-pc-windows-msvc --crate-type=rlib -Cno-prepopulate-passes #![no_core] #![feature(no_core, lang_items, abi_vectorcall)] -#[lang = "sized"] -trait Sized {} + +extern crate minicore; +use minicore::*; // Test that `nounwind` attributes are correctly applied to exported `vectorcall` and // `vectorcall-unwind` extern functions. `vectorcall-unwind` functions MUST NOT have this attribute. diff --git a/tests/codegen/unwind-abis/win64-unwind-abi.rs b/tests/codegen/unwind-abis/win64-unwind-abi.rs index 2697d3cbcd68e..ce6f398029bda 100644 --- a/tests/codegen/unwind-abis/win64-unwind-abi.rs +++ b/tests/codegen/unwind-abis/win64-unwind-abi.rs @@ -1,9 +1,11 @@ +//@ add-core-stubs //@ needs-llvm-components: x86 //@ compile-flags: --target=x86_64-unknown-linux-gnu --crate-type=rlib -Cno-prepopulate-passes #![no_core] #![feature(no_core, lang_items)] -#[lang = "sized"] -trait Sized {} + +extern crate minicore; +use minicore::*; // Test that `nounwind` attributes are correctly applied to exported `win64` and // `win64-unwind` extern functions. `win64-unwind` functions MUST NOT have this attribute. We diff --git a/tests/rustdoc-json/impls/auto.rs b/tests/rustdoc-json/impls/auto.rs index 5440301f96501..1a44f244a120b 100644 --- a/tests/rustdoc-json/impls/auto.rs +++ b/tests/rustdoc-json/impls/auto.rs @@ -1,8 +1,10 @@ +//@ add-core-stubs + #![feature(no_core, auto_traits, lang_items, arbitrary_self_types)] #![no_core] -#[lang = "sized"] -trait Sized {} +extern crate minicore; +use minicore::*; #[lang = "legacy_receiver"] pub trait LegacyReceiver {} diff --git a/tests/rustdoc-json/primitives/local_primitive.rs b/tests/rustdoc-json/primitives/local_primitive.rs index b58120bae052f..80f4c359e8870 100644 --- a/tests/rustdoc-json/primitives/local_primitive.rs +++ b/tests/rustdoc-json/primitives/local_primitive.rs @@ -1,3 +1,4 @@ +//@ add-core-stubs // Regression test for . #![feature(no_core)] @@ -6,7 +7,10 @@ #![no_core] #![rustc_coherence_is_core] -//! Link to [i32][prim@i32] [i64][prim@i64] +extern crate minicore; +use minicore::*; + +/// Link to [i32][prim@i32] [i64][prim@i64] #[rustc_doc_primitive = "i32"] mod prim_i32 {} diff --git a/tests/rustdoc-json/primitives/primitive_impls.rs b/tests/rustdoc-json/primitives/primitive_impls.rs index a1f0ebd11b636..cd189cc26e2cf 100644 --- a/tests/rustdoc-json/primitives/primitive_impls.rs +++ b/tests/rustdoc-json/primitives/primitive_impls.rs @@ -1,13 +1,15 @@ +//@ add-core-stubs + #![feature(no_core, lang_items)] #![feature(rustc_attrs)] #![feature(rustdoc_internals)] #![no_core] #![rustc_coherence_is_core] -//@ set impl_i32 = "$.index[?(@.docs=='Only core can do this')].id" +extern crate minicore; +use minicore::*; -#[lang = "sized"] -trait Sized {} +//@ set impl_i32 = "$.index[?(@.docs=='Only core can do this')].id" /// Only core can do this impl i32 { diff --git a/tests/rustdoc-ui/custom_code_classes_in_docs-warning3.rs b/tests/rustdoc-ui/custom_code_classes_in_docs-warning3.rs index 18ac37280c0ef..d409d269b97a1 100644 --- a/tests/rustdoc-ui/custom_code_classes_in_docs-warning3.rs +++ b/tests/rustdoc-ui/custom_code_classes_in_docs-warning3.rs @@ -1,3 +1,4 @@ +//@ add-core-stubs // This test ensures that warnings are working as expected for "custom_code_classes_in_docs" // feature. @@ -5,8 +6,8 @@ #![feature(no_core, lang_items)] #![no_core] -#[lang = "sized"] -trait Sized {} +extern crate minicore; +use minicore::*; /// ```{class="} /// main; diff --git a/tests/rustdoc-ui/target-feature-stability.rs b/tests/rustdoc-ui/target-feature-stability.rs index 17fa3ccfe3e89..e731666d7559a 100644 --- a/tests/rustdoc-ui/target-feature-stability.rs +++ b/tests/rustdoc-ui/target-feature-stability.rs @@ -2,6 +2,7 @@ //! that we can use the `neon` target feature on ARM32 targets in rustdoc despite there //! being a "forbidden" feature of the same name for aarch64, and rustdoc merging the //! target features of all targets. +//@ add-core-stubs //@ check-pass //@ revisions: arm aarch64 //@[arm] compile-flags: --target armv7-unknown-linux-gnueabihf @@ -14,8 +15,8 @@ #![feature(arm_target_feature)] #![no_core] -#[lang = "sized"] -pub trait Sized {} +extern crate minicore; +use minicore::*; // `fp-armv8` is "forbidden" on aarch64 as we tie it to `neon`. #[target_feature(enable = "fp-armv8")] diff --git a/tests/ui/stack-protector/warn-stack-protector-unsupported.rs b/tests/ui/stack-protector/warn-stack-protector-unsupported.rs index dc61e35a089a5..108ede7e7f041 100644 --- a/tests/ui/stack-protector/warn-stack-protector-unsupported.rs +++ b/tests/ui/stack-protector/warn-stack-protector-unsupported.rs @@ -1,3 +1,4 @@ +//@ add-core-stubs //@ build-pass //@ revisions: all strong basic //@ compile-flags: --target nvptx64-nvidia-cuda @@ -11,12 +12,10 @@ #![no_std] #![no_core] -#[lang = "sized"] -trait Sized {} -#[lang = "copy"] -trait Copy {} +extern crate minicore; +use minicore::*; -pub fn main(){} +pub fn main() {} //[all]~? WARN `-Z stack-protector=all` is not supported for target nvptx64-nvidia-cuda and will be ignored //[strong]~? WARN `-Z stack-protector=strong` is not supported for target nvptx64-nvidia-cuda and will be ignored