diff --git a/Cargo.lock b/Cargo.lock index 4b407d941547c..084d594ff6c21 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -462,7 +462,6 @@ dependencies = [ "cargo_metadata 0.23.1", "directories", "rustc-build-sysroot", - "rustc_tools_util 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", "rustc_version", "serde", "serde_json", @@ -667,7 +666,7 @@ dependencies = [ "itertools", "pulldown-cmark", "regex", - "rustc_tools_util 0.4.2", + "rustc_tools_util", "serde", "serde_json", "tempfile", @@ -4907,12 +4906,6 @@ dependencies = [ name = "rustc_tools_util" version = "0.4.2" -[[package]] -name = "rustc_tools_util" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3b75158011a63889ba12084cf1224baad7bcad50f6ee7c842f772b74aa148ed" - [[package]] name = "rustc_trait_selection" version = "0.0.0" diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 900fbac6b2356..13696b8f1ba08 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -637,16 +637,15 @@ impl<'hir> LoweringContext<'_, 'hir> { let (generics, (decl, fn_args)) = self.lower_generics(generics, itctx, |this| { ( // Disallow `impl Trait` in foreign items. - // Parameters are discarded because foreign functions don't have a body this.lower_fn_decl( fdec, i.id, hir_id, FnDeclKind::ExternFn, None, - DiscardParams::Yes, + DiscardParams::No, ), - this.lower_fn_params_to_idents(fdec), + this.lower_fn_params(fdec), ) }); @@ -1253,7 +1252,7 @@ impl<'hir> LoweringContext<'_, 'hir> { body_id } - fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> { + pub(super) fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> { let hir_id = self.lower_node_id(param.id); self.lower_attrs(hir_id, ¶m.attrs, param.span, AstTarget::Param(param)); hir::Param { diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index ae6bdd15853bc..a452c5f11285d 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -1954,6 +1954,15 @@ impl<'hir> LoweringContext<'_, 'hir> { )) } + fn lower_fn_params(&mut self, decl: &FnDecl) -> &'hir [hir::Param<'hir>] { + self.arena.alloc_from_iter( + decl.inputs + .iter() + .filter(|param| !param.is_const_param()) + .map(|param| self.lower_param(param)), + ) + } + /// Lowers a function declaration. /// /// `decl`: the unlowered (AST) function declaration. diff --git a/compiler/rustc_attr_ir/src/lang_items.rs b/compiler/rustc_attr_ir/src/lang_items.rs index cee591e8c0240..d8a2a54566be8 100644 --- a/compiler/rustc_attr_ir/src/lang_items.rs +++ b/compiler/rustc_attr_ir/src/lang_items.rs @@ -157,6 +157,8 @@ language_item_table! { AlignOf, sym::mem_align_const, align_const, Target::AssocConst(AssocCtxt::Trait), GenericRequirement::Exact(0); SizeOf, sym::mem_size_const, size_const, Target::AssocConst(AssocCtxt::Trait), GenericRequirement::Exact(0); OffsetOf, kw::OffsetOf, offset_of, Target::Fn, GenericRequirement::Exact(1); + RawEq, sym::raw_eq, raw_eq, Target::Fn, GenericRequirement::Exact(1); + CompareBytes, sym::compare_bytes, compare_bytes, Target::Fn, GenericRequirement::Exact(0); /// Trait injected by `#[derive(PartialEq)]`, (i.e. "Partial EQ"). StructuralPeq, sym::structural_peq, structural_peq_trait, Target::Trait, GenericRequirement::None; Debug, sym::debug, debug_trait, Target::Trait, GenericRequirement::Exact(0); diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index 650df88127911..dea799a6af08d 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -237,7 +237,11 @@ pub(crate) fn frame_pointer(sess: &Session) -> FramePointer { if let InstrumentMcount::Mcount(_) = opts.unstable_opts.instrument_mcount { fp.ratchet(FramePointer::Always); } - fp.ratchet(opts.cg.force_frame_pointers); + // On s390x, `-Cforce-frame-pointers` opts in to the `backchain` LLVM function attribute + // (set in `s390x_fn_attrs`) instead of the generic `frame-pointer` attribute. + if !(sess.target.arch == Arch::S390x) { + fp.ratchet(opts.cg.force_frame_pointers); + } fp } @@ -410,34 +414,44 @@ fn stackprotector_attr<'ll>(cx: &SimpleCx<'ll>, sess: &Session) -> Option( +/// s390x specific function attributes +/// - `-Cforce-frame-pointers` emits "backchain" +/// - "backchain" + "packed_stack" enforces "softfloat" +fn s390x_fn_attrs<'ll>( cx: &SimpleCx<'ll>, sess: &Session, - function_attributes: &[TargetFeature], -) -> Option> { + fn_target_features: &[TargetFeature], +) -> Vec> { if sess.target.arch != Arch::S390x { - return None; + return vec![]; + } + + let mut attrs = Vec::new(); + + // `-Cforce-frame-pointers` enables `backchain` + let have_backchain = sess.opts.cg.force_frame_pointers != FramePointer::MayOmit; + if have_backchain { + attrs.push(llvm::CreateAttrString(cx.llcx, "backchain")); } + + // only continue if we have packed_stack if !sess.opts.unstable_opts.packed_stack { - return None; + return attrs; } - // The backchain and softfloat flags can be set via -Ctarget-features=... - // or via #[target_features(enable = ...)] so we have to check both possibilities - let have_backchain = sess.internal_target_features.contains(&sym::backchain) - || function_attributes.iter().any(|feature| feature.name == sym::backchain); let have_softfloat = sess.internal_target_features.contains(&sym::soft_float) - || function_attributes.iter().any(|feature| feature.name == sym::soft_float); + || fn_target_features.iter().any(|f| f.name == sym::soft_float); // If both, backchain and packedstack, are enabled LLVM cannot generate valid function entry points // with the default ABI. However if the softfloat flag is set LLVM will switch to the softfloat // ABI, where this works. if have_backchain && !have_softfloat { sess.dcx().emit_err(PackedStackBackchainNeedsSoftfloat); - return None; + return attrs; } - Some(llvm::CreateAttrString(cx.llcx, "packed-stack")) + attrs.push(llvm::CreateAttrString(cx.llcx, "packed-stack")); + attrs } pub(crate) fn target_cpu_attr<'ll>(cx: &SimpleCx<'ll>, sess: &Session) -> Attribute<'ll> { @@ -666,9 +680,12 @@ pub(crate) fn llfn_attrs_from_instance<'ll, 'tcx>( if let Some(align) = codegen_fn_attrs.alignment { llvm::set_alignment(llfn, align); } - if let Some(packed_stack) = packed_stack_attr(cx, sess, &codegen_fn_attrs.target_features) { - to_add.push(packed_stack); + + // Apply and check s390x-specific attributes: backchain and packed-stack. + if sess.target.arch == Arch::S390x { + to_add.extend(s390x_fn_attrs(cx, sess, &codegen_fn_attrs.target_features)); } + to_add.extend(patchable_function_entry_attrs( cx, sess, diff --git a/compiler/rustc_codegen_llvm/src/diagnostics.rs b/compiler/rustc_codegen_llvm/src/diagnostics.rs index 7d24dec502dbb..b744947f603e1 100644 --- a/compiler/rustc_codegen_llvm/src/diagnostics.rs +++ b/compiler/rustc_codegen_llvm/src/diagnostics.rs @@ -252,9 +252,9 @@ pub(crate) struct FixedX18InvalidArch<'a> { } #[derive(Diagnostic)] -#[diag("`-Zpacked-stack` is incompatible with `backchain` target feature")] +#[diag("`-Zpacked-stack` is incompatible with `-Cforce-frame-pointers` on s390x")] #[note( - "enabling both `-Zpacked-stack` and the `backchain` target feature is incompatible with the default s390x ABI. Switch to s390x-unknown-none-softfloat if you need both attributes" + "`-Zpacked-stack` and `-Cforce-frame-pointers` is incompatible with the default s390x ABI (note that force-frame-pointers is implemented via backchain)" )] pub(crate) struct PackedStackBackchainNeedsSoftfloat; diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 779b049063b8f..2ee73dbc58570 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -4876,12 +4876,7 @@ impl ForeignItem<'_> { #[derive(Debug, Clone, Copy, StableHash)] pub enum ForeignItemKind<'hir> { /// A foreign function. - /// - /// All argument idents are actually always present (i.e. `Some`), but - /// `&[Option]` is used because of code paths shared with `TraitFn` - /// and `FnPtrTy`. The sharing is due to all of these cases not allowing - /// arbitrary patterns for parameters. - Fn(FnSig<'hir>, &'hir [Option], &'hir Generics<'hir>), + Fn(FnSig<'hir>, &'hir [Param<'hir>], &'hir Generics<'hir>), /// A foreign static item (`static ext: u8`). Static(&'hir Ty<'hir>, Mutability, Safety), /// A foreign type. diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index bac88ad43ac30..cdb0cc524e6ce 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -690,11 +690,11 @@ pub fn walk_foreign_item<'v, V: Visitor<'v>>( try_visit!(visitor.visit_ident(*ident)); match *kind { - ForeignItemKind::Fn(ref sig, param_idents, ref generics) => { + ForeignItemKind::Fn(ref sig, params, ref generics) => { try_visit!(visitor.visit_generics(generics)); try_visit!(visitor.visit_fn_decl(sig.decl)); - for ident in param_idents.iter().copied() { - visit_opt!(visitor, visit_ident, ident); + for param in params { + try_visit!(visitor.visit_param(param)); } } ForeignItemKind::Static(ref typ, _, _) => { diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 3e19351c54fcb..7758d49d39675 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -519,14 +519,15 @@ impl<'a> State<'a> { self.maybe_print_comment(item.span.lo()); self.print_attrs(self.attrs(item.hir_id())); match item.kind { - hir::ForeignItemKind::Fn(sig, arg_idents, generics) => { + hir::ForeignItemKind::Fn(sig, params, generics) => { let (cb, ib) = self.head(""); self.print_fn( sig.header, Some(item.ident.name), generics, sig.decl, - arg_idents, + &[], + params, None, ); self.end(ib); @@ -660,7 +661,15 @@ impl<'a> State<'a> { } hir::ItemKind::Fn { ident, sig, generics, body, .. } => { let (cb, ib) = self.head(""); - self.print_fn(sig.header, Some(ident.name), generics, sig.decl, &[], Some(body)); + self.print_fn( + sig.header, + Some(ident.name), + generics, + sig.decl, + &[], + &[], + Some(body), + ); self.word(" "); self.end(ib); self.end(cb); @@ -984,7 +993,7 @@ impl<'a> State<'a> { arg_idents: &[Option], body_id: Option, ) { - self.print_fn(m.header, Some(ident.name), generics, m.decl, arg_idents, body_id); + self.print_fn(m.header, Some(ident.name), generics, m.decl, arg_idents, &[], body_id); } fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) { @@ -2280,7 +2289,9 @@ impl<'a> State<'a> { name: Option, generics: &hir::Generics<'_>, decl: &hir::FnDecl<'_>, + // Will take from one of these three for the param names arg_idents: &[Option], + params: &[hir::Param<'_>], body_id: Option, ) { self.print_fn_header_info(header); @@ -2308,6 +2319,10 @@ impl<'a> State<'a> { s.word(":"); s.space(); } + } else if let Some(param) = params.get(i) { + s.print_param(param); + s.word(":"); + s.space(); } else if let Some(body_id) = body_id { s.ann.nested(s, Nested::BodyParamPat(body_id, i)); s.word(":"); @@ -2618,6 +2633,7 @@ impl<'a> State<'a> { generics, decl, arg_idents, + &[], None, ); self.end(ib); diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index 5d116feb06cb9..383256184a6a3 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -2142,14 +2142,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { is_method: bool, ) -> Option<(IndexVec, FnParam<'_>)>, &hir::Generics<'_>)> { - let (sig, generics, body_id, params) = match self.tcx.hir_get_if_local(def_id)? { + let (sig, generics, params, idents) = match self.tcx.hir_get_if_local(def_id)? { hir::Node::TraitItem(&hir::TraitItem { generics, kind: hir::TraitItemKind::Fn(sig, trait_fn), .. }) => match trait_fn { hir::TraitFn::Required(params) => (sig, generics, None, Some(params)), - hir::TraitFn::Provided(body) => (sig, generics, Some(body), None), + hir::TraitFn::Provided(body) => { + (sig, generics, Some(self.tcx.hir_body(body).params), None) + } }, hir::Node::ImplItem(&hir::ImplItem { generics, @@ -2159,11 +2161,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { | hir::Node::Item(&hir::Item { kind: hir::ItemKind::Fn { sig, generics, body, .. }, .. - }) => (sig, generics, Some(body), None), + }) => (sig, generics, Some(self.tcx.hir_body(body).params), None), hir::Node::ForeignItem(&hir::ForeignItem { kind: hir::ForeignItemKind::Fn(sig, params, generics), .. - }) => (sig, generics, None, Some(params)), + }) => (sig, generics, Some(params), None), _ => return None, }; @@ -2184,10 +2186,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None } }); - let mut params_with_generics: IndexVec = match (body_id, params) { + let mut params_with_generics: IndexVec = match (params, idents) { (Some(_), Some(_)) | (None, None) => unreachable!(), - (Some(body), None) => { - let params = self.tcx.hir_body(body).params; + (Some(params), None) => { let params = params .get(is_method as usize..params.len() - sig.decl.c_variadic() as usize)?; debug_assert_eq!(params.len(), fn_inputs.len()); diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 3b335aaa55f7c..d552b6c4ac2c9 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -24,6 +24,7 @@ use rustc_ast_pretty::pprust::expr_to_string; use rustc_attr_ir::lang_items::LangItem; use rustc_attr_ir::{AttributeKind, DocAttribute, find_attr}; use rustc_attr_parsing::AttributeParser; +use rustc_data_structures::fx::FxHashMap; use rustc_errors::{Applicability, Diagnostic, msg}; use rustc_feature::GateIssue; use rustc_hir::def::{DefKind, Res}; @@ -48,15 +49,16 @@ use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _ use crate::diagnostics::{ BuiltinAnonymousParams, BuiltinConstNoMangle, BuiltinDerefNullptr, BuiltinDoubleNegations, - BuiltinDoubleNegationsAddParens, BuiltinEllipsisInclusiveRangePatterns, - BuiltinEllipsisInclusiveRangePatternsLint, BuiltinExplicitOutlives, - BuiltinExplicitOutlivesSuggestion, BuiltinFeatureIssueNote, BuiltinIncompleteFeatures, - BuiltinIncompleteFeaturesHelp, BuiltinInternalFeatures, BuiltinKeywordIdents, - BuiltinMissingCopyImpl, BuiltinMissingDebugImpl, BuiltinMissingDoc, BuiltinMutablesTransmutes, - BuiltinNonShorthandFieldPatterns, BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds, - BuiltinTypeAliasBounds, BuiltinUngatedAsyncFnTrackCaller, BuiltinUnpermittedTypeInit, - BuiltinUnpermittedTypeInitSub, BuiltinUnreachablePub, BuiltinUnsafe, BuiltinUnstableFeatures, - BuiltinWhileTrue, EqInternalMethodImplemented, InvalidAsmLabel, + BuiltinDoubleNegationsAddParens, BuiltinDuplicateParameterNames, + BuiltinEllipsisInclusiveRangePatterns, BuiltinEllipsisInclusiveRangePatternsLint, + BuiltinExplicitOutlives, BuiltinExplicitOutlivesSuggestion, BuiltinFeatureIssueNote, + BuiltinIncompleteFeatures, BuiltinIncompleteFeaturesHelp, BuiltinInternalFeatures, + BuiltinKeywordIdents, BuiltinMissingCopyImpl, BuiltinMissingDebugImpl, BuiltinMissingDoc, + BuiltinMutablesTransmutes, BuiltinNonShorthandFieldPatterns, BuiltinSpecialModuleNameUsed, + BuiltinTrivialBounds, BuiltinTypeAliasBounds, BuiltinUngatedAsyncFnTrackCaller, + BuiltinUnpermittedTypeInit, BuiltinUnpermittedTypeInitSub, BuiltinUnreachablePub, + BuiltinUnsafe, BuiltinUnstableFeatures, BuiltinWhileTrue, EqInternalMethodImplemented, + InvalidAsmLabel, }; use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext}; @@ -737,6 +739,85 @@ impl EarlyLintPass for AnonymousParameters { } } +declare_lint! { + /// The `duplicate_parameter_names` lint detects duplicate parameter names + /// in functions without bodies. + /// + /// ### Example + /// + #[cfg_attr(bootstrap, doc = "```rust,skip")] + #[cfg_attr(not(bootstrap), doc = "```rust,compile_fail")] + /// #![deny(duplicate_parameter_names)] + /// pub trait Foo { + /// fn foo(x: usize, x: usize); + /// } + /// fn main() {} + #[doc = "```"] + /// + /// {{produces}} + /// + /// ### Explanation + /// + /// Duplicate parameter names are allowed in body-less functions, + /// in function pointers, and in parenthesised generic args, but this + /// is confusing and inconsistent behaviour, and is discouraged. + pub DUPLICATE_PARAMETER_NAMES, + Warn, + "detects duplicate parameter names in functions without bodies", +} + +declare_lint_pass!( + /// Checks for duplicate parameter names + DuplicateParameterNames => [DUPLICATE_PARAMETER_NAMES] +); + +fn find_duplicated_parameters(cx: &EarlyContext<'_>, params: &[ast::Param]) { + let mut map = FxHashMap::default(); + + for param in params { + if let ast::PatKind::Ident(_, ident, _) = param.pat.kind { + if param.is_self() { + continue; + } + + let name = ident.normalize_to_macro_rules(); + + if let Some(&prev_use) = map.get(&name) { + cx.emit_span_lint( + DUPLICATE_PARAMETER_NAMES, + ident.span, + BuiltinDuplicateParameterNames { span: ident.span, ident, prev_use }, + ); + } else { + map.insert(name, ident.span); + } + } + } +} + +impl EarlyLintPass for DuplicateParameterNames { + fn check_fn(&mut self, cx: &EarlyContext<'_>, fk: FnKind<'_>, _: Span, _: ast::NodeId) { + if let FnKind::Fn(_, _, Fn { sig, body, .. }) = fk { + // if there's a body, an error is already thrown, so we shouldn't warn + if body.is_none() { + find_duplicated_parameters(cx, &sig.decl.inputs); + } + } + } + + fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) { + if let TyKind::FnPtr(f) = &ty.kind { + find_duplicated_parameters(cx, &f.decl.inputs); + } + } + + fn check_generic_args(&mut self, cx: &EarlyContext<'_>, args: &ast::GenericArgs) { + if let ast::GenericArgs::Parenthesized(parens) = args { + find_duplicated_parameters(cx, &parens.inputs); + } + } +} + declare_lint! { /// The `no_mangle_const_items` lint detects any `const` items with the /// [`no_mangle` attribute]. diff --git a/compiler/rustc_lint/src/diagnostics.rs b/compiler/rustc_lint/src/diagnostics.rs index 69cdee19a56fb..b10cd5b4cf6d7 100644 --- a/compiler/rustc_lint/src/diagnostics.rs +++ b/compiler/rustc_lint/src/diagnostics.rs @@ -312,6 +312,17 @@ pub(crate) struct BuiltinAnonymousParams<'a> { pub ty_snip: &'a str, } +#[derive(Diagnostic)] +#[diag("identifier `{$ident}` is bound more than once in this parameter list")] +pub(crate) struct BuiltinDuplicateParameterNames { + #[primary_span] + #[label("used as parameter more than once")] + pub(crate) span: Span, + pub(crate) ident: Ident, + #[label("used here already")] + pub(crate) prev_use: Span, +} + #[derive(Diagnostic)] #[diag("const items should never be `#[no_mangle]`")] pub(crate) struct BuiltinConstNoMangle { @@ -3145,12 +3156,16 @@ pub(crate) struct EqInternalMethodImplemented; #[derive(Diagnostic)] #[diag("cast from `{$expr_ty}` to `{$cast_ty}` implicitly relies on exposed provenance")] #[help( - "if conforming to strict provenance is not possible, use `std::ptr::with_exposed_provenance()`" + "if conforming to strict provenance is not possible, use `{$krate}::ptr::with_exposed_provenance()`" +)] +#[note( + "for more information, visit " )] -#[note("for more information, visit ")] pub(crate) struct ImplicitProvenanceCastsInt2Ptr<'tcx> { pub expr_ty: Ty<'tcx>, pub cast_ty: Ty<'tcx>, + /// Either `std` or `core`. + pub krate: &'static str, #[subdiagnostic] pub sugg: Option, } @@ -3170,10 +3185,14 @@ pub(crate) struct Int2PtrSuggestion { #[derive(Diagnostic)] #[diag("cast from `{$cast_from_ty}` to `{$cast_to_ty}` implicitly exposes pointer provenance")] #[help("if conforming to strict provenance is not possible, use `.expose_provenance()`")] -#[note("for more information, visit ")] +#[note( + "for more information, visit " +)] pub(crate) struct ImplicitProvenanceCastsPtr2Int<'tcx> { pub cast_from_ty: Ty<'tcx>, pub cast_to_ty: Ty<'tcx>, + /// Either `std` or `core`, used to link to the matching documentation. + pub krate: &'static str, #[subdiagnostic] pub sugg: Option>, } diff --git a/compiler/rustc_lint/src/early.rs b/compiler/rustc_lint/src/early.rs index d55ea5553d2df..565838cec1844 100644 --- a/compiler/rustc_lint/src/early.rs +++ b/compiler/rustc_lint/src/early.rs @@ -181,6 +181,11 @@ impl<'ast, 'ecx, T: EarlyLintPass> ast_visit::Visitor<'ast> for EarlyContextAndP ast_visit::walk_generic_arg(self, arg); } + fn visit_generic_args(&mut self, args: &'ast ast::GenericArgs) { + lint_callback!(self, check_generic_args, args); + ast_visit::walk_generic_args(self, args); + } + fn visit_generic_param(&mut self, param: &'ast ast::GenericParam) { self.with_lint_attrs(param.id, ¶m.attrs, |cx| { lint_callback!(cx, check_generic_param, param); diff --git a/compiler/rustc_lint/src/implicit_provenance_casts.rs b/compiler/rustc_lint/src/implicit_provenance_casts.rs index f1646f2cc6072..470fe36ef5f5b 100644 --- a/compiler/rustc_lint/src/implicit_provenance_casts.rs +++ b/compiler/rustc_lint/src/implicit_provenance_casts.rs @@ -7,6 +7,7 @@ use crate::diagnostics::{ ImplicitProvenanceCastsInt2Ptr, ImplicitProvenanceCastsPtr2Int, Int2PtrSuggestion, Ptr2IntSuggestion, }; +use crate::utils::std_or_core; use crate::{LateContext, LateLintPass}; declare_lint! { @@ -69,12 +70,14 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitProvenanceCasts { if cast_from_ty.is_raw_ptr() { let cast_to_ty = typeck_results.expr_ty(expr); if cast_to_ty.is_integral() { - lint_ptr2int(cx, expr, cast_from_expr, cast_from_ty, cast_to_hir, cast_to_ty) + let krate = std_or_core(cx).unwrap_or("core"); + lint_ptr2int(cx, krate, expr, cast_from_expr, cast_from_ty, cast_to_hir, cast_to_ty) } } else if cast_from_ty.is_integral() { let cast_to_ty = typeck_results.expr_ty(expr); if cast_to_ty.is_raw_ptr() { - lint_int2ptr(cx, expr, cast_from_expr, cast_from_ty, cast_to_hir, cast_to_ty) + let krate = std_or_core(cx).unwrap_or("core"); + lint_int2ptr(cx, krate, expr, cast_from_expr, cast_from_ty, cast_to_hir, cast_to_ty) } } } @@ -82,6 +85,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitProvenanceCasts { fn lint_ptr2int<'tcx>( cx: &LateContext<'tcx>, + krate: &'static str, expr: &'tcx hir::Expr<'tcx>, cast_from_expr: &'tcx hir::Expr<'tcx>, cast_from_ty: Ty<'tcx>, @@ -101,12 +105,13 @@ fn lint_ptr2int<'tcx>( } }); - let lint = ImplicitProvenanceCastsPtr2Int { cast_from_ty, cast_to_ty, sugg }; + let lint = ImplicitProvenanceCastsPtr2Int { cast_from_ty, cast_to_ty, krate, sugg }; cx.tcx.emit_node_span_lint(IMPLICIT_PROVENANCE_CASTS, expr.hir_id, expr.span, lint); } fn lint_int2ptr<'tcx>( cx: &LateContext<'tcx>, + krate: &'static str, expr: &'tcx hir::Expr<'tcx>, cast_from_expr: &'tcx hir::Expr<'tcx>, cast_from_ty: Ty<'tcx>, @@ -117,6 +122,7 @@ fn lint_int2ptr<'tcx>( lo: cast_from_expr.span.shrink_to_lo(), hi: cast_from_expr.span.shrink_to_hi().to(cast_to_hir.span), }); - let lint = ImplicitProvenanceCastsInt2Ptr { expr_ty: cast_from_ty, cast_ty: cast_to_ty, sugg }; + let lint = + ImplicitProvenanceCastsInt2Ptr { expr_ty: cast_from_ty, cast_ty: cast_to_ty, krate, sugg }; cx.tcx.emit_node_span_lint(IMPLICIT_PROVENANCE_CASTS, expr.hir_id, expr.span, lint) } diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 2c3365028844a..6559a1d8dd64d 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -184,6 +184,7 @@ early_lint_methods!( // tidy-alphabetical-start AnonymousParameters: AnonymousParameters, DoubleNegations: DoubleNegations, + DuplicateParameterNames: DuplicateParameterNames, EllipsisInclusiveRangePatterns: EllipsisInclusiveRangePatterns::default(), Expr2024: Expr2024, IncompleteInternalFeatures: IncompleteInternalFeatures, @@ -724,6 +725,11 @@ fn register_builtins(store: &mut LintStore) { "dependency_on_unit_never_type_fallback", "the code warned by this lint no longer compiles", ); + store.register_removed( + "conflicting_repr_hints", + "converted into a hard error, \ + see for more information", + ); } fn register_internals(store: &mut LintStore) { diff --git a/compiler/rustc_lint/src/nonstandard_style.rs b/compiler/rustc_lint/src/nonstandard_style.rs index 66478f052d68b..2b569ea433313 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -7,7 +7,7 @@ use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{FnKind, Visitor}; -use rustc_hir::{GenericParamKind, PatExprKind, PatKind}; +use rustc_hir::{GenericParamKind, Node, PatExprKind, PatKind}; use rustc_lint_defs::{declare_lint, declare_lint_pass}; use rustc_middle::hir::nested_filter::All; use rustc_middle::ty::AssocContainer; @@ -439,17 +439,29 @@ impl<'tcx> LateLintPass<'tcx> for NonSnakeCase { } fn check_pat(&mut self, cx: &LateContext<'_>, p: &hir::Pat<'_>) { - if let PatKind::Binding(_, hid, ident, _) = p.kind { - if let hir::Node::PatField(field) = cx.tcx.parent_hir_node(hid) { - if !field.is_shorthand { - // Only check if a new name has been introduced, to avoid warning - // on both the struct definition and this pattern. - self.check_snake_case(cx, "variable", &ident); - } - return; + let PatKind::Binding(_, hid, ident, _) = p.kind else { return }; + + // Ignore patterns in foreign items for + // FIXME(#33995) remove this check + if let Node::ForeignItem(_) = cx + .tcx + .hir_parent_iter(p.hir_id) + .find(|(_, n)| !matches!(n, Node::Pat(_) | Node::Param(_))) + .unwrap() + .1 + { + return; + } + + if let hir::Node::PatField(field) = cx.tcx.parent_hir_node(hid) { + if !field.is_shorthand { + // Only check if a new name has been introduced, to avoid warning + // on both the struct definition and this pattern. + self.check_snake_case(cx, "variable", &ident); } - self.check_snake_case(cx, "variable", &ident); + return; } + self.check_snake_case(cx, "variable", &ident); } fn check_field_def(&mut self, cx: &LateContext<'_>, field: &hir::FieldDef<'_>) { diff --git a/compiler/rustc_lint/src/passes.rs b/compiler/rustc_lint/src/passes.rs index 98ab44c37e26a..fa9b2c4f67af7 100644 --- a/compiler/rustc_lint/src/passes.rs +++ b/compiler/rustc_lint/src/passes.rs @@ -148,6 +148,7 @@ macro_rules! early_lint_methods { fn check_expr_post(a: &rustc_ast::Expr); fn check_ty(a: &rustc_ast::Ty); fn check_generic_arg(a: &rustc_ast::GenericArg); + fn check_generic_args(a: &rustc_ast::GenericArgs); fn check_generic_param(a: &rustc_ast::GenericParam); fn check_generics(a: &rustc_ast::Generics); fn check_poly_trait_ref(a: &rustc_ast::PolyTraitRef); diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index f1bf802dad9d0..81c9429a60074 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -32,7 +32,6 @@ pub mod hardwired { BINDINGS_WITH_VARIANT_NAME, BREAK_WITH_LABEL_AND_LOOP, COHERENCE_LEAK_CHECK, - CONFLICTING_REPR_HINTS, CONST_EVALUATABLE_UNCHECKED, CONST_ITEM_MUTATION, DEAD_CODE, @@ -248,42 +247,6 @@ declare_lint! { crate_level_only } -declare_lint! { - /// The `conflicting_repr_hints` lint detects [`repr` attributes] with - /// conflicting hints. - /// - /// [`repr` attributes]: https://doc.rust-lang.org/reference/type-layout.html#representations - /// - /// ### Example - /// - /// ```rust,compile_fail - /// #[repr(u32, u64)] - /// enum Foo { - /// Variant1, - /// } - /// ``` - /// - /// {{produces}} - /// - /// ### Explanation - /// - /// The compiler incorrectly accepted these conflicting representations in - /// the past. This is a [future-incompatible] lint to transition this to a - /// hard error in the future. See [issue #68585] for more details. - /// - /// To correct the issue, remove one of the conflicting hints. - /// - /// [issue #68585]: https://github.com/rust-lang/rust/issues/68585 - /// [future-incompatible]: ../index.md#future-incompatible-lints - pub CONFLICTING_REPR_HINTS, - Deny, - "conflicts between `#[repr(..)]` hints that were previously accepted and used in practice", - @future_incompatible = FutureIncompatibleInfo { - reason: fcw!(FutureReleaseError #68585), - report_in_deps: true, - }; -} - declare_lint! { /// The `repeated_reprs` lint detects when the same representation is /// specified more than once in a `#[repr(..)]` attribute. diff --git a/compiler/rustc_middle/src/hir/map.rs b/compiler/rustc_middle/src/hir/map.rs index 5e65a9d57a20a..98df864151952 100644 --- a/compiler/rustc_middle/src/hir/map.rs +++ b/compiler/rustc_middle/src/hir/map.rs @@ -310,7 +310,11 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn hir_body_param_idents(self, id: BodyId) -> impl Iterator> { - self.hir_body(id).params.iter().map(|param| match param.pat.kind { + self.param_idents(self.hir_body(id).params) + } + + pub fn param_idents(self, params: &[Param<'tcx>]) -> impl Iterator> { + params.iter().map(|param| match param.pat.kind { PatKind::Binding(_, _, ident, _) => Some(ident), PatKind::Wild => Some(Ident::new(kw::Underscore, param.pat.span)), _ => None, diff --git a/compiler/rustc_middle/src/hir/mod.rs b/compiler/rustc_middle/src/hir/mod.rs index 18272069be5e7..bc1f9c1180b2b 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -479,13 +479,15 @@ pub fn provide(providers: &mut Providers) { let node = tcx.hir_node_by_def_id(def_id); if let Some(body_id) = node.body_id() { tcx.arena.alloc_from_iter(tcx.hir_body_param_idents(body_id)) + } else if let Node::ForeignItem(&ForeignItem { + kind: ForeignItemKind::Fn(_, params, _), + .. + }) = node + { + tcx.arena.alloc_from_iter(tcx.param_idents(params)) } else if let Node::TraitItem(&TraitItem { kind: TraitItemKind::Fn(_, TraitFn::Required(idents)), .. - }) - | Node::ForeignItem(&ForeignItem { - kind: ForeignItemKind::Fn(_, idents, _), - .. }) = node { idents diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index 9e8c28452299a..b522e581b0485 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -663,6 +663,13 @@ pub struct PatExtra<'tcx> { /// the pattern node back to the `DefId` of its original constant. pub expanded_const: Option>, + /// If present, the original constant value that this array or slice + /// pattern node was expanded from by `const_to_pat`. + /// + /// Match lowering uses this to compare the scrutinee against the original + /// constant as a whole, rather than element by element. + pub expanded_const_value: Option>, + /// User-written types that must be preserved into MIR so that they can be /// checked. pub ascriptions: Vec>, diff --git a/compiler/rustc_mir_build/src/builder/matches/buckets.rs b/compiler/rustc_mir_build/src/builder/matches/buckets.rs index bf634d2b9688b..4c68afb83417a 100644 --- a/compiler/rustc_mir_build/src/builder/matches/buckets.rs +++ b/compiler/rustc_mir_build/src/builder/matches/buckets.rs @@ -330,6 +330,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { value: case_val, kind: PatConstKind::Float | PatConstKind::Other, }, + ) + | ( + TestKind::AggregateEq { value: test_val, .. }, + TestableCase::Constant { value: case_val, kind: PatConstKind::Aggregate }, ) => { if test_val == case_val { fully_matched = true; @@ -360,6 +364,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { | TestKind::Range { .. } | TestKind::StringEq { .. } | TestKind::ScalarEq { .. } + | TestKind::AggregateEq { .. } | TestKind::Deref { .. }, _, ) => { diff --git a/compiler/rustc_mir_build/src/builder/matches/match_pair.rs b/compiler/rustc_mir_build/src/builder/matches/match_pair.rs index 392712619a3f2..e2b568e93a10a 100644 --- a/compiler/rustc_mir_build/src/builder/matches/match_pair.rs +++ b/compiler/rustc_mir_build/src/builder/matches/match_pair.rs @@ -12,6 +12,71 @@ use crate::builder::matches::{ FlatPat, MatchPairKind, MatchPairTree, PatConstKind, PatternExtraData, SliceLenOp, TestableCase, }; +/// Below this length, an array or slice pattern is compared element by element +/// rather than as a single aggregate. +/// +/// For a single short constant, the aggregate comparison is no slower once +/// optimised, but each aggregate test is a separate comparison that only tells +/// whether that one constant matched. A match with many short constant arms, +/// such as every combination of `[bool; 3]`, would turn its decision tree into +/// a chain of such comparisons, which is markedly slower, especially in debug +/// builds. +const AGGREGATE_EQ_MIN_LEN: usize = 4; + +/// Whether arrays and slices with this element type may be compared as an aggregate. +/// +/// The aggregate is compared with the `raw_eq` and `compare_bytes` intrinsics, +/// which only agree with structural equality when there is no padding and equal +/// values have equal bytes, so we restrict ourselves to the primitives that +/// `core::cmp::BytewiseEq` is implemented for. +fn is_bytewise_comparable(element_ty: Ty<'_>) -> bool { + matches!(element_ty.kind(), ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_)) +} + +impl<'a, 'tcx> Builder<'a, 'tcx> { + /// Check if we can use aggregate comparisons for constant array/slice patterns. + /// This is not possible in const contexts, because the `compare_bytes` + /// intrinsic used for slices is not const-stable yet, nor in `#![no_core]` + /// crates that do not define both intrinsics as lang items. + /// + /// `raw_eq`, which is used for arrays, is already const-stable, but arrays + /// and slices are gated together, as allowing one without the other is + /// not worth the extra complexity. + // FIXME(const_cmp): remove the const context restriction once `const_cmp` stabilises. + fn can_use_aggregate_eq(&self) -> bool { + let in_const_context = self.tcx.is_const_fn(self.def_id.to_def_id()) + || !self.tcx.hir_body_owner_kind(self.def_id).is_fn_or_closure(); + let lang_items = self.tcx.lang_items(); + !in_const_context && lang_items.raw_eq().is_some() && lang_items.compare_bytes().is_some() + } + + /// If the given array or slice pattern node was expanded from a constant + /// by `const_to_pat` and an aggregate comparison is both possible and + /// worthwhile, returns the original constant value, so that the scrutinee + /// can be compared against it as a whole. + /// + /// Note that this deliberately does not apply to hand-written array or + /// slice patterns, which only ever match element by element. + fn aggregate_const_value( + &self, + pattern: &Pat<'tcx>, + element_count: usize, + ) -> Option> { + let value = pattern.extra.as_deref()?.expanded_const_value?; + let (ty::Array(element_ty, _) | ty::Slice(element_ty)) = *pattern.ty.kind() else { + span_bug!(pattern.span, "expanded constant value on a non-aggregate pattern"); + }; + if element_count >= AGGREGATE_EQ_MIN_LEN + && is_bytewise_comparable(element_ty) + && self.can_use_aggregate_eq() + { + Some(value) + } else { + None + } + } +} + /// For an array or slice pattern's subpatterns (prefix/slice/suffix), returns a list /// of those subpatterns, each paired with a suitably-projected [`PlaceBuilder`]. fn prefix_slice_suffix<'a, 'tcx>( @@ -338,10 +403,30 @@ impl<'tcx> InterPat<'tcx> { let mut subpats = vec![]; if let Some(array_len) = array_len { - for (subplace, subpat) in - prefix_slice_suffix(&place_builder, Some(array_len), prefix, slice, suffix) - { - subpats.push(InterPat::lower_thir_pat(cx, subplace, subpat)); + // If this pattern was expanded from a constant, compare + // the whole array against that constant at once rather + // than element by element. + if let Some(aggregate_value) = cx.aggregate_const_value(pattern, prefix.len()) { + debug_assert!(slice.is_none() && suffix.is_empty()); + InterPatKind::Refutable { + place: unwrap_place(), + testable_case: TestableCase::Constant { + value: aggregate_value, + kind: PatConstKind::Aggregate, + }, + subpats, + } + } else { + for (subplace, subpat) in prefix_slice_suffix( + &place_builder, + Some(array_len), + prefix, + slice, + suffix, + ) { + subpats.push(InterPat::lower_thir_pat(cx, subplace, subpat)); + } + InterPatKind::Irrefutable { subpats, binding: None } } } else { // If the array length couldn't be determined, ignore the @@ -353,35 +438,66 @@ impl<'tcx> InterPat<'tcx> { pattern.ty ), ); + InterPatKind::Irrefutable { subpats, binding: None } } - - InterPatKind::Irrefutable { subpats, binding: None } } PatKind::Slice { ref prefix, ref slice, ref suffix } => { - let mut subpats = vec![]; - for (subplace, subpat) in - prefix_slice_suffix(&place_builder, None, prefix, slice, suffix) - { - subpats.push(InterPat::lower_thir_pat(cx, subplace, subpat)); - } - - if prefix.is_empty() && slice.is_some() && suffix.is_empty() { - // A slice pattern shaped like `[..]` is irrefutable. - // It can match a slice of any length, so no length test is needed. - InterPatKind::Irrefutable { subpats, binding: None } - } else { - // Any other shape of slice pattern requires a length test. - // Slice patterns with a `..` subpattern require a minimum - // length; those without `..` require an exact length. - let testable_case = TestableCase::Slice { - len: u64::try_from(prefix.len() + suffix.len()).unwrap(), - op: if slice.is_some() { - SliceLenOp::GreaterOrEqual - } else { - SliceLenOp::Equal + // If this pattern was expanded from a constant, compare the + // whole slice against that constant at once rather than + // element by element. `compare_bytes` only looks at as many + // bytes as the constant has, so the aggregate test is nested + // under an ordinary length test, whose result can then be + // shared with other patterns of the same length. + if let Some(aggregate_value) = cx.aggregate_const_value(pattern, prefix.len()) { + debug_assert!(slice.is_none() && suffix.is_empty()); + let aggregate_subpat = InterPat { + kind: InterPatKind::Refutable { + place: unwrap_place(), + testable_case: TestableCase::Constant { + value: aggregate_value, + kind: PatConstKind::Aggregate, + }, + subpats: vec![], }, + ascriptions: vec![], + pattern_span: pattern.span, + is_never: false, }; - InterPatKind::Refutable { place: unwrap_place(), testable_case, subpats } + let testable_case = TestableCase::Slice { + len: u64::try_from(prefix.len()).unwrap(), + op: SliceLenOp::Equal, + }; + InterPatKind::Refutable { + place: unwrap_place(), + testable_case, + subpats: vec![aggregate_subpat], + } + } else { + let mut subpats = vec![]; + for (subplace, subpat) in + prefix_slice_suffix(&place_builder, None, prefix, slice, suffix) + { + subpats.push(InterPat::lower_thir_pat(cx, subplace, subpat)); + } + + if prefix.is_empty() && slice.is_some() && suffix.is_empty() { + // A slice pattern shaped like `[..]` is irrefutable. + // It can match a slice of any length, so no length test is needed. + InterPatKind::Irrefutable { subpats, binding: None } + } else { + // Any other shape of slice pattern requires a length test. + // Slice patterns with a `..` subpattern require a minimum + // length; those without `..` require an exact length. + let testable_case = TestableCase::Slice { + len: u64::try_from(prefix.len() + suffix.len()).unwrap(), + op: if slice.is_some() { + SliceLenOp::GreaterOrEqual + } else { + SliceLenOp::Equal + }, + }; + InterPatKind::Refutable { place: unwrap_place(), testable_case, subpats } + } } } diff --git a/compiler/rustc_mir_build/src/builder/matches/mod.rs b/compiler/rustc_mir_build/src/builder/matches/mod.rs index 05efc2f4e7138..52922aa67f8dd 100644 --- a/compiler/rustc_mir_build/src/builder/matches/mod.rs +++ b/compiler/rustc_mir_build/src/builder/matches/mod.rs @@ -1226,6 +1226,10 @@ enum PatConstKind { Float, /// Constant string values, tested via string equality. String, + /// Constant array or slice values that array/slice patterns were expanded + /// from. Tested by comparing the bytes of the whole aggregate at once, + /// rather than comparing element by element. + Aggregate, /// Any other constant-pattern is usually tested via some kind of equality /// check. Types that might be encountered here include: /// - raw pointers derived from integer values @@ -1311,6 +1315,11 @@ enum TestKind<'tcx> { /// Tests the place against a constant using scalar equality. ScalarEq { value: ty::Value<'tcx> }, + /// Tests the place against a constant array or slice using the `raw_eq` or + /// `compare_bytes` intrinsic, comparing the whole aggregate at once rather + /// than element by element. + AggregateEq { value: ty::Value<'tcx> }, + /// Test whether the value falls within an inclusive or exclusive range. Range(Arc>), diff --git a/compiler/rustc_mir_build/src/builder/matches/test.rs b/compiler/rustc_mir_build/src/builder/matches/test.rs index a8ae60b4daba7..6b516fb2f3972 100644 --- a/compiler/rustc_mir_build/src/builder/matches/test.rs +++ b/compiler/rustc_mir_build/src/builder/matches/test.rs @@ -10,6 +10,7 @@ use std::sync::Arc; use rustc_attr_ir::lang_items::LangItem; use rustc_data_structures::fx::FxIndexMap; use rustc_hir::RangeEnd; +use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::mir::*; use rustc_middle::ty::util::IntTypeExt; use rustc_middle::ty::{self, GenericArg, Ty, TyCtxt}; @@ -46,6 +47,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { TestableCase::Constant { value, kind: PatConstKind::String } => { TestKind::StringEq { value } } + TestableCase::Constant { value, kind: PatConstKind::Aggregate } => { + TestKind::AggregateEq { value } + } TestableCase::Constant { value, kind: PatConstKind::Float | PatConstKind::Other } => { TestKind::ScalarEq { value } } @@ -180,6 +184,49 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ); } + TestKind::AggregateEq { value } => { + let tcx = self.tcx; + let success_block = target_block(TestBranch::Success); + let fail_block = target_block(TestBranch::Failure); + + // As with strings, the constant has type `[T; N]` or `[T]`, but + // we need a reference to it, and both have the same valtree + // representation. + let ref_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, value.ty); + let expected_value = ty::Value { ty: ref_ty, valtree: value.valtree }; + let expected_value_operand = + self.literal_operand(test.span, Const::from_ty_value(tcx, expected_value)); + + // Unlike strings, aggregates are compared with the `raw_eq` and + // `compare_bytes` intrinsics rather than `PartialEq::eq`. These + // cannot unwind, and an unwind edge would make borrow-checking + // stricter than for the element-by-element `SwitchInt`s they + // replace. Comparing bytes agrees with structural equality because + // the element types are restricted to primitives without padding + // (see `is_bytewise_comparable`). + match *value.ty.kind() { + ty::Array(..) => self.array_raw_eq( + block, + success_block, + fail_block, + source_info, + place, + expected_value_operand, + ), + ty::Slice(element_ty) => self.slice_compare_bytes( + block, + success_block, + fail_block, + source_info, + place, + expected_value_operand, + element_ty, + value.valtree.to_branch().len(), + ), + _ => bug!("unexpected value type for AggregateEq test: {value:?}"), + } + } + TestKind::ScalarEq { value } => { let tcx = self.tcx; let success_block = target_block(TestBranch::Success); @@ -464,6 +511,160 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { TerminatorKind::if_(Operand::Move(eq_result), success_block, fail_block), ); } + + /// Compares the array at `place` with the expected array constant using the + /// `raw_eq` intrinsic. + fn array_raw_eq( + &mut self, + block: BasicBlock, + success_block: BasicBlock, + fail_block: BasicBlock, + source_info: SourceInfo, + place: Place<'tcx>, + expected_value_operand: Operand<'tcx>, + ) { + let tcx = self.tcx; + let array_ty = place.ty(&self.local_decls, tcx).ty; + let ref_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, array_ty); + let actual_value_ref_place = self.temp(ref_ty, source_info.span); + self.cfg.push_assign( + block, + source_info, + actual_value_ref_place, + Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, place), + ); + + let eq_result = self.temp(tcx.types.bool, source_info.span); + let eq_block = self.call_nounwind_intrinsic( + block, + source_info, + LangItem::RawEq, + &[array_ty.into()], + [Operand::Copy(actual_value_ref_place), expected_value_operand], + eq_result, + ); + self.cfg.terminate( + eq_block, + source_info, + TerminatorKind::if_(Operand::Move(eq_result), success_block, fail_block), + ); + } + + /// Compares the slice at `place` with the expected slice constant of `len` + /// elements using the `compare_bytes` intrinsic. + /// + /// `compare_bytes` only looks at as many bytes as it is told to, so this + /// relies on the enclosing slice length test having already checked that + /// the slice at `place` has `len` elements too. + fn slice_compare_bytes( + &mut self, + block: BasicBlock, + success_block: BasicBlock, + fail_block: BasicBlock, + source_info: SourceInfo, + place: Place<'tcx>, + expected_value_operand: Operand<'tcx>, + element_ty: Ty<'tcx>, + len: usize, + ) { + let tcx = self.tcx; + let expected_value_ref_place = + self.temp(expected_value_operand.ty(&self.local_decls, tcx), source_info.span); + self.cfg.push_assign( + block, + source_info, + expected_value_ref_place, + Rvalue::Use(expected_value_operand, WithRetag::Yes), + ); + let actual_bytes = self.slice_bytes_ptr(block, source_info, place); + let expected_bytes = + self.slice_bytes_ptr(block, source_info, tcx.mk_place_deref(expected_value_ref_place)); + let byte_len = self.push_usize( + block, + source_info, + u64::try_from(len).unwrap() * element_ty.primitive_size(tcx).bytes(), + ); + + let cmp_result = self.temp(tcx.types.i32, source_info.span); + let cmp_block = self.call_nounwind_intrinsic( + block, + source_info, + LangItem::CompareBytes, + &[], + [Operand::Move(actual_bytes), Operand::Move(expected_bytes), Operand::Move(byte_len)], + cmp_result, + ); + // `compare_bytes` returns zero if and only if the bytes are equal. + self.cfg.terminate( + cmp_block, + source_info, + TerminatorKind::SwitchInt { + discr: Operand::Move(cmp_result), + targets: SwitchTargets::static_if(0, success_block, fail_block), + }, + ); + } + + /// Returns a `*const u8` temporary pointing to the start of the slice at `place`. + fn slice_bytes_ptr( + &mut self, + block: BasicBlock, + source_info: SourceInfo, + place: Place<'tcx>, + ) -> Place<'tcx> { + let tcx = self.tcx; + let slice_ty = place.ty(&self.local_decls, tcx).ty; + let slice_ptr = self.temp(Ty::new_imm_ptr(tcx, slice_ty), source_info.span); + self.cfg.push_assign( + block, + source_info, + slice_ptr, + Rvalue::RawPtr(RawPtrKind::Const, place), + ); + + let bytes_ptr_ty = Ty::new_imm_ptr(tcx, tcx.types.u8); + let bytes_ptr = self.temp(bytes_ptr_ty, source_info.span); + self.cfg.push_assign( + block, + source_info, + bytes_ptr, + Rvalue::Cast(CastKind::PtrToPtr, Operand::Move(slice_ptr), bytes_ptr_ty), + ); + bytes_ptr + } + + /// Calls the `#[rustc_nounwind]` intrinsic that is the given lang item, + /// and returns the block that the call returns to. + fn call_nounwind_intrinsic( + &mut self, + block: BasicBlock, + source_info: SourceInfo, + lang_item: LangItem, + generic_args: &[GenericArg<'tcx>], + args: impl IntoIterator>, + destination: Place<'tcx>, + ) -> BasicBlock { + let def_id = self.tcx.require_lang_item(lang_item, source_info.span); + debug_assert!( + self.tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::NEVER_UNWIND), + "{lang_item:?} must not unwind", + ); + let target = self.cfg.start_new_block(); + self.cfg.terminate( + block, + source_info, + TerminatorKind::Call { + func: Operand::function_handle(self.tcx, def_id, generic_args, source_info.span), + args: args.into_iter().map(|node| Spanned { node, span: DUMMY_SP }).collect(), + destination, + target: Some(target), + unwind: UnwindAction::Unreachable, + call_source: CallSource::MatchCmp, + fn_span: source_info.span, + }, + ); + target + } } fn trait_method<'tcx>( diff --git a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs index 0963587b91696..42c343aff9d95 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs @@ -484,7 +484,14 @@ impl<'tcx> ConstToPat<'tcx> { } }; - Box::new(Pat { span, ty, kind, extra: None }) + let mut pat = Box::new(Pat { span, ty, kind, extra: None }); + if matches!(ty.kind(), ty::Array(..) | ty::Slice(_)) { + // Record the original constant value on array and slice nodes, so + // that match lowering can compare the scrutinee against the whole + // constant at once, rather than element by element. + pat.extra.get_or_insert_default().expanded_const_value = Some(value); + } + pat } } diff --git a/compiler/rustc_mir_build/src/thir/print.rs b/compiler/rustc_mir_build/src/thir/print.rs index d7186829d5b22..573bbcd494a86 100644 --- a/compiler/rustc_mir_build/src/thir/print.rs +++ b/compiler/rustc_mir_build/src/thir/print.rs @@ -703,10 +703,15 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { return; }; - let PatExtra { expanded_const, ascriptions } = extra; + let PatExtra { expanded_const, expanded_const_value, ascriptions } = extra; print_indented!(self, "extra: PatExtra {", depth_lvl); print_indented!(self, format_args!("expanded_const: {expanded_const:?}"), depth_lvl + 1); + print_indented!( + self, + format_args!("expanded_const_value: {expanded_const_value:?}"), + depth_lvl + 1 + ); self.print_list( "ascriptions", ascriptions, diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 5dd1718d68d49..a20dc90f72908 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -28,9 +28,8 @@ use rustc_hir::{ ItemKind, Mod, Node, ParamName, TraitItem, }; use rustc_lint_defs::builtin::{ - CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, MALFORMED_DIAGNOSTIC_ATTRIBUTES, - MALFORMED_DIAGNOSTIC_FORMAT_LITERALS, MISPLACED_DIAGNOSTIC_ATTRIBUTES, REPEATED_REPRS, - UNUSED_ATTRIBUTES, + INVALID_DOC_ATTRIBUTES, MALFORMED_DIAGNOSTIC_ATTRIBUTES, MALFORMED_DIAGNOSTIC_FORMAT_LITERALS, + MISPLACED_DIAGNOSTIC_ATTRIBUTES, REPEATED_REPRS, UNUSED_ATTRIBUTES, }; use rustc_macros::Diagnostic; use rustc_middle::hir::nested_filter; @@ -1065,17 +1064,13 @@ impl<'tcx> CheckAttrVisitor<'tcx> { let hint_spans = hint_spans.clone().collect(); self.dcx().emit_err(diagnostics::ReprConflicting { hint_spans }); } - // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8) + // Also error on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8) if (int_reprs > 1) || (is_simd && is_c) - || (int_reprs == 1 && is_c && item.is_some_and(is_c_like_enum)) + || (int_reprs == 1 && is_c && item.is_some_and(is_fieldless_enum)) { - self.tcx.emit_node_span_lint( - CONFLICTING_REPR_HINTS, - hir_id, - hint_spans.collect::>(), - diagnostics::ReprConflictingLint, - ); + let hint_spans = hint_spans.clone().collect(); + self.dcx().emit_err(diagnostics::ReprConflicting { hint_spans }); } } @@ -1489,7 +1484,7 @@ impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> { } } -fn is_c_like_enum(item: &Item<'_>) -> bool { +fn is_fieldless_enum(item: &Item<'_>) -> bool { if let ItemKind::Enum(_, _, ref def) = item.kind { for variant in def.variants { match variant.data { diff --git a/compiler/rustc_passes/src/diagnostics.rs b/compiler/rustc_passes/src/diagnostics.rs index aae198cf05257..e77bdf3ebf177 100644 --- a/compiler/rustc_passes/src/diagnostics.rs +++ b/compiler/rustc_passes/src/diagnostics.rs @@ -104,10 +104,6 @@ pub(crate) struct ReprConflicting { pub hint_spans: Vec, } -#[derive(Diagnostic)] -#[diag("conflicting representation hints", code = E0566)] -pub(crate) struct ReprConflictingLint; - #[derive(Diagnostic)] #[diag("couldn't read {$file}: {$error}")] pub(crate) struct DebugVisualizerUnreadable<'a> { diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index a128abd07b460..191267f166326 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -553,7 +553,6 @@ symbols! { avx512bw, avx512f, await_macro, - backchain, backend_repr, begin_panic, bench, diff --git a/compiler/rustc_target/src/spec/targets/thumbv7a_vex_v5.rs b/compiler/rustc_target/src/spec/targets/thumbv7a_vex_v5.rs index 7d39b8fa4e7fc..33da299ec8acc 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv7a_vex_v5.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv7a_vex_v5.rs @@ -15,6 +15,10 @@ pub(crate) fn target() -> Target { is_like_vexos: true, llvm_floatabi: Some(FloatAbi::Hard), linker_flavor: LinkerFlavor::Gnu(Cc::No, Lld::Yes), + pre_link_args: TargetOptions::link_args( + LinkerFlavor::Gnu(Cc::No, Lld::No), + &["--build-id=sha1"], + ), linker: Some("rust-lld".into()), features: "+v7,+neon,+vfp3d16,+thumb2".into(), relocation_model: RelocModel::Static, diff --git a/compiler/rustc_target/src/spec/targets/thumbv7a_vex_v5_linker_script.ld b/compiler/rustc_target/src/spec/targets/thumbv7a_vex_v5_linker_script.ld index 2cfa343119256..f6cb0d476335d 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv7a_vex_v5_linker_script.ld +++ b/compiler/rustc_target/src/spec/targets/thumbv7a_vex_v5_linker_script.ld @@ -76,6 +76,13 @@ SECTIONS { *(.srodata .srodata.*) } > USER_RAM + /* GNU build ID, which uniquely identifies this executable. */ + .note.gnu.build-id : ALIGN(4) { + PROVIDE(__build_id_start = .); + KEEP(*(.note.gnu.build-id)) + PROVIDE(__build_id_end = .); + } > USER_RAM + /* * ARM Stack Unwinding Sections * diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index a9ccd9132f259..49fc11de17d2d 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -971,7 +971,7 @@ static LOONGARCH_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ const IBMZ_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ // tidy-alphabetical-start // For "backchain", https://github.com/rust-lang/rust/issues/142412 is a stabilization blocker - ("backchain", Unstable(sym::s390x_target_feature), &[]), + ("backchain", InternalOnly { reason: "use `-Cforce-frame-pointers` compiler flag instead", target_modifier: false, hard_error: true }, &[]), ("concurrent-functions", Unstable(sym::s390x_target_feature), &[]), ("deflate-conversion", Unstable(sym::s390x_target_feature), &[]), ("enhanced-sort", Unstable(sym::s390x_target_feature), &[]), diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index 5c20f4a93fb2e..970b9d2dc30fa 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -2400,6 +2400,7 @@ pub const fn ptr_guaranteed_cmp(ptr: *const T, other: *const T) -> u8 { /// which is UB if any of their inputs are `undef`.) #[rustc_nounwind] #[rustc_intrinsic] +#[lang = "raw_eq"] pub const unsafe fn raw_eq(a: &T, b: &T) -> bool; /// Lexicographically compare `[left, left + bytes)` and `[right, right + bytes)` @@ -2419,6 +2420,7 @@ pub const unsafe fn raw_eq(a: &T, b: &T) -> bool; #[rustc_nounwind] #[rustc_intrinsic] #[rustc_const_unstable(feature = "const_cmp", issue = "143800")] +#[lang = "compare_bytes"] pub const unsafe fn compare_bytes(left: *const u8, right: *const u8, bytes: usize) -> i32; /// See documentation of [`std::hint::black_box`] for details. diff --git a/library/core/src/iter/sources/once.rs b/library/core/src/iter/sources/once.rs index c4a9860bdd76c..6640f1220b5f6 100644 --- a/library/core/src/iter/sources/once.rs +++ b/library/core/src/iter/sources/once.rs @@ -53,6 +53,7 @@ use crate::iter::{FusedIterator, TrustedLen}; /// # std::io::Result::Ok(()) /// ``` #[stable(feature = "iter_once", since = "1.2.0")] +#[rustc_diagnostic_item = "iter_once"] pub fn once(value: T) -> Once { Once { inner: Some(value).into_iter() } } diff --git a/library/core/src/iter/sources/once_with.rs b/library/core/src/iter/sources/once_with.rs index c9698b4fd431b..da21d11b9aa72 100644 --- a/library/core/src/iter/sources/once_with.rs +++ b/library/core/src/iter/sources/once_with.rs @@ -58,6 +58,7 @@ use crate::iter::{FusedIterator, TrustedLen}; /// ``` #[inline] #[stable(feature = "iter_once_with", since = "1.43.0")] +#[rustc_diagnostic_item = "iter_once_with"] pub fn once_with A>(make: F) -> OnceWith { OnceWith { make: Some(make) } } diff --git a/library/core/src/iter/sources/repeat_n.rs b/library/core/src/iter/sources/repeat_n.rs index d19ff6b7e024f..5c1e401dc58c0 100644 --- a/library/core/src/iter/sources/repeat_n.rs +++ b/library/core/src/iter/sources/repeat_n.rs @@ -56,6 +56,7 @@ use crate::ops::Try; /// ``` #[inline] #[stable(feature = "iter_repeat_n", since = "1.82.0")] +#[rustc_diagnostic_item = "iter_repeat_n"] pub fn repeat_n(element: T, count: usize) -> RepeatN { RepeatN { inner: RepeatNInner::new(element, count) } } diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index a5165217aca43..98c65efc4e58e 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -396,6 +396,7 @@ pub const trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "iter_nth"] fn nth(&mut self, n: usize) -> Option where Self::Item: [const] Destruct, @@ -450,6 +451,7 @@ pub const trait Iterator { #[inline] #[stable(feature = "iterator_step_by", since = "1.28.0")] #[rustc_non_const_trait_method] + #[rustc_diagnostic_item = "iter_step_by"] fn step_by(self, step: usize) -> StepBy where Self: Sized, @@ -521,6 +523,7 @@ pub const trait Iterator { /// [`OsStr`]: ../../std/ffi/struct.OsStr.html #[inline] #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "iter_chain"] fn chain(self, other: U) -> Chain where Self: Sized, @@ -640,6 +643,7 @@ pub const trait Iterator { #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_non_const_trait_method] + #[rustc_diagnostic_item = "iter_zip"] fn zip(self, other: U) -> Zip where Self: Sized, @@ -888,6 +892,7 @@ pub const trait Iterator { #[inline] #[stable(feature = "iterator_for_each", since = "1.21.0")] #[rustc_non_const_trait_method] + #[rustc_diagnostic_item = "iter_for_each"] fn for_each(self, f: F) where Self: Sized, @@ -1008,6 +1013,7 @@ pub const trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "iter_filter_map"] fn filter_map(self, f: F) -> FilterMap where Self: Sized, @@ -1191,6 +1197,7 @@ pub const trait Iterator { #[inline] #[doc(alias = "drop_while")] #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "iter_skip_while"] fn skip_while

(self, predicate: P) -> SkipWhile where Self: Sized, @@ -1269,6 +1276,7 @@ pub const trait Iterator { /// the iteration should stop, but wasn't placed back into the iterator. #[inline] #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "take_while"] fn take_while

(self, predicate: P) -> TakeWhile where Self: Sized, @@ -1357,6 +1365,7 @@ pub const trait Iterator { /// [`fuse`]: Iterator::fuse #[inline] #[stable(feature = "iter_map_while", since = "1.57.0")] + #[rustc_diagnostic_item = "iter_map_while"] fn map_while(self, predicate: P) -> MapWhile where Self: Sized, @@ -1386,6 +1395,7 @@ pub const trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "iter_skip"] fn skip(self, n: usize) -> Skip where Self: Sized, @@ -1458,6 +1468,7 @@ pub const trait Iterator { #[doc(alias = "limit")] #[inline] #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "iter_take"] fn take(self, n: usize) -> Take where Self: Sized, @@ -1505,6 +1516,7 @@ pub const trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "iter_scan"] fn scan(self, initial_state: St, f: F) -> Scan where Self: Sized, @@ -1544,6 +1556,7 @@ pub const trait Iterator { #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_non_const_trait_method] + #[rustc_diagnostic_item = "iter_flat_map"] fn flat_map(self, f: F) -> FlatMap where Self: Sized, @@ -1628,6 +1641,7 @@ pub const trait Iterator { /// [`flat_map()`]: Iterator::flat_map #[inline] #[stable(feature = "iterator_flatten", since = "1.29.0")] + #[rustc_diagnostic_item = "iter_flatten"] fn flatten(self) -> Flatten where Self: Sized, @@ -1840,6 +1854,7 @@ pub const trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "iter_fuse"] fn fuse(self) -> Fuse where Self: Sized, @@ -1924,6 +1939,7 @@ pub const trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "inspect"] fn inspect(self, f: F) -> Inspect where Self: Sized, @@ -2278,6 +2294,7 @@ pub const trait Iterator { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_non_const_trait_method] + #[rustc_diagnostic_item = "iter_partition"] fn partition(self, f: F) -> (B, B) where Self: Sized, @@ -2493,6 +2510,7 @@ pub const trait Iterator { /// ``` #[inline] #[stable(feature = "iterator_try_fold", since = "1.27.0")] + #[rustc_diagnostic_item = "iter_try_fold"] fn try_fold(&mut self, init: B, mut f: F) -> R where Self: Sized, @@ -2552,6 +2570,7 @@ pub const trait Iterator { #[inline] #[stable(feature = "iterator_try_fold", since = "1.27.0")] #[rustc_non_const_trait_method] + #[rustc_diagnostic_item = "iter_try_for_each"] fn try_for_each(&mut self, f: F) -> R where Self: Sized, @@ -2671,6 +2690,7 @@ pub const trait Iterator { #[doc(alias = "inject", alias = "foldl")] #[inline] #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "iter_fold"] fn fold(mut self, init: B, mut f: F) -> B where Self: Sized + [const] Destruct, @@ -2708,6 +2728,7 @@ pub const trait Iterator { /// ``` #[inline] #[stable(feature = "iterator_fold_self", since = "1.51.0")] + #[rustc_diagnostic_item = "iter_reduce"] fn reduce(mut self, f: F) -> Option where Self: Sized + [const] Destruct, @@ -2837,6 +2858,7 @@ pub const trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "iter_all"] fn all(&mut self, f: F) -> bool where Self: Sized, @@ -2894,6 +2916,7 @@ pub const trait Iterator { #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_non_const_trait_method] + #[rustc_diagnostic_item = "iter_any"] fn any(&mut self, f: F) -> bool where Self: Sized, @@ -3607,6 +3630,7 @@ pub const trait Iterator { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] + #[rustc_diagnostic_item = "iter_cycle"] fn cycle(self) -> Cycle where Self: Sized + [const] Clone, @@ -3650,6 +3674,7 @@ pub const trait Iterator { /// ``` #[track_caller] #[unstable(feature = "iter_array_chunks", issue = "100450")] + #[rustc_diagnostic_item = "iter_array_chunks"] fn array_chunks<#[rustc_panics_when_zero] const N: usize>(self) -> ArrayChunks where Self: Sized, @@ -3686,6 +3711,7 @@ pub const trait Iterator { /// assert_eq!(sum, -0.0_f32); /// ``` #[stable(feature = "iter_arith", since = "1.11.0")] + #[rustc_diagnostic_item = "iter_sum"] fn sum(self) -> S where Self: Sized, @@ -3718,6 +3744,7 @@ pub const trait Iterator { /// assert_eq!(factorial(5), 120); /// ``` #[stable(feature = "iter_arith", since = "1.11.0")] + #[rustc_diagnostic_item = "iter_product"] fn product

(self) -> P where Self: Sized, diff --git a/library/core/src/net/ip_addr.rs b/library/core/src/net/ip_addr.rs index aeb3ceab25e05..e04fa4f24aaf2 100644 --- a/library/core/src/net/ip_addr.rs +++ b/library/core/src/net/ip_addr.rs @@ -544,6 +544,7 @@ impl IpAddr { /// &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) /// ``` #[unstable(feature = "ip_as_octets", issue = "137259")] + #[must_use] #[inline] pub const fn as_octets(&self) -> &[u8] { match self { @@ -730,6 +731,7 @@ impl Ipv4Addr { /// assert_eq!(addr.as_octets(), &[127, 0, 0, 1]); /// ``` #[unstable(feature = "ip_as_octets", issue = "137259")] + #[must_use] #[inline] pub const fn as_octets(&self) -> &[u8; 4] { &self.octets @@ -2160,6 +2162,7 @@ impl Ipv6Addr { /// &[255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) /// ``` #[unstable(feature = "ip_as_octets", issue = "137259")] + #[must_use] #[inline] pub const fn as_octets(&self) -> &[u8; 16] { &self.octets diff --git a/library/core/src/panicking.rs b/library/core/src/panicking.rs index 767707458d6a9..1c018831647d3 100644 --- a/library/core/src/panicking.rs +++ b/library/core/src/panicking.rs @@ -234,10 +234,10 @@ pub fn panic_nounwind_nobacktrace(expr: &'static str) -> ! { panic_nounwind_fmt(fmt::Arguments::from_str(expr), /* force_no_backtrace */ true); } -/// Needed by `non-fmt-panics` lint. +/// Used by `non-fmt-panics` lint. #[inline] #[track_caller] -#[rustc_diagnostic_item = "unreachable_display"] +#[rustc_diagnostic_item = "unreachable_display"] // needed for `non-fmt-panics` lint. pub fn unreachable_display(x: &T) -> ! { panic_fmt(format_args!("internal error: entered unreachable code: {}", *x)); } @@ -252,10 +252,10 @@ pub const fn panic_str_2015(expr: &str) -> ! { panic_display(&expr); } -/// Needed for const-evaluated panics. +/// Used for const-evaluated panics. #[inline] #[track_caller] -#[lang = "panic_display"] +#[lang = "panic_display"] // Needed for const-evaluated panics. #[rustc_do_not_const_check] // hooked by const-eval #[rustc_const_stable_indirect] // must follow stable const rules since it is exposed to stable pub const fn panic_display(x: &T) -> ! { diff --git a/library/std/src/net/udp/tests.rs b/library/std/src/net/udp/tests.rs index f5dd0464f430b..bc18fa47242c5 100644 --- a/library/std/src/net/udp/tests.rs +++ b/library/std/src/net/udp/tests.rs @@ -1,4 +1,4 @@ -#![cfg(not(skip_unsupported_miri_tests))] // UDP sockets are not supported in Miri +#![cfg(not(all(windows, skip_unsupported_miri_tests)))] // Miri has no net support on Windows use crate::io::ErrorKind; use crate::net::tests::{LOCALHOST_IP4, LOCALHOST_IP6, compare_ignore_zoneid}; @@ -357,6 +357,7 @@ fn ttl() { #[test] #[cfg(any(target_family = "unix", target_os = "windows"))] +#[cfg(not(skip_unsupported_miri_tests))] // socket flag not supported by Miri fn hop_limit() { let hlim = 100; @@ -392,6 +393,7 @@ fn set_nonblocking() { // and must be rejected rather than truncated. #[test] #[cfg(all(target_pointer_width = "64", unix))] +#[cfg(not(skip_unsupported_miri_tests))] // read-only mmap not supported by Miri fn send_datagram_larger_than_c_int_max() { // A read-only anonymous mapping rather than a 2 GiB `Vec`: the datagram is // rejected before the kernel ever reads the pages, so this costs no diff --git a/library/std/src/thread/tests.rs b/library/std/src/thread/tests.rs index 4b14e782193c2..d71030735c06d 100644 --- a/library/std/src/thread/tests.rs +++ b/library/std/src/thread/tests.rs @@ -451,8 +451,6 @@ fn test_minimal_thread_stack() { // Test that a stack size too large to round up to the page size is an error. // The cfg mirrors the one around the rounding in the unix `Thread::new`. #[cfg(all(unix, not(any(target_os = "espidf", target_os = "nuttx"))))] -// FIXME(https://github.com/rust-lang/miri/issues/5594): Miri ignores the requested stack size. -#[cfg_attr(skip_unsupported_miri_tests, ignore)] #[test] fn test_huge_thread_stack() { let builder = thread::Builder::new().stack_size(usize::MAX); diff --git a/library/stdarch/crates/core_arch/src/aarch64/neon/generated.rs b/library/stdarch/crates/core_arch/src/aarch64/neon/generated.rs index 72f65d0d14344..62f634172945d 100644 --- a/library/stdarch/crates/core_arch/src/aarch64/neon/generated.rs +++ b/library/stdarch/crates/core_arch/src/aarch64/neon/generated.rs @@ -12063,7 +12063,7 @@ pub unsafe fn vluti4q_lane_s16_x2(a: int16x8x2_t, b: uint8x8_t) any(target_arch = "aarch64", target_arch = "arm64ec"), link_name = "llvm.aarch64.neon.vluti4q.lane.x2.v8i16" )] - fn _vluti4q_lane_s16_x2(a: int16x8_t, a: int16x8_t, b: uint8x8_t, n: i32) -> int16x8_t; + fn _vluti4q_lane_s16_x2(a1: int16x8_t, a2: int16x8_t, b: uint8x8_t, n: i32) -> int16x8_t; } _vluti4q_lane_s16_x2(a.0, a.1, b, LANE) } diff --git a/library/stdarch/crates/stdarch-gen-arm/spec/neon/aarch64.spec.yml b/library/stdarch/crates/stdarch-gen-arm/spec/neon/aarch64.spec.yml index 4cb43ee580ecf..2b853d46d42d7 100644 --- a/library/stdarch/crates/stdarch-gen-arm/spec/neon/aarch64.spec.yml +++ b/library/stdarch/crates/stdarch-gen-arm/spec/neon/aarch64.spec.yml @@ -14059,8 +14059,8 @@ intrinsics: - LLVMLink: name: "vluti4q_lane_{neon_type[0]}_x2" arguments: - - 'a: {neon_type[2]}' - - 'a: {neon_type[2]}' + - 'a1: {neon_type[2]}' + - 'a2: {neon_type[2]}' - 'b: {neon_type[1]}' - 'n: i32' links: diff --git a/src/bootstrap/src/core/builder/cargo.rs b/src/bootstrap/src/core/builder/cargo.rs index 5928860bad0a9..68d28c39a4441 100644 --- a/src/bootstrap/src/core/builder/cargo.rs +++ b/src/bootstrap/src/core/builder/cargo.rs @@ -1176,7 +1176,6 @@ impl Builder<'_> { // Keep this scheme in sync with `rustc_metadata::rmeta::decoder`'s // `try_to_translate_virtual_to_real`. let trim_paths = |cargo: &mut BootstrapCommand, ws_remap: &str| { - cargo.arg("-Ztrim-paths"); cargo.arg("--config").arg("profile.release.trim-paths='all'"); cargo.arg("--config").arg("profile.dev.trim-paths='all'"); // This is an internal contract with cargo. diff --git a/src/doc/rustc/src/codegen-options/index.md b/src/doc/rustc/src/codegen-options/index.md index 67c4fd7806933..81702dcd1e435 100644 --- a/src/doc/rustc/src/codegen-options/index.md +++ b/src/doc/rustc/src/codegen-options/index.md @@ -178,6 +178,12 @@ values: The default behaviour, if frame pointers are not force-enabled, depends on the target. +#### Implementation notes + +On s390x targets, frame pointers cannot be used to walk the stack. Instead of enabling frame +pointers, this flag enables the `backchain`, which stores a pointer to the caller's frame in each +function's frame. + ## force-unwind-tables This flag forces the generation of unwind tables. It takes one of the following diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 7d2da65c6d7cb..489862459d71a 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1113,7 +1113,7 @@ fn clean_fn_or_proc_macro<'tcx>( cx, sig, generics, - ParamsSrc::Body(body_id), + ParamsSrc::Params(cx.tcx.hir_body(body_id).params), item.owner_id.to_def_id(), ); let mut func = Function { generics, decl }; @@ -1146,8 +1146,8 @@ fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[rustc_attr_ } enum ParamsSrc<'tcx> { - Body(hir::BodyId), Idents(&'tcx [Option]), + Params(&'tcx [hir::Param<'tcx>]), } fn clean_function<'tcx>( @@ -1171,7 +1171,7 @@ fn clean_function<'tcx>( clean_poly_fn_sig(cx, Some(def_id), sig) } else { let params = match params { - ParamsSrc::Body(body_id) => clean_params_via_body(cx, sig.decl, body_id), + ParamsSrc::Params(body_id) => clean_params_via_body(cx, sig.decl, body_id), // Let's not perpetuate anon params from Rust 2015; use `_` for them. ParamsSrc::Idents(idents) => clean_params(cx, sig.decl, idents, |ident| { Some(ident.map_or(kw::Underscore, |ident| ident.name)) @@ -1204,11 +1204,11 @@ fn clean_params<'tcx>( fn clean_params_via_body<'tcx>( cx: &mut DocContext<'tcx>, decl: &hir::FnDecl<'tcx>, - body_id: hir::BodyId, + params: &'tcx [hir::Param<'tcx>], ) -> Vec { decl.inputs .iter() - .zip(cx.tcx.hir_body(body_id).params) + .zip(params) .enumerate() .map(|(i, (ty, param))| Parameter { name: Some(name_from_pat(param.pat)), @@ -1312,7 +1312,7 @@ fn clean_trait_item<'tcx>(trait_item: &hir::TraitItem<'tcx>, cx: &mut DocContext hir::TraitItemKind::Fn(ref sig, body) => { let (params, body) = match body { hir::TraitFn::Provided(body) => ( - ParamsSrc::Body(body), + ParamsSrc::Params(cx.tcx.hir_body(body).params), Some(Defaultness::from_trait_item(trait_item.defaultness)), ), hir::TraitFn::Required(idents) => (ParamsSrc::Idents(idents), None), @@ -1356,8 +1356,13 @@ pub(crate) fn clean_impl_item<'tcx>( })) } hir::ImplItemKind::Fn(ref sig, body) => { - let (generics, decl) = - clean_function(cx, sig, impl_.generics, ParamsSrc::Body(body), local_did); + let (generics, decl) = clean_function( + cx, + sig, + impl_.generics, + ParamsSrc::Params(cx.tcx.hir_body(body).params), + local_did, + ); ItemKind::AssocFunction(Box::new(AssocFunction { generics, decl, @@ -3374,9 +3379,9 @@ fn clean_maybe_renamed_foreign_item<'tcx>( let def_id = item.owner_id.to_def_id(); cx.with_param_env(def_id, |cx| { let kind = match item.kind { - hir::ForeignItemKind::Fn(sig, idents, generics) => { + hir::ForeignItemKind::Fn(sig, params, generics) => { let (generics, decl) = - clean_function(cx, &sig, generics, ParamsSrc::Idents(idents), def_id); + clean_function(cx, &sig, generics, ParamsSrc::Params(params), def_id); ItemKind::ForeignFunction( Box::new(Function { generics, decl }), sig.header.safety(), diff --git a/src/tools/clippy/clippy_lints/src/ignored_unit_patterns.rs b/src/tools/clippy/clippy_lints/src/ignored_unit_patterns.rs index 1a016c8862e0e..100c91206895d 100644 --- a/src/tools/clippy/clippy_lints/src/ignored_unit_patterns.rs +++ b/src/tools/clippy/clippy_lints/src/ignored_unit_patterns.rs @@ -39,7 +39,8 @@ impl<'tcx> LateLintPass<'tcx> for IgnoredUnitPatterns { fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx hir::Pat<'tcx>) { if matches!(pat.kind, PatKind::Wild) && !pat.span.from_expansion() - && cx.typeck_results().pat_ty(pat).peel_refs().is_unit() + && let Some(typeck_results) = cx.typeck_results + && typeck_results.pat_ty(pat).peel_refs().is_unit() { match cx.tcx.parent_hir_node(pat.hir_id) { Node::Param(param) if matches!(cx.tcx.parent_hir_node(param.hir_id), Node::Item(_)) => { diff --git a/src/tools/clippy/tests/ui/ignored_unit_patterns.fixed b/src/tools/clippy/tests/ui/ignored_unit_patterns.fixed index ed5273125e1a5..70d168fbc27ab 100644 --- a/src/tools/clippy/tests/ui/ignored_unit_patterns.fixed +++ b/src/tools/clippy/tests/ui/ignored_unit_patterns.fixed @@ -54,3 +54,16 @@ fn test_unit_ref_2(v: &[(usize, ())]) { let _ = x; } } + +unsafe extern "C" { + #[expect(improper_ctypes)] + fn test_extern_param(_: ()); +} + +trait Test { + fn test_required_param(_: ()); +} + +fn test_fn_ty() { + let x: fn(_: ()); +} diff --git a/src/tools/clippy/tests/ui/ignored_unit_patterns.rs b/src/tools/clippy/tests/ui/ignored_unit_patterns.rs index 6d6dab8cd3aa3..b377ccc6dc59c 100644 --- a/src/tools/clippy/tests/ui/ignored_unit_patterns.rs +++ b/src/tools/clippy/tests/ui/ignored_unit_patterns.rs @@ -54,3 +54,16 @@ fn test_unit_ref_2(v: &[(usize, ())]) { let _ = x; } } + +unsafe extern "C" { + #[expect(improper_ctypes)] + fn test_extern_param(_: ()); +} + +trait Test { + fn test_required_param(_: ()); +} + +fn test_fn_ty() { + let x: fn(_: ()); +} diff --git a/src/tools/compiletest/src/directives.rs b/src/tools/compiletest/src/directives.rs index ced1641d94f6a..7ba7575d0cec5 100644 --- a/src/tools/compiletest/src/directives.rs +++ b/src/tools/compiletest/src/directives.rs @@ -348,7 +348,6 @@ impl TestProps { pub(crate) fn from_file(testfile: &Utf8Path, revision: Option<&str>, config: &Config) -> Self { let mut props = TestProps::new(); props.load_from(testfile, revision, config); - props.exec_env.push(("RUSTC".to_string(), config.rustc_path.to_string())); // UI tests default to `//@ check-fail` if unspecified. if config.mode == TestMode::Ui && props.pass_fail_mode.is_none() { diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index a9506f83de799..074b9e3104066 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -1631,12 +1631,6 @@ impl<'test> TestCx<'test> { aux_path: Option<&Utf8Path>, input: Option, ) -> ProcRes { - let cmdline = { - let cmdline = self.make_cmdline(&command, lib_path); - self.logv(format_args!("executing {cmdline}")); - cmdline - }; - command.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::piped()); let lint_driver_path = @@ -1650,6 +1644,9 @@ impl<'test> TestCx<'test> { .chain(lint_driver_path.filter(|_| !self.props.aux.lints.is_empty())), ); + let cmdline = format!("{command:?}"); + self.logv(format_args!("executing {cmdline}")); + let mut child = disable_error_reporting(|| command.spawn()) .unwrap_or_else(|e| panic!("failed to exec `{command:?}`: {e:?}")); if let Some(input) = input { @@ -2191,23 +2188,6 @@ impl<'test> TestCx<'test> { } } - fn make_cmdline(&self, command: &Command, libpath: &Utf8Path) -> String { - use crate::util; - - // Linux and mac don't require adjusting the library search path - if cfg!(unix) { - format!("{:?}", command) - } else { - // Build the LD_LIBRARY_PATH variable as it would be seen on the command line - // for diagnostic purposes - fn lib_path_cmd_prefix(path: &str) -> String { - format!("{}=\"{}\"", util::lib_path_env_var(), util::make_new_path(path)) - } - - format!("{} {:?}", lib_path_cmd_prefix(libpath.as_str()), command) - } - } - fn dump_output(&self, print_output: bool, proc_name: &str, out: &str, err: &str) { let revision = if let Some(r) = self.variant.revision() { format!("{}.", r) } else { String::new() }; @@ -2402,11 +2382,6 @@ impl<'test> TestCx<'test> { self.compose_and_run(filecheck, Utf8Path::new(""), None, None) } - fn charset() -> &'static str { - // FreeBSD 10.1 defaults to GDB 6.1.1 which doesn't support "auto" charset - if cfg!(target_os = "freebsd") { "ISO-8859-1" } else { "UTF-8" } - } - fn get_lines(&self, path: &Utf8Path, mut other_files: Option<&mut Vec>) -> Vec { let content = fs::read_to_string(path.as_std_path()).unwrap(); let mut ignore = false; diff --git a/src/tools/compiletest/src/runtest/debuginfo.rs b/src/tools/compiletest/src/runtest/debuginfo.rs index 710c7528cfee6..4657f50e9e966 100644 --- a/src/tools/compiletest/src/runtest/debuginfo.rs +++ b/src/tools/compiletest/src/runtest/debuginfo.rs @@ -132,7 +132,7 @@ impl TestCx<'_> { // write debugger script let mut script_str = String::with_capacity(2048); script_str.push_str("py import debugger_tester\n"); - script_str.push_str(&format!("set charset {}\n", Self::charset())); + script_str.push_str("set charset UTF-8\n"); script_str.push_str(&format!("set sysroot {android_cross_path}\n")); script_str.push_str(&format!("file {}\n", exe_file)); script_str.push_str("target remote :5039\n"); @@ -208,18 +208,14 @@ impl TestCx<'_> { &["-quiet".as_ref(), "-batch".as_ref(), "-nx".as_ref(), &debugger_script]; let gdb_path = self.config.gdb.as_ref().unwrap(); - let Output { status, stdout, stderr } = Command::new(&gdb_path) - .args(debugger_opts) - .output() - .unwrap_or_else(|e| panic!("failed to exec `{gdb_path:?}`: {e:?}")); - let cmdline = { - let mut gdb = Command::new(&format!("{}-gdb", self.config.target)); - gdb.args(debugger_opts); - // FIXME(jieyouxu): don't pass an empty Path - let cmdline = self.make_cmdline(&gdb, Utf8Path::new("")); - self.logv(format_args!("executing {cmdline}")); - cmdline - }; + let mut gdb = Command::new(&gdb_path); + gdb.args(debugger_opts); + + let cmdline = format!("{gdb:?}"); + self.logv(format_args!("executing {cmdline}")); + + let Output { status, stdout, stderr } = + gdb.output().unwrap_or_else(|e| panic!("failed to exec `{gdb_path:?}`: {e:?}")); debugger_run_result = ProcRes { status, @@ -236,7 +232,7 @@ impl TestCx<'_> { // write debugger script let mut script_str = String::with_capacity(2048); script_str.push_str("py import debugger_tester\n"); - script_str.push_str(&format!("set charset {}\n", Self::charset())); + script_str.push_str("set charset UTF-8\n"); script_str.push_str("show version\n"); match self.config.gdb_version { diff --git a/src/tools/compiletest/src/util.rs b/src/tools/compiletest/src/util.rs index 53c675e7d015e..ce55f84e3aef5 100644 --- a/src/tools/compiletest/src/util.rs +++ b/src/tools/compiletest/src/util.rs @@ -7,23 +7,6 @@ pub(crate) use shim_utils::ArgFileCommand; #[cfg(test)] mod tests; -pub(crate) fn make_new_path(path: &str) -> String { - assert!(cfg!(windows)); - // Windows just uses PATH as the library search path, so we have to - // maintain the current value while adding our own - match env::var(lib_path_env_var()) { - Ok(curr) => format!("{}{}{}", path, path_div(), curr), - Err(..) => path.to_owned(), - } -} - -pub(crate) fn lib_path_env_var() -> &'static str { - "PATH" -} -fn path_div() -> &'static str { - ";" -} - pub(crate) trait Utf8PathBufExt { /// Append an extension to the path, even if it already has one. fn with_extra_extension(&self, extension: &str) -> Utf8PathBuf; diff --git a/src/tools/miri/cargo-miri/Cargo.lock b/src/tools/miri/cargo-miri/Cargo.lock index 1db0a0e7061e3..d87b3f6004cd9 100644 --- a/src/tools/miri/cargo-miri/Cargo.lock +++ b/src/tools/miri/cargo-miri/Cargo.lock @@ -30,7 +30,6 @@ dependencies = [ "cargo_metadata", "directories", "rustc-build-sysroot", - "rustc_tools_util", "rustc_version", "serde", "serde_json", @@ -228,12 +227,6 @@ dependencies = [ "walkdir", ] -[[package]] -name = "rustc_tools_util" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3b75158011a63889ba12084cf1224baad7bcad50f6ee7c842f772b74aa148ed" - [[package]] name = "rustc_version" version = "0.4.1" diff --git a/src/tools/miri/cargo-miri/Cargo.toml b/src/tools/miri/cargo-miri/Cargo.toml index 5a1d3e9b68bbb..3f3ac0a30a186 100644 --- a/src/tools/miri/cargo-miri/Cargo.toml +++ b/src/tools/miri/cargo-miri/Cargo.toml @@ -23,6 +23,3 @@ rustc-build-sysroot = "0.5.13" # do not. This makes `./miri install` after `./miri build` faster. # Require a version of serde without intransparent unreproducible binary blobs. serde = { version = "1.0.185", features = ["derive"] } - -[build-dependencies] -rustc_tools_util = "0.4" diff --git a/src/tools/miri/cargo-miri/build.rs b/src/tools/miri/cargo-miri/build.rs index 52e2a083512c4..4aa52826016ac 100644 --- a/src/tools/miri/cargo-miri/build.rs +++ b/src/tools/miri/cargo-miri/build.rs @@ -1,6 +1,62 @@ +use std::path::PathBuf; +use std::process::Command; +use std::str; + +#[must_use] +fn get_output(cmd: &str, args: &[&str]) -> Option { + let output = Command::new(cmd).args(args).output().ok()?; + let mut stdout = output.status.success().then_some(output.stdout)?; + // Remove trailing newlines. + while stdout.last().copied() == Some(b'\n') { + stdout.pop(); + } + String::from_utf8(stdout).ok() +} + +#[must_use] +pub fn rerun_if_git_changes() -> Option<()> { + // Make sure we get rerun when the git commit changes. + // We want to watch two files: HEAD, which tracks which branch we are on, + // and the file for that branch that tracks which commit is checked out. + + // First, find the `HEAD` file. This should work even with worktrees. + let git_head_file = PathBuf::from(get_output("git", &["rev-parse", "--git-path", "HEAD"])?); + if git_head_file.exists() { + println!("cargo::rerun-if-changed={}", git_head_file.display()); + } + + // Determine the name of the current ref. + // This will quit if HEAD is detached. + let git_head_ref = get_output("git", &["symbolic-ref", "-q", "HEAD"])?; + // Ask git where this ref is stored. + let git_head_ref_file = + PathBuf::from(get_output("git", &["rev-parse", "--git-path", &git_head_ref])?); + // If this ref is packed, the file does not exist. However, the checked-out branch is never (?) + // packed, so we should always be able to find this file. + if git_head_ref_file.exists() { + println!("cargo::rerun-if-changed={}", git_head_ref_file.display()); + } + + Some(()) +} + +#[must_use] +pub fn get_commit_hash() -> Option { + let mut stdout = get_output("git", &["rev-parse", "HEAD"])?; + stdout.truncate(10); + Some(stdout) +} + +#[must_use] +pub fn get_commit_date() -> Option { + get_output("git", &["log", "-1", "--date=short", "--pretty=format:%cd"]) +} + fn main() { // Don't rebuild miri when nothing changed. println!("cargo:rerun-if-changed=build.rs"); // gather version info - rustc_tools_util::setup_version_info!(); + let _ = rerun_if_git_changes(); + println!("cargo:rustc-env=GIT_COMMIT_HASH={}", get_commit_hash().unwrap_or_default()); + println!("cargo:rustc-env=GIT_COMMIT_DATE={}", get_commit_date().unwrap_or_default()); } diff --git a/src/tools/miri/cargo-miri/src/phases.rs b/src/tools/miri/cargo-miri/src/phases.rs index 628bc39e7bf7b..e3565d1b06a2b 100644 --- a/src/tools/miri/cargo-miri/src/phases.rs +++ b/src/tools/miri/cargo-miri/src/phases.rs @@ -48,7 +48,7 @@ fn show_help() { fn show_version() { print!("miri {}", env!("CARGO_PKG_VERSION")); - let version = format!("{} {}", env!("GIT_HASH"), env!("COMMIT_DATE")); + let version = format!("{} {}", env!("GIT_COMMIT_HASH"), env!("GIT_COMMIT_DATE")); if version.len() > 1 { // If there is actually something here, print it. print!(" ({version})"); diff --git a/src/tools/miri/josh-sync.toml b/src/tools/miri/josh-sync.toml index 86208b3742d27..5d4b4111bef8b 100644 --- a/src/tools/miri/josh-sync.toml +++ b/src/tools/miri/josh-sync.toml @@ -1,2 +1,5 @@ repo = "miri" filter = ":rev(75dd959a3a40eb5b4574f8d2e23aa6efbeb33573:prefix=src/tools/miri):/src/tools/miri" + +[push-pr] +suffix = "r? @ghost" diff --git a/src/tools/miri/miri-script/src/commands.rs b/src/tools/miri/miri-script/src/commands.rs index 05a294d47e1bb..1ebda03d0d0fe 100644 --- a/src/tools/miri/miri-script/src/commands.rs +++ b/src/tools/miri/miri-script/src/commands.rs @@ -177,9 +177,12 @@ impl Command { cmd!(sh, "cargo clean").run()?; // Call `cargo metadata` on the sources in case that changes the lockfile // (works around ). + // Need to set `CARGO_RESOLVER_INCOMPATIBLE_PUBLISH_AGE=allow` otherwise lockfiles with + // newer packages get rejected; that's fine as everything is already pinned in the lockfile. let sysroot = cmd!(sh, "rustc --print sysroot").read()?; let sysroot = sysroot.trim(); - cmd!(sh, "cargo metadata --format-version 1 --manifest-path {sysroot}/lib/rustlib/rustc-src/rust/compiler/rustc/Cargo.toml").ignore_stdout().run()?; + cmd!(sh, "cargo metadata --format-version 1 --manifest-path {sysroot}/lib/rustlib/rustc-src/rust/compiler/rustc/Cargo.toml") + .ignore_stdout().env("CARGO_RESOLVER_INCOMPATIBLE_PUBLISH_AGE", "allow").run()?; Ok(()) } diff --git a/src/tools/miri/priroda/README.md b/src/tools/miri/priroda/README.md index 30fec23f430a7..04078eab0d5e7 100644 --- a/src/tools/miri/priroda/README.md +++ b/src/tools/miri/priroda/README.md @@ -156,7 +156,7 @@ To update the expected output files after an intentional output change, run: | `out`, `stepout` | Run until execution returns to a shallower user frame. | | `c`, `continue` | Continue until the program finishes or reaches a breakpoint. | | `b :`, `break :` | Add a source-location breakpoint. | -| `l`, `locals` | List source-level locals in the current frame by name. | +| `l`, `locals` | List the MIR locals of the current frame, with source names and projections where debug info provides them. | | `p `, `print ` | Print one MIR local by numeric id. | | `f `, `follow ` | Render allocation bytes from an offset, including the full allocation size. | | `q`, `quit` | Exit Priroda. | diff --git a/src/tools/miri/priroda/tests/ui.rs b/src/tools/miri/priroda/tests/ui.rs index 41c98300d8ebb..660dc111b0e29 100644 --- a/src/tools/miri/priroda/tests/ui.rs +++ b/src/tools/miri/priroda/tests/ui.rs @@ -27,9 +27,6 @@ fn main() -> Result<(), Box> { // so the relative `tests/ui/...` paths resolve in the same way as a standalone crate. std::env::set_current_dir(&priroda_dir)?; - let rustc_sysroot = Command::new("rustc").arg("--print").arg("sysroot").output()?; - let rustc_sysroot = String::from_utf8(rustc_sysroot.stdout)?.trim().to_owned(); - let mut program = CommandBuilder::rustc(); program.program = PathBuf::from(env!("CARGO_BIN_EXE_priroda")); @@ -47,7 +44,8 @@ fn main() -> Result<(), Box> { let manifest_dir_regex = Regex::new(®ex::escape(&priroda_dir.display().to_string())).unwrap(); let miri_dir_regex = Regex::new(®ex::escape(&miri_dir.display().to_string())).unwrap(); - let rustc_sysroot_regex = Regex::new(®ex::escape(&rustc_sysroot)).unwrap(); + let rustlib_regex = + Regex::new("[^ \n`\"\']*/library/(core|alloc|std|panic_(unwind|abort))/src").unwrap(); let pointer_regex = Regex::new(r"0x[0-9a-f]+\[alloc[0-9]+\]<[0-9]+>").unwrap(); let crlf_regex = Regex::new(r"\r\n").unwrap(); // DAP Content-Length headers embed the byte count of the following JSON, @@ -55,14 +53,30 @@ fn main() -> Result<(), Box> { // Replace them with a placeholder so path-length differences between // machines do not make Content-Length drift from the normalised body. let content_length_regex = Regex::new(r"Content-Length: \d+").unwrap(); + // Local indices are assigned while MIR is built, so a rustup that inserts a + // temporary changes them. Keep the storage projection suffix (`.0`, `.*`, + // ` as variant#1.0`): it says which field or variant of the local the row + // reads. `print ` echoes are rewritten too, so they stop pinning the id. + let local_id_regex = Regex::new(r"Id: _[0-9]+").unwrap(); + // An unnamed `` row has no name and no rendered value, so it only pins + // rustc's temporary inventory and that slot's `Ty:` string. Named locals stay + // asserted even when dead. `Name:` scoping leaves `print ` rows alone, + // since they have no such field. The `(priroda) ` prompt must match too, or + // dropping the first row of a block would splice the next row onto the + // prompt; no fixture covers that yet. Matching the id as `[^,]+` keeps this + // rule independent of the order the two rules run in. + let unnamed_dead_local_regex = + Regex::new(r"(?:\(priroda\) )?Name: , Id: [^,]+, [^\n]*Value: \n?").unwrap(); config.comment_defaults.base().normalize_stdout.extend([ (manifest_dir_regex.into(), b"{MANIFEST_DIR}".to_vec()), (miri_dir_regex.into(), b"{MIRI_DIR}".to_vec()), - (rustc_sysroot_regex.into(), b"{RUSTC_SYSROOT}".to_vec()), + (rustlib_regex.into(), b"RUSTLIB/$1/src".to_vec()), (pointer_regex.into(), b"{ALLOC_PTR}".to_vec()), // DAP frames use CRLF headers; keep checked-in stdout fixtures readable. (crlf_regex.into(), b"\n".to_vec()), (content_length_regex.into(), b"Content-Length: {CONTENT_LENGTH}".to_vec()), + (unnamed_dead_local_regex.into(), b"".to_vec()), + (local_id_regex.into(), b"Id: _{LOCAL}".to_vec()), ]); // Priroda UI tests do not currently require annotation comments in the test files. diff --git a/src/tools/miri/priroda/tests/ui/cli_step_out_command.stdout b/src/tools/miri/priroda/tests/ui/cli_step_out_command.stdout index a1d982386e047..b6900ff5d6fe7 100644 --- a/src/tools/miri/priroda/tests/ui/cli_step_out_command.stdout +++ b/src/tools/miri/priroda/tests/ui/cli_step_out_command.stdout @@ -1,3 +1,3 @@ -(priroda) {RUSTC_SYSROOT}/lib/rustlib/src/rust/library/std/src/rt.rs:206 +(priroda) RUSTLIB/std/src/rt.rs:206 (priroda) stepOut is not meaningful in the outermost user frame (priroda) quitting diff --git a/src/tools/miri/priroda/tests/ui/dap_repeated_next_from_call.stdout b/src/tools/miri/priroda/tests/ui/dap_repeated_next_from_call.stdout index 5e6d0fab18a82..93ffbe146cbce 100644 --- a/src/tools/miri/priroda/tests/ui/dap_repeated_next_from_call.stdout +++ b/src/tools/miri/priroda/tests/ui/dap_repeated_next_from_call.stdout @@ -28,4 +28,4 @@ Content-Length: {CONTENT_LENGTH} {"seq":14,"type":"event","event":"stopped","body":{"reason":"step","description":null,"threadId":1,"preserveFocusHint":null,"text":null,"allThreadsStopped":true,"hitBreakpointIds":null}}Content-Length: {CONTENT_LENGTH} -{"seq":15,"type":"response","request_seq":10,"success":true,"command":"stackTrace","body":{"stackFrames":[{"id":1,"name":">::call_once - shim(fn())","source":{"name":"function.rs","path":"{RUSTC_SYSROOT}/lib/rustlib/src/rust/library/core/src/ops/function.rs","sourceReference":0},"line":250,"column":5}],"totalFrames":1},"error":null} \ No newline at end of file +{"seq":15,"type":"response","request_seq":10,"success":true,"command":"stackTrace","body":{"stackFrames":[{"id":1,"name":">::call_once - shim(fn())","source":{"name":"function.rs","path":"RUSTLIB/core/src/ops/function.rs","sourceReference":0},"line":250,"column":5}],"totalFrames":1},"error":null} \ No newline at end of file diff --git a/src/tools/miri/priroda/tests/ui/locals_access_field.stdout b/src/tools/miri/priroda/tests/ui/locals_access_field.stdout index 8f54636373a2a..9c6134a23b72a 100644 --- a/src/tools/miri/priroda/tests/ui/locals_access_field.stdout +++ b/src/tools/miri/priroda/tests/ui/locals_access_field.stdout @@ -1,14 +1,14 @@ (priroda) breakpoint added: {MANIFEST_DIR}/tests/ui/locals_access_field.rs:14 (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_access_field.rs:14 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: extraslice, Id: _1, Ty: ExtraSlice<'_>, Value: ExtraSlice { _slice: [{ALLOC_PTR} 00 00 00 00 00 00 00 00], _extra: [00 00 00 00] } -Name: _slice, Id: _2, Ty: &[u8], Value: (pointer to {ALLOC_PTR}, 0x0000000000000000): &[u8] -Name: _extra, Id: _3, Ty: u32, Value: 0_u32 -(priroda) Id: _0, Ty: (), Value: -(priroda) Id: _1, Ty: ExtraSlice<'_>, Value: ExtraSlice { _slice: [{ALLOC_PTR} 00 00 00 00 00 00 00 00], _extra: [00 00 00 00] } -(priroda) Id: _2, Ty: &[u8], Value: (pointer to {ALLOC_PTR}, 0x0000000000000000): &[u8] -(priroda) Id: _3, Ty: u32, Value: 0_u32 +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: extraslice, Id: _{LOCAL}, Ty: ExtraSlice<'_>, Value: ExtraSlice { _slice: [{ALLOC_PTR} 00 00 00 00 00 00 00 00], _extra: [00 00 00 00] } +Name: _slice, Id: _{LOCAL}, Ty: &[u8], Value: (pointer to {ALLOC_PTR}, 0x0000000000000000): &[u8] +Name: _extra, Id: _{LOCAL}, Ty: u32, Value: 0_u32 +(priroda) Id: _{LOCAL}, Ty: (), Value: +(priroda) Id: _{LOCAL}, Ty: ExtraSlice<'_>, Value: ExtraSlice { _slice: [{ALLOC_PTR} 00 00 00 00 00 00 00 00], _extra: [00 00 00 00] } +(priroda) Id: _{LOCAL}, Ty: &[u8], Value: (pointer to {ALLOC_PTR}, 0x0000000000000000): &[u8] +(priroda) Id: _{LOCAL}, Ty: u32, Value: 0_u32 (priroda) no local for this id (priroda) no local for this id (priroda) quitting diff --git a/src/tools/miri/priroda/tests/ui/locals_corpus_async.stdout b/src/tools/miri/priroda/tests/ui/locals_corpus_async.stdout index ddd3d5c13b2b4..0792212537f01 100644 --- a/src/tools/miri/priroda/tests/ui/locals_corpus_async.stdout +++ b/src/tools/miri/priroda/tests/ui/locals_corpus_async.stdout @@ -6,33 +6,33 @@ (priroda) breakpoint added: {MANIFEST_DIR}/tests/ui/locals_corpus_async.rs:76 (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_corpus_async.rs:31 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: , Id: _1, Ty: (u32, i32), Value: (5_u32, 6_i32) -Name: first, Id: _1.0, Ty: u32, Value: 5_u32 -Name: second, Id: _1.1, Ty: i32, Value: 6_i32 +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: , Id: _{LOCAL}, Ty: (u32, i32), Value: (5_u32, 6_i32) +Name: first, Id: _{LOCAL}.0, Ty: u32, Value: 5_u32 +Name: second, Id: _{LOCAL}.1, Ty: i32, Value: 6_i32 (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_corpus_async.rs:45 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: , Id: _1, Ty: S, Value: S { x: 5f32 } -Name: x, Id: _1.0, Ty: f32, Value: 5f32 +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: , Id: _{LOCAL}, Ty: S, Value: S { x: 5f32 } +Name: x, Id: _{LOCAL}.0, Ty: f32, Value: 5f32 (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_corpus_async.rs:55 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: , Id: _1, Ty: std::option::Option, Value: Option::Some([05 00 00 00]) -Name: inner, Id: _1 as variant#1.0, Ty: i32, Value: [05 00 00 00] +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: , Id: _{LOCAL}, Ty: std::option::Option, Value: Option::Some([05 00 00 00]) +Name: inner, Id: _{LOCAL} as variant#1.0, Ty: i32, Value: [05 00 00 00] (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_corpus_async.rs:66 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: , Id: _1, Ty: std::option::Option<&i32>, Value: Option::Some([{ALLOC_PTR}]) -Name: pointer, Id: _1 as variant#1.0, Ty: &i32, Value: [{ALLOC_PTR}] -Name: deref, Id: _1 as variant#1.0.*, Ty: i32, Value: [05 00 00 00] +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: , Id: _{LOCAL}, Ty: std::option::Option<&i32>, Value: Option::Some([{ALLOC_PTR}]) +Name: pointer, Id: _{LOCAL} as variant#1.0, Ty: &i32, Value: [{ALLOC_PTR}] +Name: deref, Id: _{LOCAL} as variant#1.0.*, Ty: i32, Value: [05 00 00 00] (priroda) Allocation alloc2+0: [05 00 00 00] (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_corpus_async.rs:20 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: , Id: _1, Ty: &mut std::option::Option, Value: {&_: &mut std::option::Option} -Name: foo, Id: _1.* as variant#1.0, Ty: i32, Value: [05 00 00 00] +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: , Id: _{LOCAL}, Ty: &mut std::option::Option, Value: {&_: &mut std::option::Option} +Name: foo, Id: _{LOCAL}.* as variant#1.0, Ty: i32, Value: [05 00 00 00] (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_corpus_async.rs:76 -(priroda) Name: , Id: _0, Ty: (), Value: +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: (priroda) quitting diff --git a/src/tools/miri/priroda/tests/ui/locals_in_function.stdout b/src/tools/miri/priroda/tests/ui/locals_in_function.stdout index 5161a3397092e..58c0571853edd 100644 --- a/src/tools/miri/priroda/tests/ui/locals_in_function.stdout +++ b/src/tools/miri/priroda/tests/ui/locals_in_function.stdout @@ -1,10 +1,7 @@ (priroda) breakpoint added: {MANIFEST_DIR}/tests/ui/locals_in_function.rs:5 (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_in_function.rs:5 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: x, Id: _1, Ty: i32, Value: 1_i32 -Name: y, Id: _2, Ty: bool, Value: -Name: , Id: _3, Ty: (i32, bool), Value: -Name: , Id: _4, Ty: i32, Value: -Name: , Id: _5, Ty: bool, Value: +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: x, Id: _{LOCAL}, Ty: i32, Value: 1_i32 +Name: y, Id: _{LOCAL}, Ty: bool, Value: (priroda) quitting diff --git a/src/tools/miri/priroda/tests/ui/locals_mplace_metadata.stdout b/src/tools/miri/priroda/tests/ui/locals_mplace_metadata.stdout index c8088805d3482..fe15aa8873a20 100644 --- a/src/tools/miri/priroda/tests/ui/locals_mplace_metadata.stdout +++ b/src/tools/miri/priroda/tests/ui/locals_mplace_metadata.stdout @@ -3,23 +3,17 @@ (priroda) breakpoint added: {MANIFEST_DIR}/tests/ui/locals_mplace_metadata.rs:16 (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_mplace_metadata.rs:8 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: slice, Id: _1, Ty: [u8], Value: [[01], [02], [03]] -Name: , Id: _2, Ty: &[u8], Value: -Name: , Id: _3, Ty: &[u8], Value: -(priroda) Id: _1, Ty: [u8], Value: [[01], [02], [03]] +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: slice, Id: _{LOCAL}, Ty: [u8], Value: [[01], [02], [03]] +(priroda) Id: _{LOCAL}, Ty: [u8], Value: [[01], [02], [03]] (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_mplace_metadata.rs:12 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: text, Id: _1, Ty: str, Value: [__ __ __] -Name: , Id: _2, Ty: &str, Value: -Name: , Id: _3, Ty: &str, Value: -(priroda) Id: _1, Ty: str, Value: [__ __ __] +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: text, Id: _{LOCAL}, Ty: str, Value: [__ __ __] +(priroda) Id: _{LOCAL}, Ty: str, Value: [__ __ __] (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_mplace_metadata.rs:16 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: value, Id: _1, Ty: dyn Marker, Value: [01 00 00 00 02 00 00 00] -Name: , Id: _2, Ty: &dyn Marker, Value: -Name: , Id: _3, Ty: &dyn Marker, Value: -(priroda) Id: _1, Ty: dyn Marker, Value: [01 00 00 00 02 00 00 00] +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: value, Id: _{LOCAL}, Ty: dyn Marker, Value: [01 00 00 00 02 00 00 00] +(priroda) Id: _{LOCAL}, Ty: dyn Marker, Value: [01 00 00 00 02 00 00 00] (priroda) quitting diff --git a/src/tools/miri/priroda/tests/ui/locals_nested_field_fragment.stdout b/src/tools/miri/priroda/tests/ui/locals_nested_field_fragment.stdout index b5a5f7f19a4b2..c72d6638d8582 100644 --- a/src/tools/miri/priroda/tests/ui/locals_nested_field_fragment.stdout +++ b/src/tools/miri/priroda/tests/ui/locals_nested_field_fragment.stdout @@ -1,14 +1,12 @@ (priroda) breakpoint added: {MANIFEST_DIR}/tests/ui/locals_nested_field_fragment.rs:12 (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_nested_field_fragment.rs:12 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: , Id: _1, Ty: Outer, Value: -Name: , Id: _2, Ty: (Leaf,), Value: -Name: , Id: _3, Ty: Leaf, Value: -Name: , Id: _4, Ty: (Leaf,), Value: -Name: , Id: _5, Ty: Leaf, Value: -Name: , Id: _6, Ty: Leaf, Value: -Name: x.inner.0.field, Id: _7, Ty: u8, Value: -Name: , Id: _8, Ty: u8, Value: -Name: , Id: _9, Ty: u8, Value: +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: , Id: _{LOCAL}, Ty: Outer, Value: +Name: , Id: _{LOCAL}, Ty: (Leaf,), Value: +Name: , Id: _{LOCAL}, Ty: Leaf, Value: +Name: , Id: _{LOCAL}, Ty: (Leaf,), Value: +Name: , Id: _{LOCAL}, Ty: Leaf, Value: +Name: , Id: _{LOCAL}, Ty: Leaf, Value: +Name: x.inner.0.field, Id: _{LOCAL}, Ty: u8, Value: (priroda) quitting diff --git a/src/tools/miri/priroda/tests/ui/locals_pointer_rendering.stdout b/src/tools/miri/priroda/tests/ui/locals_pointer_rendering.stdout index b3d61198e813c..921400fabe2e3 100644 --- a/src/tools/miri/priroda/tests/ui/locals_pointer_rendering.stdout +++ b/src/tools/miri/priroda/tests/ui/locals_pointer_rendering.stdout @@ -1,56 +1,20 @@ (priroda) breakpoint added: {MANIFEST_DIR}/tests/ui/locals_pointer_rendering.rs:59 (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_pointer_rendering.rs:59 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: target, Id: _1, Ty: [u8; 2], Value: [[0a], [14]] -Name: pointer_at_offset0, Id: _2, Ty: PointerAtOffset0<'_>, Value: PointerAtOffset0 { ptr: [{ALLOC_PTR}] } -Name: , Id: _3, Ty: &u8, Value: -Name: , Id: _4, Ty: &u8, Value: -Name: , Id: _5, Ty: usize, Value: -Name: , Id: _6, Ty: bool, Value: true -Name: pointer_after_bytes, Id: _7, Ty: PointerAfterBytes<'_>, Value: PointerAfterBytes { bytes: [[01], [02], [03]], ptr: [{ALLOC_PTR}] } -Name: , Id: _8, Ty: [u8; 3], Value: -Name: , Id: _9, Ty: &u8, Value: -Name: , Id: _10, Ty: &u8, Value: -Name: , Id: _11, Ty: usize, Value: -Name: , Id: _12, Ty: bool, Value: true -Name: pointer_at_end, Id: _13, Ty: PointerAtEnd<'_>, Value: PointerAtEnd { byte: [04], ptr: [{ALLOC_PTR}] } -Name: , Id: _14, Ty: &u8, Value: -Name: , Id: _15, Ty: &u8, Value: -Name: , Id: _16, Ty: usize, Value: -Name: , Id: _17, Ty: bool, Value: true -Name: uninit_around_pointer, Id: _18, Ty: UninitAroundPointer<'_>, Value: UninitAroundPointer { before: [__ __], ptr: [{ALLOC_PTR}], after: [__ __] } -Name: , Id: _19, Ty: std::mem::MaybeUninit<[u8; 2]>, Value: -Name: , Id: _20, Ty: &u8, Value: -Name: , Id: _21, Ty: &u8, Value: -Name: , Id: _22, Ty: usize, Value: -Name: , Id: _23, Ty: bool, Value: true -Name: , Id: _24, Ty: std::mem::MaybeUninit<[u8; 2]>, Value: -Name: integer_and_pointer, Id: _25, Ty: IntegerAndPointer<'_>, Value: IntegerAndPointer { integer: [11 22 33 44], ptr: [{ALLOC_PTR}] } -Name: , Id: _26, Ty: &u8, Value: -Name: , Id: _27, Ty: &u8, Value: -Name: , Id: _28, Ty: usize, Value: -Name: , Id: _29, Ty: bool, Value: true -Name: fixed_addr_ptr, Id: _30, Ty: *const u8, Value: [0x1234[wildcard]] -Name: short_pointer_bytes, Id: _31, Ty: [u8; 1], Value: [[34]] -Name: bytes, Id: _32, Ty: std::mem::MaybeUninit<[u8; 1]>, Value: -Name: , Id: _33, Ty: (), Value: -Name: , Id: _34, Ty: *const u8, Value: -Name: , Id: _35, Ty: *const *const u8, Value: -Name: , Id: _36, Ty: &*const u8, Value: -Name: , Id: _37, Ty: *mut u8, Value: -Name: , Id: _38, Ty: *mut [u8; 1], Value: -Name: , Id: _39, Ty: &mut std::mem::MaybeUninit<[u8; 1]>, Value: -Name: , Id: _40, Ty: usize, Value: -Name: , Id: _41, Ty: std::mem::MaybeUninit<[u8; 1]>, Value: -Name: , Id: _42, Ty: (&PointerAtOffset0<'_>, &PointerAfterBytes<'_>, &PointerAtEnd<'_>, &UninitAroundPointer<'_>, &IntegerAndPointer<'_>, &*const u8, &[u8; 1]), Value: -Name: , Id: _43, Ty: (&PointerAtOffset0<'_>, &PointerAfterBytes<'_>, &PointerAtEnd<'_>, &UninitAroundPointer<'_>, &IntegerAndPointer<'_>, &*const u8, &[u8; 1]), Value: -Name: , Id: _44, Ty: &PointerAtOffset0<'_>, Value: -Name: , Id: _45, Ty: &PointerAfterBytes<'_>, Value: -Name: , Id: _46, Ty: &PointerAtEnd<'_>, Value: -Name: , Id: _47, Ty: &UninitAroundPointer<'_>, Value: -Name: , Id: _48, Ty: &IntegerAndPointer<'_>, Value: -Name: , Id: _49, Ty: &*const u8, Value: -Name: , Id: _50, Ty: &[u8; 1], Value: -(priroda) Id: _2, Ty: PointerAtOffset0<'_>, Value: PointerAtOffset0 { ptr: [{ALLOC_PTR}] } +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: target, Id: _{LOCAL}, Ty: [u8; 2], Value: [[0a], [14]] +Name: pointer_at_offset0, Id: _{LOCAL}, Ty: PointerAtOffset0<'_>, Value: PointerAtOffset0 { ptr: [{ALLOC_PTR}] } +Name: , Id: _{LOCAL}, Ty: bool, Value: true +Name: pointer_after_bytes, Id: _{LOCAL}, Ty: PointerAfterBytes<'_>, Value: PointerAfterBytes { bytes: [[01], [02], [03]], ptr: [{ALLOC_PTR}] } +Name: , Id: _{LOCAL}, Ty: bool, Value: true +Name: pointer_at_end, Id: _{LOCAL}, Ty: PointerAtEnd<'_>, Value: PointerAtEnd { byte: [04], ptr: [{ALLOC_PTR}] } +Name: , Id: _{LOCAL}, Ty: bool, Value: true +Name: uninit_around_pointer, Id: _{LOCAL}, Ty: UninitAroundPointer<'_>, Value: UninitAroundPointer { before: [__ __], ptr: [{ALLOC_PTR}], after: [__ __] } +Name: , Id: _{LOCAL}, Ty: bool, Value: true +Name: integer_and_pointer, Id: _{LOCAL}, Ty: IntegerAndPointer<'_>, Value: IntegerAndPointer { integer: [11 22 33 44], ptr: [{ALLOC_PTR}] } +Name: , Id: _{LOCAL}, Ty: bool, Value: true +Name: fixed_addr_ptr, Id: _{LOCAL}, Ty: *const u8, Value: [0x1234[wildcard]] +Name: short_pointer_bytes, Id: _{LOCAL}, Ty: [u8; 1], Value: [[34]] +Name: bytes, Id: _{LOCAL}, Ty: std::mem::MaybeUninit<[u8; 1]>, Value: +(priroda) Id: _{LOCAL}, Ty: PointerAtOffset0<'_>, Value: PointerAtOffset0 { ptr: [{ALLOC_PTR}] } (priroda) quitting diff --git a/src/tools/miri/priroda/tests/ui/locals_projected_mplace_size.stdout b/src/tools/miri/priroda/tests/ui/locals_projected_mplace_size.stdout index 150385de95b9a..d099e683d1603 100644 --- a/src/tools/miri/priroda/tests/ui/locals_projected_mplace_size.stdout +++ b/src/tools/miri/priroda/tests/ui/locals_projected_mplace_size.stdout @@ -1,10 +1,10 @@ (priroda) breakpoint added: {MANIFEST_DIR}/tests/ui/locals_projected_mplace_size.rs:36 (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_projected_mplace_size.rs:36 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: , Id: _1, Ty: Envelope, Value: Envelope { prefix: [aa], target: Payload { a: [22 11], b: [33], c: [77 66 55 44], d: [88] }, trailer: [00 ff ee dd cc bb aa 99], checksum: [34 12] } -Name: prefix, Id: _1.0, Ty: u8, Value: [aa] -Name: target, Id: _1.1, Ty: Payload, Value: Payload { a: [22 11], b: [33], c: [77 66 55 44], d: [88] } -Name: trailer, Id: _1.2, Ty: u64, Value: [00 ff ee dd cc bb aa 99] -Name: checksum, Id: _1.3, Ty: u16, Value: [34 12] +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: , Id: _{LOCAL}, Ty: Envelope, Value: Envelope { prefix: [aa], target: Payload { a: [22 11], b: [33], c: [77 66 55 44], d: [88] }, trailer: [00 ff ee dd cc bb aa 99], checksum: [34 12] } +Name: prefix, Id: _{LOCAL}.0, Ty: u8, Value: [aa] +Name: target, Id: _{LOCAL}.1, Ty: Payload, Value: Payload { a: [22 11], b: [33], c: [77 66 55 44], d: [88] } +Name: trailer, Id: _{LOCAL}.2, Ty: u64, Value: [00 ff ee dd cc bb aa 99] +Name: checksum, Id: _{LOCAL}.3, Ty: u16, Value: [34 12] (priroda) quitting diff --git a/src/tools/miri/priroda/tests/ui/locals_source_shapes.stdout b/src/tools/miri/priroda/tests/ui/locals_source_shapes.stdout index b115fd17b4875..2baa3f34d4004 100644 --- a/src/tools/miri/priroda/tests/ui/locals_source_shapes.stdout +++ b/src/tools/miri/priroda/tests/ui/locals_source_shapes.stdout @@ -1,62 +1,41 @@ (priroda) breakpoint added: {MANIFEST_DIR}/tests/ui/locals_source_shapes.rs:71 (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_source_shapes.rs:71 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: named, Id: _1, Ty: Named, Value: Named { a: [01], b: [02 03] } -Name: empty_braced, Id: _2, Ty: EmptyBraced, Value: EmptyBraced {} -Name: unit_struct, Id: _3, Ty: UnitStruct, Value: UnitStruct -Name: tuple_struct, Id: _4, Ty: TupleStruct, Value: TupleStruct([04], [05 06]) -Name: single_tuple_struct, Id: _5, Ty: SingleTupleStruct, Value: SingleTupleStruct([07]) -Name: zero_tuple_struct, Id: _6, Ty: ZeroTupleStruct, Value: ZeroTupleStruct() -Name: tuple_zero, Id: _7, Ty: (), Value: () -Name: tuple_one, Id: _8, Ty: (u8,), Value: ([08],) -Name: tuple_many, Id: _9, Ty: (u8, u16), Value: ([09], [0a 0b]) -Name: array_zero, Id: _10, Ty: [u8; 0], Value: [] -Name: array_one, Id: _11, Ty: [u8; 1], Value: [[0c]] -Name: array_many, Id: _12, Ty: [u8; 3], Value: [[0d], [0e], [0f]] -Name: variant_unit, Id: _13, Ty: Variants, Value: Variants::Unit -Name: variant_tuple, Id: _14, Ty: Variants, Value: Variants::Tuple([10], [11 12]) -Name: variant_single_tuple, Id: _15, Ty: Variants, Value: Variants::SingleTuple([13]) -Name: variant_struct, Id: _16, Ty: Variants, Value: Variants::Struct { n: [14 15 16 17], ok: [00] } -Name: variant_empty_struct, Id: _17, Ty: Variants, Value: Variants::EmptyStruct {} -Name: raw_union, Id: _18, Ty: RawUnion, Value: [18 19] -Name: , Id: _19, Ty: (&Named, &EmptyBraced, &UnitStruct, &TupleStruct, &SingleTupleStruct, &ZeroTupleStruct, &(), &(u8,), &(u8, u16), &[u8; 0], &[u8; 1], &[u8; 3], &Variants, &Variants, &Variants, &Variants, &Variants, &RawUnion), Value: -Name: , Id: _20, Ty: (&Named, &EmptyBraced, &UnitStruct, &TupleStruct, &SingleTupleStruct, &ZeroTupleStruct, &(), &(u8,), &(u8, u16), &[u8; 0], &[u8; 1], &[u8; 3], &Variants, &Variants, &Variants, &Variants, &Variants, &RawUnion), Value: -Name: , Id: _21, Ty: &Named, Value: -Name: , Id: _22, Ty: &EmptyBraced, Value: -Name: , Id: _23, Ty: &UnitStruct, Value: -Name: , Id: _24, Ty: &TupleStruct, Value: -Name: , Id: _25, Ty: &SingleTupleStruct, Value: -Name: , Id: _26, Ty: &ZeroTupleStruct, Value: -Name: , Id: _27, Ty: &(), Value: -Name: , Id: _28, Ty: &(u8,), Value: -Name: , Id: _29, Ty: &(u8, u16), Value: -Name: , Id: _30, Ty: &[u8; 0], Value: -Name: , Id: _31, Ty: &[u8; 1], Value: -Name: , Id: _32, Ty: &[u8; 3], Value: -Name: , Id: _33, Ty: &Variants, Value: -Name: , Id: _34, Ty: &Variants, Value: -Name: , Id: _35, Ty: &Variants, Value: -Name: , Id: _36, Ty: &Variants, Value: -Name: , Id: _37, Ty: &Variants, Value: -Name: , Id: _38, Ty: &RawUnion, Value: -Name: , Id: _39, Ty: u8, Value: -(priroda) Id: _1, Ty: Named, Value: Named { a: [01], b: [02 03] } -(priroda) Id: _2, Ty: EmptyBraced, Value: EmptyBraced {} -(priroda) Id: _3, Ty: UnitStruct, Value: UnitStruct -(priroda) Id: _4, Ty: TupleStruct, Value: TupleStruct([04], [05 06]) -(priroda) Id: _5, Ty: SingleTupleStruct, Value: SingleTupleStruct([07]) -(priroda) Id: _6, Ty: ZeroTupleStruct, Value: ZeroTupleStruct() -(priroda) Id: _7, Ty: (), Value: () -(priroda) Id: _8, Ty: (u8,), Value: ([08],) -(priroda) Id: _9, Ty: (u8, u16), Value: ([09], [0a 0b]) -(priroda) Id: _10, Ty: [u8; 0], Value: [] -(priroda) Id: _11, Ty: [u8; 1], Value: [[0c]] -(priroda) Id: _12, Ty: [u8; 3], Value: [[0d], [0e], [0f]] -(priroda) Id: _13, Ty: Variants, Value: Variants::Unit -(priroda) Id: _14, Ty: Variants, Value: Variants::Tuple([10], [11 12]) -(priroda) Id: _15, Ty: Variants, Value: Variants::SingleTuple([13]) -(priroda) Id: _16, Ty: Variants, Value: Variants::Struct { n: [14 15 16 17], ok: [00] } -(priroda) Id: _17, Ty: Variants, Value: Variants::EmptyStruct {} -(priroda) Id: _18, Ty: RawUnion, Value: [18 19] +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: named, Id: _{LOCAL}, Ty: Named, Value: Named { a: [01], b: [02 03] } +Name: empty_braced, Id: _{LOCAL}, Ty: EmptyBraced, Value: EmptyBraced {} +Name: unit_struct, Id: _{LOCAL}, Ty: UnitStruct, Value: UnitStruct +Name: tuple_struct, Id: _{LOCAL}, Ty: TupleStruct, Value: TupleStruct([04], [05 06]) +Name: single_tuple_struct, Id: _{LOCAL}, Ty: SingleTupleStruct, Value: SingleTupleStruct([07]) +Name: zero_tuple_struct, Id: _{LOCAL}, Ty: ZeroTupleStruct, Value: ZeroTupleStruct() +Name: tuple_zero, Id: _{LOCAL}, Ty: (), Value: () +Name: tuple_one, Id: _{LOCAL}, Ty: (u8,), Value: ([08],) +Name: tuple_many, Id: _{LOCAL}, Ty: (u8, u16), Value: ([09], [0a 0b]) +Name: array_zero, Id: _{LOCAL}, Ty: [u8; 0], Value: [] +Name: array_one, Id: _{LOCAL}, Ty: [u8; 1], Value: [[0c]] +Name: array_many, Id: _{LOCAL}, Ty: [u8; 3], Value: [[0d], [0e], [0f]] +Name: variant_unit, Id: _{LOCAL}, Ty: Variants, Value: Variants::Unit +Name: variant_tuple, Id: _{LOCAL}, Ty: Variants, Value: Variants::Tuple([10], [11 12]) +Name: variant_single_tuple, Id: _{LOCAL}, Ty: Variants, Value: Variants::SingleTuple([13]) +Name: variant_struct, Id: _{LOCAL}, Ty: Variants, Value: Variants::Struct { n: [14 15 16 17], ok: [00] } +Name: variant_empty_struct, Id: _{LOCAL}, Ty: Variants, Value: Variants::EmptyStruct {} +Name: raw_union, Id: _{LOCAL}, Ty: RawUnion, Value: [18 19] +(priroda) Id: _{LOCAL}, Ty: Named, Value: Named { a: [01], b: [02 03] } +(priroda) Id: _{LOCAL}, Ty: EmptyBraced, Value: EmptyBraced {} +(priroda) Id: _{LOCAL}, Ty: UnitStruct, Value: UnitStruct +(priroda) Id: _{LOCAL}, Ty: TupleStruct, Value: TupleStruct([04], [05 06]) +(priroda) Id: _{LOCAL}, Ty: SingleTupleStruct, Value: SingleTupleStruct([07]) +(priroda) Id: _{LOCAL}, Ty: ZeroTupleStruct, Value: ZeroTupleStruct() +(priroda) Id: _{LOCAL}, Ty: (), Value: () +(priroda) Id: _{LOCAL}, Ty: (u8,), Value: ([08],) +(priroda) Id: _{LOCAL}, Ty: (u8, u16), Value: ([09], [0a 0b]) +(priroda) Id: _{LOCAL}, Ty: [u8; 0], Value: [] +(priroda) Id: _{LOCAL}, Ty: [u8; 1], Value: [[0c]] +(priroda) Id: _{LOCAL}, Ty: [u8; 3], Value: [[0d], [0e], [0f]] +(priroda) Id: _{LOCAL}, Ty: Variants, Value: Variants::Unit +(priroda) Id: _{LOCAL}, Ty: Variants, Value: Variants::Tuple([10], [11 12]) +(priroda) Id: _{LOCAL}, Ty: Variants, Value: Variants::SingleTuple([13]) +(priroda) Id: _{LOCAL}, Ty: Variants, Value: Variants::Struct { n: [14 15 16 17], ok: [00] } +(priroda) Id: _{LOCAL}, Ty: Variants, Value: Variants::EmptyStruct {} +(priroda) Id: _{LOCAL}, Ty: RawUnion, Value: [18 19] (priroda) quitting diff --git a/src/tools/miri/priroda/tests/ui/locals_source_slices.stdout b/src/tools/miri/priroda/tests/ui/locals_source_slices.stdout index 15467092102fa..697c21f413152 100644 --- a/src/tools/miri/priroda/tests/ui/locals_source_slices.stdout +++ b/src/tools/miri/priroda/tests/ui/locals_source_slices.stdout @@ -3,23 +3,17 @@ (priroda) breakpoint added: {MANIFEST_DIR}/tests/ui/locals_source_slices.rs:12 (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_source_slices.rs:4 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: slice, Id: _1, Ty: [u8], Value: [] -Name: , Id: _2, Ty: &[u8], Value: -Name: , Id: _3, Ty: &[u8], Value: -(priroda) Id: _1, Ty: [u8], Value: [] +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: slice, Id: _{LOCAL}, Ty: [u8], Value: [] +(priroda) Id: _{LOCAL}, Ty: [u8], Value: [] (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_source_slices.rs:8 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: slice, Id: _1, Ty: [u8], Value: [[1a]] -Name: , Id: _2, Ty: &[u8], Value: -Name: , Id: _3, Ty: &[u8], Value: -(priroda) Id: _1, Ty: [u8], Value: [[1a]] +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: slice, Id: _{LOCAL}, Ty: [u8], Value: [[1a]] +(priroda) Id: _{LOCAL}, Ty: [u8], Value: [[1a]] (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_source_slices.rs:12 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: slice, Id: _1, Ty: [u8], Value: [[1b], [1c]] -Name: , Id: _2, Ty: &[u8], Value: -Name: , Id: _3, Ty: &[u8], Value: -(priroda) Id: _1, Ty: [u8], Value: [[1b], [1c]] +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: slice, Id: _{LOCAL}, Ty: [u8], Value: [[1b], [1c]] +(priroda) Id: _{LOCAL}, Ty: [u8], Value: [[1b], [1c]] (priroda) quitting diff --git a/src/tools/miri/priroda/tests/ui/locals_sroa.stdout b/src/tools/miri/priroda/tests/ui/locals_sroa.stdout index 94c44adf6ae59..03e0520d733c8 100644 --- a/src/tools/miri/priroda/tests/ui/locals_sroa.stdout +++ b/src/tools/miri/priroda/tests/ui/locals_sroa.stdout @@ -1,13 +1,9 @@ (priroda) breakpoint added: {MANIFEST_DIR}/tests/ui/locals_sroa.rs:13 (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_sroa.rs:13 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: s, Id: _1, Ty: &[u8], Value: (pointer to {ALLOC_PTR}, 0x0000000000000002): &[u8] -Name: , Id: _2, Ty: ExtraSlice<'_>, Value: -Name: , Id: _3, Ty: &[u8], Value: -Name: , Id: _4, Ty: u32, Value: -Name: , Id: _5, Ty: usize, Value: -Name: , Id: _6, Ty: &[u8], Value: -Name: _slice._slice, Id: _7, Ty: &[u8], Value: -Name: _slice._extra, Id: _8, Ty: u32, Value: +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: s, Id: _{LOCAL}, Ty: &[u8], Value: (pointer to {ALLOC_PTR}, 0x0000000000000002): &[u8] +Name: , Id: _{LOCAL}, Ty: ExtraSlice<'_>, Value: +Name: _slice._slice, Id: _{LOCAL}, Ty: &[u8], Value: +Name: _slice._extra, Id: _{LOCAL}, Ty: u32, Value: (priroda) quitting diff --git a/src/tools/miri/priroda/tests/ui/locals_struct_field_fragment.stdout b/src/tools/miri/priroda/tests/ui/locals_struct_field_fragment.stdout index cc717bfb97fe2..5192d61ce31a4 100644 --- a/src/tools/miri/priroda/tests/ui/locals_struct_field_fragment.stdout +++ b/src/tools/miri/priroda/tests/ui/locals_struct_field_fragment.stdout @@ -1,10 +1,9 @@ (priroda) breakpoint added: {MANIFEST_DIR}/tests/ui/locals_struct_field_fragment.rs:11 (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_struct_field_fragment.rs:11 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: , Id: _1, Ty: Outer, Value: -Name: , Id: _2, Ty: Inner, Value: -Name: , Id: _3, Ty: Inner, Value: -Name: x.inner.value, Id: _4, Ty: u8, Value: 7_u8 -Name: , Id: _5, Ty: u8, Value: +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: , Id: _{LOCAL}, Ty: Outer, Value: +Name: , Id: _{LOCAL}, Ty: Inner, Value: +Name: , Id: _{LOCAL}, Ty: Inner, Value: +Name: x.inner.value, Id: _{LOCAL}, Ty: u8, Value: 7_u8 (priroda) quitting diff --git a/src/tools/miri/priroda/tests/ui/locals_tuple_field_fragment.stdout b/src/tools/miri/priroda/tests/ui/locals_tuple_field_fragment.stdout index 2726eaba97b3d..b465703fc6cf7 100644 --- a/src/tools/miri/priroda/tests/ui/locals_tuple_field_fragment.stdout +++ b/src/tools/miri/priroda/tests/ui/locals_tuple_field_fragment.stdout @@ -1,8 +1,8 @@ (priroda) breakpoint added: {MANIFEST_DIR}/tests/ui/locals_tuple_field_fragment.rs:4 (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_tuple_field_fragment.rs:4 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: , Id: _1, Ty: (u8, u16), Value: -Name: t.0, Id: _2, Ty: u8, Value: -Name: t.1, Id: _3, Ty: u16, Value: +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: , Id: _{LOCAL}, Ty: (u8, u16), Value: +Name: t.0, Id: _{LOCAL}, Ty: u8, Value: +Name: t.1, Id: _{LOCAL}, Ty: u16, Value: (priroda) quitting diff --git a/src/tools/miri/priroda/tests/ui/locals_value_shapes.stdout b/src/tools/miri/priroda/tests/ui/locals_value_shapes.stdout index 084c7d10c1ecd..79b489d04d41e 100644 --- a/src/tools/miri/priroda/tests/ui/locals_value_shapes.stdout +++ b/src/tools/miri/priroda/tests/ui/locals_value_shapes.stdout @@ -1,61 +1,40 @@ (priroda) breakpoint added: {MANIFEST_DIR}/tests/ui/locals_value_shapes.rs:49 (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_value_shapes.rs:49 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: dead_box, Id: _1, Ty: std::boxed::Box, Value: Box(BoxRaw { pointer: NonNull { pointer: [{ALLOC_PTR}] }, _marker: PhantomData }, Global) -Name: consumed, Id: _2, Ty: std::boxed::Box, Value: Box(BoxRaw { pointer: NonNull { pointer: [{ALLOC_PTR}] }, _marker: PhantomData }, Global) -Name: , Id: _3, Ty: (), Value: -Name: , Id: _4, Ty: std::boxed::Box, Value: -Name: pointed_box, Id: _5, Ty: std::boxed::Box, Value: Box(BoxRaw { pointer: NonNull { pointer: [{ALLOC_PTR}] }, _marker: PhantomData }, Global) -Name: pointer_box, Id: _6, Ty: &std::boxed::Box, Value: {&_: &std::boxed::Box} -Name: scalar, Id: _7, Ty: u8, Value: 42_u8 -Name: pointed, Id: _8, Ty: u8, Value: [33] -Name: scalar_pointer, Id: _9, Ty: &u8, Value: {&_: &u8} -Name: scalar_pair, Id: _10, Ty: &[u8], Value: (pointer to {ALLOC_PTR}, 0x0000000000000002): &[u8] -Name: , Id: _11, Ty: &[u8], Value: (pointer to {ALLOC_PTR}, 0x0000000000000002): &[u8] -Name: , Id: _12, Ty: &[u8; 2], Value: -Name: , Id: _13, Ty: [u8; 2], Value: -Name: , Id: _14, Ty: std::ops::RangeFull, Value: -Name: mplace, Id: _15, Ty: Aggregate, Value: Aggregate { byte: [2a], word: [34 12] } -Name: , Id: _16, Ty: u8, Value: -Name: tuple, Id: _17, Ty: (u8, u16), Value: ([01], [03 02]) -Name: tuple_struct, Id: _18, Ty: TupleAggregate, Value: TupleAggregate([04], [06 05]) -Name: array, Id: _19, Ty: [u8; 3], Value: [[07], [08], [09]] -Name: nested, Id: _20, Ty: Nested, Value: Nested { aggregate: Aggregate { byte: [0a], word: [0c 0b] }, tuple: ([01], [03 02]) } -Name: , Id: _21, Ty: Aggregate, Value: -Name: , Id: _22, Ty: (u8, u16), Value: -Name: unit_variant, Id: _23, Ty: Choice, Value: Choice::Unit -Name: tuple_variant, Id: _24, Ty: Choice, Value: Choice::Tuple([0d], [0f 0e]) -Name: struct_variant, Id: _25, Ty: Choice, Value: Choice::Struct { n: [13 12 11 10], ok: [01] } -Name: uninit_scalar, Id: _26, Ty: u32, Value: -Name: , Id: _27, Ty: (u8, &u8, usize, &Aggregate, &(u8, u16), &TupleAggregate, &[u8; 3], &Nested, &Choice, &Choice, &Choice), Value: -Name: , Id: _28, Ty: (u8, &u8, usize, &Aggregate, &(u8, u16), &TupleAggregate, &[u8; 3], &Nested, &Choice, &Choice, &Choice), Value: -Name: , Id: _29, Ty: u8, Value: -Name: , Id: _30, Ty: &u8, Value: -Name: , Id: _31, Ty: usize, Value: -Name: , Id: _32, Ty: &[u8], Value: -Name: , Id: _33, Ty: &Aggregate, Value: -Name: , Id: _34, Ty: &(u8, u16), Value: -Name: , Id: _35, Ty: &TupleAggregate, Value: -Name: , Id: _36, Ty: &[u8; 3], Value: -Name: , Id: _37, Ty: &Nested, Value: -Name: , Id: _38, Ty: &Choice, Value: -Name: , Id: _39, Ty: &Choice, Value: -Name: , Id: _40, Ty: &Choice, Value: -Name: , Id: _41, Ty: &[u8; 2], Value: {&_: &[u8; 2]} -(priroda) Id: _0, Ty: (), Value: -(priroda) Id: _4, Ty: std::boxed::Box, Value: -(priroda) Id: _5, Ty: std::boxed::Box, Value: Box(BoxRaw { pointer: NonNull { pointer: [{ALLOC_PTR}] }, _marker: PhantomData }, Global) -(priroda) Id: _7, Ty: u8, Value: 42_u8 -(priroda) Id: _8, Ty: u8, Value: [33] -(priroda) Id: _13, Ty: [u8; 2], Value: -(priroda) Id: _15, Ty: Aggregate, Value: Aggregate { byte: [2a], word: [34 12] } -(priroda) Id: _17, Ty: (u8, u16), Value: ([01], [03 02]) -(priroda) Id: _18, Ty: TupleAggregate, Value: TupleAggregate([04], [06 05]) -(priroda) Id: _19, Ty: [u8; 3], Value: [[07], [08], [09]] -(priroda) Id: _20, Ty: Nested, Value: Nested { aggregate: Aggregate { byte: [0a], word: [0c 0b] }, tuple: ([01], [03 02]) } -(priroda) Id: _23, Ty: Choice, Value: Choice::Unit -(priroda) Id: _24, Ty: Choice, Value: Choice::Tuple([0d], [0f 0e]) -(priroda) Id: _25, Ty: Choice, Value: Choice::Struct { n: [13 12 11 10], ok: [01] } +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: dead_box, Id: _{LOCAL}, Ty: std::boxed::Box, Value: Box(BoxRaw { pointer: NonNull { pointer: [{ALLOC_PTR}] }, _marker: PhantomData }, Global) +Name: consumed, Id: _{LOCAL}, Ty: std::boxed::Box, Value: Box(BoxRaw { pointer: NonNull { pointer: [{ALLOC_PTR}] }, _marker: PhantomData }, Global) +Name: pointed_box, Id: _{LOCAL}, Ty: std::boxed::Box, Value: Box(BoxRaw { pointer: NonNull { pointer: [{ALLOC_PTR}] }, _marker: PhantomData }, Global) +Name: pointer_box, Id: _{LOCAL}, Ty: &std::boxed::Box, Value: {&_: &std::boxed::Box} +Name: scalar, Id: _{LOCAL}, Ty: u8, Value: 42_u8 +Name: pointed, Id: _{LOCAL}, Ty: u8, Value: [33] +Name: scalar_pointer, Id: _{LOCAL}, Ty: &u8, Value: {&_: &u8} +Name: scalar_pair, Id: _{LOCAL}, Ty: &[u8], Value: (pointer to {ALLOC_PTR}, 0x0000000000000002): &[u8] +Name: , Id: _{LOCAL}, Ty: &[u8], Value: (pointer to {ALLOC_PTR}, 0x0000000000000002): &[u8] +Name: , Id: _{LOCAL}, Ty: [u8; 2], Value: +Name: mplace, Id: _{LOCAL}, Ty: Aggregate, Value: Aggregate { byte: [2a], word: [34 12] } +Name: tuple, Id: _{LOCAL}, Ty: (u8, u16), Value: ([01], [03 02]) +Name: tuple_struct, Id: _{LOCAL}, Ty: TupleAggregate, Value: TupleAggregate([04], [06 05]) +Name: array, Id: _{LOCAL}, Ty: [u8; 3], Value: [[07], [08], [09]] +Name: nested, Id: _{LOCAL}, Ty: Nested, Value: Nested { aggregate: Aggregate { byte: [0a], word: [0c 0b] }, tuple: ([01], [03 02]) } +Name: unit_variant, Id: _{LOCAL}, Ty: Choice, Value: Choice::Unit +Name: tuple_variant, Id: _{LOCAL}, Ty: Choice, Value: Choice::Tuple([0d], [0f 0e]) +Name: struct_variant, Id: _{LOCAL}, Ty: Choice, Value: Choice::Struct { n: [13 12 11 10], ok: [01] } +Name: uninit_scalar, Id: _{LOCAL}, Ty: u32, Value: +Name: , Id: _{LOCAL}, Ty: &[u8; 2], Value: {&_: &[u8; 2]} +(priroda) Id: _{LOCAL}, Ty: (), Value: +(priroda) Id: _{LOCAL}, Ty: std::boxed::Box, Value: +(priroda) Id: _{LOCAL}, Ty: std::boxed::Box, Value: Box(BoxRaw { pointer: NonNull { pointer: [{ALLOC_PTR}] }, _marker: PhantomData }, Global) +(priroda) Id: _{LOCAL}, Ty: u8, Value: 42_u8 +(priroda) Id: _{LOCAL}, Ty: u8, Value: [33] +(priroda) Id: _{LOCAL}, Ty: [u8; 2], Value: +(priroda) Id: _{LOCAL}, Ty: Aggregate, Value: Aggregate { byte: [2a], word: [34 12] } +(priroda) Id: _{LOCAL}, Ty: (u8, u16), Value: ([01], [03 02]) +(priroda) Id: _{LOCAL}, Ty: TupleAggregate, Value: TupleAggregate([04], [06 05]) +(priroda) Id: _{LOCAL}, Ty: [u8; 3], Value: [[07], [08], [09]] +(priroda) Id: _{LOCAL}, Ty: Nested, Value: Nested { aggregate: Aggregate { byte: [0a], word: [0c 0b] }, tuple: ([01], [03 02]) } +(priroda) Id: _{LOCAL}, Ty: Choice, Value: Choice::Unit +(priroda) Id: _{LOCAL}, Ty: Choice, Value: Choice::Tuple([0d], [0f 0e]) +(priroda) Id: _{LOCAL}, Ty: Choice, Value: Choice::Struct { n: [13 12 11 10], ok: [01] } (priroda) no local for this id (priroda) quitting diff --git a/src/tools/miri/priroda/tests/ui/locals_wildcard_pointer.stdout b/src/tools/miri/priroda/tests/ui/locals_wildcard_pointer.stdout index 43bccfb10e4a3..a3c42d9002ecd 100644 --- a/src/tools/miri/priroda/tests/ui/locals_wildcard_pointer.stdout +++ b/src/tools/miri/priroda/tests/ui/locals_wildcard_pointer.stdout @@ -1,11 +1,8 @@ (priroda) breakpoint added: {MANIFEST_DIR}/tests/ui/locals_wildcard_pointer.rs:15 (priroda) Hit breakpoint {MANIFEST_DIR}/tests/ui/locals_wildcard_pointer.rs:15 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: ptr, Id: _1, Ty: *const u8, Value: {&_: *const u8} -Name: wildcard, Id: _2, Ty: WildcardPointer, Value: WildcardPointer { ptr: [0x1234[wildcard]] } -Name: , Id: _3, Ty: *const u8, Value: -Name: , Id: _4, Ty: &WildcardPointer, Value: -Name: , Id: _5, Ty: &WildcardPointer, Value: -(priroda) Id: _2, Ty: WildcardPointer, Value: WildcardPointer { ptr: [0x1234[wildcard]] } +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: ptr, Id: _{LOCAL}, Ty: *const u8, Value: {&_: *const u8} +Name: wildcard, Id: _{LOCAL}, Ty: WildcardPointer, Value: WildcardPointer { ptr: [0x1234[wildcard]] } +(priroda) Id: _{LOCAL}, Ty: WildcardPointer, Value: WildcardPointer { ptr: [0x1234[wildcard]] } (priroda) quitting diff --git a/src/tools/miri/priroda/tests/ui/source_step_changes_line.stdout b/src/tools/miri/priroda/tests/ui/source_step_changes_line.stdout index 10cc3a5cf980b..a8f35c9cbfc96 100644 --- a/src/tools/miri/priroda/tests/ui/source_step_changes_line.stdout +++ b/src/tools/miri/priroda/tests/ui/source_step_changes_line.stdout @@ -1,3 +1,3 @@ -(priroda) {RUSTC_SYSROOT}/lib/rustlib/src/rust/library/std/src/rt.rs:206 -(priroda) {RUSTC_SYSROOT}/lib/rustlib/src/rust/library/std/src/rt.rs:207 +(priroda) RUSTLIB/std/src/rt.rs:206 +(priroda) RUSTLIB/std/src/rt.rs:207 (priroda) quitting diff --git a/src/tools/miri/priroda/tests/ui/step_aliases.stdout b/src/tools/miri/priroda/tests/ui/step_aliases.stdout index 32233f657b41a..838c01af2cc1f 100644 --- a/src/tools/miri/priroda/tests/ui/step_aliases.stdout +++ b/src/tools/miri/priroda/tests/ui/step_aliases.stdout @@ -1,4 +1,4 @@ -(priroda) {RUSTC_SYSROOT}/lib/rustlib/src/rust/library/std/src/rt.rs:206 -(priroda) {RUSTC_SYSROOT}/lib/rustlib/src/rust/library/std/src/rt.rs:206 -(priroda) {RUSTC_SYSROOT}/lib/rustlib/src/rust/library/std/src/rt.rs:206 +(priroda) RUSTLIB/std/src/rt.rs:206 +(priroda) RUSTLIB/std/src/rt.rs:206 +(priroda) RUSTLIB/std/src/rt.rs:206 (priroda) quitting diff --git a/src/tools/miri/priroda/tests/ui/ub_exception_stop.stdout b/src/tools/miri/priroda/tests/ui/ub_exception_stop.stdout index c63037e2e1b55..92e855d4b6431 100644 --- a/src/tools/miri/priroda/tests/ui/ub_exception_stop.stdout +++ b/src/tools/miri/priroda/tests/ui/ub_exception_stop.stdout @@ -1,5 +1,5 @@ (priroda) program stopped with error: memory access failed: attempting to access 1 byte, but got null pointer {MANIFEST_DIR}/tests/ui/ub_exception_stop.rs:4 -(priroda) Name: , Id: _0, Ty: (), Value: -Name: , Id: _1, Ty: *mut u8, Value: {0x0 as *mut u8} +(priroda) Name: , Id: _{LOCAL}, Ty: (), Value: +Name: , Id: _{LOCAL}, Ty: *mut u8, Value: {0x0 as *mut u8} (priroda) quitting diff --git a/src/tools/miri/rust-version b/src/tools/miri/rust-version index cbb7ce505b51d..abbda531ad61f 100644 --- a/src/tools/miri/rust-version +++ b/src/tools/miri/rust-version @@ -1 +1 @@ -29f282561639932ad8c56c11ef6313ffbc9bdb05 +ac7bce92720268483c462f49fadb6cc3a01e73ce diff --git a/src/tools/miri/src/concurrency/genmc/scheduling.rs b/src/tools/miri/src/concurrency/genmc/scheduling.rs index 17c212b98081a..f7f556a56178a 100644 --- a/src/tools/miri/src/concurrency/genmc/scheduling.rs +++ b/src/tools/miri/src/concurrency/genmc/scheduling.rs @@ -1,7 +1,7 @@ use genmc_sys::{ActionKind, ExecutionStatus}; use rustc_data_structures::either::Either; use rustc_middle::mir::TerminatorKind; -use rustc_middle::ty::{self, Ty}; +use rustc_middle::ty::{self, Intrinsic, Ty}; use super::GenmcCtx; use crate::{ @@ -87,8 +87,8 @@ fn get_function_kind<'tcx>( // The next step is a call to a regular Rust function. return interp_ok(NonAtomic); }; - let intrinsic_name = intrinsic_def.name.as_str(); - let Some(suffix) = intrinsic_name.strip_prefix("atomic_") else { + let name = if let Intrinsic::Rustc(name) = intrinsic_def.name { Some(name) } else { None }; + let Some(suffix) = name.as_ref().and_then(|name| name.as_str().strip_prefix("atomic_")) else { return interp_ok(NonAtomic); // Non-atomic intrinsic, so guaranteed not an atomic load }; // `atomic_store`, `atomic_fence` and `atomic_singlethreadfence` are not considered loads. diff --git a/src/tools/miri/src/concurrency/thread.rs b/src/tools/miri/src/concurrency/thread.rs index 53e3a10abef50..2a56e7c8f651a 100644 --- a/src/tools/miri/src/concurrency/thread.rs +++ b/src/tools/miri/src/concurrency/thread.rs @@ -668,11 +668,29 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } } + /// Returns whether a thread stack of this size could be reserved. + fn thread_stack_size_ok(&self, stack_size: u64) -> bool { + let ecx = self.eval_context_ref(); + match ecx.pointer_size().bits() { + 32 => { + // Reject stacks occupying nearly the entire address space. Leave two pages below 4 + // GiB so adding a one-page guard does not overflow a 32-bit size_t. + let limit = (1u64 << 32) - 2 * ecx.machine.page_size; + stack_size < limit + } + 64 => { + // Approximate the user address space on 64-bit targets using 47 address bits. + let addr_bits = 47; + stack_size < (1u64 << addr_bits) + } + _ => panic!("unsupported pointer size"), + } + } + /// Start a regular (non-main) thread. #[inline] fn start_regular_thread( &mut self, - thread: Option>, start_routine: Pointer, start_abi: ExternAbi, func_arg: ImmTy<'tcx>, @@ -698,14 +716,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { new_thread_id, )?, } - // Write the current thread-id, switch to the next thread later - // to treat this write operation as occurring on the current thread. - if let Some(thread_info_place) = thread { - ecx.write_scalar( - Scalar::from_uint(new_thread_id.to_u32(), thread_info_place.layout.size), - &thread_info_place, - )?; - } // Finally switch to new thread so that we can push the first stackframe. // After this all accesses will be treated as occurring in the new thread. diff --git a/src/tools/miri/src/eval.rs b/src/tools/miri/src/eval.rs index f35860b8f2316..17d6b72582555 100644 --- a/src/tools/miri/src/eval.rs +++ b/src/tools/miri/src/eval.rs @@ -403,7 +403,8 @@ pub fn create_ecx<'tcx>( ImmTy::from_int(i64::try_from(config.args.len()).unwrap(), ecx.machine.layouts.isize); let argv = { // Put each argument in memory, collect pointers. - let mut argvs = Vec::>::with_capacity(config.args.len()); + let mut argvs = + Vec::>::with_capacity(config.args.len().strict_add(1)); for arg in config.args.iter() { // Make space for `0` terminator. let size = u64::try_from(arg.len()).unwrap().strict_add(1); @@ -414,6 +415,8 @@ pub fn create_ecx<'tcx>( ecx.mark_immutable(&arg_place); argvs.push(arg_place.to_ref(&ecx)); } + // Add trailing null. + argvs.push(Immediate::Scalar(Scalar::null_ptr(&ecx))); // Make an array with all these pointers, in the Miri memory. let u8_ptr_type = Ty::new_imm_ptr(tcx, tcx.types.u8); let u8_ptr_ptr_type = Ty::new_imm_ptr(tcx, u8_ptr_type); diff --git a/src/tools/miri/src/helpers.rs b/src/tools/miri/src/helpers.rs index 0e2d30efc8b15..ffe18611185ea 100644 --- a/src/tools/miri/src/helpers.rs +++ b/src/tools/miri/src/helpers.rs @@ -195,12 +195,28 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "`libc` crate is not reliably available on Windows targets; Miri should not use it there" ); } + // TODO: Cache the result. self.eval_path_scalar(&["libc", name]) } + /// Helper function to get a `libc` constant as an integer, when the actual underlying type + /// differs across targets. + fn eval_libc_int>(&self, name: &str) -> T { + let ecx = self.eval_context_ref(); + if ecx.tcx.sess.target.os == Os::Windows { + panic!( + "`libc` crate is not reliably available on Windows targets; Miri should not use it there" + ); + } + // TODO: Cache the result. + let path = &["libc", name]; + let val = self.eval_path(path); + ecx.read_int::(&val) + .unwrap_or_else(|err| panic!("failed to read required Rust item: {path:?}\n{err:?}")) + } + /// Helper function to get a `libc` constant as an `i16`. fn eval_libc_i16(&self, name: &str) -> i16 { - // TODO: Cache the result. self.eval_libc(name).to_i16().unwrap_or_else(|_err| { panic!("required libc item has unexpected type (not `i16`): {name}") }) @@ -208,7 +224,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// Helper function to get a `libc` constant as an `u16`. fn eval_libc_u16(&self, name: &str) -> u16 { - // TODO: Cache the result. self.eval_libc(name).to_u16().unwrap_or_else(|_err| { panic!("required libc item has unexpected type (not `u16`): {name}") }) @@ -216,7 +231,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// Helper function to get a `libc` constant as an `i32`. fn eval_libc_i32(&self, name: &str) -> i32 { - // TODO: Cache the result. self.eval_libc(name).to_i32().unwrap_or_else(|_err| { panic!("required libc item has unexpected type (not `i32`): {name}") }) @@ -224,7 +238,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// Helper function to get a `libc` constant as an `u32`. fn eval_libc_u32(&self, name: &str) -> u32 { - // TODO: Cache the result. self.eval_libc(name).to_u32().unwrap_or_else(|_err| { panic!("required libc item has unexpected type (not `u32`): {name}") }) @@ -319,6 +332,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// Write an int of the appropriate size to `dest`. The target type may be signed or unsigned, /// we try to do the right thing anyway. `i128` can fit all integer types except for `u128` so /// this method is fine for almost all integer types. + #[track_caller] fn write_int( &mut self, i: impl Into, @@ -332,8 +346,11 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let val = if dest.layout().backend_repr.is_signed() { Scalar::from_int(i, dest.layout().size) } else { - // `unwrap` can only fail here if `i` is negative - Scalar::from_uint(u128::try_from(i.into()).unwrap(), dest.layout().size) + Scalar::from_uint( + u128::try_from(i.into()) + .expect("should not store a negative value in an unsigned type"), + dest.layout().size, + ) }; self.eval_context_mut().write_scalar(val, dest) } @@ -367,6 +384,39 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { interp_ok(()) } + /// Read `val` as an integer at the type given in its layout, then convert the result to `T`. + #[track_caller] + fn read_int>( + &self, + val: &impl Projectable<'tcx, Provenance>, + ) -> InterpResult<'tcx, T> { + let ecx = self.eval_context_ref(); + let scalar = ecx.read_scalar(val)?; + + let size = val.layout().size; + // Sanity-check that T is big enough, so we catch too-small Miri host types without having + // to actually pass in an extreme value. If the sizes are the same then the signendess + // must also match to ensure all values carry over. + let host_type_signed = T::try_from(-1).is_ok(); + if size_of::() < size.bytes_usize() + || (size_of::() == size.bytes_usize() + && host_type_signed != val.layout().backend_repr.is_signed()) + { + panic!( + "reading value of machine type {} which does not fit into the chosen host type", + val.layout().ty + ); + } + let int = if val.layout().backend_repr.is_signed() { + scalar.to_int(size)? + } else { + // Can only fail for values beyond i128::MAX + i128::try_from(scalar.to_uint(size)?).unwrap() + }; + // Based on the size check above, this cannot fail. + interp_ok(int.try_into().ok().unwrap()) + } + /// Test if this pointer equals 0. fn ptr_is_null(&self, ptr: Pointer) -> InterpResult<'tcx, bool> { interp_ok(ptr.addr().bytes() == 0) @@ -717,8 +767,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { loop { // FIXME: We are re-getting the allocation each time around the loop. // Would be nice if we could somehow "extend" an existing AllocRange. - let alloc = ecx.get_ptr_alloc(ptr.wrapping_offset(len, ecx), size1)?.unwrap(); // not a ZST, so we will get a result - let byte = alloc.read_integer(alloc_range(Size::ZERO, size1))?.to_u8()?; + let place = ecx.ptr_to_mplace(ptr.wrapping_offset(len, ecx), ecx.machine.layouts.u8); + let byte = ecx.read_scalar(&place)?.to_u8()?; if byte == 0 { break; } else { @@ -755,33 +805,30 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// Helper function to read a sequence of unsigned integers of the given size and alignment /// until the first null terminator. - fn read_c_str_with_char_size( + fn read_c_str_with_char_type( &self, mut ptr: Pointer, - size: Size, - align: Align, + char_type: TyAndLayout<'tcx>, ) -> InterpResult<'tcx, Vec> where - T: TryFrom, - >::Error: std::fmt::Debug, + T: TryFrom + From + PartialEq, { - assert_ne!(size, Size::ZERO); - let ecx = self.eval_context_ref(); - ecx.check_ptr_align(ptr, align)?; + ecx.check_ptr_align(ptr, char_type.align)?; let mut wchars = Vec::new(); loop { // FIXME: We are re-getting the allocation each time around the loop. // Would be nice if we could somehow "extend" an existing AllocRange. - let alloc = ecx.get_ptr_alloc(ptr, size)?.unwrap(); // not a ZST, so we will get a result - let wchar_int = alloc.read_integer(alloc_range(Size::ZERO, size))?.to_bits(size)?; - if wchar_int == 0 { + let place = ecx.ptr_to_mplace(ptr, char_type); + let wchar = ecx.read_int::(&place)?; + if wchar == 0u8.into() { break; } else { - wchars.push(wchar_int.try_into().unwrap()); - ptr = ptr.wrapping_offset(size, ecx); + wchars.push(wchar); + // Maintains alignment because `size` is a multiple of `align`. + ptr = ptr.wrapping_offset(char_type.size, ecx); } } @@ -790,7 +837,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// Read a sequence of u16 until the first null terminator. fn read_wide_str(&self, ptr: Pointer) -> InterpResult<'tcx, Vec> { - self.read_c_str_with_char_size(ptr, Size::from_bytes(2), Align::from_bytes(2).unwrap()) + let ecx = self.eval_context_ref(); + ecx.read_c_str_with_char_type(ptr, ecx.machine.layouts.u16) } /// Helper function to write a sequence of u16 with an added 0x0000-terminator, which is what @@ -833,9 +881,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // We don't have libc on Windows so we have to hard-code the type ourselves. ecx.machine.layouts.u16 } else { - ecx.libc_ty_layout("wchar_t") + // We always read as unsigned no matter the actual signedness. + let real_type = ecx.libc_ty_layout("wchar_t"); + assert_eq!(real_type.size.bytes(), 4); + ecx.machine.layouts.u32 }; - self.read_c_str_with_char_size(ptr, wchar_t.size, wchar_t.align) + self.read_c_str_with_char_type(ptr, wchar_t) } fn frame_in_std(&self) -> bool { diff --git a/src/tools/miri/src/intrinsics/mod.rs b/src/tools/miri/src/intrinsics/mod.rs index d6e0e24e8ab15..ff41cbdb91b7d 100644 --- a/src/tools/miri/src/intrinsics/mod.rs +++ b/src/tools/miri/src/intrinsics/mod.rs @@ -9,6 +9,7 @@ mod x86; #[rustfmt::skip] // prevent `use` reordering use rand::RngExt; use rustc_abi::{Endian, Size}; +use rustc_middle::ty::Intrinsic; use rustc_middle::{mir, ty}; use rustc_span::sym; use rustc_target::spec::Arch; @@ -50,14 +51,17 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { if ecx.eval_intrinsic(instance, args, dest, ret)? { return interp_ok(None); } - let intrinsic = ecx.tcx.intrinsic(instance.def_id()).unwrap(); - let intrinsic_name = &intrinsic.name.to_string(); - let res = ecx.emulate_intrinsic_by_name(intrinsic_name, instance.args, args, dest, ret)?; + let intrinsic = ecx.tcx.intrinsic(instance.def_id()).unwrap(); + let res = match intrinsic.name { + Intrinsic::Rustc(name) => + ecx.emulate_intrinsic_by_name(name.as_str(), instance.args, args, dest, ret)?, + Intrinsic::Backend { .. } => EmulateItemResult::NotSupported, + }; res.jump_to_next_block(ecx, dest, ret, Some(unwind), |ecx| { // We haven't handled the intrinsic, let's see if we can use a fallback body. if intrinsic.must_be_overridden { - throw_unsup_format!("unimplemented intrinsic: `{intrinsic_name}`") + throw_unsup_format!("unimplemented intrinsic: `{}`", intrinsic.name) } let intrinsic_fallback_is_spec = ecx .tcx @@ -69,7 +73,11 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { .is_some(); if !intrinsic_fallback_is_spec { throw_unsup_format!( - "Miri can only use intrinsic fallback bodies that exactly reflect the specification: they fully check for UB and are as non-deterministic as possible. After verifying that `{intrinsic_name}` does so, add the `#[miri::intrinsic_fallback_is_spec]` attribute to it; also ping @rust-lang/miri when you do that" + "Miri can only use intrinsic fallback bodies that exactly reflect the specification: \ + they fully check for UB and are as non-deterministic as possible. \ + After verifying that `{}` does so, add the `#[miri::intrinsic_fallback_is_spec]` attribute to it; \ + also ping @rust-lang/miri when you do that", + intrinsic.name ); } interp_ok(Some(ty::Instance { @@ -209,15 +217,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { assert_eq!(dest_len, op_len); for i in 0..dest_len { - let op = ecx.read_immediate(&ecx.project_index(&op, i)?)?; - // Use `to_uint` to get a zero-extended `u128`. Those + // Use `read_int` to get a zero-extended `u128`. Those // extra zeros will not affect `count_ones`. - let res = op.to_scalar().to_uint(op.layout.size)?.count_ones(); + let op = ecx.read_int::(&ecx.project_index(&op, i)?)?; + let res = op.count_ones(); - ecx.write_scalar( - Scalar::from_uint(res, op.layout.size), - &ecx.project_index(&dest, i)?, - )?; + ecx.write_int(res, &ecx.project_index(&dest, i)?)?; } } diff --git a/src/tools/miri/src/intrinsics/x86/avx2.rs b/src/tools/miri/src/intrinsics/x86/avx2.rs index fe83e95f4c155..bb562523b2554 100644 --- a/src/tools/miri/src/intrinsics/x86/avx2.rs +++ b/src/tools/miri/src/intrinsics/x86/avx2.rs @@ -72,10 +72,10 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { if ecx.read_scalar(&mask)?.to_uint(mask_item_size)? >> high_bit_offset != 0 { let offset = ecx.project_index(&offsets, i)?; - let offset = - i64::try_from(ecx.read_scalar(&offset)?.to_int(offset.layout.size)?) - .unwrap(); - let ptr = slice.wrapping_signed_offset(offset.strict_mul(scale), &ecx.tcx); + let offset = ecx.read_int::(&offset)?; + // The address computation wraps around, like on real hardware. + let ptr = + slice.wrapping_signed_offset(offset.wrapping_mul(scale), &ecx.tcx); // Unaligned copy, which is what we want. ecx.mem_copy( ptr, @@ -89,7 +89,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } for i in actual_len..dest_len { let dest = ecx.project_index(&dest, i)?; - ecx.write_scalar(Scalar::from_int(0, dest.layout.size), &dest)?; + ecx.write_int(0, &dest)?; } } // Used to implement the _mm256_maddubs_epi16 function. diff --git a/src/tools/miri/src/intrinsics/x86/avx512.rs b/src/tools/miri/src/intrinsics/x86/avx512.rs index 06e6990aca6ff..f42b0402fa303 100644 --- a/src/tools/miri/src/intrinsics/x86/avx512.rs +++ b/src/tools/miri/src/intrinsics/x86/avx512.rs @@ -2,7 +2,7 @@ use rustc_span::Symbol; use super::{ ShiftOp, packssdw, packsswb, packusdw, packuswb, pavg, permute, permute2, pmaddbw, pmaddwd, - psadbw, pshufb, shift_simd_by_simd, + psadbw, pshufb, shift_simd_by_scalar, shift_simd_by_simd, }; use crate::*; @@ -30,6 +30,24 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }; shift_simd_by_simd(this, left, right, which, dest)?; } + // Used by _mm512_{sll,srl,sra}_epi{16, 32, 64} and _mm{256}_sra_epi64. + "psll.w.512" | "psrl.w.512" | "psra.w.512" | "psll.d.512" | "psrl.d.512" + | "psra.d.512" | "psll.q.512" | "psrl.q.512" | "psra.q.512" | "psra.q.128" + | "psra.q.256" => { + let target = + if unprefixed_name.ends_with("w.512") { "avx512bw" } else { "avx512f" }; + this.expect_target_feature_for_intrinsic(link_name, target)?; + + let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; + let which = match unprefixed_name.split_at(4).0 { + "psll" => ShiftOp::Left, + "psrl" => ShiftOp::RightLogic, + "psra" => ShiftOp::RightArith, + _ => unreachable!(), + }; + + shift_simd_by_scalar(this, left, right, which, dest)?; + } // Used by the ternarylogic functions. "pternlog.d.128" | "pternlog.d.256" | "pternlog.d.512" | "pternlog.q.128" | "pternlog.q.256" | "pternlog.q.512" => { diff --git a/src/tools/miri/src/intrinsics/x86/mod.rs b/src/tools/miri/src/intrinsics/x86/mod.rs index 3d99eed671f58..192897ac6a726 100644 --- a/src/tools/miri/src/intrinsics/x86/mod.rs +++ b/src/tools/miri/src/intrinsics/x86/mod.rs @@ -680,7 +680,7 @@ fn convert_float_to_int<'tcx>( // Fill remainder with zeros for i in op_len..dest_len { let dest = ecx.project_index(&dest, i)?; - ecx.write_scalar(Scalar::from_int(0, dest.layout.size), &dest)?; + ecx.write_int(0, &dest)?; } interp_ok(()) @@ -740,30 +740,39 @@ fn conditional_dot_product<'tcx>( let (_, _, dest) = split_simd_to_128bit_chunks(ecx, dest)?; let element_layout = left.layout.field(ecx, 0).field(ecx, 0); - assert!(items_per_chunk <= 4); + assert!(matches!(items_per_chunk, 2 | 4)); // `imm` is a `u8` for SSE4.1 or an `i32` for AVX :/ - let imm = ecx.read_scalar(imm)?.to_uint(imm.layout.size)?; + let imm = ecx.read_int::(imm)?; for i in 0..num_chunks { let left = ecx.project_index(&left, i)?; let right = ecx.project_index(&right, i)?; let dest = ecx.project_index(&dest, i)?; - // Calculate dot product - // Elements are floating point numbers, but we can use `from_int` - // for the initial value because the representation of 0.0 is all zero bits. - let mut sum = ImmTy::from_int(0u8, element_layout); + // Masked-out products are +0.0, represented by all zero bits. + let mut products: [_; 4] = std::array::from_fn(|_| ImmTy::from_int(0u8, element_layout)); for j in 0..items_per_chunk { if imm & (1 << j.strict_add(4)) != 0 { let left = ecx.read_immediate(&ecx.project_index(&left, j)?)?; let right = ecx.read_immediate(&ecx.project_index(&right, j)?)?; - let mul = ecx.binary_op(mir::BinOp::Mul, &left, &right)?; - sum = ecx.binary_op(mir::BinOp::Add, &sum, &mul)?; + products[usize::try_from(j).unwrap()] = + ecx.binary_op(mir::BinOp::Mul, &left, &right)?; } } + // Reduce in the right order (tree reduction). + let sum = match items_per_chunk { + 2 => ecx.binary_op(mir::BinOp::Add, &products[0], &products[1])?, + 4 => { + let lower_sum = ecx.binary_op(mir::BinOp::Add, &products[0], &products[1])?; + let upper_sum = ecx.binary_op(mir::BinOp::Add, &products[2], &products[3])?; + ecx.binary_op(mir::BinOp::Add, &lower_sum, &upper_sum)? + } + _ => unreachable!(), + }; + // Write to destination (conditioned to imm) for j in 0..items_per_chunk { let dest = ecx.project_index(&dest, j)?; @@ -971,7 +980,7 @@ fn mpsadbw<'tcx>( assert_eq!(op_items_per_chunk, dest_items_per_chunk.strict_mul(2)); - let imm = ecx.read_scalar(imm)?.to_uint(imm.layout.size)?; + let imm = ecx.read_int::(imm)?; for i in 0..num_chunks { let left = ecx.project_index(&left, i)?; diff --git a/src/tools/miri/src/intrinsics/x86/sse41.rs b/src/tools/miri/src/intrinsics/x86/sse41.rs index 602c1229efdb3..df60ac4f2e920 100644 --- a/src/tools/miri/src/intrinsics/x86/sse41.rs +++ b/src/tools/miri/src/intrinsics/x86/sse41.rs @@ -11,8 +11,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { args: &[OpTy<'tcx>], dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx, EmulateItemResult> { - let this = self.eval_context_mut(); - this.expect_target_feature_for_intrinsic(link_name, "sse4.1")?; + let ecx = self.eval_context_mut(); + ecx.expect_target_feature_for_intrinsic(link_name, "sse4.1")?; // Prefix should have already been checked. let unprefixed_name = link_name.as_str().strip_prefix("llvm.x86.sse41.").unwrap(); @@ -24,34 +24,34 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // bits `4..=5` if `imm`, and `i`th bit specifies whether element // `i` is zeroed. "insertps" => { - let [left, right, imm] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; + let [left, right, imm] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; - let (left, left_len) = this.project_to_simd(left)?; - let (right, right_len) = this.project_to_simd(right)?; - let (dest, dest_len) = this.project_to_simd(dest)?; + let (left, left_len) = ecx.project_to_simd(left)?; + let (right, right_len) = ecx.project_to_simd(right)?; + let (dest, dest_len) = ecx.project_to_simd(dest)?; assert_eq!(dest_len, left_len); assert_eq!(dest_len, right_len); assert!(dest_len <= 4); - let imm = this.read_scalar(imm)?.to_u8()?; + let imm = ecx.read_scalar(imm)?.to_u8()?; let src_index = u64::from((imm >> 6) & 0b11); let dst_index = u64::from((imm >> 4) & 0b11); - let src_value = this.read_immediate(&this.project_index(&right, src_index)?)?; + let src_value = ecx.read_immediate(&ecx.project_index(&right, src_index)?)?; for i in 0..dest_len { - let dest = this.project_index(&dest, i)?; + let dest = ecx.project_index(&dest, i)?; if imm & (1 << i) != 0 { // zeroed - this.write_scalar(Scalar::from_u32(0), &dest)?; + ecx.write_scalar(Scalar::from_u32(0), &dest)?; } else if i == dst_index { // copy from `right` at specified index - this.write_immediate(*src_value, &dest)?; + ecx.write_immediate(*src_value, &dest)?; } else { // copy from `left` - this.copy_op(&this.project_index(&left, i)?, &dest)?; + ecx.copy_op(&ecx.project_index(&left, i)?, &dest)?; } } } @@ -59,9 +59,9 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Concatenates two 32-bit signed integer vectors and converts // the result to a 16-bit unsigned integer vector with saturation. "packusdw" => { - let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; + let [left, right] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; - packusdw(this, left, right, dest)?; + packusdw(ecx, left, right, dest)?; } // Used to implement the _mm_dp_ps and _mm_dp_pd functions. // Conditionally multiplies the packed floating-point elements in @@ -69,56 +69,54 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // products, and conditionally stores the sum in `dest` using the low // 4 bits of `imm`. "dpps" | "dppd" => { - let [left, right, imm] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; + let [left, right, imm] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; - conditional_dot_product(this, left, right, imm, dest)?; + conditional_dot_product(ecx, left, right, imm, dest)?; } // Used to implement the _mm_floor_ss, _mm_ceil_ss and _mm_round_ss // functions. Rounds the first element of `right` according to `rounding` // and copies the remaining elements from `left`. "round.ss" => { - let [left, right, rounding] = - this.check_shim_sig_llvm_intrinsic(link_name, args)?; + let [left, right, rounding] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; - round_first::(this, left, right, rounding, dest)?; + round_first::(ecx, left, right, rounding, dest)?; } // Used to implement the _mm_floor_ps, _mm_ceil_ps and _mm_round_ps // functions. Rounds the elements of `op` according to `rounding`. "round.ps" => { - let [op, rounding] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; + let [op, rounding] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; - round_all::(this, op, rounding, dest)?; + round_all::(ecx, op, rounding, dest)?; } // Used to implement the _mm_floor_sd, _mm_ceil_sd and _mm_round_sd // functions. Rounds the first element of `right` according to `rounding` // and copies the remaining elements from `left`. "round.sd" => { - let [left, right, rounding] = - this.check_shim_sig_llvm_intrinsic(link_name, args)?; + let [left, right, rounding] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; - round_first::(this, left, right, rounding, dest)?; + round_first::(ecx, left, right, rounding, dest)?; } // Used to implement the _mm_floor_pd, _mm_ceil_pd and _mm_round_pd // functions. Rounds the elements of `op` according to `rounding`. "round.pd" => { - let [op, rounding] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; + let [op, rounding] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; - round_all::(this, op, rounding, dest)?; + round_all::(ecx, op, rounding, dest)?; } // Used to implement the _mm_minpos_epu16 function. // Find the minimum unsigned 16-bit integer in `op` and // returns its value and position. "phminposuw" => { - let [op] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; + let [op] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; - let (op, op_len) = this.project_to_simd(op)?; - let (dest, dest_len) = this.project_to_simd(dest)?; + let (op, op_len) = ecx.project_to_simd(op)?; + let (dest, dest_len) = ecx.project_to_simd(dest)?; // Find minimum let mut min_value = u16::MAX; let mut min_index = 0; for i in 0..op_len { - let op = this.read_scalar(&this.project_index(&op, i)?)?.to_u16()?; + let op = ecx.read_scalar(&ecx.project_index(&op, i)?)?.to_u16()?; if op < min_value { min_value = op; min_index = i; @@ -126,14 +124,14 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } // Write value and index - this.write_scalar(Scalar::from_u16(min_value), &this.project_index(&dest, 0)?)?; - this.write_scalar( + ecx.write_scalar(Scalar::from_u16(min_value), &ecx.project_index(&dest, 0)?)?; + ecx.write_scalar( Scalar::from_u16(min_index.try_into().unwrap()), - &this.project_index(&dest, 1)?, + &ecx.project_index(&dest, 1)?, )?; // Fill remainder with zeros for i in 2..dest_len { - this.write_scalar(Scalar::from_u16(0), &this.project_index(&dest, i)?)?; + ecx.write_scalar(Scalar::from_u16(0), &ecx.project_index(&dest, i)?)?; } } // Used to implement the _mm_mpsadbw_epu8 function. @@ -143,19 +141,19 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // offsets specified in `imm`. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mpsadbw_epu8 "mpsadbw" => { - let [left, right, imm] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; + let [left, right, imm] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; - mpsadbw(this, left, right, imm, dest)?; + mpsadbw(ecx, left, right, imm, dest)?; } // Used to implement the _mm_testnzc_si128 function. // Tests `(op & mask) != 0 && (op & mask) != mask` "ptestnzc" => { - let [op, mask] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; + let [op, mask] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; - let (all_zero, masked_set) = test_bits_masked(this, op, mask)?; + let (all_zero, masked_set) = test_bits_masked(ecx, op, mask)?; let res = !all_zero && !masked_set; - this.write_scalar(Scalar::from_i32(res.into()), dest)?; + ecx.write_scalar(Scalar::from_i32(res.into()), dest)?; } _ => return interp_ok(EmulateItemResult::NotSupported), } diff --git a/src/tools/miri/src/intrinsics/x86/sse42.rs b/src/tools/miri/src/intrinsics/x86/sse42.rs index 39603d201d47a..51704b207f32f 100644 --- a/src/tools/miri/src/intrinsics/x86/sse42.rs +++ b/src/tools/miri/src/intrinsics/x86/sse42.rs @@ -298,8 +298,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { args: &[OpTy<'tcx>], dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx, EmulateItemResult> { - let this = self.eval_context_mut(); - this.expect_target_feature_for_intrinsic(link_name, "sse4.2")?; + let ecx = self.eval_context_mut(); + ecx.expect_target_feature_for_intrinsic(link_name, "sse4.2")?; // Prefix should have already been checked. let unprefixed_name = link_name.as_str().strip_prefix("llvm.x86.sse42.").unwrap(); @@ -309,28 +309,28 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#ig_expand=1044,922 "pcmpistrm128" | "pcmpestrm128" => { let (str1, str2, len, imm) = - deconstruct_args(unprefixed_name, this, link_name, args)?; - let mask = compare_strings(this, &str1, &str2, len, imm)?; + deconstruct_args(unprefixed_name, ecx, link_name, args)?; + let mask = compare_strings(ecx, &str1, &str2, len, imm)?; // The sixth bit inside the immediate byte distinguishes // between a bit mask or a byte mask when generating a mask. if imm & 0b100_0000 != 0 { let (array_layout, size) = if imm & USE_WORDS != 0 { - (this.layout_of(Ty::new_array(this.tcx.tcx, this.tcx.types.u16, 8))?, 2) + (ecx.layout_of(Ty::new_array(ecx.tcx.tcx, ecx.tcx.types.u16, 8))?, 2) } else { - (this.layout_of(Ty::new_array(this.tcx.tcx, this.tcx.types.u8, 16))?, 1) + (ecx.layout_of(Ty::new_array(ecx.tcx.tcx, ecx.tcx.types.u8, 16))?, 1) }; let size = Size::from_bytes(size); - let dest = dest.transmute(array_layout, this)?; + let dest = dest.transmute(array_layout, ecx)?; for i in 0..default_len::(imm) { let result = helpers::bool_to_simd_element(mask & (1 << i) != 0, size); - this.write_scalar(result, &this.project_index(&dest, i)?)?; + ecx.write_scalar(result, &ecx.project_index(&dest, i)?)?; } } else { - let layout = this.layout_of(this.tcx.types.i128)?; - let dest = dest.transmute(layout, this)?; - this.write_scalar(Scalar::from_i128(i128::from(mask)), &dest)?; + let layout = ecx.layout_of(ecx.tcx.types.i128)?; + let dest = dest.transmute(layout, ecx)?; + ecx.write_scalar(Scalar::from_i128(i128::from(mask)), &dest)?; } } @@ -340,17 +340,17 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#ig_expand=919,1041 "pcmpistria128" | "pcmpestria128" => { let (str1, str2, len, imm) = - deconstruct_args(unprefixed_name, this, link_name, args)?; - let result = if compare_strings(this, &str1, &str2, len, imm)? != 0 { + deconstruct_args(unprefixed_name, ecx, link_name, args)?; + let result = if compare_strings(ecx, &str1, &str2, len, imm)? != 0 { false } else if let Some((_, len)) = len { len >= default_len::(imm) } else { // Test if the second string has no null-terminator. - implicit_len(this, &str2, imm)?.is_none() + implicit_len(ecx, &str2, imm)?.is_none() }; - this.write_scalar(Scalar::from_i32(i32::from(result)), dest)?; + ecx.write_scalar(Scalar::from_i32(i32::from(result)), dest)?; } // Used to implement the `_mm_cmpestri` and the `_mm_cmpistri` functions. @@ -359,8 +359,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#ig_expand=921,1043 "pcmpistri128" | "pcmpestri128" => { let (str1, str2, len, imm) = - deconstruct_args(unprefixed_name, this, link_name, args)?; - let mask = compare_strings(this, &str1, &str2, len, imm)?; + deconstruct_args(unprefixed_name, ecx, link_name, args)?; + let mask = compare_strings(ecx, &str1, &str2, len, imm)?; let len = default_len::(imm); // The sixth bit inside the immediate byte distinguishes between the least @@ -372,7 +372,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // least significant bit mask.trailing_zeros().min(len) }; - this.write_scalar(Scalar::from_i32(i32::try_from(result).unwrap()), dest)?; + ecx.write_scalar(Scalar::from_i32(i32::try_from(result).unwrap()), dest)?; } // Used to implement the `_mm_cmpestro` and the `_mm_cmpistro` functions. @@ -381,9 +381,9 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#ig_expand=923,1045 "pcmpistrio128" | "pcmpestrio128" => { let (str1, str2, len, imm) = - deconstruct_args(unprefixed_name, this, link_name, args)?; - let mask = compare_strings(this, &str1, &str2, len, imm)?; - this.write_scalar(Scalar::from_i32(mask & 1), dest)?; + deconstruct_args(unprefixed_name, ecx, link_name, args)?; + let mask = compare_strings(ecx, &str1, &str2, len, imm)?; + ecx.write_scalar(Scalar::from_i32(mask & 1), dest)?; } // Used to implement the `_mm_cmpestrc` and the `_mm_cmpistrc` functions. @@ -392,9 +392,9 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#ig_expand=920,1042 "pcmpistric128" | "pcmpestric128" => { let (str1, str2, len, imm) = - deconstruct_args(unprefixed_name, this, link_name, args)?; - let mask = compare_strings(this, &str1, &str2, len, imm)?; - this.write_scalar(Scalar::from_i32(i32::from(mask != 0)), dest)?; + deconstruct_args(unprefixed_name, ecx, link_name, args)?; + let mask = compare_strings(ecx, &str1, &str2, len, imm)?; + ecx.write_scalar(Scalar::from_i32(i32::from(mask != 0)), dest)?; } // Used to implement the `_mm_cmpistrz` and the `_mm_cmpistrs` functions. @@ -403,19 +403,19 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // search for a null terminator (see `deconstruct_args` for more details). // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#ig_expand=924,925 "pcmpistriz128" | "pcmpistris128" => { - let [str1, str2, imm] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; - let imm = this.read_scalar(imm)?.to_u8()?; + let [str1, str2, imm] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; + let imm = ecx.read_scalar(imm)?.to_u8()?; let str = if unprefixed_name == "pcmpistris128" { str1 } else { str2 }; let array_layout = if imm & USE_WORDS != 0 { - this.layout_of(Ty::new_array(this.tcx.tcx, this.tcx.types.u16, 8))? + ecx.layout_of(Ty::new_array(ecx.tcx.tcx, ecx.tcx.types.u16, 8))? } else { - this.layout_of(Ty::new_array(this.tcx.tcx, this.tcx.types.u8, 16))? + ecx.layout_of(Ty::new_array(ecx.tcx.tcx, ecx.tcx.types.u8, 16))? }; - let str = str.transmute(array_layout, this)?; - let result = implicit_len(this, &str, imm)?.is_some(); + let str = str.transmute(array_layout, ecx)?; + let result = implicit_len(ecx, &str, imm)?.is_some(); - this.write_scalar(Scalar::from_i32(i32::from(result)), dest)?; + ecx.write_scalar(Scalar::from_i32(i32::from(result)), dest)?; } // Used to implement the `_mm_cmpestrz` and the `_mm_cmpestrs` functions. @@ -423,17 +423,13 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // than 16 for byte-sized operands or 8 for word-sized operands. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#ig_expand=1046,1047 "pcmpestriz128" | "pcmpestris128" => { - let [_, len1, _, len2, imm] = - this.check_shim_sig_llvm_intrinsic(link_name, args)?; + let [_, len1, _, len2, imm] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; let len = if unprefixed_name == "pcmpestris128" { len1 } else { len2 }; // According to https://intel.github.io/SDM/instruction/PCMPESTRM.html, the length argument // is initially signed and turned into an unsigned integer by taking its absolute value. - let len = this.read_scalar(len)?.to_i32()?.unsigned_abs(); - let imm = this.read_scalar(imm)?.to_u8()?; - this.write_scalar( - Scalar::from_i32(i32::from(len < default_len::(imm))), - dest, - )?; + let len = ecx.read_scalar(len)?.to_i32()?.unsigned_abs(); + let imm = ecx.read_scalar(imm)?.to_u8()?; + ecx.write_scalar(Scalar::from_i32(i32::from(len < default_len::(imm))), dest)?; } // Used to implement the `_mm_crc32_u{8, 16, 32, 64}` functions. @@ -449,13 +445,13 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { _ => unreachable!(), }; - if bit_size == 64 && this.tcx.sess.target.arch != Arch::X86_64 { + if bit_size == 64 && ecx.tcx.sess.target.arch != Arch::X86_64 { return interp_ok(EmulateItemResult::NotSupported); } - let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; - let left = this.read_scalar(left)?; - let right = this.read_scalar(right)?; + let [left, right] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; + let left = ecx.read_scalar(left)?; + let right = ecx.read_scalar(right)?; let crc = if bit_size == 64 { // The 64-bit version will only consider the lower 32 bits, @@ -480,7 +476,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { Scalar::from_u32(result) }; - this.write_scalar(result, dest)?; + ecx.write_scalar(result, dest)?; } _ => return interp_ok(EmulateItemResult::NotSupported), } diff --git a/src/tools/miri/src/math.rs b/src/tools/miri/src/math.rs index 1964c74a56565..698c8333f4cad 100644 --- a/src/tools/miri/src/math.rs +++ b/src/tools/miri/src/math.rs @@ -183,7 +183,9 @@ fn strip_float_suffix(intrinsic_name: &str) -> &str { } /// Given a floating-point operation and a floating-point value, clamps the result to the output -/// range of the given operation according to the C standard, if any. +/// range of the given operation according to the C standard ([C23 Section 7.12]), if any. +/// +/// [C23 Section 7.12]: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf#section.7.12 pub(crate) fn clamp_float_value( intrinsic_name: &str, val: IeeeFloat, @@ -210,16 +212,16 @@ where // acos: [0, Ï€] "acos" => val.clamp(zero, pi), - // asin: [-Ï€, +Ï€] - "asin" => val.clamp(pi.neg(), pi), + // asin: [-Ï€/2, +Ï€/2] + "asin" => val.clamp(pi_over_2.neg(), pi_over_2), - // atan: (-Ï€/2, +Ï€/2) + // atan: [-Ï€/2, +Ï€/2] "atan" => val.clamp(pi_over_2.neg(), pi_over_2), - // erfc: (-1, 1) + // erfc: [-1, 1] "erf" => val.clamp(one.neg(), one), - // erfc: (0, 2) + // erfc: [0, 2] "erfc" => val.clamp(zero, two), // atan2(y, x): arctan(y/x) in [−π, +Ï€] @@ -242,10 +244,12 @@ where /// # Return /// /// Returns `Some(output)` if the `intrinsic` results in a defined fixed `output` specified in the C standard -/// (specifically, C23 annex F.10) when given `args` as arguments. Outputs that are unaffected by a relative error +/// (specifically, [C23 annex F.10]) when given `args` as arguments. Outputs that are unaffected by a relative error /// (such as INF and zero) are not handled here, they are assumed to be handled by the underlying /// implementation. Returns `None` if no specific value is guaranteed. /// +/// [C23 annex F.10]: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf#section.13.10 +/// /// # Note /// /// For `powf*` operations of the form: @@ -269,7 +273,7 @@ pub(crate) fn fixed_float_value( where IeeeFloat: IeeeExt, { - let this = ecx.eval_context_mut(); + let ecx = ecx.eval_context_mut(); let one = IeeeFloat::::one(); let two = IeeeFloat::::two(); let three = IeeeFloat::::three(); @@ -300,10 +304,13 @@ where // `_hypot` is the Windows name for this. ("_hypot" | "hypot", [x, y]) if !x.is_nan() && y.is_zero() => x.abs(), + // atan2 has many cases, but NaNs are excluded from all of them. It's easiest + // to handle that upfront. + ("atan2", [x, y]) if x.is_nan() || y.is_nan() => return None, + // atan2(±0,−0) = ±π. // atan2(±0, y) = ±π for y < 0. - // Must check for non NaN because `y.is_negative()` also applies to NaN. - ("atan2", [x, y]) if (x.is_zero() && (y.is_negative() && !y.is_nan())) => pi.copy_sign(*x), + ("atan2", [x, y]) if (x.is_zero() && y.is_negative()) => pi.copy_sign(*x), // atan2(±x,−∞) = ±π for finite x > 0. ("atan2", [x, y]) if (!x.is_zero() && !x.is_infinite()) && y.is_neg_infinity() => @@ -321,30 +328,29 @@ where ("atan2", [x, y]) if x.is_infinite() && y.is_pos_infinity() => pi_over_4.copy_sign(*x), // atan2(±∞, y) returns ±π/2 for finite y. - ("atan2", [x, y]) if x.is_infinite() && (!y.is_infinite() && !y.is_nan()) => - pi_over_2.copy_sign(*x), + ("atan2", [x, y]) if x.is_infinite() && !y.is_infinite() => pi_over_2.copy_sign(*x), // (-1)^(±INF) = 1 ("pow", [base, exp]) if *base == -one && exp.is_infinite() => one, // 1^y = 1 for any y, even a NaN ("pow", [base, exp]) if *base == one => { - let rng = this.machine.rng.get_mut(); + let rng = ecx.machine.rng.get_mut(); // SNaN exponents get special treatment: they might return 1, or a NaN. // This is non-deterministic because LLVM can treat SNaN as QNaN, and because // implementation behavior differs between glibc and musl. - let return_nan = exp.is_signaling() && this.machine.float_nondet && rng.random(); - if return_nan { this.generate_nan(args) } else { one } + let return_nan = exp.is_signaling() && ecx.machine.float_nondet && rng.random(); + if return_nan { ecx.generate_nan(args) } else { one } } // x^(±0) = 1 for any x, even a NaN ("pow", [base, exp]) if exp.is_zero() => { - let rng = this.machine.rng.get_mut(); + let rng = ecx.machine.rng.get_mut(); // SNaN bases get special treatment: they might return 1, or a NaN. // This is non-deterministic because LLVM can treat SNaN as QNaN, and because // implementation behavior differs between glibc and musl. - let return_nan = base.is_signaling() && this.machine.float_nondet && rng.random(); - if return_nan { this.generate_nan(args) } else { one } + let return_nan = base.is_signaling() && ecx.machine.float_nondet && rng.random(); + if return_nan { ecx.generate_nan(args) } else { one } } // There are a lot of cases for fixed outputs according to the C Standard, but these are diff --git a/src/tools/miri/src/meta_obj.rs b/src/tools/miri/src/meta_obj.rs index 4d961efcbb5be..4c30d73f2d42f 100644 --- a/src/tools/miri/src/meta_obj.rs +++ b/src/tools/miri/src/meta_obj.rs @@ -14,14 +14,19 @@ pub const OPAQUE_OBJ_COOKIE: u8 = 0x42; /// A trait for the synchronization metadata that can be attached to a memory location. /// Must *not* contain any provenance! pub trait MetaObj: Any { + /// Determines whether this object is opaque, which means that the underlying memory is "hidden" + /// from the program for as long as the meta object exists. Opaque objects have their memory + /// contents reset to "uninit" on creation, and are implicitly removed on writes. + fn opaque(&self) -> bool { + true + } + /// Determines whether reads/writes to this object's location are currently permitted. + /// The default is to allow them, but treat the object as opaque (see above), which means reads + /// will return `Uninit` and writes will destroy the meta object. fn on_access<'tcx>(&self) -> InterpResult<'tcx> { interp_ok(()) } - - /// Determines whether this object is opaque. Opaque objects have their memory contents - /// reset to "uninit" on creation, and are implicitly removed on writes. - fn opaque(&self) -> bool; } impl dyn MetaObj { diff --git a/src/tools/miri/src/provenance_gc.rs b/src/tools/miri/src/provenance_gc.rs index c2e4188c904b8..ef8b4d7e04276 100644 --- a/src/tools/miri/src/provenance_gc.rs +++ b/src/tools/miri/src/provenance_gc.rs @@ -1,4 +1,5 @@ use std::collections::BTreeMap; +use std::net::SocketAddr; use std::rc::Rc; use rustc_data_structures::either::Either; @@ -23,7 +24,7 @@ macro_rules! no_provenance { )+ } } -no_provenance!(i8 i16 i32 i64 isize u8 u16 u32 u64 usize bool ThreadId Deadline Symbol); +no_provenance!(i8 i16 i32 i64 isize u8 u16 u32 u64 usize bool ThreadId Deadline Symbol SocketAddr); impl VisitProvenance for &'static str { fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {} diff --git a/src/tools/miri/src/shims/foreign_items.rs b/src/tools/miri/src/shims/foreign_items.rs index f40ebcce3aa86..7ef79808558f3 100644 --- a/src/tools/miri/src/shims/foreign_items.rs +++ b/src/tools/miri/src/shims/foreign_items.rs @@ -477,13 +477,13 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { let start_routine = ecx.read_pointer(start_routine)?; let func_arg = ecx.read_immediate(func_arg)?; - ecx.start_regular_thread( - Some(dest.clone()), + let thread_id = ecx.start_regular_thread( start_routine, ExternAbi::Rust, func_arg, ecx.machine.layouts.unit, )?; + ecx.write_int(thread_id.to_u32(), dest)?; } "miri_thread_join" => { let [thread_id] = &ecx.check_shim_sig( @@ -629,7 +629,6 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { return interp_ok(EmulateItemResult::AlreadyJumped); } "abort" => { - // FIXME: This does not have a direct test (#3179). let [] = &ecx.check_shim_sig(shim_sig!(extern "C" fn() -> ()), (link_name, abi, args))?; throw_machine_stop!(TerminationInfo::Abort( diff --git a/src/tools/miri/src/shims/sig.rs b/src/tools/miri/src/shims/sig.rs index e5c3b58b25268..02e0323d62f7a 100644 --- a/src/tools/miri/src/shims/sig.rs +++ b/src/tools/miri/src/shims/sig.rs @@ -386,7 +386,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ); } VarArgCompatible::CastIntTo { source_is_signed } => { - // Check that the value can be represented in the target type. + // Check that the value can be represented in the target type: when read as + // a signed integer, it must be non-negative. let size = caller_gave.layout.size; let scalar = ecx.read_scalar(caller_gave)?; if scalar.to_int(size)? < 0 { diff --git a/src/tools/miri/src/shims/time.rs b/src/tools/miri/src/shims/time.rs index 97127d8e34a97..84e3542fba023 100644 --- a/src/tools/miri/src/shims/time.rs +++ b/src/tools/miri/src/shims/time.rs @@ -22,24 +22,24 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // This clock support is deliberately minimal because a lot of clock types have fiddly // properties (is it possible for Miri to be suspended independently of the host?). If you // have a use for another clock type, please open an issue. - let this = self.eval_context_ref(); + let ecx = self.eval_context_ref(); // Portable names that exist everywhere. - if clk_id == this.eval_libc_i32("CLOCK_REALTIME") { + if clk_id == ecx.eval_libc_i32("CLOCK_REALTIME") { return Some(TimeoutClock::RealTime); - } else if clk_id == this.eval_libc_i32("CLOCK_MONOTONIC") { + } else if clk_id == ecx.eval_libc_i32("CLOCK_MONOTONIC") { return Some(TimeoutClock::Monotonic); } // Some further platform-specific names we support. - match &this.tcx.sess.target.os { + match &ecx.tcx.sess.target.os { Os::Linux | Os::FreeBsd | Os::Android => { // Linux further distinguishes regular and "coarse" clocks, but the "coarse" version // is just specified to be "faster and less precise", so we treat it like normal // clocks. - if clk_id == this.eval_libc_i32("CLOCK_REALTIME_COARSE") { + if clk_id == ecx.eval_libc_i32("CLOCK_REALTIME_COARSE") { return Some(TimeoutClock::RealTime); - } else if clk_id == this.eval_libc_i32("CLOCK_MONOTONIC_COARSE") { + } else if clk_id == ecx.eval_libc_i32("CLOCK_MONOTONIC_COARSE") { return Some(TimeoutClock::Monotonic); } } @@ -48,7 +48,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // `CLOCK_UPTIME_RAW` supposed to not increment while the system is asleep... but // that's not really something a program running inside Miri can tell, anyway. // We need to support it because std uses it. - if clk_id == this.eval_libc_i32("CLOCK_UPTIME_RAW") { + if clk_id == ecx.eval_libc_i32("CLOCK_UPTIME_RAW") { return Some(TimeoutClock::Monotonic); } } @@ -64,33 +64,33 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { tp_op: &OpTy<'tcx>, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - this.assert_target_os_is_unix("clock_gettime"); + ecx.assert_target_os_is_unix("clock_gettime"); - let clk_id = this.read_scalar(clk_id_op)?.to_i32()?; - let tp = this.deref_pointer(tp_op)?; + let clk_id = ecx.read_scalar(clk_id_op)?.to_i32()?; + let tp = ecx.deref_pointer(tp_op)?; - let duration = match this.parse_clockid(clk_id) { + let duration = match ecx.parse_clockid(clk_id) { Some(TimeoutClock::RealTime) => { - this.check_no_isolation("`clock_gettime` with `REALTIME` clocks")?; + ecx.check_no_isolation("`clock_gettime` with `REALTIME` clocks")?; system_time_to_duration(&SystemTime::now())? } Some(TimeoutClock::Monotonic) => - this.machine + ecx.machine .monotonic_clock .now() - .duration_since(this.machine.monotonic_clock.epoch()), + .duration_since(ecx.machine.monotonic_clock.epoch()), None => { - return this.set_errno_and_return_neg1(LibcError("EINVAL"), dest); + return ecx.set_errno_and_return_neg1(LibcError("EINVAL"), dest); } }; let tv_sec = duration.as_secs(); let tv_nsec = duration.subsec_nanos(); - this.write_int_fields(&[tv_sec.into(), tv_nsec.into()], &tp)?; - this.write_int(0, dest)?; + ecx.write_int_fields(&[tv_sec.into(), tv_nsec.into()], &tp)?; + ecx.write_int(0, dest)?; interp_ok(()) } @@ -100,24 +100,24 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { tv_op: &OpTy<'tcx>, tz_op: &OpTy<'tcx>, ) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - this.assert_target_os_is_unix("gettimeofday"); - this.check_no_isolation("`gettimeofday`")?; + ecx.assert_target_os_is_unix("gettimeofday"); + ecx.check_no_isolation("`gettimeofday`")?; - let tv = this.deref_pointer(tv_op)?; + let tv = ecx.deref_pointer(tv_op)?; // Using tz is obsolete and should always be null - let tz = this.read_pointer(tz_op)?; - if !this.ptr_is_null(tz)? { - return this.set_errno_and_return_neg1_i32(LibcError("EINVAL")); + let tz = ecx.read_pointer(tz_op)?; + if !ecx.ptr_is_null(tz)? { + return ecx.set_errno_and_return_neg1_i32(LibcError("EINVAL")); } let duration = system_time_to_duration(&SystemTime::now())?; let tv_sec = duration.as_secs(); let tv_usec = duration.subsec_micros(); - this.write_int_fields(&[tv_sec.into(), tv_usec.into()], &tv)?; + ecx.write_int_fields(&[tv_sec.into(), tv_usec.into()], &tv)?; interp_ok(Scalar::from_i32(0)) } @@ -130,23 +130,22 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { timep: &OpTy<'tcx>, result_op: &OpTy<'tcx>, ) -> InterpResult<'tcx, Pointer> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - this.assert_target_os_is_unix("localtime_r"); - this.check_no_isolation("`localtime_r`")?; + ecx.assert_target_os_is_unix("localtime_r"); + ecx.check_no_isolation("`localtime_r`")?; - let timep = this.deref_pointer(timep)?; - let result = this.deref_pointer(result_op)?; + let timep = ecx.deref_pointer(timep)?; + let result = ecx.deref_pointer(result_op)?; // The input "represents the number of seconds elapsed since the Epoch, // 1970-01-01 00:00:00 +0000 (UTC)". - let sec_since_epoch: i64 = - this.read_scalar(&timep)?.to_int(timep.layout.size)?.try_into().unwrap(); + let sec_since_epoch: i64 = ecx.read_int::(&timep)?; let dt_utc: DateTime = DateTime::from_timestamp(sec_since_epoch, 0).expect("Invalid timestamp"); // Figure out what time zone is in use - let tz = this.get_env_var(OsStr::new("TZ"))?.unwrap_or_else(|| OsString::from("UTC")); + let tz = ecx.get_env_var(OsStr::new("TZ"))?.unwrap_or_else(|| OsString::from("UTC")); let tz = match tz.into_string() { Ok(tz) => Tz::from_str(&tz).unwrap_or(Tz::UTC), _ => Tz::UTC, @@ -159,7 +158,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // chrono crate yet. // This may not be consistent with libc::localtime_r's result. let tm_isdst = -1; - this.write_int_fields_named( + ecx.write_int_fields_named( &[ ("tm_sec", dt.second().into()), ("tm_min", dt.minute().into()), @@ -177,7 +176,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // solaris/illumos system tm struct does not have // the additional tm_zone/tm_gmtoff fields. // https://docs.oracle.com/cd/E36784_01/html/E36874/localtime-r-3c.html - if !matches!(&this.tcx.sess.target.os, Os::Solaris | Os::Illumos) { + if !matches!(&ecx.tcx.sess.target.os, Os::Solaris | Os::Illumos) { // tm_zone represents the timezone value in the form of: +0730, +08, -0730 or -08. // This may not be consistent with libc::localtime_r's result. @@ -200,11 +199,11 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { tm_zone.push('\0'); // Deduplicate and allocate the string. - let tm_zone_ptr = this.allocate_bytes_dedup(tm_zone.as_bytes())?; + let tm_zone_ptr = ecx.allocate_bytes_dedup(tm_zone.as_bytes())?; // Write the timezone pointer and offset into the result structure. - this.write_pointer(tm_zone_ptr, &this.project_field_named(&result, "tm_zone")?)?; - this.write_int_fields_named(&[("tm_gmtoff", tm_gmtoff.into())], &result)?; + ecx.write_pointer(tm_zone_ptr, &ecx.project_field_named(&result, "tm_zone")?)?; + ecx.write_int_fields_named(&[("tm_gmtoff", tm_gmtoff.into())], &result)?; } interp_ok(result.ptr()) } @@ -214,19 +213,19 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { shim_name: &str, LPFILETIME_op: &OpTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - this.assert_target_os(Os::Windows, shim_name); - this.check_no_isolation(shim_name)?; + ecx.assert_target_os(Os::Windows, shim_name); + ecx.check_no_isolation(shim_name)?; - let filetime = this.deref_pointer(LPFILETIME_op)?; + let filetime = ecx.deref_pointer(LPFILETIME_op)?; - let duration = this.system_time_since_windows_epoch(&SystemTime::now())?; - let duration_ticks = this.windows_ticks_for(duration)?; + let duration = ecx.system_time_since_windows_epoch(&SystemTime::now())?; + let duration_ticks = ecx.windows_ticks_for(duration)?; let dwLowDateTime = u32::try_from(duration_ticks & 0x00000000FFFFFFFF).unwrap(); let dwHighDateTime = u32::try_from((duration_ticks & 0xFFFFFFFF00000000) >> 32).unwrap(); - this.write_int_fields(&[dwLowDateTime.into(), dwHighDateTime.into()], &filetime)?; + ecx.write_int_fields(&[dwLowDateTime.into(), dwHighDateTime.into()], &filetime)?; interp_ok(()) } @@ -236,19 +235,19 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { &mut self, lpPerformanceCount_op: &OpTy<'tcx>, ) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - this.assert_target_os(Os::Windows, "QueryPerformanceCounter"); + ecx.assert_target_os(Os::Windows, "QueryPerformanceCounter"); // QueryPerformanceCounter uses a hardware counter as its basis. // Miri will emulate a counter with a resolution of 1 nanosecond. let duration = - this.machine.monotonic_clock.now().duration_since(this.machine.monotonic_clock.epoch()); + ecx.machine.monotonic_clock.now().duration_since(ecx.machine.monotonic_clock.epoch()); let qpc = i64::try_from(duration.as_nanos()).map_err(|_| { err_unsup_format!("programs running longer than 2^63 nanoseconds are not supported") })?; - this.write_scalar(Scalar::from_i64(qpc), &this.deref_pointer(lpPerformanceCount_op)?)?; + ecx.write_scalar(Scalar::from_i64(qpc), &ecx.deref_pointer(lpPerformanceCount_op)?)?; interp_ok(Scalar::from_i32(-1)) // return non-zero on success } @@ -257,16 +256,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { &mut self, lpFrequency_op: &OpTy<'tcx>, ) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - this.assert_target_os(Os::Windows, "QueryPerformanceFrequency"); + ecx.assert_target_os(Os::Windows, "QueryPerformanceFrequency"); // Retrieves the frequency of the hardware performance counter. // The frequency of the performance counter is fixed at system boot and // is consistent across all processors. // Miri emulates a "hardware" performance counter with a resolution of 1ns, // and thus 10^9 counts per second. - this.write_scalar(Scalar::from_i64(1_000_000_000), &this.deref_pointer(lpFrequency_op)?)?; + ecx.write_scalar(Scalar::from_i64(1_000_000_000), &ecx.deref_pointer(lpFrequency_op)?)?; interp_ok(Scalar::from_i32(-1)) // Return non-zero on success } @@ -292,14 +291,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } fn mach_absolute_time(&self) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_ref(); + let ecx = self.eval_context_ref(); - this.assert_target_os(Os::MacOs, "mach_absolute_time"); + ecx.assert_target_os(Os::MacOs, "mach_absolute_time"); // This returns a u64, with time units determined dynamically by `mach_timebase_info`. // We return plain nanoseconds. let duration = - this.machine.monotonic_clock.now().duration_since(this.machine.monotonic_clock.epoch()); + ecx.machine.monotonic_clock.now().duration_since(ecx.machine.monotonic_clock.epoch()); let res = u64::try_from(duration.as_nanos()).map_err(|_| { err_unsup_format!("programs running longer than 2^64 nanoseconds are not supported") })?; @@ -307,32 +306,32 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } fn mach_timebase_info(&mut self, info_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - this.assert_target_os(Os::MacOs, "mach_timebase_info"); + ecx.assert_target_os(Os::MacOs, "mach_timebase_info"); - let info = this.deref_pointer(info_op)?; + let info = ecx.deref_pointer(info_op)?; // Since our emulated ticks in `mach_absolute_time` *are* nanoseconds, // no scaling needs to happen. let (numerator, denom) = (1, 1); - this.write_int_fields(&[numerator.into(), denom.into()], &info)?; + ecx.write_int_fields(&[numerator.into(), denom.into()], &info)?; interp_ok(Scalar::from_i32(0)) // KERN_SUCCESS } fn mach_wait_until(&mut self, deadline_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - this.assert_target_os(Os::MacOs, "mach_wait_until"); + ecx.assert_target_os(Os::MacOs, "mach_wait_until"); - let deadline = this.read_scalar(deadline_op)?.to_u64()?; + let deadline = ecx.read_scalar(deadline_op)?.to_u64()?; // Our mach_absolute_time "ticks" are plain nanoseconds. let deadline = Duration::from_nanos(deadline); // This is *absolute* time. - let deadline = this.machine.monotonic_clock.epoch().add_lossy(deadline); + let deadline = ecx.machine.monotonic_clock.epoch().add_lossy(deadline); - this.block_thread( + ecx.block_thread( BlockReason::Sleep, Some(deadline.into()), callback!( @@ -348,19 +347,19 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } fn nanosleep(&mut self, duration: &OpTy<'tcx>, rem: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - this.assert_target_os_is_unix("nanosleep"); + ecx.assert_target_os_is_unix("nanosleep"); - let duration = this.deref_pointer(duration)?; - let _rem = this.read_pointer(rem)?; // Signal handlers are not supported, so rem will never be written to. + let duration = ecx.deref_pointer(duration)?; + let _rem = ecx.read_pointer(rem)?; // Signal handlers are not supported, so rem will never be written to. - let Some(duration) = this.read_timespec(&duration)? else { - return this.set_errno_and_return_neg1_i32(LibcError("EINVAL")); + let Some(duration) = ecx.read_timespec(&duration)? else { + return ecx.set_errno_and_return_neg1_i32(LibcError("EINVAL")); }; - let deadline = this.machine.monotonic_clock.now().add_lossy(duration); + let deadline = ecx.machine.monotonic_clock.now().add_lossy(duration); - this.block_thread( + ecx.block_thread( BlockReason::Sleep, Some(deadline.into()), callback!( @@ -381,28 +380,27 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { timespec: &OpTy<'tcx>, rem: &OpTy<'tcx>, ) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); - let clockid_t_size = this.libc_ty_layout("clockid_t").size; + let ecx = self.eval_context_mut(); - let clock_id = this.read_scalar(clock_id)?.to_int(clockid_t_size)?; - let timespec = this.deref_pointer(timespec)?; - let flags = this.read_scalar(flags)?.to_i32()?; - let _rem = this.read_pointer(rem)?; // Signal handlers are not supported, so rem will never be written to. + let clock_id = ecx.read_scalar(clock_id)?.to_i32()?; + let timespec = ecx.deref_pointer(timespec)?; + let flags = ecx.read_scalar(flags)?.to_i32()?; + let _rem = ecx.read_pointer(rem)?; // Signal handlers are not supported, so rem will never be written to. // The standard lib through sleep_until only needs CLOCK_MONOTONIC - if clock_id != this.eval_libc("CLOCK_MONOTONIC").to_int(clockid_t_size)? { + if clock_id != ecx.eval_libc_i32("CLOCK_MONOTONIC") { throw_unsup_format!("clock_nanosleep: only CLOCK_MONOTONIC is supported"); } - let Some(duration) = this.read_timespec(×pec)? else { - return this.set_errno_and_return_neg1_i32(LibcError("EINVAL")); + let Some(duration) = ecx.read_timespec(×pec)? else { + return ecx.set_errno_and_return_neg1_i32(LibcError("EINVAL")); }; let timeout_style = if flags == 0 { // No flags set, the timespec should be interpreted as a duration // to sleep for, i.e., a relative time. TimeoutStyle::Relative - } else if flags == this.eval_libc_i32("TIMER_ABSTIME") { + } else if flags == ecx.eval_libc_i32("TIMER_ABSTIME") { // Only flag TIMER_ABSTIME set, the timespec should be interpreted as // an absolute time. TimeoutStyle::Absolute @@ -413,9 +411,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { TIMER_ABSTIME is supported" ); }; - let deadline = this.machine.timeout(TimeoutClock::Monotonic, timeout_style, duration); + let deadline = ecx.machine.timeout(TimeoutClock::Monotonic, timeout_style, duration); - this.block_thread( + ecx.block_thread( BlockReason::Sleep, Some(deadline), callback!( @@ -431,16 +429,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { #[allow(non_snake_case)] fn Sleep(&mut self, timeout: &OpTy<'tcx>) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - this.assert_target_os(Os::Windows, "Sleep"); + ecx.assert_target_os(Os::Windows, "Sleep"); - let timeout_ms = this.read_scalar(timeout)?.to_u32()?; + let timeout_ms = ecx.read_scalar(timeout)?.to_u32()?; let duration = Duration::from_millis(timeout_ms.into()); - let deadline = this.machine.monotonic_clock.now().add_lossy(duration); + let deadline = ecx.machine.monotonic_clock.now().add_lossy(duration); - this.block_thread( + ecx.block_thread( BlockReason::Sleep, Some(deadline.into()), callback!( @@ -458,11 +456,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// if the value in the `timespec` struct is invalid. Some libc functions will return /// EINVAL in this case. fn read_timespec(&self, tp: &MPlaceTy<'tcx>) -> InterpResult<'tcx, Option> { - let this = self.eval_context_ref(); - let sec_field = this.project_field_named(tp, "tv_sec")?; - let sec = this.read_scalar(&sec_field)?.to_int(sec_field.layout.size)?; - let nsec_field = this.project_field_named(tp, "tv_nsec")?; - let nsec = this.read_scalar(&nsec_field)?.to_int(nsec_field.layout.size)?; + let ecx = self.eval_context_ref(); + + let sec_field = ecx.project_field_named(tp, "tv_sec")?; + let sec = ecx.read_int::(&sec_field)?; + let nsec_field = ecx.project_field_named(tp, "tv_nsec")?; + let nsec = ecx.read_int::(&nsec_field)?; // tv_sec can be negative; this does not actually return EINVAL natively. // Since we cannot represent a negative duration, we just don't support this for now. @@ -485,16 +484,20 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// if the value in the `timeval` struct is invalid. Some libc functions will return /// EINVAL in this case. fn read_timeval(&self, tp: &MPlaceTy<'tcx>) -> InterpResult<'tcx, Option> { - let this = self.eval_context_ref(); - let sec_field = this.project_field_named(tp, "tv_sec")?; - let sec = this.read_scalar(&sec_field)?.to_int(sec_field.layout.size)?; + let ecx = self.eval_context_ref(); - let usec_field = this.project_field_named(tp, "tv_usec")?; - let usec = this.read_scalar(&usec_field)?.to_int(usec_field.layout.size)?; + let sec_field = ecx.project_field_named(tp, "tv_sec")?; + let sec = ecx.read_int::(&sec_field)?; + let usec_field = ecx.project_field_named(tp, "tv_usec")?; + let usec = ecx.read_int::(&usec_field)?; + // tv_sec can be negative; this does not actually return EINVAL natively. + // Since we cannot represent a negative duration, we just don't support this for now. + if sec < 0 { + throw_unsup_format!("timespec with negative tv_sec is not supported"); + } interp_ok(try { - // tv_sec must be non-negative. - let seconds: u64 = sec.try_into().ok()?; + let seconds: u64 = sec.try_into().expect("tv_sec should fit in 64 bits"); // tv_usec must be non-negative. let microseconds: u32 = usec.try_into().ok()?; if microseconds >= 1_000_000 { diff --git a/src/tools/miri/src/shims/tls.rs b/src/tools/miri/src/shims/tls.rs index e69103b85200b..20261c5431b4e 100644 --- a/src/tools/miri/src/shims/tls.rs +++ b/src/tools/miri/src/shims/tls.rs @@ -11,7 +11,7 @@ use rustc_target::spec::Os; use crate::*; -pub type TlsKey = u128; +pub type TlsKey = u64; #[derive(Clone, Debug)] pub struct TlsEntry<'tcx> { @@ -63,18 +63,17 @@ impl<'tcx> Default for TlsData<'tcx> { impl<'tcx> TlsData<'tcx> { /// Generate a new TLS key with the given destructor. /// `key_size` determines the integer size the key has to fit in. - #[expect(clippy::arithmetic_side_effects)] pub fn create_tls_key( &mut self, dtor: Option<(ty::Instance<'tcx>, Span)>, key_size: Size, ) -> InterpResult<'tcx, TlsKey> { let new_key = self.next_key; - self.next_key += 1; + self.next_key = self.next_key.strict_add(1); self.keys.try_insert(new_key, TlsEntry { data: Default::default(), dtor }).unwrap(); trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor); - if new_key > key_size.unsigned_int_max() { + if u128::from(new_key) > key_size.unsigned_int_max() { throw_unsup_format!("we ran out of TLS key space"); } interp_ok(new_key) diff --git a/src/tools/miri/src/shims/unix/android/foreign_items.rs b/src/tools/miri/src/shims/unix/android/foreign_items.rs index 52d66c5b329b8..87adf2711c6b5 100644 --- a/src/tools/miri/src/shims/unix/android/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/android/foreign_items.rs @@ -34,7 +34,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let fd = ecx.read_scalar(fd)?.to_i32()?; let buf = ecx.read_pointer(buf)?; let count = ecx.read_target_usize(count)?; - let offset = ecx.read_scalar(offset)?.to_int(offset.layout.size)?; + let offset = ecx.read_scalar(offset)?.to_i64()?; ecx.read(fd, buf, count, Some(offset), dest)?; } "pwrite64" => { @@ -45,7 +45,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let fd = ecx.read_scalar(fd)?.to_i32()?; let buf = ecx.read_pointer(buf)?; let count = ecx.read_target_usize(n)?; - let offset = ecx.read_scalar(offset)?.to_int(offset.layout.size)?; + let offset = ecx.read_scalar(offset)?.to_i64()?; trace!("Called pwrite64({:?}, {:?}, {:?}, {:?})", fd, buf, count, offset); ecx.write(fd, buf, count, Some(offset), dest)?; } @@ -55,7 +55,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; let fd = ecx.read_scalar(fd)?.to_i32()?; - let offset = ecx.read_scalar(offset)?.to_int(offset.layout.size)?; + let offset = ecx.read_scalar(offset)?.to_i64()?; let whence = ecx.read_scalar(whence)?.to_i32()?; ecx.lseek(fd, offset, whence, dest)?; } @@ -65,7 +65,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; let fd = ecx.read_scalar(fd)?.to_i32()?; - let length = ecx.read_scalar(length)?.to_int(length.layout.size)?; + let length = ecx.read_scalar(length)?.to_i64()?; let result = ecx.ftruncate64(fd, length)?; ecx.write_scalar(result, dest)?; } diff --git a/src/tools/miri/src/shims/unix/env.rs b/src/tools/miri/src/shims/unix/env.rs index 7e06d138caa2e..cf0f79be5f91d 100644 --- a/src/tools/miri/src/shims/unix/env.rs +++ b/src/tools/miri/src/shims/unix/env.rs @@ -423,7 +423,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { return interp_ok(ecx.eval_libc("EINVAL")); } - let thread = ecx.read_scalar(thread_op)?.to_int(ecx.libc_ty_layout("pthread_t").size)?; + let thread = ecx.read_int::(thread_op)?; let thread = if thread == 0 { // Null thread ID indicates that we are querying the active thread. ecx.machine.threads.active_thread() diff --git a/src/tools/miri/src/shims/unix/fd.rs b/src/tools/miri/src/shims/unix/fd.rs index 79bbd73eb5fb8..53bbfc4118d14 100644 --- a/src/tools/miri/src/shims/unix/fd.rs +++ b/src/tools/miri/src/shims/unix/fd.rs @@ -372,7 +372,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { fd_num: i32, buf: Pointer, count: u64, - offset: Option, + offset: Option, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { let ecx = self.eval_context_mut(); @@ -423,7 +423,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { fd_num: i32, buf: Pointer, count: u64, - offset: Option, + offset: Option, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { let ecx = self.eval_context_mut(); @@ -492,7 +492,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "preadv: vectored reads with offsets aren't supported on Solaris" ) } - Some(ecx.read_scalar(offset)?.to_int(offset.layout.size)?) + Some(ecx.read_int::(offset)?) } else { None }; @@ -599,7 +599,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "pwritev: vectored writes with offsets aren't supported on Solaris" ) } - Some(ecx.read_scalar(offset)?.to_int(offset.layout.size)?) + Some(ecx.read_int::(offset)?) } else { None }; @@ -685,7 +685,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { fd: DynFileDescriptionRef, ptr: Pointer, len: u64, - offset: Option, + offset: Option, finish: DynMachineCallback<'tcx, Result>, ) -> InterpResult<'tcx> { let ecx = self.eval_context_mut(); @@ -735,7 +735,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { fd: DynFileDescriptionRef, ptr: Pointer, len: u64, - offset: Option, + offset: Option, finish: DynMachineCallback<'tcx, Result>, ) -> InterpResult<'tcx> { let ecx = self.eval_context_mut(); diff --git a/src/tools/miri/src/shims/unix/foreign_items.rs b/src/tools/miri/src/shims/unix/foreign_items.rs index c6169fb7fdfe8..a9fc1a310ab41 100644 --- a/src/tools/miri/src/shims/unix/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/foreign_items.rs @@ -17,6 +17,7 @@ use self::shims::unix::solarish::foreign_items as solarish; use crate::shims::alloc::EvalContextExt as _; use crate::shims::cpu_affinity::EvalContextExt as _; use crate::shims::files::FD_LIMIT; +use crate::shims::tls::TlsKey; use crate::shims::unix::*; use crate::{shim_sig, *}; @@ -89,21 +90,21 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { buf: &OpTy<'tcx>, buflen: &OpTy<'tcx>, ) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let errnum = this.read_scalar(errnum)?; - let buf = this.read_pointer(buf)?; - let buflen = this.read_target_usize(buflen)?; - let error = this.try_errnum_to_io_error(errnum)?; + let errnum = ecx.read_scalar(errnum)?; + let buf = ecx.read_pointer(buf)?; + let buflen = ecx.read_target_usize(buflen)?; + let error = ecx.try_errnum_to_io_error(errnum)?; let formatted = match error { Some(err) => format!("{err}"), None => format!(""), }; - let (complete, _) = this.write_os_str_to_c_str(OsStr::new(&formatted), buf, buflen)?; + let (complete, _) = ecx.write_os_str_to_c_str(OsStr::new(&formatted), buf, buflen)?; if complete { interp_ok(Scalar::from_i32(0)) } else { - interp_ok(Scalar::from_i32(this.eval_libc_i32("ERANGE"))) + interp_ok(Scalar::from_i32(ecx.eval_libc_i32("ERANGE"))) } } @@ -114,226 +115,226 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { args: &[OpTy<'tcx>], dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx, EmulateItemResult> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - if this.machine.communicate() { + if ecx.machine.communicate() { // When isolation is disabled we need to check for new host I/O events before // running any shimmed function. This is needed to ensure that the shim we // execute has up-to-date information about host readiness (as reflected // e.g. by epoll) even if the current thread never yields. // Perform a non-blocking poll for newly available I/O events from the OS. - this.poll_and_unblock(Some(Duration::ZERO))?; + ecx.poll_and_unblock(Some(Duration::ZERO))?; } // See `fn emulate_foreign_item_inner` in `shims/foreign_items.rs` for the general pattern. match link_name.as_str() { // Environment related shims "getenv" => { - let [name] = &this + let [name] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(*_) -> *_), (link_name, abi, args))?; - let result = this.getenv(name)?; - this.write_pointer(result, dest)?; + let result = ecx.getenv(name)?; + ecx.write_pointer(result, dest)?; } "unsetenv" => { - let [name] = &this + let [name] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?; - let result = this.unsetenv(name)?; - this.write_scalar(result, dest)?; + let result = ecx.unsetenv(name)?; + ecx.write_scalar(result, dest)?; } "setenv" => { - let [name, value, overwrite] = &this.check_shim_sig( + let [name, value, overwrite] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, *_, i32) -> i32), (link_name, abi, args), )?; - this.read_scalar(overwrite)?.to_i32()?; - let result = this.setenv(name, value)?; - this.write_scalar(result, dest)?; + ecx.read_scalar(overwrite)?.to_i32()?; + let result = ecx.setenv(name, value)?; + ecx.write_scalar(result, dest)?; } "getcwd" => { - let [buf, size] = &this.check_shim_sig( + let [buf, size] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, usize) -> *_), (link_name, abi, args), )?; - let result = this.getcwd(buf, size)?; - this.write_pointer(result, dest)?; + let result = ecx.getcwd(buf, size)?; + ecx.write_pointer(result, dest)?; } "gethostname" => { - let [name, len] = &this.check_shim_sig( + let [name, len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, usize) -> i32), (link_name, abi, args), )?; - let result = this.gethostname(name, len)?; - this.write_scalar(result, dest)?; + let result = ecx.gethostname(name, len)?; + ecx.write_scalar(result, dest)?; } "chdir" => { - let [path] = &this + let [path] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?; - let result = this.chdir(path)?; - this.write_scalar(result, dest)?; + let result = ecx.chdir(path)?; + ecx.write_scalar(result, dest)?; } "getpid" => { - let [] = &this.check_shim_sig( + let [] = &ecx.check_shim_sig( shim_sig!(extern "C" fn() -> libc::pid_t), (link_name, abi, args), )?; - let result = this.getpid()?; - this.write_scalar(result, dest)?; + let result = ecx.getpid()?; + ecx.write_scalar(result, dest)?; } "uname" => { // Not all Unixes have the `uname` symbol, e.g. FreeBSD does not. - this.check_target_os( + ecx.check_target_os( &[Os::Linux, Os::Android, Os::MacOs, Os::Solaris, Os::Illumos], link_name, )?; - let [uname] = &this.check_shim_sig( + let [uname] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::utsname) -> i32), (link_name, abi, args), )?; - let result = this.uname(uname, None)?; - this.write_scalar(result, dest)?; + let result = ecx.uname(uname, None)?; + ecx.write_scalar(result, dest)?; } "sysconf" => { - let [val] = &this.check_shim_sig( + let [val] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32) -> isize), (link_name, abi, args), )?; - let result = this.sysconf(val)?; - this.write_scalar(result, dest)?; + let result = ecx.sysconf(val)?; + ecx.write_scalar(result, dest)?; } // File descriptors "read" => { - let [fd, buf, count] = &this.check_shim_sig( + let [fd, buf, count] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, usize) -> isize), (link_name, abi, args), )?; - let fd = this.read_scalar(fd)?.to_i32()?; - let buf = this.read_pointer(buf)?; - let count = this.read_target_usize(count)?; - this.read(fd, buf, count, None, dest)?; + let fd = ecx.read_scalar(fd)?.to_i32()?; + let buf = ecx.read_pointer(buf)?; + let count = ecx.read_target_usize(count)?; + ecx.read(fd, buf, count, None, dest)?; } "write" => { - let [fd, buf, n] = &this.check_shim_sig( + let [fd, buf, n] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, usize) -> isize), (link_name, abi, args), )?; - let fd = this.read_scalar(fd)?.to_i32()?; - let buf = this.read_pointer(buf)?; - let count = this.read_target_usize(n)?; + let fd = ecx.read_scalar(fd)?.to_i32()?; + let buf = ecx.read_pointer(buf)?; + let count = ecx.read_target_usize(n)?; trace!("Called write({:?}, {:?}, {:?})", fd, buf, count); - this.write(fd, buf, count, None, dest)?; + ecx.write(fd, buf, count, None, dest)?; } "readv" => { - let [fd, iov, iovcnt] = &this.check_shim_sig( + let [fd, iov, iovcnt] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::iovec, i32) -> isize), (link_name, abi, args), )?; - this.readv(fd, iov, iovcnt, None, dest)?; + ecx.readv(fd, iov, iovcnt, None, dest)?; } "writev" => { - let [fd, iov, iovcnt] = &this.check_shim_sig( + let [fd, iov, iovcnt] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::iovec, i32) -> isize), (link_name, abi, args), )?; - this.writev(fd, iov, iovcnt, None, dest)?; + ecx.writev(fd, iov, iovcnt, None, dest)?; } "pread" => { - let [fd, buf, count, offset] = &this.check_shim_sig( + let [fd, buf, count, offset] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, usize, libc::off_t) -> isize), (link_name, abi, args), )?; - let fd = this.read_scalar(fd)?.to_i32()?; - let buf = this.read_pointer(buf)?; - let count = this.read_target_usize(count)?; - let offset = this.read_scalar(offset)?.to_int(offset.layout.size)?; - this.read(fd, buf, count, Some(offset), dest)?; + let fd = ecx.read_scalar(fd)?.to_i32()?; + let buf = ecx.read_pointer(buf)?; + let count = ecx.read_target_usize(count)?; + let offset = ecx.read_int::(offset)?; + ecx.read(fd, buf, count, Some(offset), dest)?; } "pwrite" => { - let [fd, buf, n, offset] = &this.check_shim_sig( + let [fd, buf, n, offset] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, usize, libc::off_t) -> isize), (link_name, abi, args), )?; - let fd = this.read_scalar(fd)?.to_i32()?; - let buf = this.read_pointer(buf)?; - let count = this.read_target_usize(n)?; - let offset = this.read_scalar(offset)?.to_int(offset.layout.size)?; + let fd = ecx.read_scalar(fd)?.to_i32()?; + let buf = ecx.read_pointer(buf)?; + let count = ecx.read_target_usize(n)?; + let offset = ecx.read_int::(offset)?; trace!("Called pwrite({:?}, {:?}, {:?}, {:?})", fd, buf, count, offset); - this.write(fd, buf, count, Some(offset), dest)?; + ecx.write(fd, buf, count, Some(offset), dest)?; } "preadv" => { - let [fd, iov, iovcnt, offset] = &this.check_shim_sig( + let [fd, iov, iovcnt, offset] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::iovec, i32, libc::off_t) -> isize), (link_name, abi, args), )?; - this.readv(fd, iov, iovcnt, Some(offset), dest)?; + ecx.readv(fd, iov, iovcnt, Some(offset), dest)?; } "pwritev" => { - let [fd, iov, iovcnt, offset] = &this.check_shim_sig( + let [fd, iov, iovcnt, offset] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::iovec, i32, libc::off_t) -> isize), (link_name, abi, args), )?; - this.writev(fd, iov, iovcnt, Some(offset), dest)?; + ecx.writev(fd, iov, iovcnt, Some(offset), dest)?; } "close" => { - let [fd] = &this + let [fd] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(i32) -> i32), (link_name, abi, args))?; - let fd = this.read_scalar(fd)?.to_i32()?; - let result = this.close(fd)?; - this.write_scalar(result, dest)?; + let fd = ecx.read_scalar(fd)?.to_i32()?; + let result = ecx.close(fd)?; + ecx.write_scalar(result, dest)?; } "fcntl" => { - let ([fd_num, cmd], varargs) = this.check_shim_sig_variadic( + let ([fd_num, cmd], varargs) = ecx.check_shim_sig_variadic( shim_sig!(extern "C" fn(i32, i32, ...) -> i32), (link_name, abi, args), )?; - let result = this.fcntl(&fd_num, &cmd, varargs)?; - this.write_scalar(result, dest)?; + let result = ecx.fcntl(&fd_num, &cmd, varargs)?; + ecx.write_scalar(result, dest)?; } "dup" => { - let [old_fd] = &this + let [old_fd] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(i32) -> i32), (link_name, abi, args))?; - let old_fd = this.read_scalar(old_fd)?.to_i32()?; - let new_fd = this.dup(old_fd)?; - this.write_scalar(new_fd, dest)?; + let old_fd = ecx.read_scalar(old_fd)?.to_i32()?; + let new_fd = ecx.dup(old_fd)?; + ecx.write_scalar(new_fd, dest)?; } "dup2" => { - let [old_fd, new_fd] = &this.check_shim_sig( + let [old_fd, new_fd] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, i32) -> i32), (link_name, abi, args), )?; - let old_fd = this.read_scalar(old_fd)?.to_i32()?; - let new_fd = this.read_scalar(new_fd)?.to_i32()?; - let result = this.dup2(old_fd, new_fd)?; - this.write_scalar(result, dest)?; + let old_fd = ecx.read_scalar(old_fd)?.to_i32()?; + let new_fd = ecx.read_scalar(new_fd)?.to_i32()?; + let result = ecx.dup2(old_fd, new_fd)?; + ecx.write_scalar(result, dest)?; } "flock" => { // Currently this function does not exist on all Unixes, e.g. on Solaris. - this.check_target_os( + ecx.check_target_os( &[Os::Linux, Os::Android, Os::FreeBsd, Os::MacOs, Os::Illumos], link_name, )?; - let [fd, op] = &this.check_shim_sig( + let [fd, op] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, i32) -> i32), (link_name, abi, args), )?; - let fd = this.read_scalar(fd)?.to_i32()?; - let op = this.read_scalar(op)?.to_i32()?; - let result = this.flock(fd, op)?; - this.write_scalar(result, dest)?; + let fd = ecx.read_scalar(fd)?.to_i32()?; + let op = ecx.read_scalar(op)?.to_i32()?; + let result = ecx.flock(fd, op)?; + ecx.write_scalar(result, dest)?; } "ioctl" => { // The type of `op` depends on the libc. :( // glibc, BSD use `unsigned long`, the rest uses `int`. - let op_is_ulong = match this.tcx.sess.target.os { + let op_is_ulong = match ecx.tcx.sess.target.os { Os::FreeBsd | Os::NetBsd | Os::MacOs => true, - Os::Linux if this.tcx.sess.target.env == Env::Gnu => true, + Os::Linux if ecx.tcx.sess.target.env == Env::Gnu => true, _ => false, }; - let ([fd, op], varargs) = this.check_shim_sig_variadic( + let ([fd, op], varargs) = ecx.check_shim_sig_variadic( if op_is_ulong { shim_sig!(extern "C" fn(i32, usize, ...) -> i32) } else { @@ -341,962 +342,994 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }, (link_name, abi, args), )?; - let result = this.ioctl(&fd, &op, varargs)?; - this.write_scalar(result, dest)?; + let result = ecx.ioctl(&fd, &op, varargs)?; + ecx.write_scalar(result, dest)?; } // File and file system access "open" => { // `open` is variadic, the third argument is only present when the second argument // has O_CREAT (or on linux O_TMPFILE, but miri doesn't support that) set - let ([path_raw, flag], varargs) = this.check_shim_sig_variadic( + let ([path_raw, flag], varargs) = ecx.check_shim_sig_variadic( shim_sig!(extern "C" fn(*_, i32, ...) -> i32), (link_name, abi, args), )?; - let result = this.open(None, &path_raw, &flag, varargs)?; - this.write_scalar(result, dest)?; + let result = ecx.open(None, &path_raw, &flag, varargs)?; + ecx.write_scalar(result, dest)?; } "openat" => { - let ([dirfd, path_raw, flag], varargs) = this.check_shim_sig_variadic( + let ([dirfd, path_raw, flag], varargs) = ecx.check_shim_sig_variadic( shim_sig!(extern "C" fn(i32, *_, i32, ...) -> i32), (link_name, abi, args), )?; - let result = this.open(Some(&dirfd), &path_raw, &flag, varargs)?; - this.write_scalar(result, dest)?; + let result = ecx.open(Some(&dirfd), &path_raw, &flag, varargs)?; + ecx.write_scalar(result, dest)?; } "unlink" => { - // FIXME: This does not have a direct test (#3179). - let [path] = &this + let [path] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?; - let result = this.unlink(path)?; - this.write_scalar(result, dest)?; + let result = ecx.unlink(path)?; + ecx.write_scalar(result, dest)?; + } + "unlinkat" => { + let [dirfd, path, flags] = &ecx.check_shim_sig( + shim_sig!(extern "C" fn(i32, *_, i32) -> i32), + (link_name, abi, args), + )?; + let result = ecx.unlinkat(dirfd, path, flags)?; + ecx.write_scalar(result, dest)?; } "symlink" => { - // FIXME: This does not have a direct test (#3179). - let [target, linkpath] = &this.check_shim_sig( + let [target, linkpath] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, *_) -> i32), (link_name, abi, args), )?; - let result = this.symlink(target, linkpath)?; - this.write_scalar(result, dest)?; + let result = ecx.symlink(target, linkpath)?; + ecx.write_scalar(result, dest)?; } "linkat" => { - let [oldfd, oldpath, newfd, newpath, flags] = &this.check_shim_sig( + let [oldfd, oldpath, newfd, newpath, flags] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, i32, *_, i32) -> i32), (link_name, abi, args), )?; - let result = this.linkat(oldfd, oldpath, newfd, newpath, flags)?; - this.write_scalar(result, dest)?; + let result = ecx.linkat(oldfd, oldpath, newfd, newpath, flags)?; + ecx.write_scalar(result, dest)?; } "fstat" => { - let [fd, buf] = &this.check_shim_sig( + let [fd, buf] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::stat) -> i32), (link_name, abi, args), )?; - let result = this.fstat(fd, buf)?; - this.write_scalar(result, dest)?; + let result = ecx.fstat(fd, buf)?; + ecx.write_scalar(result, dest)?; } "lstat" => { - let [path, buf] = &this.check_shim_sig( + let [path, buf] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, *libc::stat) -> i32), (link_name, abi, args), )?; - let result = this.lstat(path, buf)?; - this.write_scalar(result, dest)?; + let result = ecx.lstat(path, buf)?; + ecx.write_scalar(result, dest)?; } "stat" => { - let [path, buf] = &this.check_shim_sig( + let [path, buf] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, *libc::stat) -> i32), (link_name, abi, args), )?; - let result = this.stat(path, buf)?; - this.write_scalar(result, dest)?; + let result = ecx.stat(path, buf)?; + ecx.write_scalar(result, dest)?; } "fstatat" => { - let [dirfd, path, buf, flags] = &this.check_shim_sig( + let [dirfd, path, buf, flags] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, *libc::stat, i32) -> i32), (link_name, abi, args), )?; - let result = this.fstatat(dirfd, path, buf, flags)?; - this.write_scalar(result, dest)?; + let result = ecx.fstatat(dirfd, path, buf, flags)?; + ecx.write_scalar(result, dest)?; } "chmod" => { - let [path, mode] = &this.check_shim_sig( + let [path, mode] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, libc::mode_t) -> i32), (link_name, abi, args), )?; - let result = this.chmod(path, mode)?; - this.write_scalar(result, dest)?; + let result = ecx.chmod(path, mode)?; + ecx.write_scalar(result, dest)?; } "fchmod" => { - let [fd, mode] = &this.check_shim_sig( + let [fd, mode] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, libc::mode_t) -> i32), (link_name, abi, args), )?; - let result = this.fchmod(fd, mode)?; - this.write_scalar(result, dest)?; + let result = ecx.fchmod(fd, mode)?; + ecx.write_scalar(result, dest)?; } "rename" => { - let [oldpath, newpath] = &this.check_shim_sig( + let [oldpath, newpath] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, *_) -> i32), (link_name, abi, args), )?; - let result = this.rename(oldpath, newpath)?; - this.write_scalar(result, dest)?; + let result = ecx.rename(oldpath, newpath)?; + ecx.write_scalar(result, dest)?; } "mkdir" => { - let [path, mode] = &this.check_shim_sig( + let [path, mode] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, libc::mode_t) -> i32), (link_name, abi, args), )?; - let result = this.mkdir(path, mode)?; - this.write_scalar(result, dest)?; + ecx.mkdir(None, path, mode, dest)?; + } + "mkdirat" => { + let [dirfd, path, mode] = &ecx.check_shim_sig( + shim_sig!(extern "C" fn(i32, *_, libc::mode_t) -> i32), + (link_name, abi, args), + )?; + ecx.mkdir(Some(dirfd), path, mode, dest)?; } "rmdir" => { - let [path] = &this + let [path] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?; - let result = this.rmdir(path)?; - this.write_scalar(result, dest)?; + let result = ecx.rmdir(path)?; + ecx.write_scalar(result, dest)?; } "opendir" => { - let [name] = &this + let [name] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(*_) -> *_), (link_name, abi, args))?; - let result = this.opendir(name)?; - this.write_scalar(result, dest)?; + let result = ecx.opendir(name)?; + ecx.write_scalar(result, dest)?; } "closedir" => { - let [dirp] = &this + let [dirp] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?; - let result = this.closedir(dirp)?; - this.write_scalar(result, dest)?; + let result = ecx.closedir(dirp)?; + ecx.write_scalar(result, dest)?; } "readdir" => { - let [dirp] = &this + let [dirp] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(*_) -> *_), (link_name, abi, args))?; - this.readdir(dirp, dest, "dirent")?; + ecx.readdir(dirp, dest, "dirent")?; } "dirfd" => { - let [dirp] = &this + let [dirp] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?; - this.dirfd(dirp, dest)?; + ecx.dirfd(dirp, dest)?; } "lseek" => { - let [fd, offset, whence] = &this.check_shim_sig( + let [fd, offset, whence] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, libc::off_t, i32) -> libc::off_t), (link_name, abi, args), )?; - let fd = this.read_scalar(fd)?.to_i32()?; - let offset = this.read_scalar(offset)?.to_int(offset.layout.size)?; - let whence = this.read_scalar(whence)?.to_i32()?; - this.lseek(fd, offset, whence, dest)?; + let fd = ecx.read_scalar(fd)?.to_i32()?; + let offset = ecx.read_int::(offset)?; + let whence = ecx.read_scalar(whence)?.to_i32()?; + ecx.lseek(fd, offset, whence, dest)?; } "ftruncate" => { - let [fd, length] = &this.check_shim_sig( + let [fd, length] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, libc::off_t) -> i32), (link_name, abi, args), )?; - let fd = this.read_scalar(fd)?.to_i32()?; - let length = this.read_scalar(length)?.to_int(length.layout.size)?; - let result = this.ftruncate64(fd, length)?; - this.write_scalar(result, dest)?; + let fd = ecx.read_scalar(fd)?.to_i32()?; + let length = ecx.read_int::(length)?; + let result = ecx.ftruncate64(fd, length)?; + ecx.write_scalar(result, dest)?; } "fsync" => { - let [fd] = &this + let [fd] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(i32) -> i32), (link_name, abi, args))?; - let result = this.fsync(fd)?; - this.write_scalar(result, dest)?; + let result = ecx.fsync(fd)?; + ecx.write_scalar(result, dest)?; } "fdatasync" => { // fdatasync is not supported by macos. - this.check_target_os( + ecx.check_target_os( &[Os::Linux, Os::FreeBsd, Os::NetBsd, Os::Solaris, Os::Illumos, Os::Android], link_name, )?; - let [fd] = &this + let [fd] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(i32) -> i32), (link_name, abi, args))?; - let result = this.fdatasync(fd)?; - this.write_scalar(result, dest)?; + let result = ecx.fdatasync(fd)?; + ecx.write_scalar(result, dest)?; } "futimens" => { - let [fd, times] = &this.check_shim_sig( + let [fd, times] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::timespec) -> i32), (link_name, abi, args), )?; - let result = this.futimens(fd, times)?; - this.write_scalar(result, dest)?; + let result = ecx.futimens(fd, times)?; + ecx.write_scalar(result, dest)?; } "utimensat" => { - let [dirfd, path, times, flags] = &this.check_shim_sig( + let [dirfd, path, times, flags] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, *libc::timespec, i32) -> i32), (link_name, abi, args), )?; - let result = this.utimensat(dirfd, path, times, flags)?; - this.write_scalar(result, dest)?; + let result = ecx.utimensat(dirfd, path, times, flags)?; + ecx.write_scalar(result, dest)?; } "readlink" => { - let [pathname, buf, bufsize] = &this.check_shim_sig( + let [pathname, buf, bufsize] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, *_, usize) -> isize), (link_name, abi, args), )?; - let result = this.readlink(pathname, buf, bufsize)?; - this.write_scalar(Scalar::from_target_isize(result, this), dest)?; + let result = ecx.readlink(pathname, buf, bufsize)?; + ecx.write_scalar(Scalar::from_target_isize(result, ecx), dest)?; } "posix_fadvise" => { - let [fd, offset, len, advice] = &this.check_shim_sig( + let [fd, offset, len, advice] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, libc::off_t, libc::off_t, i32) -> i32), (link_name, abi, args), )?; - this.read_scalar(fd)?.to_i32()?; - this.read_scalar(offset)?.to_int(offset.layout.size)?; - this.read_scalar(len)?.to_int(len.layout.size)?; - this.read_scalar(advice)?.to_i32()?; + ecx.read_scalar(fd)?.to_i32()?; + ecx.read_int::(offset)?; + ecx.read_int::(len)?; + ecx.read_scalar(advice)?.to_i32()?; // fadvise is only informational, we can ignore it. - this.write_int(0, dest)?; + ecx.write_int(0, dest)?; } "posix_fallocate" => { // posix_fallocate is not supported by macos. - this.check_target_os( + ecx.check_target_os( &[Os::Linux, Os::FreeBsd, Os::Solaris, Os::Illumos, Os::Android], link_name, )?; - let [fd, offset, len] = &this.check_shim_sig( + let [fd, offset, len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, libc::off_t, libc::off_t) -> i32), (link_name, abi, args), )?; - let fd = this.read_scalar(fd)?.to_i32()?; + let fd = ecx.read_scalar(fd)?.to_i32()?; // We don't support platforms which have libc::off_t bigger than 64 bits. - let offset = - i64::try_from(this.read_scalar(offset)?.to_int(offset.layout.size)?).unwrap(); - let len = i64::try_from(this.read_scalar(len)?.to_int(len.layout.size)?).unwrap(); + let offset = ecx.read_int::(offset)?; + let len = ecx.read_int::(len)?; - let result = this.posix_fallocate(fd, offset, len)?; - this.write_scalar(result, dest)?; + let result = ecx.posix_fallocate(fd, offset, len)?; + ecx.write_scalar(result, dest)?; } "realpath" => { - let [path, resolved_path] = &this.check_shim_sig( + let [path, resolved_path] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, *_) -> *_), (link_name, abi, args), )?; - let result = this.realpath(path, resolved_path)?; - this.write_scalar(result, dest)?; + let result = ecx.realpath(path, resolved_path)?; + ecx.write_scalar(result, dest)?; } "mkstemp" => { - let [template] = &this + let [template] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?; - let result = this.mkstemp(template)?; - this.write_scalar(result, dest)?; + let result = ecx.mkstemp(template)?; + ecx.write_scalar(result, dest)?; } // Poll "poll" => { - let [fds, nfds, timeout] = &this.check_shim_sig( + let [fds, nfds, timeout] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pollfd, libc::nfds_t, i32) -> i32), (link_name, abi, args), )?; - this.poll(fds, nfds, timeout, dest)?; + ecx.poll(fds, nfds, timeout, dest)?; } // Sockets and pipes "socketpair" => { - let [domain, type_, protocol, sv] = &this.check_shim_sig( + let [domain, type_, protocol, sv] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, i32, i32, *i32) -> i32), (link_name, abi, args), )?; - let result = this.socketpair(domain, type_, protocol, sv)?; - this.write_scalar(result, dest)?; + let result = ecx.socketpair(domain, type_, protocol, sv)?; + ecx.write_scalar(result, dest)?; } "pipe" => { - let [pipefd] = &this.check_shim_sig( + let [pipefd] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*i32) -> i32), (link_name, abi, args), )?; - let result = this.pipe2(pipefd, /*flags*/ None)?; - this.write_scalar(result, dest)?; + let result = ecx.pipe2(pipefd, /*flags*/ None)?; + ecx.write_scalar(result, dest)?; } "pipe2" => { // Currently this function does not exist on all Unixes, e.g. on macOS. - this.check_target_os( + ecx.check_target_os( &[Os::Linux, Os::Android, Os::FreeBsd, Os::Solaris, Os::Illumos], link_name, )?; - let [pipefd, flags] = &this.check_shim_sig( + let [pipefd, flags] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*i32, i32) -> i32), (link_name, abi, args), )?; - let result = this.pipe2(pipefd, Some(flags))?; - this.write_scalar(result, dest)?; + let result = ecx.pipe2(pipefd, Some(flags))?; + ecx.write_scalar(result, dest)?; } "socket" => { - let [domain, type_, protocol] = &this.check_shim_sig( + let [domain, type_, protocol] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, i32, i32) -> i32), (link_name, abi, args), )?; - let result = this.socket(domain, type_, protocol)?; - this.write_scalar(result, dest)?; + let result = ecx.socket(domain, type_, protocol)?; + ecx.write_scalar(result, dest)?; } "bind" => { - let [socket, address, address_len] = &this.check_shim_sig( + let [socket, address, address_len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::sockaddr, libc::socklen_t) -> i32), (link_name, abi, args), )?; - let result = this.bind(socket, address, address_len)?; - this.write_scalar(result, dest)?; + let result = ecx.bind(socket, address, address_len)?; + ecx.write_scalar(result, dest)?; } "listen" => { - let [socket, backlog] = &this.check_shim_sig( + let [socket, backlog] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, i32) -> i32), (link_name, abi, args), )?; - let result = this.listen(socket, backlog)?; - this.write_scalar(result, dest)?; + let result = ecx.listen(socket, backlog)?; + ecx.write_scalar(result, dest)?; } "accept" => { - let [socket, address, address_len] = &this.check_shim_sig( + let [socket, address, address_len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::sockaddr, *libc::socklen_t) -> i32), (link_name, abi, args), )?; - this.accept4(socket, address, address_len, /* flags */ None, dest)?; + ecx.accept4(socket, address, address_len, /* flags */ None, dest)?; } "accept4" => { - let [socket, address, address_len, flags] = &this.check_shim_sig( + let [socket, address, address_len, flags] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::sockaddr, *libc::socklen_t, i32) -> i32), (link_name, abi, args), )?; - this.accept4(socket, address, address_len, Some(flags), dest)?; + ecx.accept4(socket, address, address_len, Some(flags), dest)?; } "connect" => { - let [socket, address, address_len] = &this.check_shim_sig( + let [socket, address, address_len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::sockaddr, libc::socklen_t) -> i32), (link_name, abi, args), )?; - this.connect(socket, address, address_len, dest)?; + ecx.connect(socket, address, address_len, dest)?; } "send" => { - let [socket, buffer, length, flags] = &this.check_shim_sig( + let [socket, buffer, length, flags] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, libc::size_t, i32) -> libc::ssize_t), (link_name, abi, args), )?; - this.send(socket, buffer, length, flags, /* dest_addr */ None, dest)?; + ecx.send(socket, buffer, length, flags, /* dest_addr */ None, dest)?; } "sendto" => { - let [socket, buffer, length, flags, dest_addr, dest_addr_len] = &this.check_shim_sig( + let [socket, buffer, length, flags, dest_addr, dest_addr_len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, libc::size_t, i32, *libc::sockaddr, libc::socklen_t) -> libc::ssize_t), (link_name, abi, args), )?; - this.send(socket, buffer, length, flags, Some((dest_addr, dest_addr_len)), dest)?; + ecx.send(socket, buffer, length, flags, Some((dest_addr, dest_addr_len)), dest)?; } "recv" => { - let [socket, buffer, length, flags] = &this.check_shim_sig( + let [socket, buffer, length, flags] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, libc::size_t, i32) -> libc::ssize_t), (link_name, abi, args), )?; - this.recv(socket, buffer, length, flags, /* dest_addr */ None, dest)?; + ecx.recv(socket, buffer, length, flags, /* dest_addr */ None, dest)?; } "recvfrom" => { - let [socket, buffer, length, flags, dest_addr, dest_addr_len] = &this.check_shim_sig( + let [socket, buffer, length, flags, dest_addr, dest_addr_len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, libc::size_t, i32, *libc::sockaddr, *libc::socklen_t) -> libc::ssize_t), (link_name, abi, args), )?; - this.recv(socket, buffer, length, flags, Some((dest_addr, dest_addr_len)), dest)?; + ecx.recv(socket, buffer, length, flags, Some((dest_addr, dest_addr_len)), dest)?; } "setsockopt" => { - let [socket, level, option_name, option_value, option_len] = &this.check_shim_sig( + let [socket, level, option_name, option_value, option_len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, i32, i32, *_, libc::socklen_t) -> i32), (link_name, abi, args), )?; let result = - this.setsockopt(socket, level, option_name, option_value, option_len)?; - this.write_scalar(result, dest)?; + ecx.setsockopt(socket, level, option_name, option_value, option_len)?; + ecx.write_scalar(result, dest)?; } "getsockopt" => { - let [socket, level, option_name, option_value, option_len] = &this.check_shim_sig( - shim_sig!(extern "C" fn(i32, i32, i32, *_, *_) -> i32), + let [socket, level, option_name, option_value, option_len] = &ecx.check_shim_sig( + shim_sig!(extern "C" fn(i32, i32, i32, *_, *libc::socklen_t) -> i32), (link_name, abi, args), )?; let result = - this.getsockopt(socket, level, option_name, option_value, option_len)?; - this.write_scalar(result, dest)?; + ecx.getsockopt(socket, level, option_name, option_value, option_len)?; + ecx.write_scalar(result, dest)?; } "getsockname" => { - let [socket, address, address_len] = &this.check_shim_sig( + let [socket, address, address_len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::sockaddr, *libc::socklen_t) -> i32), (link_name, abi, args), )?; - let result = this.getsockname(socket, address, address_len)?; - this.write_scalar(result, dest)?; + let result = ecx.getsockname(socket, address, address_len)?; + ecx.write_scalar(result, dest)?; } "getpeername" => { - let [socket, address, address_len] = &this.check_shim_sig( + let [socket, address, address_len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::sockaddr, *libc::socklen_t) -> i32), (link_name, abi, args), )?; - this.getpeername(socket, address, address_len, dest)?; + ecx.getpeername(socket, address, address_len, dest)?; } "shutdown" => { - let [sockfd, how] = &this.check_shim_sig( + let [sockfd, how] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, i32) -> i32), (link_name, abi, args), )?; - let result = this.shutdown(sockfd, how)?; - this.write_scalar(result, dest)?; + let result = ecx.shutdown(sockfd, how)?; + ecx.write_scalar(result, dest)?; } "getaddrinfo" => { - let [node, service, hints, res] = &this.check_shim_sig( - shim_sig!(extern "C" fn(*_, *_, *_, **_) -> i32), + let [node, service, hints, res] = &ecx.check_shim_sig( + shim_sig!(extern "C" fn(*_, *_, *libc::addrinfo, **libc::addrinfo) -> i32), (link_name, abi, args), )?; - let result = this.getaddrinfo(node, service, hints, res)?; - this.write_scalar(result, dest)?; + let result = ecx.getaddrinfo(node, service, hints, res)?; + ecx.write_scalar(result, dest)?; } "freeaddrinfo" => { - let [res] = &this - .check_shim_sig(shim_sig!(extern "C" fn(*_) -> ()), (link_name, abi, args))?; - this.freeaddrinfo(res)?; + let [res] = &ecx.check_shim_sig( + shim_sig!(extern "C" fn(*libc::addrinfo) -> ()), + (link_name, abi, args), + )?; + ecx.freeaddrinfo(res)?; } // Time "gettimeofday" => { - let [tv, tz] = &this.check_shim_sig( + let [tv, tz] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::timeval, *libc::timezone) -> i32), (link_name, abi, args), )?; - let result = this.gettimeofday(tv, tz)?; - this.write_scalar(result, dest)?; + let result = ecx.gettimeofday(tv, tz)?; + ecx.write_scalar(result, dest)?; } "localtime_r" => { - let [timep, result_op] = &this.check_shim_sig( + let [timep, result_op] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::time_t, *libc::tm) -> *libc::tm), (link_name, abi, args), )?; - let result = this.localtime_r(timep, result_op)?; - this.write_pointer(result, dest)?; + let result = ecx.localtime_r(timep, result_op)?; + ecx.write_pointer(result, dest)?; } "clock_gettime" => { - let [clk_id, tp] = &this.check_shim_sig( + let [clk_id, tp] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::clockid_t, *libc::timespec) -> i32), (link_name, abi, args), )?; - this.clock_gettime(clk_id, tp, dest)?; + ecx.clock_gettime(clk_id, tp, dest)?; } // Allocation "posix_memalign" => { - let [memptr, align, size] = &this.check_shim_sig( + let [memptr, align, size] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(**_, usize, usize) -> i32), (link_name, abi, args), )?; - let result = this.posix_memalign(memptr, align, size)?; - this.write_scalar(result, dest)?; + let result = ecx.posix_memalign(memptr, align, size)?; + ecx.write_scalar(result, dest)?; } "mmap" => { - let [addr, length, prot, flags, fd, offset] = &this.check_shim_sig( + let [addr, length, prot, flags, fd, offset] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, usize, i32, i32, i32, libc::off_t) -> *_), (link_name, abi, args), )?; - let offset = this.read_scalar(offset)?.to_int(this.libc_ty_layout("off_t").size)?; - let ptr = this.mmap(addr, length, prot, flags, fd, offset)?; - this.write_scalar(ptr, dest)?; + let offset = ecx.read_int::(offset)?; + let ptr = ecx.mmap(addr, length, prot, flags, fd, offset)?; + ecx.write_scalar(ptr, dest)?; } "munmap" => { - let [addr, length] = &this.check_shim_sig( + let [addr, length] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, usize) -> i32), (link_name, abi, args), )?; - let result = this.munmap(addr, length)?; - this.write_scalar(result, dest)?; + let result = ecx.munmap(addr, length)?; + ecx.write_scalar(result, dest)?; } "mprotect" => { - let [addr, length, prot] = &this.check_shim_sig( + let [addr, length, prot] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, usize, i32) -> i32), (link_name, abi, args), )?; - let result = this.mprotect(addr, length, prot)?; - this.write_scalar(result, dest)?; + let result = ecx.mprotect(addr, length, prot)?; + ecx.write_scalar(result, dest)?; } "madvise" => { - let [addr, length, advice] = &this.check_shim_sig( + let [addr, length, advice] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, usize, i32) -> i32), (link_name, abi, args), )?; - let result = this.madvise(addr, length, advice)?; - this.write_scalar(result, dest)?; + let result = ecx.madvise(addr, length, advice)?; + ecx.write_scalar(result, dest)?; } "reallocarray" => { // Currently this function does not exist on all Unixes, e.g. on macOS. - this.check_target_os(&[Os::Linux, Os::FreeBsd, Os::Android], link_name)?; + ecx.check_target_os(&[Os::Linux, Os::FreeBsd, Os::Android], link_name)?; - let [ptr, nmemb, size] = &this.check_shim_sig( + let [ptr, nmemb, size] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, usize, usize) -> *_), (link_name, abi, args), )?; - let ptr = this.read_pointer(ptr)?; - let nmemb = this.read_target_usize(nmemb)?; - let size = this.read_target_usize(size)?; + let ptr = ecx.read_pointer(ptr)?; + let nmemb = ecx.read_target_usize(nmemb)?; + let size = ecx.read_target_usize(size)?; // reallocarray checks a possible overflow and returns ENOMEM // if that happens. // // Linux: https://www.unix.com/man-page/linux/3/reallocarray/ // FreeBSD: https://man.freebsd.org/cgi/man.cgi?query=reallocarray - match this.compute_size_in_bytes(Size::from_bytes(size), nmemb) { + match ecx.compute_size_in_bytes(Size::from_bytes(size), nmemb) { None => { - this.set_last_error(LibcError("ENOMEM"))?; - this.write_int(0, dest)?; + ecx.set_last_error(LibcError("ENOMEM"))?; + ecx.write_int(0, dest)?; } Some(len) => { - let res = this.realloc(ptr, len.bytes())?; - this.write_pointer(res, dest)?; + let res = ecx.realloc(ptr, len.bytes())?; + ecx.write_pointer(res, dest)?; } } } "aligned_alloc" => { // This is a C11 function, we assume all Unixes have it. // (MSVC explicitly does not support this.) - let [align, size] = &this.check_shim_sig( + let [align, size] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(usize, usize) -> *_), (link_name, abi, args), )?; - let res = this.aligned_alloc(align, size)?; - this.write_pointer(res, dest)?; + let res = ecx.aligned_alloc(align, size)?; + ecx.write_pointer(res, dest)?; } // Dynamic symbol loading "dlsym" => { - let [handle, symbol] = &this.check_shim_sig( + let [handle, symbol] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, *_) -> *_), (link_name, abi, args), )?; - this.read_target_usize(handle)?; - let symbol = this.read_pointer(symbol)?; - let name = this.read_c_str(symbol)?; + ecx.read_target_usize(handle)?; + let symbol = ecx.read_pointer(symbol)?; + let name = ecx.read_c_str(symbol)?; let Ok(name) = str::from_utf8(name) else { throw_unsup_format!("dlsym: non UTF-8 symbol name not supported") }; - if this.is_dyn_sym(name) { - let ptr = this.fn_ptr(FnVal::Other(DynSym::from_str(name))); - this.write_pointer(ptr, dest)?; - } else if let Some(&ptr) = this.machine.extern_statics.get(&Symbol::intern(name)) { - this.write_pointer(ptr, dest)?; + if ecx.is_dyn_sym(name) { + let ptr = ecx.fn_ptr(FnVal::Other(DynSym::from_str(name))); + ecx.write_pointer(ptr, dest)?; + } else if let Some(&ptr) = ecx.machine.extern_statics.get(&Symbol::intern(name)) { + ecx.write_pointer(ptr, dest)?; } else { - this.write_int(0, dest)?; + ecx.write_int(0, dest)?; } } // Thread-local storage "pthread_key_create" => { - let [key, dtor] = &this.check_shim_sig( + let [key, dtor] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_key_t, fn(..) -> _) -> i32), (link_name, abi, args), )?; - let key_place = this.deref_pointer(key)?; - let dtor = this.read_pointer(dtor)?; + let key_place = ecx.deref_pointer(key)?; + let dtor = ecx.read_pointer(dtor)?; // Extract the function type out of the signature (that seems easier than constructing it ourselves). - let dtor = if !this.ptr_is_null(dtor)? { + let dtor = if !ecx.ptr_is_null(dtor)? { Some(( - this.get_ptr_fn(dtor)?.as_instance()?, - this.machine.current_user_relevant_span(), + ecx.get_ptr_fn(dtor)?.as_instance()?, + ecx.machine.current_user_relevant_span(), )) } else { None }; // Create key and write it into the memory where `key_ptr` wants it. - let key = this.machine.tls.create_tls_key(dtor, key_place.layout.size)?; - this.write_scalar(Scalar::from_uint(key, key_place.layout.size), &key_place)?; + let key = ecx.machine.tls.create_tls_key(dtor, key_place.layout.size)?; + ecx.write_int(key, &key_place)?; // Return success (`0`). - this.write_int(0, dest)?; + ecx.write_int(0, dest)?; } "pthread_key_delete" => { - let [key] = &this.check_shim_sig( + let [key] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::pthread_key_t) -> i32), (link_name, abi, args), )?; - let key = this.read_scalar(key)?.to_bits(key.layout.size)?; - this.machine.tls.delete_tls_key(key)?; + let key = ecx.read_int::(key)?; + ecx.machine.tls.delete_tls_key(key)?; // Return success (0) - this.write_int(0, dest)?; + ecx.write_int(0, dest)?; } "pthread_getspecific" => { - let [key] = &this.check_shim_sig( + let [key] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::pthread_key_t) -> *_), (link_name, abi, args), )?; - let key = this.read_scalar(key)?.to_bits(key.layout.size)?; - let active_thread = this.active_thread(); - let ptr = this.machine.tls.load_tls_key(key, active_thread)?; - this.write_pointer(ptr, dest)?; + let key = ecx.read_int::(key)?; + let active_thread = ecx.active_thread(); + let ptr = ecx.machine.tls.load_tls_key(key, active_thread)?; + ecx.write_pointer(ptr, dest)?; } "pthread_setspecific" => { - let [key, new_ptr] = &this.check_shim_sig( + let [key, new_ptr] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::pthread_key_t, *_) -> i32), (link_name, abi, args), )?; - let key = this.read_scalar(key)?.to_bits(key.layout.size)?; - let active_thread = this.active_thread(); - let new_data = this.read_pointer(new_ptr)?; - this.machine.tls.store_tls_key(key, active_thread, new_data)?; + let key = ecx.read_int::(key)?; + let active_thread = ecx.active_thread(); + let new_data = ecx.read_pointer(new_ptr)?; + ecx.machine.tls.store_tls_key(key, active_thread, new_data)?; // Return success (`0`). - this.write_int(0, dest)?; + ecx.write_int(0, dest)?; } // Synchronization primitives "pthread_mutexattr_init" => { - let [attr] = &this.check_shim_sig( + let [attr] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_mutexattr_t) -> i32), (link_name, abi, args), )?; - this.pthread_mutexattr_init(attr)?; - this.write_int(0, dest)?; + ecx.pthread_mutexattr_init(attr)?; + ecx.write_int(0, dest)?; } "pthread_mutexattr_settype" => { - let [attr, kind] = &this.check_shim_sig( + let [attr, kind] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_mutexattr_t, i32) -> i32), (link_name, abi, args), )?; - let result = this.pthread_mutexattr_settype(attr, kind)?; - this.write_scalar(result, dest)?; + let result = ecx.pthread_mutexattr_settype(attr, kind)?; + ecx.write_scalar(result, dest)?; } "pthread_mutexattr_destroy" => { - let [attr] = &this.check_shim_sig( + let [attr] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_mutexattr_t) -> i32), (link_name, abi, args), )?; - this.pthread_mutexattr_destroy(attr)?; - this.write_int(0, dest)?; + ecx.pthread_mutexattr_destroy(attr)?; + ecx.write_int(0, dest)?; } "pthread_mutex_init" => { - let [mutex, attr] = &this.check_shim_sig( + let [mutex, attr] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_mutex_t, *libc::pthread_mutexattr_t) -> i32), (link_name, abi, args), )?; - this.pthread_mutex_init(mutex, attr)?; - this.write_int(0, dest)?; + ecx.pthread_mutex_init(mutex, attr)?; + ecx.write_int(0, dest)?; } "pthread_mutex_lock" => { - let [mutex] = &this.check_shim_sig( + let [mutex] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_mutex_t) -> i32), (link_name, abi, args), )?; - this.pthread_mutex_lock(mutex, dest)?; + ecx.pthread_mutex_lock(mutex, dest)?; } "pthread_mutex_trylock" => { - let [mutex] = &this.check_shim_sig( + let [mutex] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_mutex_t) -> i32), (link_name, abi, args), )?; - let result = this.pthread_mutex_trylock(mutex)?; - this.write_scalar(result, dest)?; + let result = ecx.pthread_mutex_trylock(mutex)?; + ecx.write_scalar(result, dest)?; } "pthread_mutex_unlock" => { - let [mutex] = &this.check_shim_sig( + let [mutex] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_mutex_t) -> i32), (link_name, abi, args), )?; - let result = this.pthread_mutex_unlock(mutex)?; - this.write_scalar(result, dest)?; + let result = ecx.pthread_mutex_unlock(mutex)?; + ecx.write_scalar(result, dest)?; } "pthread_mutex_destroy" => { - let [mutex] = &this.check_shim_sig( + let [mutex] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_mutex_t) -> i32), (link_name, abi, args), )?; - this.pthread_mutex_destroy(mutex)?; - this.write_int(0, dest)?; + ecx.pthread_mutex_destroy(mutex)?; + ecx.write_int(0, dest)?; } "pthread_rwlock_rdlock" => { - let [rwlock] = &this.check_shim_sig( + let [rwlock] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_rwlock_t) -> i32), (link_name, abi, args), )?; - this.pthread_rwlock_rdlock(rwlock, dest)?; + ecx.pthread_rwlock_rdlock(rwlock, dest)?; } "pthread_rwlock_tryrdlock" => { - let [rwlock] = &this.check_shim_sig( + let [rwlock] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_rwlock_t) -> i32), (link_name, abi, args), )?; - let result = this.pthread_rwlock_tryrdlock(rwlock)?; - this.write_scalar(result, dest)?; + let result = ecx.pthread_rwlock_tryrdlock(rwlock)?; + ecx.write_scalar(result, dest)?; } "pthread_rwlock_wrlock" => { - let [rwlock] = &this.check_shim_sig( + let [rwlock] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_rwlock_t) -> i32), (link_name, abi, args), )?; - this.pthread_rwlock_wrlock(rwlock, dest)?; + ecx.pthread_rwlock_wrlock(rwlock, dest)?; } "pthread_rwlock_trywrlock" => { - let [rwlock] = &this.check_shim_sig( + let [rwlock] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_rwlock_t) -> i32), (link_name, abi, args), )?; - let result = this.pthread_rwlock_trywrlock(rwlock)?; - this.write_scalar(result, dest)?; + let result = ecx.pthread_rwlock_trywrlock(rwlock)?; + ecx.write_scalar(result, dest)?; } "pthread_rwlock_unlock" => { - let [rwlock] = &this.check_shim_sig( + let [rwlock] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_rwlock_t) -> i32), (link_name, abi, args), )?; - this.pthread_rwlock_unlock(rwlock)?; - this.write_int(0, dest)?; + ecx.pthread_rwlock_unlock(rwlock)?; + ecx.write_int(0, dest)?; } "pthread_rwlock_destroy" => { - let [rwlock] = &this.check_shim_sig( + let [rwlock] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_rwlock_t) -> i32), (link_name, abi, args), )?; - this.pthread_rwlock_destroy(rwlock)?; - this.write_int(0, dest)?; + ecx.pthread_rwlock_destroy(rwlock)?; + ecx.write_int(0, dest)?; } "pthread_condattr_init" => { - let [attr] = &this.check_shim_sig( + let [attr] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_condattr_t) -> i32), (link_name, abi, args), )?; - this.pthread_condattr_init(attr)?; - this.write_int(0, dest)?; + ecx.pthread_condattr_init(attr)?; + ecx.write_int(0, dest)?; } "pthread_condattr_setclock" => { - let [attr, clock_id] = &this.check_shim_sig( + let [attr, clock_id] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_condattr_t, i32) -> i32), (link_name, abi, args), )?; - let result = this.pthread_condattr_setclock(attr, clock_id)?; - this.write_scalar(result, dest)?; + let result = ecx.pthread_condattr_setclock(attr, clock_id)?; + ecx.write_scalar(result, dest)?; } "pthread_condattr_getclock" => { - let [attr, clock_id] = &this.check_shim_sig( + let [attr, clock_id] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_condattr_t, *libc::clockid_t) -> i32), (link_name, abi, args), )?; - this.pthread_condattr_getclock(attr, clock_id)?; - this.write_int(0, dest)?; + ecx.pthread_condattr_getclock(attr, clock_id)?; + ecx.write_int(0, dest)?; } "pthread_condattr_destroy" => { - let [attr] = &this.check_shim_sig( + let [attr] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_condattr_t) -> i32), (link_name, abi, args), )?; - this.pthread_condattr_destroy(attr)?; - this.write_int(0, dest)?; + ecx.pthread_condattr_destroy(attr)?; + ecx.write_int(0, dest)?; } "pthread_cond_init" => { - let [cond, attr] = &this.check_shim_sig( + let [cond, attr] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_cond_t, *libc::pthread_condattr_t) -> i32), (link_name, abi, args), )?; - this.pthread_cond_init(cond, attr)?; - this.write_int(0, dest)?; + ecx.pthread_cond_init(cond, attr)?; + ecx.write_int(0, dest)?; } "pthread_cond_signal" => { - let [cond] = &this.check_shim_sig( + let [cond] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_cond_t) -> i32), (link_name, abi, args), )?; - this.pthread_cond_signal(cond)?; - this.write_int(0, dest)?; + ecx.pthread_cond_signal(cond)?; + ecx.write_int(0, dest)?; } "pthread_cond_broadcast" => { - let [cond] = &this.check_shim_sig( + let [cond] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_cond_t) -> i32), (link_name, abi, args), )?; - this.pthread_cond_broadcast(cond)?; - this.write_int(0, dest)?; + ecx.pthread_cond_broadcast(cond)?; + ecx.write_int(0, dest)?; } "pthread_cond_wait" => { - let [cond, mutex] = &this.check_shim_sig( + let [cond, mutex] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_cond_t, *libc::pthread_mutex_t) -> i32), (link_name, abi, args), )?; - this.pthread_cond_wait(cond, mutex, dest)?; + ecx.pthread_cond_wait(cond, mutex, dest)?; } "pthread_cond_timedwait" => { - let [cond, mutex, abstime] = &this.check_shim_sig( + let [cond, mutex, abstime] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_cond_t, *libc::pthread_mutex_t, *libc::timespec) -> i32), (link_name, abi, args), )?; - this.pthread_cond_timedwait( + ecx.pthread_cond_timedwait( cond, mutex, abstime, dest, /* macos_relative_np */ false, )?; } "pthread_cond_destroy" => { - let [cond] = &this.check_shim_sig( + let [cond] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_cond_t) -> i32), (link_name, abi, args), )?; - this.pthread_cond_destroy(cond)?; - this.write_int(0, dest)?; + ecx.pthread_cond_destroy(cond)?; + ecx.write_int(0, dest)?; } "sem_init" => { - let [sem, pshared, value] = &this.check_shim_sig( + let [sem, pshared, value] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::sem_t, i32, u32) -> i32), (link_name, abi, args), )?; - this.pthread_sem_init(sem, pshared, value, dest)?; + ecx.pthread_sem_init(sem, pshared, value, dest)?; } "sem_wait" => { - let [sem] = &this.check_shim_sig( + let [sem] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::sem_t) -> i32), (link_name, abi, args), )?; - this.pthread_sem_wait(sem, dest)?; + ecx.pthread_sem_wait(sem, dest)?; } "sem_timedwait" => { - let [sem, abs_timeout] = &this.check_shim_sig( + let [sem, abs_timeout] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::sem_t, *libc::timespec) -> i32), (link_name, abi, args), )?; - this.pthread_sem_timedwait(sem, abs_timeout, dest)?; + ecx.pthread_sem_timedwait(sem, abs_timeout, dest)?; } "sem_post" => { - let [sem] = &this.check_shim_sig( + let [sem] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::sem_t) -> i32), (link_name, abi, args), )?; - this.pthread_sem_post(sem, dest)?; + ecx.pthread_sem_post(sem, dest)?; } "sem_destroy" => { - let [sem] = &this.check_shim_sig( + let [sem] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::sem_t) -> i32), (link_name, abi, args), )?; - this.pthread_sem_destroy(sem, dest)?; + ecx.pthread_sem_destroy(sem, dest)?; } // Threading + "pthread_attr_init" => { + let [attr] = &ecx.check_shim_sig( + shim_sig!(extern "C" fn(*libc::pthread_attr_t) -> i32), + (link_name, abi, args), + )?; + ecx.pthread_attr_init(attr, dest)?; + } + "pthread_attr_destroy" => { + let [attr] = &ecx.check_shim_sig( + shim_sig!(extern "C" fn(*libc::pthread_attr_t) -> i32), + (link_name, abi, args), + )?; + ecx.pthread_attr_destroy(attr, dest)?; + } + "pthread_attr_setstacksize" => { + let [attr, stack_size] = &ecx.check_shim_sig( + shim_sig!(extern "C" fn(*libc::pthread_attr_t, usize) -> i32), + (link_name, abi, args), + )?; + ecx.pthread_attr_setstacksize(attr, stack_size, dest)?; + } "pthread_create" => { - let [thread, attr, start, arg] = &this.check_shim_sig( - shim_sig!(extern "C" fn(*libc::pthread_t, *_, fn(..) -> _, *_) -> i32), + let [thread, attr, start, arg] = &ecx.check_shim_sig( + shim_sig!( + extern "C" fn(*libc::pthread_t, *libc::pthread_attr_t, fn(..) -> _, *_) -> i32 + ), (link_name, abi, args), )?; - this.pthread_create(thread, attr, start, arg)?; - this.write_int(0, dest)?; + ecx.pthread_create(thread, attr, start, arg, dest)?; } "pthread_join" => { - let [thread, retval] = &this.check_shim_sig( + let [thread, retval] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::pthread_t, *_) -> i32), (link_name, abi, args), )?; - this.pthread_join(thread, retval, dest)?; + ecx.pthread_join(thread, retval, dest)?; } "pthread_detach" => { - let [thread] = &this.check_shim_sig( + let [thread] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::pthread_t) -> i32), (link_name, abi, args), )?; - let res = this.pthread_detach(thread)?; - this.write_scalar(res, dest)?; + let res = ecx.pthread_detach(thread)?; + ecx.write_scalar(res, dest)?; } "pthread_self" => { - let [] = &this.check_shim_sig( + let [] = &ecx.check_shim_sig( shim_sig!(extern "C" fn() -> libc::pthread_t), (link_name, abi, args), )?; - let res = this.pthread_self()?; - this.write_scalar(res, dest)?; + ecx.pthread_self(dest)?; } "sched_yield" => { - // FIXME: This does not have a direct test (#3179). - let [] = &this - .check_shim_sig(shim_sig!(extern "C" fn() -> i32), (link_name, abi, args))?; - this.sched_yield()?; - this.write_int(0, dest)?; + let [] = + &ecx.check_shim_sig(shim_sig!(extern "C" fn() -> i32), (link_name, abi, args))?; + ecx.sched_yield()?; + ecx.write_int(0, dest)?; } "nanosleep" => { - let [duration, rem] = &this.check_shim_sig( + let [duration, rem] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::timespec, *_) -> i32), (link_name, abi, args), )?; - let result = this.nanosleep(duration, rem)?; - this.write_scalar(result, dest)?; + let result = ecx.nanosleep(duration, rem)?; + ecx.write_scalar(result, dest)?; } "clock_nanosleep" => { // Currently this function does not exist on all Unixes, e.g. on macOS. - this.check_target_os( + ecx.check_target_os( &[Os::FreeBsd, Os::Linux, Os::Android, Os::Solaris, Os::Illumos], link_name, )?; - let [clock_id, flags, req, rem] = &this.check_shim_sig( + let [clock_id, flags, req, rem] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::clockid_t, i32, *libc::timespec, *_) -> i32), (link_name, abi, args), )?; - let result = this.clock_nanosleep(clock_id, flags, req, rem)?; - this.write_scalar(result, dest)?; + let result = ecx.clock_nanosleep(clock_id, flags, req, rem)?; + ecx.write_scalar(result, dest)?; } "sched_getaffinity" => { // Currently this function does not exist on all Unixes, e.g. on macOS. - this.check_target_os(&[Os::Linux, Os::FreeBsd, Os::Android], link_name)?; + ecx.check_target_os(&[Os::Linux, Os::FreeBsd, Os::Android], link_name)?; - let [pid, cpusetsize, mask] = &this.check_shim_sig( + let [pid, cpusetsize, mask] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::pid_t, usize, *_) -> i32), (link_name, abi, args), )?; - this.sched_getaffinity(pid, cpusetsize, mask, dest)?; + ecx.sched_getaffinity(pid, cpusetsize, mask, dest)?; } "sched_setaffinity" => { // Currently this function does not exist on all Unixes, e.g. on macOS. - this.check_target_os(&[Os::Linux, Os::FreeBsd, Os::Android], link_name)?; + ecx.check_target_os(&[Os::Linux, Os::FreeBsd, Os::Android], link_name)?; - let [pid, cpusetsize, mask] = &this.check_shim_sig( + let [pid, cpusetsize, mask] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::pid_t, usize, *_) -> i32), (link_name, abi, args), )?; - this.sched_setaffinity(pid, cpusetsize, mask, dest)?; + ecx.sched_setaffinity(pid, cpusetsize, mask, dest)?; } // Miscellaneous "isatty" => { - let [fd] = &this + let [fd] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(i32) -> i32), (link_name, abi, args))?; - let result = this.isatty(fd)?; - this.write_scalar(result, dest)?; + let result = ecx.isatty(fd)?; + ecx.write_scalar(result, dest)?; } "pthread_atfork" => { - // FIXME: This does not have a direct test (#3179). - let [prepare, parent, child] = &this.check_shim_sig( + let [prepare, parent, child] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(fn(..) -> _, fn(..) -> _, fn(..) -> _) -> i32), (link_name, abi, args), )?; - this.read_pointer(prepare)?; - this.read_pointer(parent)?; - this.read_pointer(child)?; + ecx.read_pointer(prepare)?; + ecx.read_pointer(parent)?; + ecx.read_pointer(child)?; // We do not support forking, so there is nothing to do here. - this.write_int(0, dest)?; + ecx.write_int(0, dest)?; } "strerror_r" => { - let [errnum, buf, buflen] = &this.check_shim_sig( + let [errnum, buf, buflen] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, usize) -> i32), (link_name, abi, args), )?; - let result = this.strerror_r(errnum, buf, buflen)?; - this.write_scalar(result, dest)?; + let result = ecx.strerror_r(errnum, buf, buflen)?; + ecx.write_scalar(result, dest)?; } "getentropy" => { // This function is non-standard but exists with the same signature and behavior on // Linux, macOS, FreeBSD and Solaris/Illumos. - this.check_target_os( + ecx.check_target_os( &[Os::Linux, Os::MacOs, Os::FreeBsd, Os::Illumos, Os::Solaris, Os::Android], link_name, )?; - let [buf, bufsize] = &this.check_shim_sig( + let [buf, bufsize] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, usize) -> i32), (link_name, abi, args), )?; - let buf = this.read_pointer(buf)?; - let bufsize = this.read_target_usize(bufsize)?; + let buf = ecx.read_pointer(buf)?; + let bufsize = ecx.read_target_usize(bufsize)?; // getentropy sets errno to EIO when the buffer size exceeds 256 bytes. // FreeBSD: https://man.freebsd.org/cgi/man.cgi?query=getentropy&sektion=3&format=html @@ -1304,43 +1337,43 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // macOS: https://keith.github.io/xcode-man-pages/getentropy.2.html // Solaris/Illumos: https://illumos.org/man/3C/getentropy if bufsize > 256 { - this.set_errno_and_return_neg1(LibcError("EIO"), dest)?; + ecx.set_errno_and_return_neg1(LibcError("EIO"), dest)?; } else { - this.gen_random(buf, bufsize)?; - this.write_int(0, dest)?; + ecx.gen_random(buf, bufsize)?; + ecx.write_int(0, dest)?; } } "getrandom" => { // This function is non-standard but exists with the same signature and behavior on // Linux, FreeBSD and Solaris/Illumos. - this.check_target_os( + ecx.check_target_os( &[Os::Linux, Os::FreeBsd, Os::Illumos, Os::Solaris, Os::Android], link_name, )?; - let [ptr, len, flags] = &this.check_shim_sig( + let [ptr, len, flags] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, usize, u32) -> isize), (link_name, abi, args), )?; - let ptr = this.read_pointer(ptr)?; - let len = this.read_target_usize(len)?; - let _flags = this.read_scalar(flags)?.to_i32()?; + let ptr = ecx.read_pointer(ptr)?; + let len = ecx.read_target_usize(len)?; + let _flags = ecx.read_scalar(flags)?.to_i32()?; // We ignore the flags, just always use the same PRNG / host RNG. - this.gen_random(ptr, len)?; - this.write_scalar(Scalar::from_target_usize(len, this), dest)?; + ecx.gen_random(ptr, len)?; + ecx.write_scalar(Scalar::from_target_usize(len, ecx), dest)?; } "arc4random_buf" => { // This function is non-standard but exists with the same signature and // same behavior (eg never fails) on FreeBSD and Solaris/Illumos. - this.check_target_os(&[Os::FreeBsd, Os::Illumos, Os::Solaris], link_name)?; + ecx.check_target_os(&[Os::FreeBsd, Os::Illumos, Os::Solaris], link_name)?; - let [ptr, len] = &this.check_shim_sig( + let [ptr, len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, usize) -> ()), (link_name, abi, args), )?; - let ptr = this.read_pointer(ptr)?; - let len = this.read_target_usize(len)?; - this.gen_random(ptr, len)?; + let ptr = ecx.read_pointer(ptr)?; + let len = ecx.read_target_usize(len)?; + ecx.gen_random(ptr, len)?; } "_Unwind_RaiseException" => { // This is not formally part of POSIX, but it is very wide-spread on POSIX systems. @@ -1356,35 +1389,35 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // For arm32 they did something custom, but similar enough that the same // `_Unwind_RaiseException` impl in miri should work: // https://github.com/ARM-software/abi-aa/blob/main/ehabi32/ehabi32.rst - this.check_target_os( + ecx.check_target_os( &[Os::Linux, Os::FreeBsd, Os::Illumos, Os::Solaris, Os::Android, Os::MacOs], link_name, )?; // This function looks and behaves exactly like miri_start_unwind. - let [payload] = &this.check_shim_sig( + let [payload] = &ecx.check_shim_sig( // Look up the return type via `panic_unwind::`, not via `unwind::`, as // the latter it not always unique. shim_sig!(extern "C" fn(*_) -> panic_unwind::imp::uw::_Unwind_Reason_Code), (link_name, abi, args), )?; - this.handle_miri_start_unwind(payload)?; + ecx.handle_miri_start_unwind(payload)?; return interp_ok(EmulateItemResult::NeedsUnwind); } "getuid" | "geteuid" => { - let [] = &this.check_shim_sig( + let [] = &ecx.check_shim_sig( shim_sig!(extern "C" fn() -> libc::uid_t), (link_name, abi, args), )?; // For now, just pretend we always have this fixed UID. - this.write_int(UID, dest)?; + ecx.write_int(UID, dest)?; } "pause" => { - let [] = &this - .check_shim_sig(shim_sig!(extern "C" fn() -> i32), (link_name, abi, args))?; + let [] = + &ecx.check_shim_sig(shim_sig!(extern "C" fn() -> i32), (link_name, abi, args))?; // This blocks the current thread until a signal gets delivered. We don't support // signals, so we block forever. - this.block_thread( + ecx.block_thread( BlockReason::Pause, None, callback!(@capture<'tcx> {} @@ -1396,94 +1429,71 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Incomplete shims that we "stub out" just to get pre-main initialization code to work. // These shims are enabled only when the caller is in the standard library. - "pthread_attr_getguardsize" if this.frame_in_std() => { - let [_attr, guard_size] = &this.check_shim_sig( + "pthread_attr_getguardsize" if ecx.frame_in_std() => { + let [_attr, guard_size] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, *usize) -> i32), (link_name, abi, args), )?; - let guard_size = this.deref_pointer(guard_size)?; - this.write_scalar( - Scalar::from_uint(this.machine.page_size, guard_size.layout.size), - &guard_size, - )?; + let guard_size = ecx.deref_pointer(guard_size)?; + ecx.write_int(ecx.machine.page_size, &guard_size)?; // Return success (`0`). - this.write_int(0, dest)?; - } - - "pthread_attr_init" | "pthread_attr_destroy" if this.frame_in_std() => { - let [_] = &this - .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?; - this.write_int(0, dest)?; + ecx.write_int(0, dest)?; } - "pthread_attr_setstacksize" if this.frame_in_std() => { - let [_, _] = &this.check_shim_sig( - shim_sig!(extern "C" fn(*_, usize) -> i32), - (link_name, abi, args), - )?; - this.write_int(0, dest)?; - } - - "pthread_attr_getstack" if this.frame_in_std() => { + "pthread_attr_getstack" if ecx.frame_in_std() => { // We don't support "pthread_attr_setstack", so we just pretend all stacks have the same values here. // Hence we can mostly ignore the input `attr_place`. - let [attr_place, addr_place, size_place] = &this.check_shim_sig( + let [attr_place, addr_place, size_place] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_attr_t, *usize, *usize) -> i32), (link_name, abi, args), )?; - let _attr_place = this.deref_pointer(attr_place)?; - let addr_place = this.deref_pointer(addr_place)?; - let size_place = this.deref_pointer(size_place)?; + let _attr_place = ecx.deref_pointer(attr_place)?; + let addr_place = ecx.deref_pointer(addr_place)?; + let size_place = ecx.deref_pointer(size_place)?; - this.write_scalar( - Scalar::from_uint(this.machine.stack_addr, this.pointer_size()), - &addr_place, - )?; - this.write_scalar( - Scalar::from_uint(this.machine.stack_size, this.pointer_size()), - &size_place, - )?; + ecx.write_int(ecx.machine.stack_addr, &addr_place)?; + ecx.write_int(ecx.machine.stack_size, &size_place)?; // Return success (`0`). - this.write_int(0, dest)?; + ecx.write_int(0, dest)?; } - "signal" if this.frame_in_std() => { - let [_, _] = &this.check_shim_sig( + "signal" if ecx.frame_in_std() => { + let [_, _] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, libc::sighandler_t) -> libc::sighandler_t), (link_name, abi, args), )?; - this.write_int(0, dest)?; + ecx.write_int(0, dest)?; } - "sigaltstack" if this.frame_in_std() => { - let [_, _] = &this.check_shim_sig( + "sigaltstack" if ecx.frame_in_std() => { + let [_, _] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, *_) -> i32), (link_name, abi, args), )?; - this.write_int(0, dest)?; + ecx.write_int(0, dest)?; } - "sigaction" if this.frame_in_std() => { - let [_, _, _] = &this.check_shim_sig( + "sigaction" if ecx.frame_in_std() => { + let [_, _, _] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, *_) -> i32), (link_name, abi, args), )?; - this.write_int(0, dest)?; + ecx.write_int(0, dest)?; } - "getpwuid_r" | "__posix_getpwuid_r" if this.frame_in_std() => { + "getpwuid_r" | "__posix_getpwuid_r" if ecx.frame_in_std() => { // getpwuid_r is the standard name, __posix_getpwuid_r is used on solarish - let [uid, pwd, buf, buflen, result] = &this.check_shim_sig( + let [uid, pwd, buf, buflen, result] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::uid_t, *libc::passwd, *_, usize, **_) -> i32), (link_name, abi, args), )?; - this.check_no_isolation("`getpwuid_r`")?; + ecx.check_no_isolation("`getpwuid_r`")?; - let uid = this.read_scalar(uid)?.to_u32()?; - let pwd = this.deref_pointer(pwd)?; - let buf = this.read_pointer(buf)?; - let buflen = this.read_target_usize(buflen)?; - let result = this.deref_pointer(result)?; + let uid = ecx.read_scalar(uid)?.to_u32()?; + let pwd = ecx.deref_pointer(pwd)?; + let buf = ecx.read_pointer(buf)?; + let buflen = ecx.read_target_usize(buflen)?; + let result = ecx.deref_pointer(result)?; // Must be for "us". if uid != UID { @@ -1492,51 +1502,51 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Reset all fields to `uninit` to make sure nobody reads them. // (This is a std-only shim so we are okay with such hacks.) - this.write_uninit(&pwd)?; + ecx.write_uninit(&pwd)?; // We only set the home_dir field. #[allow(deprecated)] let home_dir = std::env::home_dir().unwrap(); - let (written, _) = this.write_path_to_c_str(&home_dir, buf, buflen)?; - let pw_dir = this.project_field_named(&pwd, "pw_dir")?; - this.write_pointer(buf, &pw_dir)?; + let (written, _) = ecx.write_path_to_c_str(&home_dir, buf, buflen)?; + let pw_dir = ecx.project_field_named(&pwd, "pw_dir")?; + ecx.write_pointer(buf, &pw_dir)?; if written { - this.write_pointer(pwd.ptr(), &result)?; - this.write_int(0, dest)?; + ecx.write_pointer(pwd.ptr(), &result)?; + ecx.write_int(0, dest)?; } else { - this.write_int(0, &result)?; - this.write_scalar(this.eval_libc("ERANGE"), dest)?; + ecx.write_int(0, &result)?; + ecx.write_scalar(ecx.eval_libc("ERANGE"), dest)?; } } // Platform-specific shims _ => { - let target_os = &this.tcx.sess.target.os; + let target_os = &ecx.tcx.sess.target.os; return match target_os { Os::Android => android::EvalContextExt::emulate_foreign_item_inner( - this, link_name, abi, args, dest, + ecx, link_name, abi, args, dest, ), Os::FreeBsd => freebsd::EvalContextExt::emulate_foreign_item_inner( - this, link_name, abi, args, dest, + ecx, link_name, abi, args, dest, ), Os::Linux => linux::EvalContextExt::emulate_foreign_item_inner( - this, link_name, abi, args, dest, + ecx, link_name, abi, args, dest, ), Os::MacOs => macos::EvalContextExt::emulate_foreign_item_inner( - this, link_name, abi, args, dest, + ecx, link_name, abi, args, dest, ), Os::Solaris | Os::Illumos => solarish::EvalContextExt::emulate_foreign_item_inner( - this, link_name, abi, args, dest, + ecx, link_name, abi, args, dest, ), Os::NetBsd => netbsd::EvalContextExt::emulate_foreign_item_inner( - this, link_name, abi, args, dest, + ecx, link_name, abi, args, dest, ), _ => interp_ok(EmulateItemResult::NotSupported), }; diff --git a/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs b/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs index 1ca4570477049..2b40cdbbdb0e3 100644 --- a/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs @@ -19,94 +19,94 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { args: &[OpTy<'tcx>], dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx, EmulateItemResult> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); match link_name.as_str() { // Threading "pthread_setname_np" => { - let [thread, name] = &this.check_shim_sig( + let [thread, name] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::pthread_t, *_) -> i32), (link_name, abi, args), )?; let max_len = u64::MAX; // FreeBSD does not seem to have a limit. - let res = match this.pthread_setname_np( - this.read_scalar(thread)?, - this.read_scalar(name)?, + let res = match ecx.pthread_setname_np( + Some(thread), + ecx.read_pointer(name)?, max_len, /* truncate */ false, )? { ThreadNameResult::Ok => Scalar::from_u32(0), ThreadNameResult::NameTooLong => unreachable!(), }; - this.write_scalar(res, dest)?; + ecx.write_scalar(res, dest)?; } "pthread_getname_np" => { - let [thread, name, len] = &this.check_shim_sig( + let [thread, name, len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::pthread_t, *_, usize) -> i32), (link_name, abi, args), )?; // FreeBSD's pthread_getname_np uses strlcpy, which truncates the resulting value, // but always adds a null terminator (except for zero-sized buffers). // https://github.com/freebsd/freebsd-src/blob/c2d93a803acef634bd0eede6673aeea59e90c277/lib/libthr/thread/thr_info.c#L119-L144 - let res = match this.pthread_getname_np( - this.read_scalar(thread)?, - this.read_scalar(name)?, - this.read_scalar(len)?, + let res = match ecx.pthread_getname_np( + Some(thread), + ecx.read_pointer(name)?, + ecx.read_scalar(len)?, /* truncate */ true, )? { ThreadNameResult::Ok => Scalar::from_u32(0), // `NameTooLong` is possible when the buffer is zero sized, ThreadNameResult::NameTooLong => Scalar::from_u32(0), }; - this.write_scalar(res, dest)?; + ecx.write_scalar(res, dest)?; } "pthread_getthreadid_np" => { - let [] = &this - .check_shim_sig(shim_sig!(extern "C" fn() -> i32), (link_name, abi, args))?; - let result = this.unix_gettid(link_name.as_str())?; - this.write_scalar(result, dest)?; + let [] = + &ecx.check_shim_sig(shim_sig!(extern "C" fn() -> i32), (link_name, abi, args))?; + let result = ecx.unix_gettid(link_name.as_str())?; + ecx.write_scalar(result, dest)?; } "cpuset_getaffinity" => { // The "same" kind of api as `sched_getaffinity` but more fine grained control for FreeBSD specifically. - let [level, which, id, set_size, mask] = &this.check_shim_sig( + let [level, which, id, set_size, mask] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, i32, i64, usize, *_) -> i32), (link_name, abi, args), )?; - let level = this.read_scalar(level)?.to_i32()?; - let which = this.read_scalar(which)?.to_i32()?; - let id = this.read_scalar(id)?.to_i64()?; - let set_size = this.read_target_usize(set_size)?; // measured in bytes - let mask = this.read_pointer(mask)?; + let level = ecx.read_scalar(level)?.to_i32()?; + let which = ecx.read_scalar(which)?.to_i32()?; + let id = ecx.read_scalar(id)?.to_i64()?; + let set_size = ecx.read_target_usize(set_size)?; // measured in bytes + let mask = ecx.read_pointer(mask)?; - if this.machine.thread_cpu_affinity.is_none() { + if ecx.machine.thread_cpu_affinity.is_none() { throw_unsup_format!( "`cpuset_getaffinity` is not supported on #![no_core] programs" ) } - let _level_root = this.eval_libc_i32("CPU_LEVEL_ROOT"); - let _level_cpuset = this.eval_libc_i32("CPU_LEVEL_CPUSET"); - let level_which = this.eval_libc_i32("CPU_LEVEL_WHICH"); + let _level_root = ecx.eval_libc_i32("CPU_LEVEL_ROOT"); + let _level_cpuset = ecx.eval_libc_i32("CPU_LEVEL_CPUSET"); + let level_which = ecx.eval_libc_i32("CPU_LEVEL_WHICH"); - let _which_tid = this.eval_libc_i32("CPU_WHICH_TID"); - let which_pid = this.eval_libc_i32("CPU_WHICH_PID"); - let _which_jail = this.eval_libc_i32("CPU_WHICH_JAIL"); - let _which_cpuset = this.eval_libc_i32("CPU_WHICH_CPUSET"); - let _which_irq = this.eval_libc_i32("CPU_WHICH_IRQ"); + let _which_tid = ecx.eval_libc_i32("CPU_WHICH_TID"); + let which_pid = ecx.eval_libc_i32("CPU_WHICH_PID"); + let _which_jail = ecx.eval_libc_i32("CPU_WHICH_JAIL"); + let _which_cpuset = ecx.eval_libc_i32("CPU_WHICH_CPUSET"); + let _which_irq = ecx.eval_libc_i32("CPU_WHICH_IRQ"); // For sched_getaffinity, the current process is identified by -1. // TODO: Use gettid? I'm (LorrensP-2158466) not that familiar with this api . let id = match id { - -1 => this.active_thread(), + -1 => ecx.active_thread(), _ => throw_unsup_format!( "`cpuset_getaffinity` is only supported with a pid of -1 (indicating the current thread)" ), }; - if this.ptr_is_null(mask)? { - this.set_errno_and_return_neg1(LibcError("EFAULT"), dest)?; + if ecx.ptr_is_null(mask)? { + ecx.set_errno_and_return_neg1(LibcError("EFAULT"), dest)?; } // We only support CPU_LEVEL_WHICH and CPU_WHICH_PID for now. // This is the bare minimum to make the tests pass. @@ -115,24 +115,21 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "`cpuset_getaffinity` is only supported with `level` set to CPU_LEVEL_WHICH and `which` set to CPU_WHICH_PID." ); } else if let Some(cpuset) = - this.machine.thread_cpu_affinity.as_ref().unwrap().get(&id) + ecx.machine.thread_cpu_affinity.as_ref().unwrap().get(&id) { // `cpusetsize` must be large enough to contain the entire CPU mask. // FreeBSD only uses `cpusetsize` to verify that it's sufficient for the kernel's CPU mask. // If it's too small, the syscall returns ERANGE. // If it's large enough, copying the kernel mask to user space is safe, regardless of the actual size. // See https://github.com/freebsd/freebsd-src/blob/909aa6781340f8c0b4ae01c6366bf1556ee2d1be/sys/kern/kern_cpuset.c#L1985 - if set_size < u64::from(this.machine.num_cpus).div_ceil(8) { - this.set_errno_and_return_neg1(LibcError("ERANGE"), dest)?; + if set_size < u64::from(ecx.machine.num_cpus).div_ceil(8) { + ecx.set_errno_and_return_neg1(LibcError("ERANGE"), dest)?; } else { let cpuset = cpuset.clone(); let byte_count = Ord::min(cpuset.as_slice().len(), set_size.try_into().unwrap()); - this.write_bytes_ptr( - mask, - cpuset.as_slice()[..byte_count].iter().copied(), - )?; - this.write_int(0, dest)?; + ecx.write_bytes_ptr(mask, cpuset.as_slice()[..byte_count].iter().copied())?; + ecx.write_int(0, dest)?; } } else { // `id` is always that of the active thread, so this is currently unreachable. @@ -142,40 +139,41 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Synchronization primitives "_umtx_op" => { - let [obj, op, val, uaddr, uaddr2] = &this.check_shim_sig( + let [obj, op, val, uaddr, uaddr2] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, i32, usize, *_, *_) -> i32), (link_name, abi, args), )?; - this._umtx_op(obj, op, val, uaddr, uaddr2, dest)?; + ecx._umtx_op(obj, op, val, uaddr, uaddr2, dest)?; } // Miscellaneous "__error" => { - let [] = &this - .check_shim_sig(shim_sig!(extern "C" fn() -> *_), (link_name, abi, args))?; - let errno_place = this.last_error_place()?; - this.write_scalar(errno_place.to_ref(this).to_scalar(), dest)?; + let [] = + &ecx.check_shim_sig(shim_sig!(extern "C" fn() -> *_), (link_name, abi, args))?; + let errno_place = ecx.last_error_place()?; + ecx.write_scalar(errno_place.to_ref(ecx).to_scalar(), dest)?; } "__xuname" => { // FreeBSD uses __xuname under the hood to implement uname, see: // https://github.com/freebsd/freebsd-src/blob/3542d60fb8042474f66fbf2d779ed8c5a80d0f78/sys/sys/utsname.h#L64 // https://github.com/freebsd/freebsd-src/blob/3542d60fb8042474f66fbf2d779ed8c5a80d0f78/lib/libc/gen/uname.c#L44 - let [size, uname] = &this.check_shim_sig( + let [size, uname] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::utsname) -> i32), (link_name, abi, args), )?; - let result = this.uname(uname, Some(size))?; - this.write_scalar(result, dest)?; + let result = ecx.uname(uname, Some(size))?; + ecx.write_scalar(result, dest)?; } // Incomplete shims that we "stub out" just to get pre-main initialization code to work. // These shims are enabled only when the caller is in the standard library. - "pthread_attr_get_np" if this.frame_in_std() => { - let [_thread, _attr] = &this.check_shim_sig( - shim_sig!(extern "C" fn(libc::pthread_t, *_) -> i32), + "pthread_attr_get_np" if ecx.frame_in_std() => { + let [_thread, attr] = &ecx.check_shim_sig( + shim_sig!(extern "C" fn(libc::pthread_t, *libc::pthread_attr_t) -> i32), (link_name, abi, args), )?; - this.write_int(0, dest)?; + // The caller will `pthread_attr_destroy` this, so it needs to be initialized. + ecx.pthread_attr_init(attr, dest)?; } _ => return 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 383c505684e99..066ff0d429270 100644 --- a/src/tools/miri/src/shims/unix/fs.rs +++ b/src/tools/miri/src/shims/unix/fs.rs @@ -113,6 +113,10 @@ impl UnixFileDescription for FileHandle { if !self.writable { return finish.call(ecx, Err(LibcError("EBADF"))); } + if self.append { + // On "append" files, pwrite cannot be emulated with seeking. + throw_unsup_format!("pwrite is not supported on files opened with O_APPEND"); + } let file = &mut &self.file; // Emulates pwrite using seek + write + seek to restore cursor position. @@ -239,6 +243,60 @@ fn maybe_sync_file( } } +/// Whether `path` is a symlink to a directory on the host. +/// If `dir` is given, a relative `path` is resolved relative to that directory. +#[cfg(windows)] +fn host_is_symlink_dir(dir: Option<&DirHandle>, path: &Path) -> bool { + use std::os::windows::fs::FileTypeExt; + let metadata = match dir { + Some(dir) => dir.dir.symlink_metadata(path), + None => path.symlink_metadata(), + }; + metadata.is_ok_and(|m| m.file_type().is_symlink_dir()) +} + +/// Removes the file at `path` on the host, with the semantics of `unlink`. +/// If `dir` is given, a relative `path` is resolved relative to that directory. +fn host_remove_file(dir: Option<&DirHandle>, path: &Path) -> io::Result<()> { + cfg_select! { + unix => + match dir { + Some(dir) => dir.dir.remove_file(path), + None => fs::remove_file(path), + }, + windows => {{ + // This should be able to remove symlinks to dirs, but on Windows that requires + // `remove_dir`. Our work-around is racy but there's not a lot we can do about that. + // FIXME: maybe we can retry based on the error code? + let symlink_dir = host_is_symlink_dir(dir, path); + match (dir, symlink_dir) { + (Some(dir), true) => dir.dir.remove_dir(path), + (Some(dir), false) => dir.dir.remove_file(path), + (None, true) => fs::remove_dir(path), + (None, false) => fs::remove_file(path), + } + }} + } +} + +/// Removes the directory at `path` on the host, with the semantics of `rmdir`. +/// If `dir` is given, a relative `path` is resolved relative to that directory. +fn host_remove_dir(dir: Option<&DirHandle>, path: &Path) -> io::Result<()> { + #[cfg(windows)] + { + // This should *not* be able to remove symlinks to dirs, but on Windows it is. Our + // work-around is racy (it might change to being a directory symlink after we + // checked it), but there's not a lot we can do about that. + if host_is_symlink_dir(dir, path) { + return Err(ErrorKind::NotADirectory.into()); + } + } + match dir { + Some(dir) => dir.dir.remove_dir(path), + None => fs::remove_dir(path), + } +} + /// The host `FileTimes` that applies the given access and modification time updates. fn host_file_times_from_updates(access: TimeUpdate, modified: TimeUpdate) -> FileTimes { let mut filetimes = FileTimes::new(); @@ -448,8 +506,7 @@ trait EvalContextExtPrivate<'tcx>: crate::MiriInterpCxExt<'tcx> { }; // Only support default mode for non-UNIX (i.e. Windows) host. // Ignore the "regular file" bit which is a NOP. - let s_ifreg = ecx.eval_libc("S_IFREG"); - let s_ifreg = u32::try_from(s_ifreg.to_bits(s_ifreg.size())?).unwrap(); + let s_ifreg = ecx.eval_libc_int::("S_IFREG"); match mode & !s_ifreg { 0o666 => { permissions.set_readonly(false); @@ -531,8 +588,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Only support default mode for non-UNIX (i.e. Windows) host. // Ignore the "regular file" bit which is a NOP. - let s_ifreg = ecx.eval_libc("S_IFREG"); - let s_ifreg = u32::try_from(s_ifreg.to_bits(s_ifreg.size())?).unwrap(); + let s_ifreg = ecx.eval_libc_int::("S_IFREG"); if mode & !s_ifreg != 0o666 { throw_unsup_format!( "{open_name}: non-default mode 0o{:o} is not supported on non-Unix hosts", @@ -621,7 +677,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let append = flag & o_append == o_append; if append { flag &= !o_append; - options.append(true); + // The flag is a NOP if the file is not writable. + if writable { + options.append(true); + } } let o_trunc = ecx.eval_libc_i32("O_TRUNC"); if flag & o_trunc == o_trunc { @@ -655,6 +714,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } else { options.create(true); } + // Creating a file requires opening it for writing. + // Write accesses will still get rejected as `writable` is not set on the `FileHandle`. + options.write(true); } let o_cloexec = ecx.eval_libc_i32("O_CLOEXEC"); if flag & o_cloexec == o_cloexec { @@ -771,7 +833,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { fn lseek( &mut self, fd_num: i32, - offset: i128, + offset: i64, whence: i32, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { @@ -780,16 +842,15 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Isolation check is done via `FileDescription` trait. let seek_from = if whence == this.eval_libc_i32("SEEK_SET") { - if offset < 0 { + let Ok(offset) = u64::try_from(offset) else { // Negative offsets return `EINVAL`. return this.set_errno_and_return_neg1(LibcError("EINVAL"), dest); - } else { - SeekFrom::Start(u64::try_from(offset).unwrap()) - } + }; + SeekFrom::Start(offset) } else if whence == this.eval_libc_i32("SEEK_CUR") { - SeekFrom::Current(i64::try_from(offset).unwrap()) + SeekFrom::Current(offset) } else if whence == this.eval_libc_i32("SEEK_END") { - SeekFrom::End(i64::try_from(offset).unwrap()) + SeekFrom::End(offset) } else { return this.set_errno_and_return_neg1(LibcError("EINVAL"), dest); }; @@ -808,32 +869,65 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } fn unlink(&mut self, path_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?; + let path = ecx.read_path_from_c_str(ecx.read_pointer(path_op)?)?; // Reject if isolation is enabled. - if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op { - this.reject_in_isolation("`unlink`", reject_with)?; - return this.set_errno_and_return_neg1_i32(ErrorKind::PermissionDenied); + if let IsolatedOp::Reject(reject_with) = ecx.machine.isolated_op { + ecx.reject_in_isolation("`unlink`", reject_with)?; + return ecx.set_errno_and_return_neg1_i32(ErrorKind::PermissionDenied); } - let result = cfg_select! { - unix => fs::remove_file(path), - windows => {{ - // This should be able to remove symlinks to dirs, but on Windows that requires - // `remove_dir`. Our work-around is racy but there's not a lot we can do about that. - // FIXME: maybe we can retry based on the error code? - use std::os::windows::fs::FileTypeExt; - let metadata = path.symlink_metadata(); - if metadata.is_ok_and(|m| m.file_type().is_symlink_dir()) { - fs::remove_dir(path) - } else { - fs::remove_file(path) - } - }} + let result = host_remove_file(None, &path); + interp_ok(Scalar::from_i32(ecx.try_unwrap_io_result(result.map(|()| 0))?)) + } + + fn unlinkat( + &mut self, + dirfd_op: &OpTy<'tcx>, + path_op: &OpTy<'tcx>, + flags_op: &OpTy<'tcx>, + ) -> InterpResult<'tcx, Scalar> { + let ecx = self.eval_context_mut(); + + let dirfd = ecx.read_scalar(dirfd_op)?.to_i32()?; + let path = ecx.read_path_from_c_str(ecx.read_pointer(path_op)?)?.into_owned(); + let flags = ecx.read_scalar(flags_op)?.to_i32()?; + + // Reject if isolation is enabled. + if let IsolatedOp::Reject(reject_with) = ecx.machine.isolated_op { + ecx.reject_in_isolation("`unlinkat`", reject_with)?; + return ecx.set_errno_and_return_neg1_i32(LibcError("EACCES")); + } + + // We only support `AT_REMOVEDIR`, which makes this behave like `rmdir`. + let remove_dir = if flags == 0 { + false + } else if flags == ecx.eval_libc_i32("AT_REMOVEDIR") { + true + } else { + throw_unsup_format!("unsupported flags for `unlinkat`: {flags:#x}") + }; + + let dir = if path.is_absolute() || dirfd == ecx.eval_libc_i32("AT_FDCWD") { + None + } else { + // relative to dirfd, which must be a directory handle + let Some(fd) = ecx.machine.fds.get(dirfd) else { + return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF")); + }; + let Some(dir) = fd.downcast::() else { + return ecx.set_errno_and_return_neg1_i32(LibcError("ENOTDIR")); + }; + Some(dir) + }; + let result = if remove_dir { + host_remove_dir(dir.as_deref(), &path) + } else { + host_remove_file(dir.as_deref(), &path) }; - interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result.map(|()| 0))?)) + interp_ok(Scalar::from_i32(ecx.try_unwrap_io_result(result.map(|()| 0))?)) } fn symlink( @@ -1235,7 +1329,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let this = self.eval_context_mut(); let path_ptr = this.read_pointer(path_op)?; - let mode = this.read_scalar(mode_op)?.to_uint(this.libc_ty_layout("mode_t").size)?; + let mode = this.read_int::(mode_op)?; if this.ptr_is_null(path_ptr)? { return this.set_errno_and_return_neg1_i32(LibcError("EFAULT")); @@ -1248,7 +1342,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { return this.set_errno_and_return_neg1_i32(LibcError("EACCES")); } - let permissions = this.host_permissions_from_mode(mode.try_into().unwrap(), || { + let permissions = this.host_permissions_from_mode(mode, || { // We get here if we need to read the old permissions before we can set new ones. // This is fundamentally racy. We cannot even use a file handle to make it less racy: // setting permissions requires opening for writing, but opening for writing fails @@ -1267,7 +1361,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let this = self.eval_context_mut(); let fd_num = this.read_scalar(fd_op)?.to_i32()?; - let mode = this.read_scalar(mode_op)?.to_uint(this.libc_ty_layout("mode_t").size)?; + let mode = this.read_int::(mode_op)?; let Some(fd) = this.machine.fds.get(fd_num) else { return this.set_errno_and_return_neg1_i32(LibcError("EBADF")); @@ -1283,7 +1377,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } assert!(this.machine.communicate(), "isolation should have prevented even opening a file"); - let permissions = this.host_permissions_from_mode(mode.try_into().unwrap(), || { + let permissions = this.host_permissions_from_mode(mode, || { // We get here if we need to read the old permissions before we can set new ones. // This is fundamentally racy. file.file.metadata().map(|m| m.permissions()) @@ -1324,38 +1418,86 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result)?)) } - fn mkdir(&mut self, path_op: &OpTy<'tcx>, mode_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + fn mkdir( + &mut self, + dirfd_op: Option<&OpTy<'tcx>>, + path_op: &OpTy<'tcx>, + mode_op: &OpTy<'tcx>, + dest: &MPlaceTy<'tcx>, + ) -> InterpResult<'tcx> { + let ecx = self.eval_context_mut(); + let mkdir_name = if dirfd_op.is_some() { "mkdirat" } else { "mkdir" }; - #[cfg_attr(not(unix), allow(unused_variables))] - let mode = if matches!(&this.tcx.sess.target.os, Os::MacOs | Os::FreeBsd) { - u32::from(this.read_scalar(mode_op)?.to_u16()?) - } else { - this.read_scalar(mode_op)?.to_u32()? + let dirfd = match dirfd_op { + Some(dirfd_op) => Some(ecx.read_scalar(dirfd_op)?.to_i32()?), + None => None, }; - - let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?; + let path = ecx.read_path_from_c_str(ecx.read_pointer(path_op)?)?; + let mode = ecx.read_int::(mode_op)?; // Reject if isolation is enabled. - if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op { - this.reject_in_isolation("`mkdir`", reject_with)?; - return this.set_errno_and_return_neg1_i32(ErrorKind::PermissionDenied); + if let IsolatedOp::Reject(reject_with) = ecx.machine.isolated_op { + ecx.reject_in_isolation(&format!("`{mkdir_name}`"), reject_with)?; + return ecx.set_errno_and_return_neg1(LibcError("EACCES"), dest); } - #[cfg_attr(not(unix), allow(unused_mut))] - let mut builder = DirBuilder::new(); + let dir = match dirfd { + Some(dirfd) => { + if path.is_absolute() || dirfd == ecx.eval_libc_i32("AT_FDCWD") { + None + } else { + // relative to dirfd, which must be a directory handle + let Some(fd) = ecx.machine.fds.get(dirfd) else { + return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest); + }; + let Some(dir) = fd.downcast::() else { + return ecx.set_errno_and_return_neg1(LibcError("ENOTDIR"), dest); + }; + Some(dir) + } + } + None => None, + }; - // If the host supports it, forward on the mode of the directory - // (i.e. permission bits and the sticky bit) - #[cfg(unix)] - { - use std::os::unix::fs::DirBuilderExt; - builder.mode(mode); - } + let result = match dir { + Some(dir) => { + // `Dir::create_dir` does not take a mode; std always uses 0o777 internally. + // So we can only support that mode here. + if mode != 0o777 { + throw_unsup_format!( + "`mkdirat` relative to a directory file descriptor with mode {mode:#o} is not supported \ + (only 0o777 is supported)" + ); + } + dir.dir.create_dir(&path) + } + None => { + #[cfg_attr(not(unix), allow(unused_mut))] + let mut builder = DirBuilder::new(); - let result = builder.create(path).map(|_| 0i32); + // On Unix hosts, forward the mode of the directory + // (i.e. permission bits and the sticky bit). + // Other hosts can't represent it, so we only support the default mode there. + cfg_select! { + unix => { + use std::os::unix::fs::DirBuilderExt; + builder.mode(mode); + } + _ => + if mode != 0o777 { + throw_unsup_format!( + "`{mkdir_name}` with mode {mode:#o} is not supported on non-Unix hosts \ + (only 0o777 is supported)" + ); + }, + } - interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result)?)) + builder.create(path) + } + }; + + ecx.return_io_result_via_errno(result.map(|()| 0), dest)?; + interp_ok(()) } fn rmdir(&mut self, path_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> { @@ -1369,22 +1511,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { return this.set_errno_and_return_neg1_i32(ErrorKind::PermissionDenied); } - let result = cfg_select! { - unix => fs::remove_dir(path), - windows => {{ - // This should *not* be able to remove symlinks to dirs, but on Windows it is. Our - // work-around is racy (it might change to being a directory symlink after we - // checked it), but there's not a lot we can do about that. - use std::os::windows::fs::FileTypeExt; - let metadata = path.symlink_metadata(); - if metadata.is_ok_and(|m| m.file_type().is_symlink_dir()) { - return this.set_errno_and_return_neg1_i32(LibcError("ENOTDIR")); - } else { - fs::remove_dir(path) - } - }} - }; - + let result = host_remove_dir(None, &path); interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result.map(|_| 0i32))?)) } @@ -1634,7 +1761,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { interp_ok(Scalar::from_i32(0)) } - fn ftruncate64(&mut self, fd_num: i32, length: i128) -> InterpResult<'tcx, Scalar> { + fn ftruncate64(&mut self, fd_num: i32, length: i64) -> InterpResult<'tcx, Scalar> { let this = self.eval_context_mut(); let Some(fd) = this.machine.fds.get(fd_num) else { @@ -2429,8 +2556,7 @@ impl FileMetadata { ecx: &mut MiriInterpCx<'tcx>, mode_name: &str, ) -> InterpResult<'tcx, Result> { - let mode = ecx.eval_libc(mode_name); - let mode: u32 = mode.to_uint(ecx.libc_ty_layout("mode_t").size)?.try_into().unwrap(); + let mode = ecx.eval_libc_int::(mode_name); // We observed 0x777 on sockets and 0x600 on pipes... let mode = mode | 0o666; interp_ok(Ok(FileMetadata { @@ -2461,8 +2587,7 @@ impl FileMetadata { }; let file_type = metadata.file_type(); - let mode = ecx.eval_libc(file_type_to_mode_name(file_type)); - let mut mode = mode.to_uint(ecx.libc_ty_layout("mode_t").size)?.try_into().unwrap(); + let mut mode = ecx.eval_libc_int::(file_type_to_mode_name(file_type)); let size = metadata.len(); diff --git a/src/tools/miri/src/shims/unix/linux/foreign_items.rs b/src/tools/miri/src/shims/unix/linux/foreign_items.rs index b30b2f298ee7f..f3395719aa1f1 100644 --- a/src/tools/miri/src/shims/unix/linux/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/linux/foreign_items.rs @@ -71,7 +71,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let fd = ecx.read_scalar(fd)?.to_i32()?; let buf = ecx.read_pointer(buf)?; let count = ecx.read_target_usize(count)?; - let offset = ecx.read_scalar(offset)?.to_int(offset.layout.size)?; + let offset = ecx.read_scalar(offset)?.to_i64()?; ecx.read(fd, buf, count, Some(offset), dest)?; } "pwrite64" => { @@ -82,7 +82,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let fd = ecx.read_scalar(fd)?.to_i32()?; let buf = ecx.read_pointer(buf)?; let count = ecx.read_target_usize(n)?; - let offset = ecx.read_scalar(offset)?.to_int(offset.layout.size)?; + let offset = ecx.read_scalar(offset)?.to_i64()?; trace!("Called pwrite64({:?}, {:?}, {:?}, {:?})", fd, buf, count, offset); ecx.write(fd, buf, count, Some(offset), dest)?; } @@ -92,7 +92,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; let fd = ecx.read_scalar(fd)?.to_i32()?; - let offset = ecx.read_scalar(offset)?.to_int(offset.layout.size)?; + let offset = ecx.read_scalar(offset)?.to_i64()?; let whence = ecx.read_scalar(whence)?.to_i32()?; ecx.lseek(fd, offset, whence, dest)?; } @@ -118,9 +118,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let fd = ecx.read_scalar(fd)?.to_i32()?; let mode = ecx.read_scalar(mode)?.to_i32()?; // We don't support platforms which have libc::off_t bigger than 64 bits. - let offset = - i64::try_from(ecx.read_scalar(offset)?.to_int(offset.layout.size)?).unwrap(); - let len = i64::try_from(ecx.read_scalar(len)?.to_int(len.layout.size)?).unwrap(); + let offset = ecx.read_int::(offset)?; + let len = ecx.read_int::(len)?; let result = ecx.linux_fallocate(fd, mode, offset, len)?; ecx.write_scalar(result, dest)?; @@ -145,7 +144,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; let fd = ecx.read_scalar(fd)?.to_i32()?; - let length = ecx.read_scalar(length)?.to_int(length.layout.size)?; + let length = ecx.read_scalar(length)?.to_i64()?; let result = ecx.ftruncate64(fd, length)?; ecx.write_scalar(result, dest)?; } @@ -234,8 +233,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; let res = match ecx.pthread_setname_np( - ecx.read_scalar(thread)?, - ecx.read_scalar(name)?, + Some(thread), + ecx.read_pointer(name)?, TASK_COMM_LEN, /* truncate */ false, )? { @@ -255,8 +254,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let len = ecx.read_scalar(len)?; let res = if len.to_target_usize(ecx)? >= TASK_COMM_LEN { match ecx.pthread_getname_np( - ecx.read_scalar(thread)?, - ecx.read_scalar(name)?, + Some(thread), + ecx.read_pointer(name)?, len, /* truncate*/ false, )? { @@ -318,7 +317,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; let offset = ecx.read_scalar(offset)?.to_i64()?; - let ptr = ecx.mmap(addr, length, prot, flags, fd, offset.into())?; + let ptr = ecx.mmap(addr, length, prot, flags, fd, offset)?; ecx.write_scalar(ptr, dest)?; } "mremap" => { @@ -359,11 +358,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Incomplete shims that we "stub out" just to get pre-main initialization code to work. // These shims are enabled only when the caller is in the standard library. "pthread_getattr_np" if ecx.frame_in_std() => { - let [_thread, _attr] = &ecx.check_shim_sig( - shim_sig!(extern "C" fn(libc::pthread_t, *_) -> i32), + let [_thread, attr] = &ecx.check_shim_sig( + shim_sig!(extern "C" fn(libc::pthread_t, *libc::pthread_attr_t) -> i32), (link_name, abi, args), )?; - ecx.write_int(0, dest)?; + // The caller will `pthread_attr_destroy` this, so it needs to be initialized. + ecx.pthread_attr_init(attr, dest)?; } "gnu_get_libc_version" if ecx.frame_in_std() diff --git a/src/tools/miri/src/shims/unix/linux_like/syscall.rs b/src/tools/miri/src/shims/unix/linux_like/syscall.rs index 5535a129a7811..a8a2b3368812e 100644 --- a/src/tools/miri/src/shims/unix/linux_like/syscall.rs +++ b/src/tools/miri/src/shims/unix/linux_like/syscall.rs @@ -40,7 +40,6 @@ pub fn syscall<'tcx>( let sys_accept4 = ecx.eval_libc("SYS_accept4").to_target_usize(ecx)?; let sys_copy_file_range = ecx.eval_libc("SYS_copy_file_range").to_target_usize(ecx)?; - // FIXME: Do these all have direct tests (#3179)? match ecx.read_target_usize(&op)? { // `libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)` // is called if a `HashMap` is created the regular way (e.g. HashMap). diff --git a/src/tools/miri/src/shims/unix/linux_like/thread.rs b/src/tools/miri/src/shims/unix/linux_like/thread.rs index d233afa8fb638..7393f36848a59 100644 --- a/src/tools/miri/src/shims/unix/linux_like/thread.rs +++ b/src/tools/miri/src/shims/unix/linux_like/thread.rs @@ -31,12 +31,11 @@ pub fn prctl<'tcx>( "prctl(PR_SET_NAME, ...)", )?; - let name = ecx.read_scalar(&name)?; - let thread = ecx.pthread_self()?; + let name = ecx.read_pointer(&name)?; // The Linux kernel silently truncates long names. // https://www.man7.org/linux/man-pages/man2/PR_SET_NAME.2const.html let res = - ecx.pthread_setname_np(thread, name, TASK_COMM_LEN, /* truncate */ true)?; + ecx.pthread_setname_np(None, name, TASK_COMM_LEN, /* truncate */ true)?; assert_eq!(res, ThreadNameResult::Ok); Scalar::from_u32(0) } @@ -47,15 +46,14 @@ pub fn prctl<'tcx>( "prctl(PR_GET_NAME, ...)", )?; - let name = ecx.read_scalar(&name)?; - let thread = ecx.pthread_self()?; + let name = ecx.read_pointer(&name)?; let len = Scalar::from_target_usize(TASK_COMM_LEN, ecx); ecx.check_ptr_access( - name.to_pointer(ecx), + name, Size::from_bytes(TASK_COMM_LEN), CheckInAllocMsg::MemoryAccess, )?; - let res = ecx.pthread_getname_np(thread, name, len, /* truncate*/ false)?; + let res = ecx.pthread_getname_np(None, name, len, /* truncate*/ false)?; assert_eq!(res, ThreadNameResult::Ok); Scalar::from_u32(0) } diff --git a/src/tools/miri/src/shims/unix/macos/foreign_items.rs b/src/tools/miri/src/shims/unix/macos/foreign_items.rs index 875abab202c6b..2dcd640f73e20 100644 --- a/src/tools/miri/src/shims/unix/macos/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/macos/foreign_items.rs @@ -27,211 +27,206 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { args: &[OpTy<'tcx>], dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx, EmulateItemResult> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); // See `fn emulate_foreign_item_inner` in `shims/foreign_items.rs` for the general pattern. match link_name.as_str() { // errno "__error" => { - let [] = &this - .check_shim_sig(shim_sig!(extern "C" fn() -> *_), (link_name, abi, args))?; - let errno_place = this.last_error_place()?; - this.write_scalar(errno_place.to_ref(this).to_scalar(), dest)?; + let [] = + &ecx.check_shim_sig(shim_sig!(extern "C" fn() -> *_), (link_name, abi, args))?; + let errno_place = ecx.last_error_place()?; + ecx.write_scalar(errno_place.to_ref(ecx).to_scalar(), dest)?; } // File related shims "close$NOCANCEL" => { - let [fd] = &this + let [fd] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(i32) -> i32), (link_name, abi, args))?; - let fd = this.read_scalar(fd)?.to_i32()?; - let result = this.close(fd)?; - this.write_scalar(result, dest)?; + let fd = ecx.read_scalar(fd)?.to_i32()?; + let result = ecx.close(fd)?; + ecx.write_scalar(result, dest)?; } "stat$INODE64" => { - let [path, buf] = &this.check_shim_sig( + let [path, buf] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, *libc::stat) -> i32), (link_name, abi, args), )?; - let result = this.stat(path, buf)?; - this.write_scalar(result, dest)?; + let result = ecx.stat(path, buf)?; + ecx.write_scalar(result, dest)?; } "lstat$INODE64" => { - let [path, buf] = &this.check_shim_sig( + let [path, buf] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, *libc::stat) -> i32), (link_name, abi, args), )?; - let result = this.lstat(path, buf)?; - this.write_scalar(result, dest)?; + let result = ecx.lstat(path, buf)?; + ecx.write_scalar(result, dest)?; } "fstat$INODE64" => { - let [fd, buf] = &this.check_shim_sig( + let [fd, buf] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::stat) -> i32), (link_name, abi, args), )?; - let result = this.fstat(fd, buf)?; - this.write_scalar(result, dest)?; + let result = ecx.fstat(fd, buf)?; + ecx.write_scalar(result, dest)?; } "fstatat$INODE64" => { - let [dirfd, path, buf, flags] = &this.check_shim_sig( + let [dirfd, path, buf, flags] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, *libc::stat, i32) -> i32), (link_name, abi, args), )?; - let result = this.fstatat(dirfd, path, buf, flags)?; - this.write_scalar(result, dest)?; + let result = ecx.fstatat(dirfd, path, buf, flags)?; + ecx.write_scalar(result, dest)?; } "opendir$INODE64" => { - let [name] = &this + let [name] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(*_) -> *_), (link_name, abi, args))?; - let result = this.opendir(name)?; - this.write_scalar(result, dest)?; + let result = ecx.opendir(name)?; + ecx.write_scalar(result, dest)?; } "readdir$INODE64" => { - let [dirp] = &this + let [dirp] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(*_) -> *_), (link_name, abi, args))?; - this.readdir(dirp, dest, "dirent")?; + ecx.readdir(dirp, dest, "dirent")?; } "realpath$DARWIN_EXTSN" => { - let [path, resolved_path] = &this.check_shim_sig( + let [path, resolved_path] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, *_) -> *_), (link_name, abi, args), )?; - let result = this.realpath(path, resolved_path)?; - this.write_scalar(result, dest)?; + let result = ecx.realpath(path, resolved_path)?; + ecx.write_scalar(result, dest)?; } // Environment related shims "_NSGetEnviron" => { - // FIXME: This does not have a direct test (#3179). - let [] = &this - .check_shim_sig(shim_sig!(extern "C" fn() -> *_), (link_name, abi, args))?; - let environ = this.machine.env_vars.unix().environ(); - this.write_pointer(environ, dest)?; + let [] = + &ecx.check_shim_sig(shim_sig!(extern "C" fn() -> *_), (link_name, abi, args))?; + let environ = ecx.machine.env_vars.unix().environ(); + ecx.write_pointer(environ, dest)?; } // Random data generation "CCRandomGenerateBytes" => { - let [bytes, count] = &this.check_shim_sig( + let [bytes, count] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, usize) -> i32), (link_name, abi, args), )?; - let bytes = this.read_pointer(bytes)?; - let count = this.read_target_usize(count)?; - let success = this.eval_libc_i32("kCCSuccess"); - this.gen_random(bytes, count)?; - this.write_int(success, dest)?; + let bytes = ecx.read_pointer(bytes)?; + let count = ecx.read_target_usize(count)?; + let success = ecx.eval_libc_i32("kCCSuccess"); + ecx.gen_random(bytes, count)?; + ecx.write_int(success, dest)?; } // Time related shims "mach_absolute_time" => { - let [] = &this - .check_shim_sig(shim_sig!(extern "C" fn() -> u64), (link_name, abi, args))?; - let result = this.mach_absolute_time()?; - this.write_scalar(result, dest)?; + let [] = + &ecx.check_shim_sig(shim_sig!(extern "C" fn() -> u64), (link_name, abi, args))?; + let result = ecx.mach_absolute_time()?; + ecx.write_scalar(result, dest)?; } "mach_timebase_info" => { - let [info] = &this.check_shim_sig( + let [info] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::mach_timebase_info) -> i32), (link_name, abi, args), )?; - let result = this.mach_timebase_info(info)?; - this.write_scalar(result, dest)?; + let result = ecx.mach_timebase_info(info)?; + ecx.write_scalar(result, dest)?; } "mach_wait_until" => { // FIXME: This does not have a direct test (#3179). - let [deadline] = &this + let [deadline] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(u64) -> i32), (link_name, abi, args))?; - let result = this.mach_wait_until(deadline)?; - this.write_scalar(result, dest)?; + let result = ecx.mach_wait_until(deadline)?; + ecx.write_scalar(result, dest)?; } // Access to command-line arguments "_NSGetArgc" => { - // FIXME: This does not have a direct test (#3179). - let [] = &this - .check_shim_sig(shim_sig!(extern "C" fn() -> *_), (link_name, abi, args))?; - this.write_pointer(this.machine.argc.expect("machine must be initialized"), dest)?; + let [] = + &ecx.check_shim_sig(shim_sig!(extern "C" fn() -> *_), (link_name, abi, args))?; + ecx.write_pointer(ecx.machine.argc.expect("machine must be initialized"), dest)?; } "_NSGetArgv" => { - // FIXME: This does not have a direct test (#3179). - let [] = &this - .check_shim_sig(shim_sig!(extern "C" fn() -> *_), (link_name, abi, args))?; - this.write_pointer(this.machine.argv.expect("machine must be initialized"), dest)?; + let [] = + &ecx.check_shim_sig(shim_sig!(extern "C" fn() -> *_), (link_name, abi, args))?; + ecx.write_pointer(ecx.machine.argv.expect("machine must be initialized"), dest)?; } "_NSGetExecutablePath" => { // FIXME: This does not have a direct test (#3179). - let [buf, bufsize] = &this.check_shim_sig( + let [buf, bufsize] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, *u32) -> i32), (link_name, abi, args), )?; - this.check_no_isolation("`_NSGetExecutablePath`")?; + ecx.check_no_isolation("`_NSGetExecutablePath`")?; - let buf_ptr = this.read_pointer(buf)?; - let bufsize = this.deref_pointer(bufsize)?; + let buf_ptr = ecx.read_pointer(buf)?; + let bufsize = ecx.deref_pointer(bufsize)?; - let Some(path) = this.machine.current_exe.clone() else { + let Some(path) = ecx.machine.current_exe.clone() else { throw_unsup_format!( "_NSGetExecutablePath only works when Miri is run on a file" ) }; - let (written, size_needed) = this.write_path_to_c_str( + let (written, size_needed) = ecx.write_path_to_c_str( &path, buf_ptr, - this.read_scalar(&bufsize)?.to_u32()?.into(), + ecx.read_scalar(&bufsize)?.to_u32()?.into(), )?; if written { - this.write_int(0, dest)?; + ecx.write_int(0, dest)?; } else { - this.write_scalar(Scalar::from_u32(size_needed.try_into().unwrap()), &bufsize)?; - this.write_int(-1, dest)?; + ecx.write_scalar(Scalar::from_u32(size_needed.try_into().unwrap()), &bufsize)?; + ecx.write_int(-1, dest)?; } } // Thread-local storage "_tlv_atexit" => { - let [dtor, data] = &this.check_shim_sig( + let [dtor, data] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(fn(..) -> _, *_) -> ()), (link_name, abi, args), )?; - let dtor = this.read_pointer(dtor)?; - let dtor = this.get_ptr_fn(dtor)?.as_instance()?; - let data = this.read_scalar(data)?; - this.machine.tls.add_thread_atexit( - this.active_thread(), + let dtor = ecx.read_pointer(dtor)?; + let dtor = ecx.get_ptr_fn(dtor)?.as_instance()?; + let data = ecx.read_scalar(data)?; + ecx.machine.tls.add_thread_atexit( + ecx.active_thread(), dtor, data, - this.machine.current_user_relevant_span(), + ecx.machine.current_user_relevant_span(), )?; } // Querying system information "pthread_get_stackaddr_np" => { // FIXME: This does not have a direct test (#3179). - let [thread] = &this.check_shim_sig( + let [thread] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::pthread_t) -> *_), (link_name, abi, args), )?; - this.read_target_usize(thread)?; - let stack_addr = Scalar::from_uint(this.machine.stack_addr, this.pointer_size()); - this.write_scalar(stack_addr, dest)?; + ecx.read_target_usize(thread)?; + ecx.write_int(ecx.machine.stack_addr, dest)?; } "pthread_get_stacksize_np" => { // FIXME: This does not have a direct test (#3179). - let [thread] = &this.check_shim_sig( + let [thread] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::pthread_t) -> usize), (link_name, abi, args), )?; - this.read_target_usize(thread)?; - let stack_size = Scalar::from_uint(this.machine.stack_size, this.pointer_size()); - this.write_scalar(stack_size, dest)?; + ecx.read_target_usize(thread)?; + ecx.write_int(ecx.machine.stack_size, dest)?; } // Threading "pthread_setname_np" => { - let [name] = &this + let [name] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?; // The real implementation has logic in two places: @@ -243,25 +238,24 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // are met, then the name is set and 0 is returned. Otherwise, if // the specified name is lomnger than MAXTHREADNAMESIZE, then // ENAMETOOLONG is returned. - let thread = this.pthread_self()?; - let res = match this.pthread_setname_np( - thread, - this.read_scalar(name)?, - this.eval_libc("MAXTHREADNAMESIZE").to_target_usize(this)?, + let res = match ecx.pthread_setname_np( + None, + ecx.read_pointer(name)?, + ecx.eval_libc("MAXTHREADNAMESIZE").to_target_usize(ecx)?, /* truncate */ false, )? { ThreadNameResult::Ok => Scalar::from_i32(0), ThreadNameResult::NameTooLong => { // Testing on native systems indicates that the error is returned via errno. - this.set_errno_and_return_neg1_i32(LibcError("ENAMETOOLONG"))? + ecx.set_errno_and_return_neg1_i32(LibcError("ENAMETOOLONG"))? } }; // Contrary to the manpage, `pthread_setname_np` on macOS still // returns an integer indicating success. - this.write_scalar(res, dest)?; + ecx.write_scalar(res, dest)?; } "pthread_getname_np" => { - let [thread, name, len] = &this.check_shim_sig( + let [thread, name, len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::pthread_t, *_, usize) -> i32), (link_name, abi, args), )?; @@ -274,34 +268,34 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // https://github.com/apple-oss-distributions/libpthread/blob/c032e0b076700a0a47db75528a282b8d3a06531a/src/pthread.c#L1160-L1175. // The key part is the strlcpy, which truncates the resulting value, // but always null terminates (except for zero sized buffers). - let res = match this.pthread_getname_np( - this.read_scalar(thread)?, - this.read_scalar(name)?, - this.read_scalar(len)?, + let res = match ecx.pthread_getname_np( + Some(thread), + ecx.read_pointer(name)?, + ecx.read_scalar(len)?, /* truncate */ true, )? { ThreadNameResult::Ok => Scalar::from_i32(0), // `NameTooLong` is possible when the buffer is zero sized, ThreadNameResult::NameTooLong => Scalar::from_i32(0), }; - this.write_scalar(res, dest)?; + ecx.write_scalar(res, dest)?; } "pthread_threadid_np" => { - let [thread, tid_ptr] = &this.check_shim_sig( + let [thread, tid_ptr] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::pthread_t, *u64) -> i32), (link_name, abi, args), )?; - let res = this.apple_pthread_threadid_np(thread, tid_ptr)?; - this.write_scalar(res, dest)?; + let res = ecx.apple_pthread_threadid_np(thread, tid_ptr)?; + ecx.write_scalar(res, dest)?; } // Synchronization primitives "os_sync_wait_on_address" => { - let [addr_op, value_op, size_op, flags_op] = &this.check_shim_sig( + let [addr_op, value_op, size_op, flags_op] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, u64, usize, u32) -> i32), (link_name, abi, args), )?; - this.os_sync_wait_on_address( + ecx.os_sync_wait_on_address( addr_op, value_op, size_op, @@ -311,12 +305,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; } "os_sync_wait_on_address_with_deadline" => { - let [addr_op, value_op, size_op, flags_op, clock_op, timeout_op] = &this + let [addr_op, value_op, size_op, flags_op, clock_op, timeout_op] = &ecx .check_shim_sig( shim_sig!(extern "C" fn(*_, u64, usize, u32, u32, u64) -> i32), (link_name, abi, args), )?; - this.os_sync_wait_on_address( + ecx.os_sync_wait_on_address( addr_op, value_op, size_op, @@ -326,12 +320,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; } "os_sync_wait_on_address_with_timeout" => { - let [addr_op, value_op, size_op, flags_op, clock_op, timeout_op] = &this + let [addr_op, value_op, size_op, flags_op, clock_op, timeout_op] = &ecx .check_shim_sig( shim_sig!(extern "C" fn(*_, u64, usize, u32, u32, u64) -> i32), (link_name, abi, args), )?; - this.os_sync_wait_on_address( + ecx.os_sync_wait_on_address( addr_op, value_op, size_op, @@ -341,98 +335,96 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; } "os_sync_wake_by_address_any" => { - let [addr_op, size_op, flags_op] = &this.check_shim_sig( + let [addr_op, size_op, flags_op] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, usize, u32) -> i32), (link_name, abi, args), )?; - this.os_sync_wake_by_address( + ecx.os_sync_wake_by_address( addr_op, size_op, flags_op, /* all */ false, dest, )?; } "os_sync_wake_by_address_all" => { - let [addr_op, size_op, flags_op] = &this.check_shim_sig( + let [addr_op, size_op, flags_op] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, usize, u32) -> i32), (link_name, abi, args), )?; - this.os_sync_wake_by_address( - addr_op, size_op, flags_op, /* all */ true, dest, - )?; + ecx.os_sync_wake_by_address(addr_op, size_op, flags_op, /* all */ true, dest)?; } "os_unfair_lock_lock" => { - let [lock_op] = &this.check_shim_sig( + let [lock_op] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::os_unfair_lock_s) -> ()), (link_name, abi, args), )?; - this.os_unfair_lock_lock(lock_op)?; + ecx.os_unfair_lock_lock(lock_op)?; } "os_unfair_lock_trylock" => { - let [lock_op] = &this.check_shim_sig( + let [lock_op] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::os_unfair_lock_s) -> bool), (link_name, abi, args), )?; - this.os_unfair_lock_trylock(lock_op, dest)?; + ecx.os_unfair_lock_trylock(lock_op, dest)?; } "os_unfair_lock_unlock" => { - let [lock_op] = &this.check_shim_sig( + let [lock_op] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::os_unfair_lock_s) -> ()), (link_name, abi, args), )?; - this.os_unfair_lock_unlock(lock_op)?; + ecx.os_unfair_lock_unlock(lock_op)?; } "os_unfair_lock_assert_owner" => { - let [lock_op] = &this.check_shim_sig( + let [lock_op] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::os_unfair_lock_s) -> ()), (link_name, abi, args), )?; - this.os_unfair_lock_assert_owner(lock_op)?; + ecx.os_unfair_lock_assert_owner(lock_op)?; } "os_unfair_lock_assert_not_owner" => { - let [lock_op] = &this.check_shim_sig( + let [lock_op] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::os_unfair_lock_s) -> ()), (link_name, abi, args), )?; - this.os_unfair_lock_assert_not_owner(lock_op)?; + ecx.os_unfair_lock_assert_not_owner(lock_op)?; } "dispatch_semaphore_create" => { - let [value] = &this.check_shim_sig( + let [value] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(isize) -> *_), (link_name, abi, args), )?; - this.dispatch_semaphore_create(value, dest)?; + ecx.dispatch_semaphore_create(value, dest)?; } "dispatch_semaphore_wait" => { - let [sem, timeout] = &this.check_shim_sig( + let [sem, timeout] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, u64) -> isize), (link_name, abi, args), )?; - this.dispatch_semaphore_wait(sem, timeout, dest)?; + ecx.dispatch_semaphore_wait(sem, timeout, dest)?; } "dispatch_semaphore_signal" => { - let [sem] = &this.check_shim_sig( + let [sem] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_) -> isize), (link_name, abi, args), )?; - this.dispatch_semaphore_signal(sem, dest)?; + ecx.dispatch_semaphore_signal(sem, dest)?; } "dispatch_release" => { - let [sem] = &this + let [sem] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(*_) -> ()), (link_name, abi, args))?; - this.dispatch_release(sem)?; + ecx.dispatch_release(sem)?; } "dispatch_time" => { - let [when, delta] = &this.check_shim_sig( + let [when, delta] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(u64, i64) -> u64), (link_name, abi, args), )?; - this.dispatch_time(when, delta, dest)?; + ecx.dispatch_time(when, delta, dest)?; } "pthread_cond_timedwait_relative_np" => { - let [cond, mutex, reltime] = &this.check_shim_sig( + let [cond, mutex, reltime] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::pthread_cond_t, *libc::pthread_mutex_t, *libc::timespec) -> i32), (link_name, abi, args), )?; - this.pthread_cond_timedwait( + ecx.pthread_cond_timedwait( cond, mutex, reltime, dest, /* macos_relative_np */ true, )?; } @@ -441,13 +433,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // These shims are enabled only when the caller is in the standard library. "confstr" => { // FIXME: This does not have a direct test (#3179). - let [_key, _buf, _buflen] = &this.check_shim_sig( + let [_key, _buf, _buflen] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, usize) -> usize), (link_name, abi, args), )?; // We just pretend that no configuration key exists, and return EINVAL. - this.set_last_error(LibcError("EINVAL"))?; - this.write_int(0, dest)?; + ecx.set_last_error(LibcError("EINVAL"))?; + ecx.write_int(0, dest)?; } _ => return interp_ok(EmulateItemResult::NotSupported), diff --git a/src/tools/miri/src/shims/unix/macos/sync.rs b/src/tools/miri/src/shims/unix/macos/sync.rs index 08ac18e420326..251b23596c7aa 100644 --- a/src/tools/miri/src/shims/unix/macos/sync.rs +++ b/src/tools/miri/src/shims/unix/macos/sync.rs @@ -45,10 +45,6 @@ impl MetaObj for MacOsUnfairLock { } interp_ok(()) } - - fn opaque(&self) -> bool { - true - } } pub enum MacOsFutexTimeout<'a, 'tcx> { @@ -94,10 +90,6 @@ impl MetaObj for MacOsSemaphore { } interp_ok(()) } - - fn opaque(&self) -> bool { - true - } } fn dispatch_semaphore_layout<'tcx>(ecx: &MiriInterpCx<'tcx>) -> TyAndLayout<'tcx> { diff --git a/src/tools/miri/src/shims/unix/mem.rs b/src/tools/miri/src/shims/unix/mem.rs index dde2e74206ae1..48761fd0821a5 100644 --- a/src/tools/miri/src/shims/unix/mem.rs +++ b/src/tools/miri/src/shims/unix/mem.rs @@ -28,7 +28,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { prot: &OpTy<'tcx>, flags: &OpTy<'tcx>, fd: &OpTy<'tcx>, - offset: i128, + offset: i64, ) -> InterpResult<'tcx, Scalar> { let ecx = self.eval_context_mut(); diff --git a/src/tools/miri/src/shims/unix/netbsd/foreign_items.rs b/src/tools/miri/src/shims/unix/netbsd/foreign_items.rs index b5acfe6ea448a..161dcebc0c3e0 100644 --- a/src/tools/miri/src/shims/unix/netbsd/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/netbsd/foreign_items.rs @@ -18,22 +18,22 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { args: &[OpTy<'tcx>], dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx, EmulateItemResult> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); match link_name.as_str() { // Environment "__unsetenv13" => { - let [name] = &this + let [name] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?; - let result = this.unsetenv(name)?; - this.write_scalar(result, dest)?; + let result = ecx.unsetenv(name)?; + ecx.write_scalar(result, dest)?; } // Miscellaneous "__errno" => { - let [] = &this - .check_shim_sig(shim_sig!(extern "C" fn() -> *_), (link_name, abi, args))?; - let errno_place = this.last_error_place()?; - this.write_scalar(errno_place.to_ref(this).to_scalar(), dest)?; + let [] = + &ecx.check_shim_sig(shim_sig!(extern "C" fn() -> *_), (link_name, abi, args))?; + let errno_place = ecx.last_error_place()?; + ecx.write_scalar(errno_place.to_ref(ecx).to_scalar(), dest)?; } _ => return interp_ok(EmulateItemResult::NotSupported), diff --git a/src/tools/miri/src/shims/unix/poll.rs b/src/tools/miri/src/shims/unix/poll.rs index 14689ce6e84f4..61ad0cc955f3c 100644 --- a/src/tools/miri/src/shims/unix/poll.rs +++ b/src/tools/miri/src/shims/unix/poll.rs @@ -32,7 +32,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ) -> InterpResult<'tcx> { let ecx = self.eval_context_mut(); - let nfds: u64 = ecx.read_scalar(nfds)?.to_uint(nfds.layout.size)?.try_into().unwrap(); + let nfds = ecx.read_int::(nfds)?; let timeout = ecx.read_scalar(timeout)?.to_i32()?; // Return `EINVAL`` if `nfds` is greater than `FD_LIMIT`. @@ -157,21 +157,21 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { watcher: Rc, interests: BTreeMap>, ) -> InterpResult<'tcx, u32> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); // Counts the number of poll interests that are fulfilled. let mut fulfilled_interests = 0u32; // Iterate over all ready interests of the watcher and // write the output readiness of all related poll interests. - for ready in watcher.get_ready_interests(watcher.ready_count(), this)? { + for ready in watcher.get_ready_interests(watcher.ready_count(), ecx)? { let fd_num = FdNum::try_from(ready.data).expect("Data is always a file descriptor"); let interest = interests.get(&fd_num).expect("Interest should exist"); fulfilled_interests = fulfilled_interests.strict_add(1); - let poll_events = this.readiness_to_poll_bitflag(ready.active()); - this.write_scalar(Scalar::from_u16(poll_events), &interest.revents_place)?; + let poll_events = ecx.readiness_to_poll_bitflag(ready.active()); + ecx.write_scalar(Scalar::from_u16(poll_events), &interest.revents_place)?; } interp_ok(fulfilled_interests) @@ -180,12 +180,12 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// Convert a [`Readiness`] instance into the corresponding poll /// readiness bitflag. fn readiness_to_poll_bitflag(&self, readiness: &Readiness) -> u16 { - let this = self.eval_context_ref(); + let ecx = self.eval_context_ref(); - let pollin = this.eval_libc_u16("POLLIN"); - let pollout = this.eval_libc_u16("POLLOUT"); - let pollhup = this.eval_libc_u16("POLLHUP"); - let pollerr = this.eval_libc_u16("POLLERR"); + let pollin = ecx.eval_libc_u16("POLLIN"); + let pollout = ecx.eval_libc_u16("POLLOUT"); + let pollhup = ecx.eval_libc_u16("POLLHUP"); + let pollerr = ecx.eval_libc_u16("POLLERR"); let mut bitflag = 0; if readiness.readable { @@ -201,9 +201,9 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { bitflag |= pollerr; } - if matches!(this.tcx.sess.target.os, Os::Linux | Os::Android | Os::FreeBsd | Os::Illumos) { + if matches!(ecx.tcx.sess.target.os, Os::Linux | Os::Android | Os::FreeBsd | Os::Illumos) { // POLLRDHUP only exists on Linux, Android, FreeBSD, and Illumos. - let pollrdhup = this.eval_libc_u16("POLLRDHUP"); + let pollrdhup = ecx.eval_libc_u16("POLLRDHUP"); if readiness.read_closed { bitflag |= pollrdhup; } @@ -217,13 +217,13 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// This always sets the `write_closed` and `error` readiness since they are /// implicitly registered for any interest with `poll`. fn poll_bitflag_to_readiness(&self, mut bitflag: u16) -> InterpResult<'tcx, Readiness> { - let this = self.eval_context_ref(); + let ecx = self.eval_context_ref(); - let pollin = this.eval_libc_u16("POLLIN"); - let pollout = this.eval_libc_u16("POLLOUT"); - let pollhup = this.eval_libc_u16("POLLHUP"); - let pollerr = this.eval_libc_u16("POLLERR"); - let pollnval = this.eval_libc_u16("POLLNVAL"); + let pollin = ecx.eval_libc_u16("POLLIN"); + let pollout = ecx.eval_libc_u16("POLLOUT"); + let pollhup = ecx.eval_libc_u16("POLLHUP"); + let pollerr = ecx.eval_libc_u16("POLLERR"); + let pollnval = ecx.eval_libc_u16("POLLNVAL"); // The POLLHUP and POLLERR interests are always set. let mut readiness = Readiness { write_closed: true, error: true, ..Readiness::EMPTY }; @@ -247,9 +247,9 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { bitflag &= !pollnval; } - if matches!(this.tcx.sess.target.os, Os::Linux | Os::Android | Os::FreeBsd | Os::Illumos) { + if matches!(ecx.tcx.sess.target.os, Os::Linux | Os::Android | Os::FreeBsd | Os::Illumos) { // POLLRDHUP only exists on Linux, Android, FreeBSD, and Illumos. - let pollrdhup = this.eval_libc_u16("POLLRDHUP"); + let pollrdhup = ecx.eval_libc_u16("POLLRDHUP"); if bitflag & pollrdhup == pollrdhup { readiness.read_closed = true; bitflag &= !pollrdhup; diff --git a/src/tools/miri/src/shims/unix/socket.rs b/src/tools/miri/src/shims/unix/socket.rs index 55644d8b6f0f4..51af729b61a6a 100644 --- a/src/tools/miri/src/shims/unix/socket.rs +++ b/src/tools/miri/src/shims/unix/socket.rs @@ -227,16 +227,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { type_: &OpTy<'tcx>, protocol: &OpTy<'tcx>, ) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let domain = this.read_scalar(domain)?.to_i32()?; - let mut flags = this.read_scalar(type_)?.to_i32()?; - let protocol = this.read_scalar(protocol)?.to_i32()?; + let domain = ecx.read_scalar(domain)?.to_i32()?; + let mut flags = ecx.read_scalar(type_)?.to_i32()?; + let protocol = ecx.read_scalar(protocol)?.to_i32()?; // Reject if isolation is enabled - if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op { - this.reject_in_isolation("`socket`", reject_with)?; - return this.set_errno_and_return_neg1_i32(LibcError("EACCES")); + if let IsolatedOp::Reject(reject_with) = ecx.machine.isolated_op { + ecx.reject_in_isolation("`socket`", reject_with)?; + return ecx.set_errno_and_return_neg1_i32(LibcError("EACCES")); } let mut is_non_block = false; @@ -244,13 +244,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Interpret the flag. Every flag we recognize is "subtracted" from `flags`, so // if there is anything left at the end, that's an unsupported flag. if matches!( - this.tcx.sess.target.os, + ecx.tcx.sess.target.os, Os::Linux | Os::Android | Os::FreeBsd | Os::Solaris | Os::Illumos ) { // SOCK_NONBLOCK and SOCK_CLOEXEC only exist on Linux, Android, FreeBSD, // Solaris, and Illumos targets. - let sock_nonblock = this.eval_libc_i32("SOCK_NONBLOCK"); - let sock_cloexec = this.eval_libc_i32("SOCK_CLOEXEC"); + let sock_nonblock = ecx.eval_libc_i32("SOCK_NONBLOCK"); + let sock_cloexec = ecx.eval_libc_i32("SOCK_CLOEXEC"); if flags & sock_nonblock == sock_nonblock { is_non_block = true; flags &= !sock_nonblock; @@ -261,9 +261,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } } - let family = if domain == this.eval_libc_i32("AF_INET") { + let family = if domain == ecx.eval_libc_i32("AF_INET") { socket2::Domain::IPV4 - } else if domain == this.eval_libc_i32("AF_INET6") { + } else if domain == ecx.eval_libc_i32("AF_INET6") { socket2::Domain::IPV6 } else { throw_unsup_format!( @@ -273,24 +273,24 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ); }; - let fd_result = if flags == this.eval_libc_i32("SOCK_STREAM") { - if ![0, this.eval_libc_i32("IPPROTO_TCP")].contains(&protocol) { + let fd_result = if flags == ecx.eval_libc_i32("SOCK_STREAM") { + if ![0, ecx.eval_libc_i32("IPPROTO_TCP")].contains(&protocol) { throw_unsup_format!( "socket: socket protocol {protocol} is unsupported for \ streaming socket, only IPPROTO_TCP and 0 are allowed" ); } - TcpSocket::new(family, is_non_block, this).map(|fd| fd.as_unix()) - } else if flags == this.eval_libc_i32("SOCK_DGRAM") { - if ![0, this.eval_libc_i32("IPPROTO_UDP")].contains(&protocol) { + TcpSocket::new(family, is_non_block, ecx).map(|fd| fd.as_unix()) + } else if flags == ecx.eval_libc_i32("SOCK_DGRAM") { + if ![0, ecx.eval_libc_i32("IPPROTO_UDP")].contains(&protocol) { throw_unsup_format!( "socket: socket protocol {protocol} is unsupported for \ datagram socket, only IPPROTO_UDP and 0 are allowed" ); } - UdpSocket::new(family, is_non_block, this).map(|fd| fd.as_unix()) + UdpSocket::new(family, is_non_block, ecx).map(|fd| fd.as_unix()) } else { throw_unsup_format!( "socket: type {:#x} is unsupported, only SOCK_STREAM, \ @@ -300,10 +300,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }; let fd = match fd_result { Ok(fd) => fd, - Err(e) => return this.set_errno_and_return_neg1_i32(e), + Err(e) => return ecx.set_errno_and_return_neg1_i32(e), }; - let Some(fd_num) = this.machine.fds.insert(fd) else { - return this.set_errno_and_return_neg1_i32(LibcError("EMFILE")); + let Some(fd_num) = ecx.machine.fds.insert(fd) else { + return ecx.set_errno_and_return_neg1_i32(LibcError("EMFILE")); }; interp_ok(Scalar::from_i32(fd_num)) } @@ -314,47 +314,47 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { address: &OpTy<'tcx>, address_len: &OpTy<'tcx>, ) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let socket = this.read_scalar(socket)?.to_i32()?; - let address = match this.read_socket_address(address, address_len, "bind")? { + let socket = ecx.read_scalar(socket)?.to_i32()?; + let address = match ecx.read_socket_address(address, address_len, "bind")? { Ok(addr) => addr, - Err(e) => return this.set_errno_and_return_neg1_i32(e), + Err(e) => return ecx.set_errno_and_return_neg1_i32(e), }; // Get the file handle - let Some(fd) = this.machine.fds.get(socket) else { - return this.set_errno_and_return_neg1_i32(LibcError("EBADF")); + let Some(fd) = ecx.machine.fds.get(socket) else { + return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF")); }; let Some(socket) = fd.as_unix().as_socket() else { - return this.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK")); + return ecx.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK")); }; - match socket.bind(this.machine.communicate(), address, this)? { + match socket.bind(ecx.machine.communicate(), address, ecx)? { Ok(_) => interp_ok(Scalar::from_i32(0)), - Err(e) => this.set_errno_and_return_neg1_i32(e), + Err(e) => ecx.set_errno_and_return_neg1_i32(e), } } fn listen(&mut self, socket: &OpTy<'tcx>, backlog: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let socket = this.read_scalar(socket)?.to_i32()?; - let backlog = this.read_scalar(backlog)?.to_i32()?; + let socket = ecx.read_scalar(socket)?.to_i32()?; + let backlog = ecx.read_scalar(backlog)?.to_i32()?; // Get the file handle - let Some(fd) = this.machine.fds.get(socket) else { - return this.set_errno_and_return_neg1_i32(LibcError("EBADF")); + let Some(fd) = ecx.machine.fds.get(socket) else { + return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF")); }; let Some(socket) = fd.as_unix().as_socket() else { - return this.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK")); + return ecx.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK")); }; - match socket.listen(this.machine.communicate(), backlog, this)? { + match socket.listen(ecx.machine.communicate(), backlog, ecx)? { Ok(_) => interp_ok(Scalar::from_i32(0)), - Err(e) => this.set_errno_and_return_neg1_i32(e), + Err(e) => ecx.set_errno_and_return_neg1_i32(e), } } @@ -369,21 +369,21 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Location where the output scalar is written to. dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let socket = this.read_scalar(socket)?.to_i32()?; - let address_ptr = this.read_pointer(address)?; - let address_len_place = this.deref_pointer(address_len)?; + let socket = ecx.read_scalar(socket)?.to_i32()?; + let address_ptr = ecx.read_pointer(address)?; + let address_len_place = ecx.deref_pointer(address_len)?; let mut flags = - if let Some(flags) = flags { this.read_scalar(flags)?.to_i32()? } else { 0 }; + if let Some(flags) = flags { ecx.read_scalar(flags)?.to_i32()? } else { 0 }; // Get the file handle - let Some(fd) = this.machine.fds.get(socket) else { - return this.set_errno_and_return_neg1(LibcError("EBADF"), dest); + let Some(fd) = ecx.machine.fds.get(socket) else { + return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest); }; let Some(socket) = fd.as_unix().as_socket() else { - return this.set_errno_and_return_neg1(LibcError("ENOTSOCK"), dest); + return ecx.set_errno_and_return_neg1(LibcError("ENOTSOCK"), dest); }; let mut is_client_sock_nonblock = false; @@ -391,13 +391,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Interpret the flag. Every flag we recognize is "subtracted" from `flags`, so // if there is anything left at the end, that's an unsupported flag. if matches!( - this.tcx.sess.target.os, + ecx.tcx.sess.target.os, Os::Linux | Os::Android | Os::FreeBsd | Os::Solaris | Os::Illumos ) { // SOCK_NONBLOCK and SOCK_CLOEXEC only exist on Linux, Android, FreeBSD, // Solaris, and Illumos targets. - let sock_nonblock = this.eval_libc_i32("SOCK_NONBLOCK"); - let sock_cloexec = this.eval_libc_i32("SOCK_CLOEXEC"); + let sock_nonblock = ecx.eval_libc_i32("SOCK_NONBLOCK"); + let sock_cloexec = ecx.eval_libc_i32("SOCK_CLOEXEC"); if flags & sock_nonblock == sock_nonblock { is_client_sock_nonblock = true; flags &= !sock_nonblock; @@ -417,9 +417,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let dest = dest.clone(); socket.accept( - this.machine.communicate(), + ecx.machine.communicate(), is_client_sock_nonblock, - this, + ecx, callback!( @capture<'tcx> { address_ptr: Pointer, @@ -438,11 +438,11 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ecx.write_socket_address(Some(&address), address_ptr, &address_len_place)?; } - // We need to create the scalar using the destination size since + // We need to write the FD using the destination size since // `syscall(SYS_accept4, ...)` returns a long which doesn't match // the int returned from the `accept`/`accept4` syscalls. // See . - ecx.write_scalar(Scalar::from_int(client_sockfd, dest.layout.size), &dest) + ecx.write_int(client_sockfd, &dest) } ), ) @@ -456,29 +456,29 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Location where the output scalar is written to. dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let socket = this.read_scalar(socket)?.to_i32()?; - let address = match this.read_socket_address(address, address_len, "connect")? { + let socket = ecx.read_scalar(socket)?.to_i32()?; + let address = match ecx.read_socket_address(address, address_len, "connect")? { Ok(address) => address, - Err(e) => return this.set_errno_and_return_neg1(e, dest), + Err(e) => return ecx.set_errno_and_return_neg1(e, dest), }; // Get the file handle - let Some(fd) = this.machine.fds.get(socket) else { - return this.set_errno_and_return_neg1(LibcError("EBADF"), dest); + let Some(fd) = ecx.machine.fds.get(socket) else { + return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest); }; let Some(socket) = fd.as_unix().as_socket() else { - return this.set_errno_and_return_neg1(LibcError("ENOTSOCK"), dest); + return ecx.set_errno_and_return_neg1(LibcError("ENOTSOCK"), dest); }; let dest = dest.clone(); socket.connect( - this.machine.communicate(), + ecx.machine.communicate(), address, - this, + ecx, callback!( @capture<'tcx> { dest: MPlaceTy<'tcx> @@ -499,32 +499,30 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Location where the output scalar is written to. dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let socket = this.read_scalar(socket)?.to_i32()?; - let buffer_ptr = this.read_pointer(buffer)?; - let length = this.read_target_usize(length)?; - let mut flags = this.read_scalar(flags)?.to_i32()?; + let socket = ecx.read_scalar(socket)?.to_i32()?; + let buffer_ptr = ecx.read_pointer(buffer)?; + let length = ecx.read_target_usize(length)?; + let mut flags = ecx.read_scalar(flags)?.to_i32()?; let dest_addr = match dest_addr { Some((dest_addr, dest_addr_len)) => { - let dest_addr_ptr = this.read_pointer(dest_addr)?; - let socklen_layout = this.libc_ty_layout("socklen_t"); - let dest_addr_len_int = - this.read_scalar(dest_addr_len)?.to_uint(socklen_layout.size)?; + let dest_addr_ptr = ecx.read_pointer(dest_addr)?; + let dest_addr_len_int = ecx.read_int::(dest_addr_len)?; // POSIX says the destination is entirely ignored for TCP sockets, but that does not // match reality, so we eagerly read the destination when one is given. - if this.ptr_is_null(dest_addr_ptr)? || dest_addr_len_int == 0 { + if ecx.ptr_is_null(dest_addr_ptr)? || dest_addr_len_int == 0 { // If the address pointer is a nullptr or the address length is zero we ignore // the destination address. BSDs return EINVAL when the address length is zero // and the address pointer is an invalid pointer; that is so far away from what // POSIX documents for TCP sockets that we do not try to emulate it. None } else { - match this.read_socket_address(dest_addr, dest_addr_len, "sendto")? { + match ecx.read_socket_address(dest_addr, dest_addr_len, "sendto")? { Ok(dest_addr) => Some(dest_addr), - Err(e) => return this.set_errno_and_return_neg1(e, dest), + Err(e) => return ecx.set_errno_and_return_neg1(e, dest), } } } @@ -532,12 +530,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }; // Get the file handle - let Some(fd) = this.machine.fds.get(socket) else { - return this.set_errno_and_return_neg1(LibcError("EBADF"), dest); + let Some(fd) = ecx.machine.fds.get(socket) else { + return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest); }; let Some(socket) = fd.as_unix().as_socket() else { - return this.set_errno_and_return_neg1(LibcError("ENOTSOCK"), dest); + return ecx.set_errno_and_return_neg1(LibcError("ENOTSOCK"), dest); }; let mut is_non_block = false; @@ -545,13 +543,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Interpret the flag. Every flag we recognize is "subtracted" from `flags`, so // if there is anything left at the end, that's an unsupported flag. if matches!( - this.tcx.sess.target.os, + ecx.tcx.sess.target.os, Os::Linux | Os::Android | Os::FreeBsd | Os::Solaris | Os::Illumos ) { // MSG_NOSIGNAL and MSG_DONTWAIT only exist on Linux, Android, FreeBSD, // Solaris, and Illumos targets. - let msg_nosignal = this.eval_libc_i32("MSG_NOSIGNAL"); - let msg_dontwait = this.eval_libc_i32("MSG_DONTWAIT"); + let msg_nosignal = ecx.eval_libc_i32("MSG_NOSIGNAL"); + let msg_dontwait = ecx.eval_libc_i32("MSG_DONTWAIT"); if flags & msg_nosignal == msg_nosignal { // This is only needed to ensure that no EPIPE signal is sent when // trying to send into a stream which is no longer connected. @@ -573,12 +571,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let dest = dest.clone(); socket.send( - this.machine.communicate(), + ecx.machine.communicate(), buffer_ptr, length, is_non_block, dest_addr, - this, + ecx, callback!( @capture<'tcx> { dest: MPlaceTy<'tcx>, @@ -603,26 +601,25 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Location where the output scalar is written to. dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let socket = this.read_scalar(socket)?.to_i32()?; - let buffer_ptr = this.read_pointer(buffer)?; - let length = this.read_target_usize(length)?; - let mut flags = this.read_scalar(flags)?.to_i32()?; + let socket = ecx.read_scalar(socket)?.to_i32()?; + let buffer_ptr = ecx.read_pointer(buffer)?; + let length = ecx.read_target_usize(length)?; + let mut flags = ecx.read_scalar(flags)?.to_i32()?; let dest_addr = match dest_addr { - Some((addr, addr_len)) => - Some((this.read_pointer(addr)?, this.deref_pointer(addr_len)?)), + Some((addr, addr_len)) => Some((ecx.read_pointer(addr)?, ecx.deref_pointer(addr_len)?)), None => None, }; // Get the file handle - let Some(fd) = this.machine.fds.get(socket) else { - return this.set_errno_and_return_neg1(LibcError("EBADF"), dest); + let Some(fd) = ecx.machine.fds.get(socket) else { + return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest); }; let Some(socket) = fd.as_unix().as_socket() else { - return this.set_errno_and_return_neg1(LibcError("ENOTSOCK"), dest); + return ecx.set_errno_and_return_neg1(LibcError("ENOTSOCK"), dest); }; let mut is_peek = false; @@ -631,16 +628,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Interpret the flag. Every flag we recognize is "subtracted" from `flags`, so // if there is anything left at the end, that's an unsupported flag. - let msg_peek = this.eval_libc_i32("MSG_PEEK"); + let msg_peek = ecx.eval_libc_i32("MSG_PEEK"); if flags & msg_peek == msg_peek { is_peek = true; flags &= !msg_peek; } - if matches!(this.tcx.sess.target.os, Os::Linux | Os::Android | Os::FreeBsd | Os::Illumos) { + if matches!(ecx.tcx.sess.target.os, Os::Linux | Os::Android | Os::FreeBsd | Os::Illumos) { // MSG_CMSG_CLOEXEC only exists on Linux, Android, FreeBSD, // and Illumos targets. - let msg_cmsg_cloexec = this.eval_libc_i32("MSG_CMSG_CLOEXEC"); + let msg_cmsg_cloexec = ecx.eval_libc_i32("MSG_CMSG_CLOEXEC"); if flags & msg_cmsg_cloexec == msg_cmsg_cloexec { // We don't support `exec` so we can ignore this. flags &= !msg_cmsg_cloexec; @@ -648,12 +645,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } if matches!( - this.tcx.sess.target.os, + ecx.tcx.sess.target.os, Os::Linux | Os::Android | Os::FreeBsd | Os::Solaris | Os::Illumos ) { // MSG_DONTWAIT only exists on Linux, Android, FreeBSD, // Solaris, and Illumos targets. - let msg_dontwait = this.eval_libc_i32("MSG_DONTWAIT"); + let msg_dontwait = ecx.eval_libc_i32("MSG_DONTWAIT"); if flags & msg_dontwait == msg_dontwait { flags &= !msg_dontwait; is_non_block = true; @@ -670,12 +667,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let dest = dest.clone(); socket.recv( - this.machine.communicate(), + ecx.machine.communicate(), buffer_ptr, length, is_peek, is_non_block, - this, + ecx, callback!( @capture<'tcx> { dest_addr: Option<(Pointer, MPlaceTy<'tcx>)>, @@ -714,36 +711,36 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { option_value: &OpTy<'tcx>, option_len: &OpTy<'tcx>, ) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); - - let socket = this.read_scalar(socket)?.to_i32()?; - let level = this.read_scalar(level)?.to_i32()?; - let option_name = this.read_scalar(option_name)?.to_i32()?; - let option_value_ptr = this.read_pointer(option_value)?; - let Some(option_len) = this.read_socklen(option_len)? else { - return this.set_errno_and_return_neg1_i32(LibcError("EINVAL")); + let ecx = self.eval_context_mut(); + + let socket = ecx.read_scalar(socket)?.to_i32()?; + let level = ecx.read_scalar(level)?.to_i32()?; + let option_name = ecx.read_scalar(option_name)?.to_i32()?; + let option_value_ptr = ecx.read_pointer(option_value)?; + let Ok(option_len) = u64::try_from(ecx.read_int::(option_len)?) else { + return ecx.set_errno_and_return_neg1_i32(LibcError("EINVAL")); }; // Check that the buffer has (at least) the given size. - this.check_ptr_access( + ecx.check_ptr_access( option_value_ptr, Size::from_bytes(option_len), CheckInAllocMsg::MemoryAccess, )?; // Get the file handle - let Some(fd) = this.machine.fds.get(socket) else { - return this.set_errno_and_return_neg1_i32(LibcError("EBADF")); + let Some(fd) = ecx.machine.fds.get(socket) else { + return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF")); }; let Some(socket) = fd.as_unix().as_socket() else { - return this.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK")); + return ecx.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK")); }; - let result = socket.setsockopt(level, option_name, option_value_ptr, option_len, this)?; + let result = socket.setsockopt(level, option_name, option_value_ptr, option_len, ecx)?; match result { Ok(_) => interp_ok(Scalar::from_i32(0)), - Err(e) => this.set_errno_and_return_neg1_i32(e), + Err(e) => ecx.set_errno_and_return_neg1_i32(e), } } @@ -753,44 +750,42 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { level: &OpTy<'tcx>, option_name: &OpTy<'tcx>, option_value: &OpTy<'tcx>, - option_len: &OpTy<'tcx>, + option_len_ptr: &OpTy<'tcx>, ) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let socket = this.read_scalar(socket)?.to_i32()?; - let level = this.read_scalar(level)?.to_i32()?; - let option_name = this.read_scalar(option_name)?.to_i32()?; + let socket = ecx.read_scalar(socket)?.to_i32()?; + let level = ecx.read_scalar(level)?.to_i32()?; + let option_name = ecx.read_scalar(option_name)?.to_i32()?; // These two pointers are used to return the value: `len_ptr` initially stores how much space // is available. If the actual value fits into that space, it is written to // `value_ptr` and `len_ptr` is updated to represent how many bytes // were actually written. If the value does not fit, it is silently truncated. // Also see . - let option_value_ptr = this.read_pointer(option_value)?; - let option_len_ptr = this.read_pointer(option_len)?; + let option_value_ptr = ecx.read_pointer(option_value)?; + let option_len_place = ecx.deref_pointer(option_len_ptr)?; // Get the file handle - let Some(fd) = this.machine.fds.get(socket) else { - return this.set_errno_and_return_neg1_i32(LibcError("EBADF")); + let Some(fd) = ecx.machine.fds.get(socket) else { + return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF")); }; let Some(socket) = fd.as_unix().as_socket() else { - return this.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK")); + return ecx.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK")); }; - if this.ptr_is_null(option_value_ptr)? || this.ptr_is_null(option_len_ptr)? { + if ecx.ptr_is_null(option_value_ptr)? || ecx.ptr_is_null(option_len_place.ptr())? { // This socket option returns a value and thus we need to return EFAULT // when either the value or the length pointers are null pointers. - return this.set_errno_and_return_neg1_i32(LibcError("EFAULT")); + return ecx.set_errno_and_return_neg1_i32(LibcError("EFAULT")); } - let socklen_layout = this.libc_ty_layout("socklen_t"); - let option_len_ptr_mplace = this.ptr_to_mplace(option_len_ptr, socklen_layout); - let Some(option_len) = this.read_socklen(&option_len_ptr_mplace)? else { - return this.set_errno_and_return_neg1_i32(LibcError("EINVAL")); + let Ok(option_len) = u64::try_from(ecx.read_int::(&option_len_place)?) else { + return ecx.set_errno_and_return_neg1_i32(LibcError("EINVAL")); }; // Check that the buffer has (at least) the given size. - this.check_ptr_access( + ecx.check_ptr_access( option_value_ptr, Size::from_bytes(option_len), CheckInAllocMsg::MemoryAccess, @@ -798,15 +793,15 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // `socket.getsockopt` returns a temporary buffer as `option_value_ptr` might not point // to a large enough buffer, in which case we have to truncate. - let value_mplace = match socket.getsockopt(level, option_name, this)? { + let value_mplace = match socket.getsockopt(level, option_name, ecx)? { Ok(value_mplace) => value_mplace, - Err(e) => return this.set_errno_and_return_neg1_i32(e), + Err(e) => return ecx.set_errno_and_return_neg1_i32(e), }; // Truncated size of the output value. let output_value_len = value_mplace.layout.size.min(Size::from_bytes(option_len)); // Copy the truncated value into the buffer pointed to by `option_value_ptr`. - this.mem_copy( + ecx.mem_copy( value_mplace.ptr(), option_value_ptr, // Truncate the value to fit the provided buffer. @@ -817,14 +812,11 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; // Deallocate the value buffer as it was only needed to store the value and // copy it into the buffer pointed to by `option_value_ptr`. - this.deallocate_ptr(value_mplace.ptr(), None, MemoryKind::Stack)?; + ecx.deallocate_ptr(value_mplace.ptr(), None, MemoryKind::Stack)?; // On output, the length pointer contains the amount of bytes written -- not the size // of the value before truncation. - this.write_scalar( - Scalar::from_uint(output_value_len.bytes(), socklen_layout.size), - &option_len_ptr_mplace, - )?; + ecx.write_int(output_value_len.bytes(), &option_len_place)?; interp_ok(Scalar::from_i32(0)) } @@ -835,27 +827,27 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { address: &OpTy<'tcx>, address_len: &OpTy<'tcx>, ) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let socket = this.read_scalar(socket)?.to_i32()?; - let address_ptr = this.read_pointer(address)?; - let address_len_place = this.deref_pointer(address_len)?; + let socket = ecx.read_scalar(socket)?.to_i32()?; + let address_ptr = ecx.read_pointer(address)?; + let address_len_place = ecx.deref_pointer(address_len)?; // Get the file handle - let Some(fd) = this.machine.fds.get(socket) else { - return this.set_errno_and_return_neg1_i32(LibcError("EBADF")); + let Some(fd) = ecx.machine.fds.get(socket) else { + return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF")); }; let Some(socket) = fd.as_unix().as_socket() else { - return this.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK")); + return ecx.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK")); }; - let address = match socket.getsockname(this.machine.communicate(), this)? { + let address = match socket.getsockname(ecx.machine.communicate(), ecx)? { Ok(address) => address, - Err(e) => return this.set_errno_and_return_neg1_i32(e), + Err(e) => return ecx.set_errno_and_return_neg1_i32(e), }; - this.write_socket_address(Some(&address), address_ptr, &address_len_place) + ecx.write_socket_address(Some(&address), address_ptr, &address_len_place) .map(|()| Scalar::from_i32(0)) } @@ -867,26 +859,26 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Location where the output scalar is written to. dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let socket = this.read_scalar(socket)?.to_i32()?; - let address_ptr = this.read_pointer(address)?; - let address_len_place = this.deref_pointer(address_len)?; + let socket = ecx.read_scalar(socket)?.to_i32()?; + let address_ptr = ecx.read_pointer(address)?; + let address_len_place = ecx.deref_pointer(address_len)?; // Get the file handle - let Some(fd) = this.machine.fds.get(socket) else { - return this.set_errno_and_return_neg1(LibcError("EBADF"), dest); + let Some(fd) = ecx.machine.fds.get(socket) else { + return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest); }; let Some(socket) = fd.as_unix().as_socket() else { - return this.set_errno_and_return_neg1(LibcError("ENOTSOCK"), dest); + return ecx.set_errno_and_return_neg1(LibcError("ENOTSOCK"), dest); }; let dest = dest.clone(); socket.getpeername( - this.machine.communicate(), - this, + ecx.machine.communicate(), + ecx, callback!( @capture<'tcx> { address_ptr: Pointer, @@ -910,35 +902,35 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } fn shutdown(&mut self, socket: &OpTy<'tcx>, how: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let socket = this.read_scalar(socket)?.to_i32()?; - let how = this.read_scalar(how)?.to_i32()?; + let socket = ecx.read_scalar(socket)?.to_i32()?; + let how = ecx.read_scalar(how)?.to_i32()?; // Get the file handle - let Some(fd) = this.machine.fds.get(socket) else { - return this.set_errno_and_return_neg1_i32(LibcError("EBADF")); + let Some(fd) = ecx.machine.fds.get(socket) else { + return ecx.set_errno_and_return_neg1_i32(LibcError("EBADF")); }; let Some(socket) = fd.as_unix().as_socket() else { - return this.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK")); + return ecx.set_errno_and_return_neg1_i32(LibcError("ENOTSOCK")); }; - let is_read_shutdown = how == this.eval_libc_i32("SHUT_RD"); - let is_write_shutdown = how == this.eval_libc_i32("SHUT_WR"); - let is_read_write_shutdown = how == this.eval_libc_i32("SHUT_RDWR"); + let is_read_shutdown = how == ecx.eval_libc_i32("SHUT_RD"); + let is_write_shutdown = how == ecx.eval_libc_i32("SHUT_WR"); + let is_read_write_shutdown = how == ecx.eval_libc_i32("SHUT_RDWR"); let how = match () { _ if is_read_shutdown => Shutdown::Read, _ if is_write_shutdown => Shutdown::Write, _ if is_read_write_shutdown => Shutdown::Both, // An invalid value was passed to `how`. - _ => return this.set_errno_and_return_neg1_i32(LibcError("EINVAL")), + _ => return ecx.set_errno_and_return_neg1_i32(LibcError("EINVAL")), }; - match socket.shutdown(this.machine.communicate(), how, this)? { + match socket.shutdown(ecx.machine.communicate(), how, ecx)? { Ok(_) => interp_ok(Scalar::from_i32(0)), - Err(e) => this.set_errno_and_return_neg1_i32(e), + Err(e) => ecx.set_errno_and_return_neg1_i32(e), } } @@ -1293,3 +1285,22 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { throw_unsup_format!("getsockopt: option {option:#x} is unsupported for level IPPROTO_TCP"); } } + +/// Get the deadline for an action (e.g. reading or writing). +/// When `is_non_block` is [`true`], the returned deadline is "now", i.e., +/// we wake up immediately if the action cannot be completed. +/// If `action_timeout` is `Some(duration)`, the returned deadline is in the +/// future, at now + `duration`. Otherwise, no deadline ([`None`]) is +/// returned, indicating that the action can block indefinitely. +pub(crate) fn socket_action_deadline<'tcx>( + ecx: &MiriInterpCx<'tcx>, + is_non_block: bool, + action_timeout: Option, +) -> Option { + if is_non_block { + // Non-blocking sockets always have a zero timeout. + Some(ecx.machine.monotonic_clock.now().into()) + } else { + action_timeout.map(|duration| ecx.machine.monotonic_clock.now().add_lossy(duration).into()) + } +} diff --git a/src/tools/miri/src/shims/unix/socket_address.rs b/src/tools/miri/src/shims/unix/socket_address.rs index 154e3c60c3dfd..262aaa9fa00dc 100644 --- a/src/tools/miri/src/shims/unix/socket_address.rs +++ b/src/tools/miri/src/shims/unix/socket_address.rs @@ -14,14 +14,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { hints: &OpTy<'tcx>, res: &OpTy<'tcx>, ) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let node_ptr = this.read_pointer(node)?; - let service_ptr = this.read_pointer(service)?; - let hints_ptr = this.read_pointer(hints)?; - let res_mplace = this.deref_pointer(res)?; + let node_ptr = ecx.read_pointer(node)?; + let service_ptr = ecx.read_pointer(service)?; + let hints_place = ecx.deref_pointer(hints)?; + let res_place = ecx.deref_pointer(res)?; - if this.ptr_is_null(node_ptr)? { + if ecx.ptr_is_null(node_ptr)? { // We cannot get an address without the `node` part because // the [`ToSocketAddrs`] trait requires an address. throw_unsup_format!( @@ -30,10 +30,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } let mut port = 0; - if !this.ptr_is_null(service_ptr)? { + if !ecx.ptr_is_null(service_ptr)? { // The C-string at `service_ptr` is either a port number or a name of a // well-known service. - let service_c_str = this.read_c_str(service_ptr)?; + let service_c_str = ecx.read_c_str(service_ptr)?; // Try to parse `service_c_str` as a number -- the only case we support. match str::from_utf8(service_c_str).ok().and_then(|s| s.parse::().ok()) { @@ -49,12 +49,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } } - let node_c_str = this.read_c_str(node_ptr)?; + let node_c_str = ecx.read_c_str(node_ptr)?; let Some(node_str) = str::from_utf8(node_c_str).ok() else { throw_unsup_format!("getaddrinfo: node is not a valid UTF-8 string") }; - if this.ptr_is_null(hints_ptr)? { + if ecx.ptr_is_null(hints_place.ptr())? { // The standard library only supports getting TCP address information. The // empty hints pointer would allow any socket type so we cannot support it. throw_unsup_format!( @@ -62,34 +62,31 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ) } - let hints_layout = this.libc_ty_layout("addrinfo"); - let hints_mplace = this.ptr_to_mplace(hints_ptr, hints_layout); - - let family_field = this.project_field_named(&hints_mplace, "ai_family")?; - let family = this.read_scalar(&family_field)?; + let family_field = ecx.project_field_named(&hints_place, "ai_family")?; + let family = ecx.read_scalar(&family_field)?; if family != Scalar::from_i32(0) { // We cannot provide a family hint to the standard library implementation. throw_unsup_format!("getaddrinfo: family hints are not supported") } - let socktype_field = this.project_field_named(&hints_mplace, "ai_socktype")?; - let socktype = this.read_scalar(&socktype_field)?; - if socktype != this.eval_libc("SOCK_STREAM") { + let socktype_field = ecx.project_field_named(&hints_place, "ai_socktype")?; + let socktype = ecx.read_scalar(&socktype_field)?; + if socktype != ecx.eval_libc("SOCK_STREAM") { // The standard library only supports getting TCP address information. throw_unsup_format!( "getaddrinfo: only queries with socket type SOCK_STREAM are supported" ) } - let protocol_field = this.project_field_named(&hints_mplace, "ai_protocol")?; - let protocol = this.read_scalar(&protocol_field)?; + let protocol_field = ecx.project_field_named(&hints_place, "ai_protocol")?; + let protocol = ecx.read_scalar(&protocol_field)?; if protocol != Scalar::from_i32(0) { // We cannot provide a protocol hint to the standard library implementation. throw_unsup_format!("getaddrinfo: protocol hints are not supported") } - let flags_field = this.project_field_named(&hints_mplace, "ai_flags")?; - let flags = this.read_scalar(&flags_field)?; + let flags_field = ecx.project_field_named(&hints_place, "ai_flags")?; + let flags = ecx.read_scalar(&flags_field)?; if flags != Scalar::from_i32(0) { // We cannot provide any flag hints to the standard library implementation. throw_unsup_format!("getaddrinfo: flag hints are not supported") @@ -102,42 +99,22 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // address resolution. Because the standard library doesn't expose those integer values // directly, we just return a generic protocol error. // The actual error is emitted as part of a warning diagnostic. - this.emit_diagnostic(NonHaltingDiagnostic::SocketAddressResolution { error: e }); - this.set_last_error(LibcError("EPROTO"))?; - return interp_ok(this.eval_libc("EAI_SYSTEM")); + ecx.emit_diagnostic(NonHaltingDiagnostic::SocketAddressResolution { error: e }); + ecx.set_last_error(LibcError("EPROTO"))?; + return interp_ok(ecx.eval_libc("EAI_SYSTEM")); } }; - let res_ptr = this.allocate_address_infos(socket_addrs)?; + let res_ptr = ecx.allocate_address_infos(socket_addrs)?; - this.write_pointer(res_ptr, &res_mplace)?; + ecx.write_pointer(res_ptr, &res_place)?; interp_ok(Scalar::from_i32(0)) } fn freeaddrinfo(&mut self, res: &OpTy<'tcx>) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); - - let res_ptr = this.read_pointer(res)?; - - this.free_address_infos(res_ptr) - } - - /// Read a `socklen_t` value. Returns `None` if it does not fit into a `u64`, e.g. if it - /// is negative, which is possible on targets where `socklen_t` is signed. - fn read_socklen( - &self, - op: &impl Projectable<'tcx, Provenance>, - ) -> InterpResult<'tcx, Option> { - let ecx = self.eval_context_ref(); - - let layout = op.layout(); - let scalar = ecx.read_scalar(op)?; - let len = if layout.backend_repr.is_signed() { - u64::try_from(scalar.to_int(layout.size)?).ok() - } else { - u64::try_from(scalar.to_uint(layout.size)?).ok() - }; - interp_ok(len) + let ecx = self.eval_context_mut(); + let addrinfo_place = ecx.deref_pointer(res)?; + ecx.free_address_infos(&addrinfo_place) } /// Attempt to turn an address and length operand into a standard library socket address. @@ -149,17 +126,17 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { address_len: &OpTy<'tcx>, foreign_name: &'static str, ) -> InterpResult<'tcx, Result> { - let this = self.eval_context_ref(); + let ecx = self.eval_context_ref(); // We only support address lengths which can be stored in a u64 since the // size of a layout is also stored in a u64. - let Some(address_len) = this.read_socklen(address_len)? else { + let Ok(address_len) = u64::try_from(ecx.read_int::(address_len)?) else { return interp_ok(Err(LibcError("EINVAL"))); }; - let address = this.deref_pointer(address)?; + let address = ecx.deref_pointer(address)?; // Ensure the pointer is actually dereferenceable for that length. - this.check_ptr_access( + ecx.check_ptr_access( address.ptr(), Size::from_bytes(address_len), CheckInAllocMsg::MemoryAccess, @@ -171,32 +148,31 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { return interp_ok(Err(LibcError("EINVAL"))); } - let family_field = this.project_field_named(&address, "sa_family")?; - let family_layout = this.libc_ty_layout("sa_family_t"); - let family = this.read_scalar(&family_field)?.to_int(family_layout.size)?; + let family_field = ecx.project_field_named(&address, "sa_family")?; + let family = ecx.read_int::(&family_field)?; // Depending on the family, decide whether it's IPv4 or IPv6 and use specialized layout // to extract address and port. - let socket_addr = if family == this.eval_libc_i32("AF_INET").into() { - let sockaddr_in_layout = this.libc_ty_layout("sockaddr_in"); + let socket_addr = if family == ecx.eval_libc_i32("AF_INET").into() { + let sockaddr_in_layout = ecx.libc_ty_layout("sockaddr_in"); if address_len != sockaddr_in_layout.size.bytes() { // Address length should be exactly the length of an IPv4 address. return interp_ok(Err(LibcError("EINVAL"))); } - let address = this.ptr_to_mplace(address.ptr(), sockaddr_in_layout); + let address = ecx.ptr_to_mplace(address.ptr(), sockaddr_in_layout); - let port_field = this.project_field_named(&address, "sin_port")?; + let port_field = ecx.project_field_named(&address, "sin_port")?; // Read bytes and treat them as big endian since port is stored in network byte order. - let port_bytes: [u8; 2] = this + let port_bytes: [u8; 2] = ecx .read_bytes_ptr_strip_provenance(port_field.ptr(), Size::from_bytes(2))? .try_into() .unwrap(); let port = u16::from_be_bytes(port_bytes); - let addr_field = this.project_field_named(&address, "sin_addr")?; - let s_addr_field = this.project_field_named(&addr_field, "s_addr")?; + let addr_field = ecx.project_field_named(&address, "sin_addr")?; + let s_addr_field = ecx.project_field_named(&addr_field, "s_addr")?; // Read bytes and treat them as big endian since address is stored in network byte order. - let addr_bytes: [u8; 4] = this + let addr_bytes: [u8; 4] = ecx .read_bytes_ptr_strip_provenance(s_addr_field.ptr(), Size::from_bytes(4))? .try_into() .unwrap(); @@ -206,42 +182,42 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // We ignore the `sin_len` field as it isn't respected by any of the supported targets. SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from_bits(addr_bits), port)) - } else if family == this.eval_libc_i32("AF_INET6").into() { - let sockaddr_in6_layout = this.libc_ty_layout("sockaddr_in6"); + } else if family == ecx.eval_libc_i32("AF_INET6").into() { + let sockaddr_in6_layout = ecx.libc_ty_layout("sockaddr_in6"); if address_len != sockaddr_in6_layout.size.bytes() { // Address length should be exactly the length of an IPv6 address. return interp_ok(Err(LibcError("EINVAL"))); } - let address = this.ptr_to_mplace(address.ptr(), sockaddr_in6_layout); + let address = ecx.ptr_to_mplace(address.ptr(), sockaddr_in6_layout); - let port_field = this.project_field_named(&address, "sin6_port")?; + let port_field = ecx.project_field_named(&address, "sin6_port")?; // Read bytes and treat them as big endian since port is stored in network byte order. - let port_bytes: [u8; 2] = this + let port_bytes: [u8; 2] = ecx .read_bytes_ptr_strip_provenance(port_field.ptr(), Size::from_bytes(2))? .try_into() .unwrap(); let port = u16::from_be_bytes(port_bytes); - let addr_field = this.project_field_named(&address, "sin6_addr")?; - let s_addr_field = this + let addr_field = ecx.project_field_named(&address, "sin6_addr")?; + let s_addr_field = ecx .project_field_named(&addr_field, "s6_addr")? - .transmute(this.machine.layouts.u128, this)?; + .transmute(ecx.machine.layouts.u128, ecx)?; // Read bytes and treat them as big endian since address is stored in network byte order. - let addr_bytes: [u8; 16] = this + let addr_bytes: [u8; 16] = ecx .read_bytes_ptr_strip_provenance(s_addr_field.ptr(), Size::from_bytes(16))? .try_into() .unwrap(); let addr_bits = u128::from_be_bytes(addr_bytes); - let flowinfo_field = this.project_field_named(&address, "sin6_flowinfo")?; + let flowinfo_field = ecx.project_field_named(&address, "sin6_flowinfo")?; // flowinfo doesn't get the big endian treatment as this field is stored in native byte order // and not in network byte order. - let flowinfo = this.read_scalar(&flowinfo_field)?.to_u32()?; + let flowinfo = ecx.read_scalar(&flowinfo_field)?.to_u32()?; - let scope_id_field = this.project_field_named(&address, "sin6_scope_id")?; + let scope_id_field = ecx.project_field_named(&address, "sin6_scope_id")?; // scope_id doesn't get the big endian treatment as this field is stored in native byte order // and not in network byte order. - let scope_id = this.read_scalar(&scope_id_field)?.to_u32()?; + let scope_id = ecx.read_scalar(&scope_id_field)?.to_u32()?; // We ignore the `sin6_len` field as it isn't respected by any of the supported targets. @@ -282,9 +258,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { address_ptr: Pointer, address_len_place: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - if address.is_none() && this.ptr_is_null(address_len_place.ptr())? { + if address.is_none() && ecx.ptr_is_null(address_len_place.ptr())? { // It is okay for the len ptr to be null *if* we have nothing to write. return interp_ok(()); } @@ -297,14 +273,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // We only support buffer lengths which can be stored in a u64 since the // size of a layout in bytes is also stored in a u64. - let address_buffer_len: u64 = this - .read_scalar(address_len_place)? - .to_int(address_len_place.layout.size)? - .try_into() - .unwrap(); + let address_buffer_len: u64 = ecx.read_int::(address_len_place)?; // Check that the buffer indeed has (at least) the given size. - this.check_ptr_access( + ecx.check_ptr_access( address_ptr, Size::from_bytes(address_buffer_len), CheckInAllocMsg::MemoryAccess, @@ -313,7 +285,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let Some(address) = address else { // We want to write an "empty" socket address. In this case we just set // the address length to zero. - return this.write_int(0, address_len_place); + return ecx.write_int(0, address_len_place); }; let address_buffer = match address { @@ -323,44 +295,42 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Port needs to be manually turned into network byte order. let port = address.port().to_be(); - let sockaddr_in_layout = this.libc_ty_layout("sockaddr_in"); + let sockaddr_in_layout = ecx.libc_ty_layout("sockaddr_in"); // Allocate new buffer on the stack with the `sockaddr_in` layout. // We need a temporary buffer as `address_ptr` might not point to a large enough // buffer, in which case we have to truncate. - let address_buffer = this.allocate(sockaddr_in_layout, MemoryKind::Stack)?; + let address_buffer = ecx.allocate(sockaddr_in_layout, MemoryKind::Stack)?; - let sin_family_field = this.project_field_named(&address_buffer, "sin_family")?; + let sin_family_field = ecx.project_field_named(&address_buffer, "sin_family")?; // We cannot simply write the `AF_INET` scalar into the `sin_family_field` because on most // systems the field has a layout of 16-bit whilst the scalar has a size of 32-bit. // Since the `AF_INET` constant is chosen such that it can safely be converted into // a 16-bit integer, we use the following logic to get a scalar of the right size. - let af_inet = this.eval_libc("AF_INET"); - let address_family = - Scalar::from_int(af_inet.to_int(af_inet.size())?, sin_family_field.layout.size); - this.write_scalar(address_family, &sin_family_field)?; + let af_inet = ecx.eval_libc_i32("AF_INET"); + ecx.write_int(af_inet, &sin_family_field)?; - let sin_port_field = this.project_field_named(&address_buffer, "sin_port")?; + let sin_port_field = ecx.project_field_named(&address_buffer, "sin_port")?; // Write the port in target native endianness bytes as we already converted it // to big endian above. - this.write_bytes_ptr(sin_port_field.ptr(), port.to_ne_bytes())?; + ecx.write_bytes_ptr(sin_port_field.ptr(), port.to_ne_bytes())?; - let sin_addr_field = this.project_field_named(&address_buffer, "sin_addr")?; - let s_addr_field = this.project_field_named(&sin_addr_field, "s_addr")?; - this.write_bytes_ptr(s_addr_field.ptr(), address_bytes)?; + let sin_addr_field = ecx.project_field_named(&address_buffer, "sin_addr")?; + let s_addr_field = ecx.project_field_named(&sin_addr_field, "s_addr")?; + ecx.write_bytes_ptr(s_addr_field.ptr(), address_bytes)?; // Zero out the reserved `sin_zero` field. It's unclear if we must do this: old // POSIX explicitly specified the field, but it has been removed since. We aim for // compatibilty with old code; in particular libstd relies on it being initialized. - let sin_zero_field = this.project_field_named(&address_buffer, "sin_zero")?; - let mut sin_zero_elems = this.project_array_fields(&sin_zero_field)?; - while let Some((_idx, elem)) = sin_zero_elems.next(this)? { - this.write_int(0, &elem)?; + let sin_zero_field = ecx.project_field_named(&address_buffer, "sin_zero")?; + let mut sin_zero_elems = ecx.project_array_fields(&sin_zero_field)?; + while let Some((_idx, elem)) = sin_zero_elems.next(ecx)? { + ecx.write_int(0, &elem)?; } // OS-specific fields. std assumes they are initialized, too. - if matches!(this.tcx.sess.target.os, Os::FreeBsd | Os::MacOs) { - let sin_len_field = this.project_field_named(&address_buffer, "sin_len")?; - this.write_int(sockaddr_in_layout.size.bytes(), &sin_len_field)?; + if matches!(ecx.tcx.sess.target.os, Os::FreeBsd | Os::MacOs) { + let sin_len_field = ecx.project_field_named(&address_buffer, "sin_len")?; + ecx.write_int(sockaddr_in_layout.size.bytes(), &sin_len_field)?; } address_buffer @@ -375,49 +345,45 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Scope id is stored in native byte order. let scope_id = address.scope_id(); - let sockaddr_in6_layout = this.libc_ty_layout("sockaddr_in6"); + let sockaddr_in6_layout = ecx.libc_ty_layout("sockaddr_in6"); // Allocate new buffer on the stack with the `sockaddr_in6` layout. // We need a temporary buffer as `address_ptr` might not point to a large enough // buffer, in which case we have to truncate. - let address_buffer = this.allocate(sockaddr_in6_layout, MemoryKind::Stack)?; + let address_buffer = ecx.allocate(sockaddr_in6_layout, MemoryKind::Stack)?; - let sin6_family_field = this.project_field_named(&address_buffer, "sin6_family")?; + let sin6_family_field = ecx.project_field_named(&address_buffer, "sin6_family")?; // We cannot simply write the `AF_INET6` scalar into the `sin6_family_field` because on most // systems the field has a layout of 16-bit whilst the scalar has a size of 32-bit. // Since the `AF_INET6` constant is chosen such that it can safely be converted into // a 16-bit integer, we use the following logic to get a scalar of the right size. - let af_inet6 = this.eval_libc("AF_INET6"); - let address_family = Scalar::from_int( - af_inet6.to_int(af_inet6.size())?, - sin6_family_field.layout.size, - ); - this.write_scalar(address_family, &sin6_family_field)?; - - let sin6_port_field = this.project_field_named(&address_buffer, "sin6_port")?; + let af_inet6 = ecx.eval_libc_i32("AF_INET6"); + ecx.write_int(af_inet6, &sin6_family_field)?; + + let sin6_port_field = ecx.project_field_named(&address_buffer, "sin6_port")?; // Write the port in target native endianness bytes as we already converted it // to big endian above. - this.write_bytes_ptr(sin6_port_field.ptr(), port.to_ne_bytes())?; + ecx.write_bytes_ptr(sin6_port_field.ptr(), port.to_ne_bytes())?; let sin6_flowinfo_field = - this.project_field_named(&address_buffer, "sin6_flowinfo")?; - this.write_scalar(Scalar::from_u32(flowinfo), &sin6_flowinfo_field)?; + ecx.project_field_named(&address_buffer, "sin6_flowinfo")?; + ecx.write_scalar(Scalar::from_u32(flowinfo), &sin6_flowinfo_field)?; let sin6_scope_id_field = - this.project_field_named(&address_buffer, "sin6_scope_id")?; - this.write_scalar(Scalar::from_u32(scope_id), &sin6_scope_id_field)?; + ecx.project_field_named(&address_buffer, "sin6_scope_id")?; + ecx.write_scalar(Scalar::from_u32(scope_id), &sin6_scope_id_field)?; - let sin6_addr_field = this.project_field_named(&address_buffer, "sin6_addr")?; - let s6_addr_field = this.project_field_named(&sin6_addr_field, "s6_addr")?; - this.write_bytes_ptr(s6_addr_field.ptr(), address_bytes)?; + let sin6_addr_field = ecx.project_field_named(&address_buffer, "sin6_addr")?; + let s6_addr_field = ecx.project_field_named(&sin6_addr_field, "s6_addr")?; + ecx.write_bytes_ptr(s6_addr_field.ptr(), address_bytes)?; // OS-specific fields. std assumes they are initialized, too. - if matches!(this.tcx.sess.target.os, Os::Solaris | Os::Illumos) { + if matches!(ecx.tcx.sess.target.os, Os::Solaris | Os::Illumos) { let sin6_src_id_field = - this.project_field_named(&address_buffer, "__sin6_src_id")?; - this.write_int(0, &sin6_src_id_field)?; - } else if matches!(this.tcx.sess.target.os, Os::FreeBsd | Os::MacOs) { - let sin6_len_field = this.project_field_named(&address_buffer, "sin6_len")?; - this.write_int(sockaddr_in6_layout.size.bytes(), &sin6_len_field)?; + ecx.project_field_named(&address_buffer, "__sin6_src_id")?; + ecx.write_int(0, &sin6_src_id_field)?; + } else if matches!(ecx.tcx.sess.target.os, Os::FreeBsd | Os::MacOs) { + let sin6_len_field = ecx.project_field_named(&address_buffer, "sin6_len")?; + ecx.write_int(sockaddr_in6_layout.size.bytes(), &sin6_len_field)?; } address_buffer @@ -425,7 +391,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }; // Copy the truncated address into the pointer pointed to by `address_ptr`. - this.mem_copy( + ecx.mem_copy( address_buffer.ptr(), address_ptr, // Truncate the address to fit the provided buffer. @@ -436,10 +402,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; // Deallocate the address buffer as it was only needed to construct the address and // copy it into the buffer pointed to by `address_ptr`. - this.deallocate_ptr(address_buffer.ptr(), None, MemoryKind::Stack)?; + ecx.deallocate_ptr(address_buffer.ptr(), None, MemoryKind::Stack)?; // Store size of the non-truncated address. - this.write_int(address_buffer.layout.size.bytes(), address_len_place)?; + ecx.write_int(address_buffer.layout.size.bytes(), address_len_place)?; interp_ok(()) } @@ -453,89 +419,86 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { &mut self, mut addresses: impl Iterator, ) -> InterpResult<'tcx, Pointer> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); let Some(address) = addresses.next() else { // Iterator is empty; we return a null pointer. return interp_ok(Pointer::null()); }; - let addrinfo_layout = this.libc_ty_layout("addrinfo"); + let addrinfo_layout = ecx.libc_ty_layout("addrinfo"); let addrinfo_mplace = - this.allocate(addrinfo_layout, MiriMemoryKind::SocketAddress.into())?; + ecx.allocate(addrinfo_layout, MiriMemoryKind::SocketAddress.into())?; - let flags_mplace = this.project_field_named(&addrinfo_mplace, "ai_flags")?; + let flags_mplace = ecx.project_field_named(&addrinfo_mplace, "ai_flags")?; // We don't support flag hints and depending on the target libc we have different default values: // "According to POSIX.1, specifying hints as NULL should cause `ai_flags` to be assumed as 0. // The GNU C library instead assumes a value of (AI_V4MAPPED | AI_ADDRCONFIG) for this case, // since this value is considered an improvement on the specification." - let flags = if matches!(this.tcx.sess.target.env, Env::Gnu) { - this.eval_libc_i32("AI_V4MAPPED") | this.eval_libc_i32("AI_ADDRCONFIG") + let flags = if matches!(ecx.tcx.sess.target.env, Env::Gnu) { + ecx.eval_libc_i32("AI_V4MAPPED") | ecx.eval_libc_i32("AI_ADDRCONFIG") } else { 0 }; - this.write_int(flags, &flags_mplace)?; + ecx.write_int(flags, &flags_mplace)?; - let family_mplace = this.project_field_named(&addrinfo_mplace, "ai_family")?; + let family_mplace = ecx.project_field_named(&addrinfo_mplace, "ai_family")?; let family = match &address { - SocketAddr::V4(_) => this.eval_libc("AF_INET"), - SocketAddr::V6(_) => this.eval_libc("AF_INET6"), + SocketAddr::V4(_) => ecx.eval_libc("AF_INET"), + SocketAddr::V6(_) => ecx.eval_libc("AF_INET6"), }; - this.write_scalar(family, &family_mplace)?; + ecx.write_scalar(family, &family_mplace)?; - let socktype_mplace = this.project_field_named(&addrinfo_mplace, "ai_socktype")?; - this.write_scalar(this.eval_libc("SOCK_STREAM"), &socktype_mplace)?; + let socktype_mplace = ecx.project_field_named(&addrinfo_mplace, "ai_socktype")?; + ecx.write_scalar(ecx.eval_libc("SOCK_STREAM"), &socktype_mplace)?; - let protocol_mplace = this.project_field_named(&addrinfo_mplace, "ai_protocol")?; + let protocol_mplace = ecx.project_field_named(&addrinfo_mplace, "ai_protocol")?; // We don't support protocol hints and thus we just return zero which falls back // to the default protocol for the provided socket type. - this.write_int(0, &protocol_mplace)?; + ecx.write_int(0, &protocol_mplace)?; // `sockaddr_storage` is guaranteed to fit any `sockaddr_*` address structure. - let sockaddr_layout = this.libc_ty_layout("sockaddr_storage"); + let sockaddr_layout = ecx.libc_ty_layout("sockaddr_storage"); - let addrlen_mplace = this.project_field_named(&addrinfo_mplace, "ai_addrlen")?; - let addr_mplace = this.project_field_named(&addrinfo_mplace, "ai_addr")?; - this.write_int(sockaddr_layout.size.bytes(), &addrlen_mplace)?; + let addrlen_mplace = ecx.project_field_named(&addrinfo_mplace, "ai_addrlen")?; + let addr_mplace = ecx.project_field_named(&addrinfo_mplace, "ai_addr")?; + ecx.write_int(sockaddr_layout.size.bytes(), &addrlen_mplace)?; - let sockaddr_mplace = this.allocate(sockaddr_layout, MiriMemoryKind::Machine.into())?; - this.write_socket_address(Some(&address), sockaddr_mplace.ptr(), &addrlen_mplace)?; - this.write_pointer(sockaddr_mplace.ptr(), &addr_mplace)?; + let sockaddr_mplace = ecx.allocate(sockaddr_layout, MiriMemoryKind::Machine.into())?; + ecx.write_socket_address(Some(&address), sockaddr_mplace.ptr(), &addrlen_mplace)?; + ecx.write_pointer(sockaddr_mplace.ptr(), &addr_mplace)?; - let canonname_mplace = this.project_field_named(&addrinfo_mplace, "ai_canonname")?; - this.write_pointer(Pointer::null(), &canonname_mplace)?; + let canonname_mplace = ecx.project_field_named(&addrinfo_mplace, "ai_canonname")?; + ecx.write_pointer(Pointer::null(), &canonname_mplace)?; // Allocate remaining list and store a pointer to it. - let next_mplace = this.project_field_named(&addrinfo_mplace, "ai_next")?; - let next_ptr = this.allocate_address_infos(addresses)?; - this.write_pointer(next_ptr, &next_mplace)?; + let next_mplace = ecx.project_field_named(&addrinfo_mplace, "ai_next")?; + let next_ptr = ecx.allocate_address_infos(addresses)?; + ecx.write_pointer(next_ptr, &next_mplace)?; interp_ok(addrinfo_mplace.ptr()) } /// Deallocate the linked list of address info structs. /// `address_ptr` points to the start from where we deallocate recursively. - fn free_address_infos(&mut self, address_ptr: Pointer) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + fn free_address_infos(&mut self, addrinfo_place: &MPlaceTy<'tcx>) -> InterpResult<'tcx> { + let ecx = self.eval_context_mut(); - if this.ptr_is_null(address_ptr)? { + if ecx.ptr_is_null(addrinfo_place.ptr())? { // We're at the end of the linked list. return interp_ok(()); } - let addrinfo_layout = this.libc_ty_layout("addrinfo"); - let addrinfo_mplace = this.ptr_to_mplace(address_ptr, addrinfo_layout); - - let addr_field = this.project_field_named(&addrinfo_mplace, "ai_addr")?; - let addr_ptr = this.read_pointer(&addr_field)?; - this.deallocate_ptr(addr_ptr, None, MiriMemoryKind::Machine.into())?; + let addr_field = ecx.project_field_named(addrinfo_place, "ai_addr")?; + let addr_ptr = ecx.read_pointer(&addr_field)?; + ecx.deallocate_ptr(addr_ptr, None, MiriMemoryKind::Machine.into())?; - let next_field = this.project_field_named(&addrinfo_mplace, "ai_next")?; - let next_ptr = this.read_pointer(&next_field)?; - this.free_address_infos(next_ptr)?; + let next_field = ecx.project_field_named(addrinfo_place, "ai_next")?; + let next_addrinfo = ecx.deref_pointer(&next_field)?; + ecx.free_address_infos(&next_addrinfo)?; - this.deallocate_ptr(address_ptr, None, MiriMemoryKind::SocketAddress.into())?; + ecx.deallocate_ptr(addrinfo_place.ptr(), None, MiriMemoryKind::SocketAddress.into())?; interp_ok(()) } diff --git a/src/tools/miri/src/shims/unix/solarish/foreign_items.rs b/src/tools/miri/src/shims/unix/solarish/foreign_items.rs index 3628ec259af69..44405d57cbb28 100644 --- a/src/tools/miri/src/shims/unix/solarish/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/solarish/foreign_items.rs @@ -22,46 +22,46 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { args: &[OpTy<'tcx>], dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx, EmulateItemResult> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); match link_name.as_str() { // epoll, eventfd (NOT available on Solaris!) "epoll_create1" => { - this.assert_target_os(Os::Illumos, "epoll_create1"); - let [flag] = &this + ecx.assert_target_os(Os::Illumos, "epoll_create1"); + let [flag] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(i32) -> i32), (link_name, abi, args))?; - let result = this.epoll_create1(flag)?; - this.write_scalar(result, dest)?; + let result = ecx.epoll_create1(flag)?; + ecx.write_scalar(result, dest)?; } "epoll_ctl" => { - this.assert_target_os(Os::Illumos, "epoll_ctl"); - let [epfd, op, fd, event] = &this.check_shim_sig( + ecx.assert_target_os(Os::Illumos, "epoll_ctl"); + let [epfd, op, fd, event] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, i32, i32, *libc::epoll_event) -> i32), (link_name, abi, args), )?; - let result = this.epoll_ctl(epfd, op, fd, event)?; - this.write_scalar(result, dest)?; + let result = ecx.epoll_ctl(epfd, op, fd, event)?; + ecx.write_scalar(result, dest)?; } "epoll_wait" => { - this.assert_target_os(Os::Illumos, "epoll_wait"); - let [epfd, events, maxevents, timeout] = &this.check_shim_sig( + ecx.assert_target_os(Os::Illumos, "epoll_wait"); + let [epfd, events, maxevents, timeout] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::epoll_event, i32, i32) -> i32), (link_name, abi, args), )?; - this.epoll_wait(epfd, events, maxevents, timeout, dest)?; + ecx.epoll_wait(epfd, events, maxevents, timeout, dest)?; } "eventfd" => { - this.assert_target_os(Os::Illumos, "eventfd"); - let [val, flag] = &this.check_shim_sig( + ecx.assert_target_os(Os::Illumos, "eventfd"); + let [val, flag] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(u32, i32) -> i32), (link_name, abi, args), )?; - let result = this.eventfd(val, flag)?; - this.write_scalar(result, dest)?; + let result = ecx.eventfd(val, flag)?; + ecx.write_scalar(result, dest)?; } // Threading "pthread_setname_np" => { - let [thread, name] = &this.check_shim_sig( + let [thread, name] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::pthread_t, *_) -> i32), (link_name, abi, args), )?; @@ -69,114 +69,114 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // https://github.com/illumos/illumos-gate/blob/7671517e13b8123748eda4ef1ee165c6d9dba7fe/usr/src/uts/common/sys/thread.h#L613 let max_len = 32; // See https://illumos.org/man/3C/pthread_setname_np for the error codes. - let res = match this.pthread_setname_np( - this.read_scalar(thread)?, - this.read_scalar(name)?, + let res = match ecx.pthread_setname_np( + Some(thread), + ecx.read_pointer(name)?, max_len, /* truncate */ false, )? { ThreadNameResult::Ok => Scalar::from_u32(0), - ThreadNameResult::NameTooLong => this.eval_libc("ERANGE"), + ThreadNameResult::NameTooLong => ecx.eval_libc("ERANGE"), }; - this.write_scalar(res, dest)?; + ecx.write_scalar(res, dest)?; } "pthread_getname_np" => { - let [thread, name, len] = &this.check_shim_sig( + let [thread, name, len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(libc::pthread_t, *_, usize) -> i32), (link_name, abi, args), )?; // See https://illumos.org/man/3C/pthread_getname_np for the error codes. - let res = match this.pthread_getname_np( - this.read_scalar(thread)?, - this.read_scalar(name)?, - this.read_scalar(len)?, + let res = match ecx.pthread_getname_np( + Some(thread), + ecx.read_pointer(name)?, + ecx.read_scalar(len)?, /* truncate */ false, )? { ThreadNameResult::Ok => Scalar::from_u32(0), - ThreadNameResult::NameTooLong => this.eval_libc("ERANGE"), + ThreadNameResult::NameTooLong => ecx.eval_libc("ERANGE"), }; - this.write_scalar(res, dest)?; + ecx.write_scalar(res, dest)?; } // Sockets and pipes "__xnet_socketpair" => { - let [domain, type_, protocol, sv] = &this.check_shim_sig( + let [domain, type_, protocol, sv] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, i32, i32, *i32) -> i32), (link_name, abi, args), )?; - let result = this.socketpair(domain, type_, protocol, sv)?; - this.write_scalar(result, dest)?; + let result = ecx.socketpair(domain, type_, protocol, sv)?; + ecx.write_scalar(result, dest)?; } // Network sockets "__xnet_socket" | "__xnet7_socket" => { - let [domain, type_, protocol] = &this.check_shim_sig( + let [domain, type_, protocol] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, i32, i32) -> i32), (link_name, abi, args), )?; - let result = this.socket(domain, type_, protocol)?; - this.write_scalar(result, dest)?; + let result = ecx.socket(domain, type_, protocol)?; + ecx.write_scalar(result, dest)?; } "__xnet_bind" => { - let [socket, address, address_len] = &this.check_shim_sig( + let [socket, address, address_len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::sockaddr, libc::socklen_t) -> i32), (link_name, abi, args), )?; - let result = this.bind(socket, address, address_len)?; - this.write_scalar(result, dest)?; + let result = ecx.bind(socket, address, address_len)?; + ecx.write_scalar(result, dest)?; } "__xnet_connect" => { - let [socket, address, address_len] = &this.check_shim_sig( + let [socket, address, address_len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *libc::sockaddr, libc::socklen_t) -> i32), (link_name, abi, args), )?; - this.connect(socket, address, address_len, dest)?; + ecx.connect(socket, address, address_len, dest)?; } "__xnet_sendto" => { - let [socket, buffer, length, flags, dest_addr, dest_addr_len] = &this.check_shim_sig( + let [socket, buffer, length, flags, dest_addr, dest_addr_len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, libc::size_t, i32, *libc::sockaddr, libc::socklen_t) -> libc::ssize_t), (link_name, abi, args), )?; - this.send(socket, buffer, length, flags, Some((dest_addr, dest_addr_len)), dest)?; + ecx.send(socket, buffer, length, flags, Some((dest_addr, dest_addr_len)), dest)?; } "__xnet_getaddrinfo" => { - let [node, service, hints, res] = &this.check_shim_sig( - shim_sig!(extern "C" fn(*_, *_, *_, **_) -> i32), + let [node, service, hints, res] = &ecx.check_shim_sig( + shim_sig!(extern "C" fn(*_, *_, *libc::addrinfo, **libc::addrinfo) -> i32), (link_name, abi, args), )?; - let result = this.getaddrinfo(node, service, hints, res)?; - this.write_scalar(result, dest)?; + let result = ecx.getaddrinfo(node, service, hints, res)?; + ecx.write_scalar(result, dest)?; } "__xnet_getsockopt" => { - let [socket, level, option_name, option_value, option_len] = &this.check_shim_sig( - shim_sig!(extern "C" fn(i32, i32, i32, *_, *_) -> i32), + let [socket, level, option_name, option_value, option_len] = &ecx.check_shim_sig( + shim_sig!(extern "C" fn(i32, i32, i32, *_, *libc::socklen_t) -> i32), (link_name, abi, args), )?; let result = - this.getsockopt(socket, level, option_name, option_value, option_len)?; - this.write_scalar(result, dest)?; + ecx.getsockopt(socket, level, option_name, option_value, option_len)?; + ecx.write_scalar(result, dest)?; } // Miscellaneous "___errno" => { - let [] = &this - .check_shim_sig(shim_sig!(extern "C" fn() -> *_), (link_name, abi, args))?; - let errno_place = this.last_error_place()?; - this.write_scalar(errno_place.to_ref(this).to_scalar(), dest)?; + let [] = + &ecx.check_shim_sig(shim_sig!(extern "C" fn() -> *_), (link_name, abi, args))?; + let errno_place = ecx.last_error_place()?; + ecx.write_scalar(errno_place.to_ref(ecx).to_scalar(), dest)?; } "stack_getbounds" => { // FIXME: This does not have a direct test (#3179). - let [stack] = &this.check_shim_sig( + let [stack] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*libc::stack_t) -> i32), (link_name, abi, args), )?; - let stack = this.deref_pointer(stack)?; + let stack = ecx.deref_pointer(stack)?; - this.write_int_fields_named( + ecx.write_int_fields_named( &[ - ("ss_sp", this.machine.stack_addr.into()), - ("ss_size", this.machine.stack_size.into()), + ("ss_sp", ecx.machine.stack_addr.into()), + ("ss_size", ecx.machine.stack_size.into()), // field set to 0 means not in an alternate signal stack // https://docs.oracle.com/cd/E86824_01/html/E54766/stack-getbounds-3c.html ("ss_flags", 0), @@ -184,12 +184,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { &stack, )?; - this.write_int(0, dest)?; + ecx.write_int(0, dest)?; } "pset_info" => { // FIXME: This does not have a direct test (#3179). - let [pset, tpe, cpus, list] = &this.check_shim_sig( + let [pset, tpe, cpus, list] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, *u32, *_) -> i32), (link_name, abi, args), )?; @@ -198,35 +198,35 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // cpus. // https://docs.oracle.com/cd/E88353_01/html/E37841/pset-info-2.html - let pset = this.read_scalar(pset)?.to_i32()?; - let tpe = this.read_pointer(tpe)?; - let list = this.read_pointer(list)?; + let pset = ecx.read_scalar(pset)?.to_i32()?; + let tpe = ecx.read_pointer(tpe)?; + let list = ecx.read_pointer(list)?; - let ps_myid = this.eval_libc_i32("PS_MYID"); + let ps_myid = ecx.eval_libc_i32("PS_MYID"); if ps_myid != pset { throw_unsup_format!("pset_info is only supported with pset==PS_MYID"); } - if !this.ptr_is_null(tpe)? { + if !ecx.ptr_is_null(tpe)? { throw_unsup_format!("pset_info is only supported with type==NULL"); } - if !this.ptr_is_null(list)? { + if !ecx.ptr_is_null(list)? { throw_unsup_format!("pset_info is only supported with list==NULL"); } - let cpus = this.deref_pointer(cpus)?; - this.write_scalar(Scalar::from_u32(this.machine.num_cpus), &cpus)?; - this.write_int(0, dest)?; + let cpus = ecx.deref_pointer(cpus)?; + ecx.write_scalar(Scalar::from_u32(ecx.machine.num_cpus), &cpus)?; + ecx.write_int(0, dest)?; } "__sysconf_xpg7" => { - let [val] = &this.check_shim_sig( + let [val] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32) -> isize), (link_name, abi, args), )?; - let result = this.sysconf(val)?; - this.write_scalar(result, dest)?; + let result = ecx.sysconf(val)?; + ecx.write_scalar(result, dest)?; } _ => return interp_ok(EmulateItemResult::NotSupported), diff --git a/src/tools/miri/src/shims/unix/sync.rs b/src/tools/miri/src/shims/unix/sync.rs index 7579d358158e3..b5984640dc881 100644 --- a/src/tools/miri/src/shims/unix/sync.rs +++ b/src/tools/miri/src/shims/unix/sync.rs @@ -47,11 +47,7 @@ enum MutexKind { ErrorCheck, } -impl MetaObj for PthreadMutexAttr { - fn opaque(&self) -> bool { - true - } -} +impl MetaObj for PthreadMutexAttr {} fn mutexattr_create<'tcx>( ecx: &mut MiriInterpCx<'tcx>, @@ -123,10 +119,6 @@ impl MetaObj for PthreadMutex { } interp_ok(()) } - - fn opaque(&self) -> bool { - true - } } /// Eagerly create and initialize a new mutex. @@ -207,10 +199,6 @@ impl MetaObj for PthreadRwLock { } interp_ok(()) } - - fn opaque(&self) -> bool { - true - } } fn rwlock_get_data<'tcx, 'a>( @@ -251,11 +239,7 @@ struct PthreadCondAttr { clock: TimeoutClock, } -impl MetaObj for PthreadCondAttr { - fn opaque(&self) -> bool { - true - } -} +impl MetaObj for PthreadCondAttr {} fn condattr_create<'tcx>( ecx: &mut MiriInterpCx<'tcx>, @@ -310,10 +294,6 @@ impl MetaObj for PthreadCondvar { } interp_ok(()) } - - fn opaque(&self) -> bool { - true - } } fn cond_create<'tcx>( @@ -379,10 +359,6 @@ impl MetaObj for PthreadSem { } interp_ok(()) } - - fn opaque(&self) -> bool { - true - } } fn sem_create<'tcx>( @@ -412,8 +388,8 @@ where impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {} pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { fn pthread_mutexattr_init(&mut self, attr_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> { - let this = self.eval_context_mut(); - mutexattr_create(this, attr_op) + let ecx = self.eval_context_mut(); + mutexattr_create(ecx, attr_op) } fn pthread_mutexattr_settype( @@ -421,23 +397,23 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { attr_op: &OpTy<'tcx>, kind_op: &OpTy<'tcx>, ) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let kind = this.read_scalar(kind_op)?.to_i32()?; - let Some(kind) = mutexattr_translate_kind(this, kind) else { - let einval = this.eval_libc_i32("EINVAL"); + let kind = ecx.read_scalar(kind_op)?.to_i32()?; + let Some(kind) = mutexattr_translate_kind(ecx, kind) else { + let einval = ecx.eval_libc_i32("EINVAL"); return interp_ok(Scalar::from_i32(einval)); }; - let mutexattr = mutexattr_get_data(this, attr_op)?; + let mutexattr = mutexattr_get_data(ecx, attr_op)?; mutexattr.kind = Some(kind); interp_ok(Scalar::from_i32(0)) } fn pthread_mutexattr_destroy(&mut self, attr_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> { - let this = self.eval_context_mut(); - mutexattr_destroy(this, attr_op) + let ecx = self.eval_context_mut(); + mutexattr_destroy(ecx, attr_op) } fn pthread_mutex_init( @@ -445,17 +421,17 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { mutex_op: &OpTy<'tcx>, attr_op: &OpTy<'tcx>, ) -> InterpResult<'tcx, ()> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let attr = this.read_pointer(attr_op)?; - let kind = if this.ptr_is_null(attr)? { + let attr = ecx.read_pointer(attr_op)?; + let kind = if ecx.ptr_is_null(attr)? { MutexKind::Default } else { - let mutexattr = mutexattr_get_data(this, attr_op)?; + let mutexattr = mutexattr_get_data(ecx, attr_op)?; mutexattr.kind.unwrap_or(MutexKind::Default) }; - mutex_create(this, mutex_op, kind)?; + mutex_create(ecx, mutex_op, kind)?; interp_ok(()) } @@ -465,13 +441,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { mutex_op: &OpTy<'tcx>, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let mutex = mutex_get_data(this, mutex_op)?.clone(); + let mutex = mutex_get_data(ecx, mutex_op)?.clone(); let ret = if let Some(owner_thread) = mutex.mutex_ref.owner() { - if owner_thread != this.active_thread() { - this.mutex_enqueue_and_block( + if owner_thread != ecx.active_thread() { + ecx.mutex_enqueue_and_block( mutex.mutex_ref, Some((Scalar::from_i32(0), dest.clone())), ); @@ -484,53 +460,53 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "trying to acquire default mutex already locked by the current thread" ), MutexKind::Normal => throw_machine_stop!(TerminationInfo::LocalDeadlock), - MutexKind::ErrorCheck => this.eval_libc_i32("EDEADLK"), + MutexKind::ErrorCheck => ecx.eval_libc_i32("EDEADLK"), MutexKind::Recursive => { - this.mutex_lock(&mutex.mutex_ref)?; + ecx.mutex_lock(&mutex.mutex_ref)?; 0 } } } } else { // The mutex is unlocked. Let's lock it. - this.mutex_lock(&mutex.mutex_ref)?; + ecx.mutex_lock(&mutex.mutex_ref)?; 0 }; - this.write_scalar(Scalar::from_i32(ret), dest)?; + ecx.write_scalar(Scalar::from_i32(ret), dest)?; interp_ok(()) } fn pthread_mutex_trylock(&mut self, mutex_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let mutex = mutex_get_data(this, mutex_op)?.clone(); + let mutex = mutex_get_data(ecx, mutex_op)?.clone(); interp_ok(Scalar::from_i32(if let Some(owner_thread) = mutex.mutex_ref.owner() { - if owner_thread != this.active_thread() { - this.eval_libc_i32("EBUSY") + if owner_thread != ecx.active_thread() { + ecx.eval_libc_i32("EBUSY") } else { match mutex.kind { MutexKind::Default | MutexKind::Normal | MutexKind::ErrorCheck => - this.eval_libc_i32("EBUSY"), + ecx.eval_libc_i32("EBUSY"), MutexKind::Recursive => { - this.mutex_lock(&mutex.mutex_ref)?; + ecx.mutex_lock(&mutex.mutex_ref)?; 0 } } } } else { // The mutex is unlocked. Let's lock it. - this.mutex_lock(&mutex.mutex_ref)?; + ecx.mutex_lock(&mutex.mutex_ref)?; 0 })) } fn pthread_mutex_unlock(&mut self, mutex_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let mutex = mutex_get_data(this, mutex_op)?.clone(); + let mutex = mutex_get_data(ecx, mutex_op)?.clone(); - if let Some(_old_locked_count) = this.mutex_unlock(&mutex.mutex_ref)? { + if let Some(_old_locked_count) = ecx.mutex_unlock(&mutex.mutex_ref)? { // The mutex was locked by the current thread. interp_ok(Scalar::from_i32(0)) } else { @@ -547,17 +523,17 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "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"))), + interp_ok(Scalar::from_i32(ecx.eval_libc_i32("EPERM"))), } } } fn pthread_mutex_destroy(&mut self, mutex_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); // Reading the field also has the side-effect that we detect double-`destroy` // since we make the field uninit below. - let mutex = mutex_get_data(this, mutex_op)?.clone(); + let mutex = mutex_get_data(ecx, mutex_op)?.clone(); if mutex.mutex_ref.owner().is_some() { throw_ub_format!("destroyed a locked mutex"); @@ -565,8 +541,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // This write also deletes the interpreter state for this mutex. // This might lead to false positives, see comment in pthread_mutexattr_destroy - let mutex_place = this.deref_pointer(mutex_op)?; - this.write_uninit(&mutex_place)?; + let mutex_place = ecx.deref_pointer(mutex_op)?; + ecx.write_uninit(&mutex_place)?; interp_ok(()) } @@ -576,33 +552,33 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { rwlock_op: &OpTy<'tcx>, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let rwlock = rwlock_get_data(this, rwlock_op)?.clone(); + let rwlock = rwlock_get_data(ecx, rwlock_op)?.clone(); if rwlock.rwlock_ref.is_write_locked() { - this.rwlock_enqueue_and_block_reader( + ecx.rwlock_enqueue_and_block_reader( rwlock.rwlock_ref, Scalar::from_i32(0), dest.clone(), ); } else { - this.rwlock_reader_lock(&rwlock.rwlock_ref)?; - this.write_int(0, dest)?; + ecx.rwlock_reader_lock(&rwlock.rwlock_ref)?; + ecx.write_int(0, dest)?; } interp_ok(()) } fn pthread_rwlock_tryrdlock(&mut self, rwlock_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let rwlock = rwlock_get_data(this, rwlock_op)?.clone(); + let rwlock = rwlock_get_data(ecx, rwlock_op)?.clone(); if rwlock.rwlock_ref.is_write_locked() { - interp_ok(Scalar::from_i32(this.eval_libc_i32("EBUSY"))) + interp_ok(Scalar::from_i32(ecx.eval_libc_i32("EBUSY"))) } else { - this.rwlock_reader_lock(&rwlock.rwlock_ref)?; + ecx.rwlock_reader_lock(&rwlock.rwlock_ref)?; interp_ok(Scalar::from_i32(0)) } } @@ -612,9 +588,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { rwlock_op: &OpTy<'tcx>, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let rwlock = rwlock_get_data(this, rwlock_op)?.clone(); + let rwlock = rwlock_get_data(ecx, rwlock_op)?.clone(); if rwlock.rwlock_ref.is_locked() { // Note: this will deadlock if the lock is already locked by this @@ -629,39 +605,39 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // report the deadlock only when no thread can continue execution, // but we could detect that this lock is already locked and report // an error.) - this.rwlock_enqueue_and_block_writer( + ecx.rwlock_enqueue_and_block_writer( rwlock.rwlock_ref, Scalar::from_i32(0), dest.clone(), ); } else { - this.rwlock_writer_lock(&rwlock.rwlock_ref)?; - this.write_int(0, dest)?; + ecx.rwlock_writer_lock(&rwlock.rwlock_ref)?; + ecx.write_int(0, dest)?; } interp_ok(()) } fn pthread_rwlock_trywrlock(&mut self, rwlock_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let rwlock = rwlock_get_data(this, rwlock_op)?.clone(); + let rwlock = rwlock_get_data(ecx, rwlock_op)?.clone(); if rwlock.rwlock_ref.is_locked() { - interp_ok(Scalar::from_i32(this.eval_libc_i32("EBUSY"))) + interp_ok(Scalar::from_i32(ecx.eval_libc_i32("EBUSY"))) } else { - this.rwlock_writer_lock(&rwlock.rwlock_ref)?; + ecx.rwlock_writer_lock(&rwlock.rwlock_ref)?; interp_ok(Scalar::from_i32(0)) } } fn pthread_rwlock_unlock(&mut self, rwlock_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let rwlock = rwlock_get_data(this, rwlock_op)?.clone(); + let rwlock = rwlock_get_data(ecx, rwlock_op)?.clone(); - if this.rwlock_reader_unlock(&rwlock.rwlock_ref)? - || this.rwlock_writer_unlock(&rwlock.rwlock_ref)? + if ecx.rwlock_reader_unlock(&rwlock.rwlock_ref)? + || ecx.rwlock_writer_unlock(&rwlock.rwlock_ref)? { interp_ok(()) } else { @@ -670,11 +646,11 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } fn pthread_rwlock_destroy(&mut self, rwlock_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); // Reading the field also has the side-effect that we detect double-`destroy` // since we make the field uninit below. - let rwlock = rwlock_get_data(this, rwlock_op)?.clone(); + let rwlock = rwlock_get_data(ecx, rwlock_op)?.clone(); if rwlock.rwlock_ref.is_locked() { throw_ub_format!("destroyed a locked rwlock"); @@ -682,15 +658,15 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // This write also deletes the interpreter state for this rwlock. // This might lead to false positives, see comment in pthread_mutexattr_destroy - let rwlock_place = this.deref_pointer(rwlock_op)?; - this.write_uninit(&rwlock_place)?; + let rwlock_place = ecx.deref_pointer(rwlock_op)?; + ecx.write_uninit(&rwlock_place)?; interp_ok(()) } fn pthread_condattr_init(&mut self, attr_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> { - let this = self.eval_context_mut(); - condattr_create(this, attr_op) + let ecx = self.eval_context_mut(); + condattr_create(ecx, attr_op) } fn pthread_condattr_setclock( @@ -698,15 +674,15 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { attr_op: &OpTy<'tcx>, clock_id_op: &OpTy<'tcx>, ) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let clock_id = this.read_scalar(clock_id_op)?.to_i32()?; - let Some(clock) = this.parse_clockid(clock_id) else { - let einval = this.eval_libc_i32("EINVAL"); + let clock_id = ecx.read_scalar(clock_id_op)?.to_i32()?; + let Some(clock) = ecx.parse_clockid(clock_id) else { + let einval = ecx.eval_libc_i32("EINVAL"); return interp_ok(Scalar::from_i32(einval)); }; - let condattr = condattr_get_data(this, attr_op)?; + let condattr = condattr_get_data(ecx, attr_op)?; condattr.clock = clock; interp_ok(Scalar::from_i32(0)) @@ -717,23 +693,23 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { attr_op: &OpTy<'tcx>, clk_id_op: &OpTy<'tcx>, ) -> InterpResult<'tcx, ()> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let clock_id_dest = this.deref_pointer(clk_id_op)?; - let condattr = condattr_get_data(this, attr_op)?; + let clock_id_dest = ecx.deref_pointer(clk_id_op)?; + let condattr = condattr_get_data(ecx, attr_op)?; let clock_id = match condattr.clock { - TimeoutClock::Monotonic => this.eval_libc_i32("CLOCK_MONOTONIC"), - TimeoutClock::RealTime => this.eval_libc_i32("CLOCK_REALTIME"), + TimeoutClock::Monotonic => ecx.eval_libc_i32("CLOCK_MONOTONIC"), + TimeoutClock::RealTime => ecx.eval_libc_i32("CLOCK_REALTIME"), }; - this.write_int(clock_id, &clock_id_dest)?; + ecx.write_int(clock_id, &clock_id_dest)?; interp_ok(()) } fn pthread_condattr_destroy(&mut self, attr_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> { - let this = self.eval_context_mut(); - condattr_destroy(this, attr_op) + let ecx = self.eval_context_mut(); + condattr_destroy(ecx, attr_op) } fn pthread_cond_init( @@ -741,33 +717,33 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { cond_op: &OpTy<'tcx>, attr_op: &OpTy<'tcx>, ) -> InterpResult<'tcx, ()> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let attr = this.read_pointer(attr_op)?; + let attr = ecx.read_pointer(attr_op)?; // Default clock if `attr` is null, and on macOS where there is no clock attribute. - let clock = if this.ptr_is_null(attr)? { + let clock = if ecx.ptr_is_null(attr)? { TimeoutClock::RealTime } else { - let condattr = condattr_get_data(this, attr_op)?; + let condattr = condattr_get_data(ecx, attr_op)?; condattr.clock }; - cond_create(this, cond_op, clock)?; + cond_create(ecx, cond_op, clock)?; interp_ok(()) } fn pthread_cond_signal(&mut self, cond_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> { - let this = self.eval_context_mut(); - let condvar = cond_get_data(this, cond_op)?.condvar_ref.clone(); - this.condvar_signal(&condvar)?; + let ecx = self.eval_context_mut(); + let condvar = cond_get_data(ecx, cond_op)?.condvar_ref.clone(); + ecx.condvar_signal(&condvar)?; interp_ok(()) } fn pthread_cond_broadcast(&mut self, cond_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> { - let this = self.eval_context_mut(); - let condvar = cond_get_data(this, cond_op)?.condvar_ref.clone(); - while this.condvar_signal(&condvar)? {} + let ecx = self.eval_context_mut(); + let condvar = cond_get_data(ecx, cond_op)?.condvar_ref.clone(); + while ecx.condvar_signal(&condvar)? {} interp_ok(()) } @@ -777,12 +753,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { mutex_op: &OpTy<'tcx>, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let data = cond_get_data(this, cond_op)?.clone(); - let mutex_ref = mutex_get_data(this, mutex_op)?.mutex_ref.clone(); + let data = cond_get_data(ecx, cond_op)?.clone(); + let mutex_ref = mutex_get_data(ecx, mutex_op)?.mutex_ref.clone(); - this.condvar_wait( + ecx.condvar_wait( data.condvar_ref, mutex_ref, None, // no timeout @@ -802,15 +778,15 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { dest: &MPlaceTy<'tcx>, macos_relative_np: bool, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let data = cond_get_data(this, cond_op)?.clone(); - let mutex_ref = mutex_get_data(this, mutex_op)?.mutex_ref.clone(); + let data = cond_get_data(ecx, cond_op)?.clone(); + let mutex_ref = mutex_get_data(ecx, mutex_op)?.mutex_ref.clone(); // Extract the timeout. - let Some(duration) = this.read_timespec(&this.deref_pointer(timeout_op)?)? else { - let einval = this.eval_libc("EINVAL"); - this.write_scalar(einval, dest)?; + let Some(duration) = ecx.read_timespec(&ecx.deref_pointer(timeout_op)?)? else { + let einval = ecx.eval_libc("EINVAL"); + ecx.write_scalar(einval, dest)?; return interp_ok(()); }; @@ -820,18 +796,18 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (TimeoutClock::Monotonic, TimeoutStyle::Relative) } else { if data.clock == TimeoutClock::RealTime { - this.check_no_isolation("`pthread_cond_timedwait` with `CLOCK_REALTIME`")?; + ecx.check_no_isolation("`pthread_cond_timedwait` with `CLOCK_REALTIME`")?; } (data.clock, TimeoutStyle::Absolute) }; - this.condvar_wait( + ecx.condvar_wait( data.condvar_ref, mutex_ref, - Some(this.machine.timeout(clock, style, duration)), + Some(ecx.machine.timeout(clock, style, duration)), Scalar::from_i32(0), - this.eval_libc("ETIMEDOUT"), // retval_timeout + ecx.eval_libc("ETIMEDOUT"), // retval_timeout dest.clone(), )?; @@ -839,19 +815,19 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } fn pthread_cond_destroy(&mut self, cond_op: &OpTy<'tcx>) -> InterpResult<'tcx, ()> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); // Reading the field also has the side-effect that we detect double-`destroy` // since we make the field uninit below. - let condvar = &cond_get_data(this, cond_op)?.condvar_ref; + let condvar = &cond_get_data(ecx, cond_op)?.condvar_ref; if !condvar.queue_is_empty() { throw_ub_format!("destroying an awaited conditional variable"); } // This write also deletes the interpreter state for this condvar. // This might lead to false positives, see comment in pthread_mutexattr_destroy - let cond_place = this.deref_pointer(cond_op)?; - this.write_uninit(&cond_place)?; + let cond_place = ecx.deref_pointer(cond_op)?; + ecx.write_uninit(&cond_place)?; interp_ok(()) } @@ -863,17 +839,17 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { value_op: &OpTy<'tcx>, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let pshared = this.read_scalar(pshared_op)?.to_i32()?; - let value = this.read_scalar(value_op)?.to_u32()?; + let pshared = ecx.read_scalar(pshared_op)?.to_i32()?; + let value = ecx.read_scalar(value_op)?.to_u32()?; // We can ignore `pshared` since memory cannot actually be shared with other processes. let _ignore = pshared; - sem_create(this, sem_op, value)?; + sem_create(ecx, sem_op, value)?; - this.write_int(0, dest)?; // we always succeed + ecx.write_int(0, dest)?; // we always succeed interp_ok(()) } @@ -882,11 +858,11 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { sem_op: &OpTy<'tcx>, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let data = sem_get_data(this, sem_op)?.clone(); + let data = sem_get_data(ecx, sem_op)?.clone(); let dest = dest.clone(); - this.semaphore_decrement( + ecx.semaphore_decrement( data.sem_ref, /* deadline */ None, callback!( @@ -910,19 +886,19 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { abs_timeout_op: &OpTy<'tcx>, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); - this.check_no_isolation("`pthread_sem_timedwait`")?; + let ecx = self.eval_context_mut(); + ecx.check_no_isolation("`pthread_sem_timedwait`")?; - let abs_timeout = this.deref_pointer(abs_timeout_op)?; + let abs_timeout = ecx.deref_pointer(abs_timeout_op)?; - let Some(duration) = this.read_timespec(&abs_timeout)? else { - return this.set_errno_and_return_neg1(LibcError("EINVAL"), dest); + let Some(duration) = ecx.read_timespec(&abs_timeout)? else { + return ecx.set_errno_and_return_neg1(LibcError("EINVAL"), dest); }; let deadline = - this.machine.timeout(TimeoutClock::RealTime, TimeoutStyle::Absolute, duration); - let data = sem_get_data(this, sem_op)?.clone(); + ecx.machine.timeout(TimeoutClock::RealTime, TimeoutStyle::Absolute, duration); + let data = sem_get_data(ecx, sem_op)?.clone(); let dest = dest.clone(); - this.semaphore_decrement( + ecx.semaphore_decrement( data.sem_ref, Some(deadline), callback!( @@ -948,12 +924,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { sem_op: &OpTy<'tcx>, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let data = sem_get_data(this, sem_op)?.clone(); - this.semaphore_increment(&data.sem_ref)?; + let data = sem_get_data(ecx, sem_op)?.clone(); + ecx.semaphore_increment(&data.sem_ref)?; - this.write_int(0, dest)?; // we always succeed + ecx.write_int(0, dest)?; // we always succeed interp_ok(()) } @@ -962,19 +938,19 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { sem_op: &OpTy<'tcx>, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let data = sem_get_data(this, sem_op)?.clone(); + let data = sem_get_data(ecx, sem_op)?.clone(); if !data.sem_ref.queue_is_empty() { throw_ub_format!("destroying an awaited semaphore"); } // This write also deletes the interpreter state for this semaphore. // This might lead to false positives, see comment in pthread_mutexattr_destroy - let sem_place = this.deref_pointer(sem_op)?; - this.write_uninit(&sem_place)?; + let sem_place = ecx.deref_pointer(sem_op)?; + ecx.write_uninit(&sem_place)?; - this.write_int(0, dest)?; // we always succeed + ecx.write_int(0, dest)?; // we always succeed interp_ok(()) } } diff --git a/src/tools/miri/src/shims/unix/tcp_socket.rs b/src/tools/miri/src/shims/unix/tcp_socket.rs index 58d7b2b256551..a3e5269673944 100644 --- a/src/tools/miri/src/shims/unix/tcp_socket.rs +++ b/src/tools/miri/src/shims/unix/tcp_socket.rs @@ -13,7 +13,9 @@ use rustc_target::spec::Os; use crate::shims::files::{EvalContextExt as _, FdNum, FileDescription, FileDescriptionRef}; use crate::shims::unix::UnixFileDescription; -use crate::shims::unix::socket::{EvalContextExt, UnixSocketFileDescription}; +use crate::shims::unix::socket::{ + EvalContextExt, UnixSocketFileDescription, socket_action_deadline, +}; use crate::*; /// On Linux a TCP socket is initally in the TCP_CLOSE state: @@ -173,8 +175,8 @@ impl FileDescription for TcpSocket { callback!( @capture<'tcx> { finish: DynMachineCallback<'tcx, Result>, - } |this, result: Result<(u64, Option), IoError>| { - finish.call(this, result.map(|(bytes, _)| bytes)) + } |ecx, result: Result<(u64, Option), IoError>| { + finish.call(ecx, result.map(|(bytes, _)| bytes)) } ), ) @@ -608,7 +610,7 @@ impl UnixSocketFileDescription for TcpSocket { assert!(communicate_allowed, "cannot have `TcpSocket` with isolation enabled!"); let is_non_block = is_non_block || self.is_non_block.get(); - let deadline = ecx.action_deadline(is_non_block, self.write_timeout.get()); + let deadline = socket_action_deadline(ecx, is_non_block, self.write_timeout.get()); let socket = self; ecx.ensure_connected( @@ -656,16 +658,8 @@ impl UnixSocketFileDescription for TcpSocket { assert!(communicate_allowed, "cannot have `TcpSocket` with isolation enabled!"); let is_non_block = is_non_block || self.is_non_block.get(); - let deadline = ecx.action_deadline(is_non_block, self.read_timeout.get()); - - let finish = callback!( - @capture<'tcx> { - finish: DynMachineCallback<'tcx, Result<(u64, Option), IoError>>, - } |this, result: Result| { - // The source address of the data isn't available for stream-based sockets. - finish.call(this, result.map(|bytes| (bytes, None))) - } - ); + let deadline = socket_action_deadline(ecx, is_non_block, self.read_timeout.get()); + let socket = self; ecx.ensure_connected( socket.clone(), @@ -679,7 +673,7 @@ impl UnixSocketFileDescription for TcpSocket { len: u64, is_peek: bool, is_non_block: bool, - finish: DynMachineCallback<'tcx, Result>, + finish: DynMachineCallback<'tcx, Result<(u64, Option), IoError>>, } |ecx, result: Result<(), ()>| { if result.is_err() { return finish.call(ecx, Err(LibcError("ENOTCONN"))) @@ -689,11 +683,18 @@ impl UnixSocketFileDescription for TcpSocket { // We have a non-blocking operation or a non-blocking socket and // thus don't want to block until we can receive. let result = ecx.try_non_block_recv(&socket, ptr, len, is_peek)?; - finish.call(ecx, result) + finish.call(ecx, result.map(|bytes| (bytes, /* source_addr */ None))) } else { // The socket is in blocking mode and thus the receive call should block // until we can receive some bytes from the socket or the timeout exceeded. - ecx.block_for_recv(socket, deadline, ptr, len, is_peek, finish) + ecx.block_for_recv(socket, deadline, ptr, len, is_peek, callback!( + @capture<'tcx> { + finish: DynMachineCallback<'tcx, Result<(u64, Option), IoError>>, + } |ecx, result: Result| { + // The source address of the data isn't available for stream-based sockets. + finish.call(ecx, result.map(|bytes| (bytes, /* source_addr */ None))) + } + )) } } ), @@ -938,28 +939,6 @@ impl UnixSocketFileDescription for TcpSocket { impl<'tcx> EvalContextPrivExt<'tcx> for crate::MiriInterpCx<'tcx> {} trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { - /// Get the deadline for an action (e.g. reading or writing). - /// When `is_non_block` is [`true`], the returned deadline is "now", i.e., - /// we wake up immediately if the action cannot be completed. - /// If `action_timeout` is `Some(duration)`, the returned deadline is in the - /// future be the specified `duration`. Otherwise, no deadline ([`None`]) is - /// returned, indicating that the action can block indefinitely. - fn action_deadline( - &self, - is_non_block: bool, - action_timeout: Option, - ) -> Option { - let this = self.eval_context_ref(); - - if is_non_block { - // Non-blocking sockets always have a zero timeout. - Some(this.machine.monotonic_clock.now().into()) - } else { - action_timeout - .map(|duration| this.machine.monotonic_clock.now().add_lossy(duration).into()) - } - } - /// Block the thread until there's an incoming connection or an error occurred. /// After a successful accept, `finish` is called with a tuple containing the /// file descriptor of the peer socket and it's address. @@ -974,11 +953,11 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { is_client_sock_nonblock: bool, finish: DynMachineCallback<'tcx, Result<(FdNum, SocketAddr), IoError>>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); // Since the callback holds a strong reference to the socket, the file description // won't be closed as long as some thread is blocked on it. While this reflects // what Linux does, for other Unix systems this might differ from the native behavior. - this.block_thread_for_io( + ecx.block_thread_for_io( socket.clone(), BlockingIoInterest::Read, /* deadline */ None, @@ -1019,7 +998,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { socket: &FileDescriptionRef, is_client_sock_nonblock: bool, ) -> InterpResult<'tcx, Result<(FdNum, SocketAddr), IoError>> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); let state = socket.state.borrow(); let SocketState::Listening(listener) = &*state else { @@ -1033,7 +1012,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { Err(e) if e.kind() == io::ErrorKind::WouldBlock => { // We know that the source is not readable so we need to update its readiness. socket.io_readiness.borrow_mut().readable = false; - this.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::DEFAULT)?; + ecx.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::DEFAULT)?; return interp_ok(Err(IoError::HostError(e))); } @@ -1045,7 +1024,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { SocketAddr::V6(_) => socket2::Domain::IPV6, }; - let fd = this.machine.fds.new_ref(TcpSocket { + let fd = ecx.machine.fds.new_ref(TcpSocket { family, state: RefCell::new(SocketState::Connected(stream)), is_non_block: Cell::new(is_client_sock_nonblock), @@ -1059,8 +1038,8 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }); // Register the socket to the blocking I/O manager because // there is an associated host socket. - this.machine.blocking_io.register(fd.clone()); - let Some(sockfd) = this.machine.fds.insert(fd) else { + ecx.machine.blocking_io.register(fd.clone()); + let Some(sockfd) = ecx.machine.fds.insert(fd) else { return interp_ok(Err(LibcError("EMFILE"))); }; interp_ok(Ok((sockfd, addr))) @@ -1081,11 +1060,11 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { length: u64, finish: DynMachineCallback<'tcx, Result>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); // Since the callback holds a strong reference to the socket, the file description // won't be closed as long as some thread is blocked on it. While this reflects // what Linux does, for other Unix systems this might differ from the native behavior. - this.block_thread_for_io( + ecx.block_thread_for_io( socket.clone(), BlockingIoInterest::Write, deadline.clone(), @@ -1126,7 +1105,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { buffer_ptr: Pointer, length: u64, ) -> InterpResult<'tcx, Result> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); let mut state = socket.state.borrow_mut(); let SocketState::Connected(stream) = &mut *state else { @@ -1134,7 +1113,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }; // This is a *non-blocking* write. - let result = this.write_to_host(buffer_ptr, length, |buf| stream.write(buf))?; + let result = ecx.write_to_host(buffer_ptr, length, |buf| stream.write(buf))?; drop(state); @@ -1149,7 +1128,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { { // We know that the source is not writable so we need to update its readiness. socket.io_readiness.borrow_mut().writable = false; - this.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::DEFAULT)?; + ecx.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::DEFAULT)?; // On Windows hosts, `send` can return WSAENOTCONN where EAGAIN or EWOULDBLOCK // would be returned on UNIX-like systems. We thus remap this error to an EWOULDBLOCK. @@ -1179,7 +1158,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { target_os = "watchos", )) { socket.io_readiness.borrow_mut().writable = false; - this.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::DEFAULT)?; + ecx.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::DEFAULT)?; } else { // On hosts which don't use the `epoll` or `kqueue` backends, a short write // doesn't imply a full write buffer. However, the target we are emulating might @@ -1190,7 +1169,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // This results in an unrealistic execution but we don't have another way of // finding out whether the write buffer is full. The "default case" of linux // host and linux target isn't affected by this. - this.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::FORCE_EDGE)?; + ecx.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::FORCE_EDGE)?; } interp_ok(result) } @@ -1214,11 +1193,11 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { should_peek: bool, finish: DynMachineCallback<'tcx, Result>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); // Since the callback holds a strong reference to the socket, the file description // won't be closed as long as some thread is blocked on it. While this reflects // what Linux does, for other Unix systems this might differ from the native behavior. - this.block_thread_for_io( + ecx.block_thread_for_io( socket.clone(), BlockingIoInterest::Read, deadline.clone(), @@ -1261,7 +1240,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { length: u64, should_peek: bool, ) -> InterpResult<'tcx, Result> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); let mut state = socket.state.borrow_mut(); let SocketState::Connected(stream) = &mut *state else { @@ -1269,7 +1248,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }; // This is a *non-blocking* read/peek. - let result = this.read_from_host(buffer_ptr, length, |buf| { + let result = ecx.read_from_host(buffer_ptr, length, |buf| { if should_peek { stream.peek(buf) } else { stream.read(buf) } })?; @@ -1281,7 +1260,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { { // We know that the source is not readable so we need to update its readiness. socket.io_readiness.borrow_mut().readable = false; - this.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::DEFAULT)?; + ecx.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::DEFAULT)?; // On Windows hosts, `recv` can return WSAENOTCONN where EAGAIN or EWOULDBLOCK // would be returned on UNIX-like systems. We thus remap this error to an EWOULDBLOCK. @@ -1320,7 +1299,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { target_os = "watchos", )) { socket.io_readiness.borrow_mut().readable = false; - this.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::DEFAULT)?; + ecx.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::DEFAULT)?; } else { // On hosts which don't use the `epoll` or `kqueue` backends, a short read // doesn't imply an empty read buffer. However, the target we are emulating @@ -1331,7 +1310,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // This results in an unrealistic execution but we don't have another way of // finding out whether the read buffer is empty. The "default case" of linux // host and linux target isn't affected by this. - this.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::FORCE_EDGE)?; + ecx.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::FORCE_EDGE)?; } interp_ok(result) } @@ -1358,19 +1337,19 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { foreign_name: &'static str, action: DynMachineCallback<'tcx, Result<(), ()>>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); let state = socket.state.borrow(); match &*state { SocketState::Connecting(_) => { /* fall-through to below */ } SocketState::Connected(_) => { drop(state); - return action.call(this, Ok(())); + return action.call(ecx, Ok(())); } _ => { drop(state); - this.ensure_not_failed(&socket, foreign_name)?; - return action.call(this, Err(())); + ecx.ensure_not_failed(&socket, foreign_name)?; + return action.call(ecx, Err(())); } }; @@ -1379,7 +1358,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // We're currently connecting. Since the underlying mio socket is non-blocking, // the only way to determine whether we are done connecting is by polling. - this.block_thread_for_io( + ecx.block_thread_for_io( socket.clone(), BlockingIoInterest::Write, deadline, diff --git a/src/tools/miri/src/shims/unix/thread.rs b/src/tools/miri/src/shims/unix/thread.rs index 34c5246059100..2d9957ad7b783 100644 --- a/src/tools/miri/src/shims/unix/thread.rs +++ b/src/tools/miri/src/shims/unix/thread.rs @@ -1,4 +1,5 @@ use rustc_abi::ExternAbi; +use rustc_target::spec::Os; use crate::concurrency::thread::ThreadLookupError; use crate::*; @@ -9,32 +10,122 @@ pub enum ThreadNameResult { NameTooLong, } +// # pthread_attr_t + +struct PthreadAttr { + /// `None` represents that the stack size has not been explicitly set. + stack_size: Option, +} + +impl MetaObj for PthreadAttr {} + +/// Returns the thread attribute data stored at the address that `attr_ptr` points to. +fn attr_get_data<'tcx, 'a>( + ecx: &'a mut MiriInterpCx<'tcx>, + attr_ptr: &OpTy<'tcx>, +) -> InterpResult<'tcx, &'a mut PthreadAttr> +where + 'tcx: 'a, +{ + let attr = ecx.deref_pointer(attr_ptr)?; + ecx.get_or_insert_meta(&attr, |_ecx| { + throw_ub_format!("`pthread_attr_t` has not been initialized or has been tampered with") + }) +} + impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {} pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { + fn pthread_attr_init( + &mut self, + attr_op: &OpTy<'tcx>, + dest: &MPlaceTy<'tcx>, + ) -> InterpResult<'tcx> { + let ecx = self.eval_context_mut(); + let attr = ecx.deref_pointer(attr_op)?; + ecx.insert_meta(&attr, Box::new(PthreadAttr { stack_size: None }))?; + ecx.write_int(0, dest) + } + + fn pthread_attr_destroy( + &mut self, + attr_op: &OpTy<'tcx>, + dest: &MPlaceTy<'tcx>, + ) -> InterpResult<'tcx> { + let ecx = self.eval_context_mut(); + let attr = ecx.deref_pointer(attr_op)?; + ecx.remove_meta::(&attr)?.ok_or_else(|| { + err_ub_format!("`pthread_attr_t` has not been initialized or has been tampered with") + })?; + ecx.write_int(0, dest) + } + + fn pthread_attr_setstacksize( + &mut self, + attr_op: &OpTy<'tcx>, + stack_size_op: &OpTy<'tcx>, + dest: &MPlaceTy<'tcx>, + ) -> InterpResult<'tcx> { + let ecx = self.eval_context_mut(); + let stack_size = ecx.read_target_usize(stack_size_op)?; + + // Check the attribute object even if the size is invalid. + attr_get_data(ecx, attr_op)?; + + // Check that the size is valid. + let os = &ecx.tcx.sess.target.os; + // NetBSD has no `PTHREAD_STACK_MIN` constant. + if *os != Os::NetBsd + && stack_size < ecx.eval_libc("PTHREAD_STACK_MIN").to_target_usize(ecx)? + { + return ecx.write_scalar(ecx.eval_libc("EINVAL"), dest); + } + // macOS additionally requires the size to be a multiple of the page size. + if *os == Os::MacOs && !stack_size.is_multiple_of(ecx.machine.page_size) { + return ecx.write_scalar(ecx.eval_libc("EINVAL"), dest); + } + + // Update size in `attr`. + attr_get_data(ecx, attr_op)?.stack_size = Some(stack_size); + ecx.write_scalar(Scalar::from_i32(0), dest) + } + fn pthread_create( &mut self, - thread: &OpTy<'tcx>, - _attr: &OpTy<'tcx>, + thread_id: &OpTy<'tcx>, + attr: &OpTy<'tcx>, start_routine: &OpTy<'tcx>, arg: &OpTy<'tcx>, - ) -> InterpResult<'tcx, ()> { - let this = self.eval_context_mut(); + dest: &MPlaceTy<'tcx>, + ) -> InterpResult<'tcx> { + let ecx = self.eval_context_mut(); + + let thread_id_place = ecx.deref_pointer(thread_id)?; - let thread_info_place = this.deref_pointer(thread)?; + let start_routine = ecx.read_pointer(start_routine)?; - let start_routine = this.read_pointer(start_routine)?; + let func_arg = ecx.read_immediate(arg)?; - let func_arg = this.read_immediate(arg)?; + // A null `attr` means default attributes. + let stack_size = if ecx.ptr_is_null(ecx.read_pointer(attr)?)? { + None + } else { + attr_get_data(ecx, attr)?.stack_size + }; + if let Some(stack_size) = stack_size + && !ecx.thread_stack_size_ok(stack_size) + { + // There are not enough resources for such a big stack. + return ecx.write_scalar(ecx.eval_libc("EAGAIN"), dest); + } - this.start_regular_thread( - Some(thread_info_place), + let thread_id = ecx.start_regular_thread( start_routine, ExternAbi::C { unwind: false }, func_arg, - this.machine.layouts.unit_ptr_mut, + ecx.machine.layouts.unit_ptr_mut, )?; - - interp_ok(()) + ecx.write_int(thread_id.to_u32(), &thread_id_place)?; // pthread_t is just the Miri ThreadId + ecx.write_scalar(Scalar::from_i32(0), dest) } fn pthread_join( @@ -43,22 +134,22 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { retval: &OpTy<'tcx>, return_dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - if !this.ptr_is_null(this.read_pointer(retval)?)? { + if !ecx.ptr_is_null(ecx.read_pointer(retval)?)? { // FIXME: implement reading the thread function's return place. throw_unsup_format!("Miri supports pthread_join only with retval==NULL"); } - let thread = this.read_scalar(thread)?.to_int(this.libc_ty_layout("pthread_t").size)?; + let thread = ecx.read_int::(thread)?; // Joining a terminated thread is valid. - let thread = match this.thread_id_try_from(thread) { + let thread = match ecx.thread_id_try_from(thread) { Ok(id) | Err(ThreadLookupError::Terminated(id)) => id, Err(ThreadLookupError::InvalidId) => throw_ub_format!("pthread_join: invalid pthread_t handle"), }; - this.join_thread_exclusive( + ecx.join_thread_exclusive( thread, /* success_retval */ Scalar::from_u32(0), return_dest, @@ -66,48 +157,54 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } fn pthread_detach(&mut self, thread: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let thread = this.read_scalar(thread)?.to_int(this.libc_ty_layout("pthread_t").size)?; + let thread = ecx.read_int::(thread)?; // Detaching a terminated thread is valid. - let thread = match this.thread_id_try_from(thread) { + let thread = match ecx.thread_id_try_from(thread) { Ok(id) | Err(ThreadLookupError::Terminated(id)) => id, Err(ThreadLookupError::InvalidId) => throw_ub_format!("pthread_detach: invalid pthread_t handle"), }; - this.detach_thread(thread, /*allow_terminated_joined*/ false)?; + ecx.detach_thread(thread, /*allow_terminated_joined*/ false)?; interp_ok(Scalar::from_u32(0)) } - fn pthread_self(&self) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_ref(); + fn pthread_self(&mut self, dest: &MPlaceTy<'tcx>) -> InterpResult<'tcx> { + let ecx = self.eval_context_mut(); - let thread_id = this.active_thread(); - interp_ok(Scalar::from_uint(thread_id.to_u32(), this.libc_ty_layout("pthread_t").size)) + let thread_id = ecx.active_thread(); + ecx.write_int(thread_id.to_u32(), dest) // pthread_t is just the Miri ThreadId } - /// Set the name of the specified thread. If the name including the null terminator + /// Set the name of the specified thread. `None` indicates the current thread. + /// If the name including the null terminator /// is longer or equals to `name_max_len`, then if `truncate` is set the truncated name /// is used as the thread name, otherwise [`ThreadNameResult::NameTooLong`] is returned. /// If the specified thread wasn't found, UB is raised. fn pthread_setname_np( &mut self, - thread: Scalar, - name: Scalar, + thread: Option<&OpTy<'tcx>>, + name: Pointer, name_max_len: u64, truncate: bool, ) -> InterpResult<'tcx, ThreadNameResult> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let thread = thread.to_int(this.libc_ty_layout("pthread_t").size)?; - let Ok(thread) = this.thread_id_try_from(thread) else { - // On Linux this has been observed to segfault. FreeBSD documents an error code - // for this condition but it is not clear whether they *guarantee* that error. - throw_ub_format!("pthread_setname_np: invalid pthread_t handle"); + let thread = match thread { + None => ecx.active_thread(), + Some(thread) => { + let thread = ecx.read_int::(thread)?; + let Ok(thread) = ecx.thread_id_try_from(thread) else { + // On Linux this has been observed to segfault. FreeBSD documents an error code + // for this condition but it is not clear whether they *guarantee* that error. + throw_ub_format!("pthread_setname_np: invalid pthread_t handle"); + }; + thread + } }; - let name = name.to_pointer(this); - let mut name = this.read_c_str(name)?.to_owned(); + let mut name = ecx.read_c_str(name)?.to_owned(); // Comparing with `>=` to account for null terminator. if name.len().to_u64() >= name_max_len { @@ -118,7 +215,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } } - this.set_thread_name(thread, name); + ecx.set_thread_name(thread, name); interp_ok(ThreadNameResult::Ok) } @@ -129,39 +226,44 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// thread wasn't found, UB is raised. fn pthread_getname_np( &mut self, - thread: Scalar, - name_out: Scalar, + thread: Option<&OpTy<'tcx>>, + name_out: Pointer, len: Scalar, truncate: bool, ) -> InterpResult<'tcx, ThreadNameResult> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let thread = thread.to_int(this.libc_ty_layout("pthread_t").size)?; - let Ok(thread) = this.thread_id_try_from(thread) else { - // On Linux this has been observed to segfault. FreeBSD documents an error code - // for this condition but it is not clear whether they *guarantee* that error. - throw_ub_format!("pthread_getname_np: invalid pthread_t handle"); + let thread = match thread { + None => ecx.active_thread(), + Some(thread) => { + let thread = ecx.read_int::(thread)?; + let Ok(thread) = ecx.thread_id_try_from(thread) else { + // On Linux this has been observed to segfault. FreeBSD documents an error code + // for this condition but it is not clear whether they *guarantee* that error. + throw_ub_format!("pthread_getname_np: invalid pthread_t handle"); + }; + thread + } }; - let name_out = name_out.to_pointer(this); - let len = len.to_target_usize(this)?; + let len = len.to_target_usize(ecx)?; // FIXME: we should use the program name if the thread name is not set - let name = this.get_thread_name(thread).unwrap_or(b"").to_owned(); + let name = ecx.get_thread_name(thread).unwrap_or(b"").to_owned(); let name = match truncate { true => &name[..name.len().min(len.try_into().unwrap_or(usize::MAX).saturating_sub(1))], false => &name, }; - let (success, _written) = this.write_c_str(name, name_out, len)?; + let (success, _written) = ecx.write_c_str(name, name_out, len)?; let res = if success { ThreadNameResult::Ok } else { ThreadNameResult::NameTooLong }; interp_ok(res) } fn sched_yield(&mut self) -> InterpResult<'tcx, ()> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - this.yield_active_thread(); + ecx.yield_active_thread(); interp_ok(()) } diff --git a/src/tools/miri/src/shims/unix/udp_socket.rs b/src/tools/miri/src/shims/unix/udp_socket.rs index 13a1e3a38f1df..46efc813cdac9 100644 --- a/src/tools/miri/src/shims/unix/udp_socket.rs +++ b/src/tools/miri/src/shims/unix/udp_socket.rs @@ -6,9 +6,11 @@ use std::time::Duration; use mio::event::Source; use rustc_target::spec::Os; -use crate::shims::files::{FileDescription, FileDescriptionRef}; +use crate::shims::files::{EvalContextExt as _, FileDescription, FileDescriptionRef}; use crate::shims::unix::UnixFileDescription; -use crate::shims::unix::socket::{EvalContextExt, UnixSocketFileDescription}; +use crate::shims::unix::socket::{ + EvalContextExt, UnixSocketFileDescription, socket_action_deadline, +}; use crate::*; #[derive(Debug)] @@ -22,6 +24,8 @@ pub(super) struct UdpSocket { is_non_block: Cell, /// Whether the socket is implicitly or explicitly bound to an address. is_bound: Cell, + /// Whether a default destination address has been set for this socket. + has_default_destination: Cell, /// The current blocking I/O readiness of the file description. io_readiness: RefCell, /// Read timeout of the socket. [`None`] means that reads can block indefinitely. @@ -71,6 +75,7 @@ impl UdpSocket { socket: RefCell::new(socket), is_non_block: Cell::new(is_non_block), is_bound: Cell::new(false), + has_default_destination: Cell::new(false), // We can set the default readiness to the empty readiness // since the socket will be registered to the blocking I/O // directly after its creation. @@ -95,6 +100,50 @@ impl FileDescription for UdpSocket { "udp socket" } + fn read<'tcx>( + self: FileDescriptionRef, + communicate_allowed: bool, + ptr: Pointer, + len: u64, + ecx: &mut MiriInterpCx<'tcx>, + finish: DynMachineCallback<'tcx, Result>, + ) -> InterpResult<'tcx> { + self.recv( + communicate_allowed, + ptr, + len, + /* is_peek */ false, + /* is_non_block */ false, + ecx, + callback!( + @capture<'tcx> { + finish: DynMachineCallback<'tcx, Result>, + } |ecx, result: Result<(u64, Option), IoError>| { + finish.call(ecx, result.map(|(bytes, _)| bytes)) + } + ), + ) + } + + fn write<'tcx>( + self: FileDescriptionRef, + communicate_allowed: bool, + ptr: Pointer, + len: u64, + ecx: &mut MiriInterpCx<'tcx>, + finish: DynMachineCallback<'tcx, Result>, + ) -> InterpResult<'tcx> { + self.send( + communicate_allowed, + ptr, + len, + /* is_non_block */ false, + /* dest_addr */ None, + ecx, + finish, + ) + } + fn as_unix(self: FileDescriptionRef) -> FileDescriptionRef { self } @@ -201,6 +250,14 @@ impl UnixSocketFileDescription for UdpSocket { ) -> InterpResult<'tcx> { assert!(communicate_allowed, "cannot have `UdpSocket` with isolation enabled!"); + if self.has_default_destination.get() { + // POSIX is very vague about whether it's allowed to set the default destination address + // of a non-connection-mode socket multiple times. Some platforms support it while others don't. + // We thus only allow setting the destination address at most once. + // See + throw_unsup_format!("calling `connect` a second time on a UDP socket is unsupported"); + } + if let Err(e) = self.socket.borrow().connect(address) { return finish.call(ecx, Err(IoError::HostError(e))); } @@ -210,9 +267,75 @@ impl UnixSocketFileDescription for UdpSocket { // We thus treat the socket as implicitly bound. self.is_bound.set(true); + self.has_default_destination.set(true); + finish.call(ecx, Ok(())) } + fn send<'tcx>( + self: FileDescriptionRef, + communicate_allowed: bool, + ptr: Pointer, + len: u64, + is_non_block: bool, + dest_addr: Option, + ecx: &mut MiriInterpCx<'tcx>, + finish: DynMachineCallback<'tcx, Result>, + ) -> InterpResult<'tcx> { + assert!(communicate_allowed, "cannot have `UdpSocket` with isolation enabled!"); + + let is_non_block = is_non_block || self.is_non_block.get(); + + if is_non_block { + // We have a non-blocking operation or a non-blocking socket and + // thus don't want to block until we can send. + let result = ecx.try_non_block_send(&self, ptr, len, dest_addr)?; + finish.call(ecx, result) + } else { + let deadline = socket_action_deadline(ecx, is_non_block, self.write_timeout.get()); + + // The socket is in blocking mode and thus the send call should block + // until we can send some bytes into the socket or the timeout exceeded. + ecx.block_for_send(self, deadline, ptr, len, dest_addr, finish) + } + } + + fn recv<'tcx>( + self: FileDescriptionRef, + communicate_allowed: bool, + ptr: Pointer, + len: u64, + is_peek: bool, + is_non_block: bool, + ecx: &mut MiriInterpCx<'tcx>, + finish: DynMachineCallback<'tcx, Result<(u64, Option), IoError>>, + ) -> InterpResult<'tcx> { + assert!(communicate_allowed, "cannot have `UdpSocket` with isolation enabled!"); + + let is_non_block = is_non_block || self.is_non_block.get(); + + if is_non_block { + // We have a non-blocking operation or a non-blocking socket and + // thus don't want to block until we can receive. + let result = ecx.try_non_block_recv(&self, ptr, len, is_peek)?; + finish.call(ecx, result.map(|(bytes, addr)| (bytes, Some(addr)))) + } else { + let deadline = socket_action_deadline(ecx, is_non_block, self.read_timeout.get()); + + // The socket is in blocking mode and thus the receive call should block + // until we can receive some bytes from the socket or the timeout exceeded. + ecx.block_for_recv(self, deadline, ptr, len, is_peek, callback!( + @capture<'tcx> { + finish: DynMachineCallback<'tcx, Result<(u64, Option), IoError>>, + } |ecx, result: Result<(u64, SocketAddr), IoError>| { + // For UDP sockets we always have access to the address from where the + // data originated. + finish.call(ecx, result.map(|(bytes, addr)| (bytes, Some(addr)))) + } + )) + } + } + fn setsockopt<'tcx>( self: FileDescriptionRef, level: i32, @@ -334,6 +457,276 @@ impl UnixSocketFileDescription for UdpSocket { } } +impl<'tcx> EvalContextPrivExt<'tcx> for crate::MiriInterpCx<'tcx> {} +trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { + /// Block the thread until we can send bytes into the connected socket + /// or an error occurred. + /// + /// This recursively calls itself should the operation still block for some reason. + fn block_for_send( + &mut self, + socket: FileDescriptionRef, + deadline: Option, + buffer_ptr: Pointer, + length: u64, + dest_addr: Option, + finish: DynMachineCallback<'tcx, Result>, + ) -> InterpResult<'tcx> { + let ecx = self.eval_context_mut(); + // Since the callback holds a strong reference to the socket, the file description + // won't be closed as long as some thread is blocked on it. While this reflects + // what Linux does, for other Unix systems this might differ from the native behavior. + ecx.block_thread_for_io( + socket.clone(), + BlockingIoInterest::Write, + deadline.clone(), + callback!(@capture<'tcx> { + socket: FileDescriptionRef, + deadline: Option, + buffer_ptr: Pointer, + length: u64, + dest_addr: Option, + finish: DynMachineCallback<'tcx, Result>, + } |ecx, kind: UnblockKind| { + // Remove the blocking I/O interest for unblocking this thread. + ecx.machine.blocking_io.remove_blocked_thread(socket.id(), ecx.machine.threads.active_thread()); + + match kind { + UnblockKind::Ready => { /* fall-through to below */ }, + // When the write timeout is exceeded EAGAIN/EWOULDBLOCK is returned. + UnblockKind::TimedOut => return finish.call(ecx, Err(LibcError("EWOULDBLOCK"))) + } + + match ecx.try_non_block_send(&socket, buffer_ptr, length, dest_addr)? { + Err(IoError::HostError(e)) if e.kind() == io::ErrorKind::WouldBlock => { + // We need to block the thread again as it would still block. + ecx.block_for_send(socket, deadline, buffer_ptr, length, dest_addr, finish) + }, + result => finish.call(ecx, result) + } + }), + ) + } + + /// Attempt to send bytes to another socket. If `dest_addr` is [`Some`], the data + /// is sent to the address specified in `dest_addr`. Otherwise, the data is sent + /// to the default destination address. + fn try_non_block_send( + &mut self, + socket: &FileDescriptionRef, + buffer_ptr: Pointer, + length: u64, + dest_addr: Option, + ) -> InterpResult<'tcx, Result> { + let ecx = self.eval_context_mut(); + + let host_socket = socket.socket.borrow(); + + if dest_addr.is_some() && socket.has_default_destination.get() { + // The sendto POSIX man page specifies that "[...] If a peer address has been pre-specified, either + // the message shall be sent to the address specified by dest_addr (overriding the pre-specified + // peer address), or the function shall return -1 and set errno to [EISCONN]. [...]". + // It turns out that Linux implements the prior option while BSD-based platforms implement the latter. + // Since both are allowed by POSIX, we try to model this as good as possible. + + if matches!(ecx.tcx.sess.target.os, Os::FreeBsd | Os::MacOs) { + // We're on a BSD target. When both `dest_addr` and a default destination address + // are available, those platforms return EISCONN and don't perform the operation. + return interp_ok(Err(LibcError("EISCONN"))); + } else if cfg!(any(target_os = "freebsd", target_vendor = "apple")) { + // We're on a BSD host and on a non-BSD target. On such targets `dest_addr` should + // overwrite the default destination address, however, we cannot achieve this nicely + // since the host disallows that. We thus throw an unsupported error. + throw_unsup_format!( + "sendto: overwriting default destination address is not supported for UDP sockets on BSD hosts" + ) + } + } + + // This is a *non-blocking* write. + let result = ecx.write_to_host(buffer_ptr, length, |bytes| { + match dest_addr { + Some(dest_addr) => host_socket.send_to(bytes, dest_addr), + None => host_socket.send(bytes), + } + })?; + + if result.is_ok() { + // A write should never succeed when the `write_closed` readiness is set for this socket. + assert!(!socket.io_readiness.borrow().write_closed, "successful write after close"); + + if dest_addr.is_some() { + // After the first successful `sendto`, the socket gets implicitly bound to a local address. + socket.is_bound.set(true); + } else { + // Can only succeed if `connect` was called, which binds the socket. + assert!(socket.is_bound.get()); + } + } + + match result { + Err(IoError::HostError(e)) if matches!(e.kind(), io::ErrorKind::WouldBlock) => { + // We know that the source is not writable so we need to update its readiness. + socket.io_readiness.borrow_mut().writable = false; + ecx.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::DEFAULT)?; + + interp_ok(Err(IoError::HostError(e))) + } + Err(IoError::HostError(e)) + if cfg!(windows) && matches!(e.kind(), io::ErrorKind::NotConnected) => + { + // Windows returns ENOTCONN instead of EDESTADDRREQ when attempting to `send` without + // having a default destination address set. We thus remap this error to an EDESTADDRREQ. + interp_ok(Err(IoError::LibcError("EDESTADDRREQ"))) + } + Err(IoError::HostError(e)) + if cfg!(windows) + && e.raw_os_error().is_some_and(|errno| errno == /* WSAEMSGSIZE */ 10040) => + { + // We attempted to write a message which doesn't fit into a single UDP datagram. + // On Windows hosts this returns WSAEMSGSIZE while on Unix-like hosts this returns EMSGSIZE. + // Since WSAEMSGSIZE doesn't map to a `io::ErrorKind`, Miri throws an unsupported error if we + // would just return this I/O error. We thus manually remap this error to EMSGSIZE on Windows + // hosts. The mapping needs to be performed here and not directly inside the callback function + // where the `host_socket.send` occurs since this callback function returns a result with `io::Error` + // instead of `IoError`. + // FIXME: remove this if WSAEMSGSIZE ever maps to a `io::ErrorKind`. + interp_ok(Err(IoError::LibcError("EMSGSIZE"))) + } + result => interp_ok(result), + } + } + + /// Block the thread until we can receive bytes from the socket or an error occurred. + /// + /// This recursively calls itself should the operation still block for some reason. + fn block_for_recv( + &mut self, + socket: FileDescriptionRef, + deadline: Option, + buffer_ptr: Pointer, + length: u64, + should_peek: bool, + finish: DynMachineCallback<'tcx, Result<(u64, SocketAddr), IoError>>, + ) -> InterpResult<'tcx> { + let recv = self.eval_context_mut(); + // Since the callback holds a strong reference to the socket, the file description + // won't be closed as long as some thread is blocked on it. While this reflects + // what Linux does, for other Unix systems this might differ from the native behavior. + recv.block_thread_for_io( + socket.clone(), + BlockingIoInterest::Read, + deadline.clone(), + callback!(@capture<'tcx> { + socket: FileDescriptionRef, + deadline: Option, + buffer_ptr: Pointer, + length: u64, + should_peek: bool, + finish: DynMachineCallback<'tcx, Result<(u64, SocketAddr), IoError>>, + } |ecx, kind: UnblockKind| { + // Remove the blocking I/O interest for unblocking this thread. + ecx.machine.blocking_io.remove_blocked_thread(socket.id(), ecx.machine.threads.active_thread()); + + match kind { + UnblockKind::Ready => { /* fall-through to below */ }, + // When the read timeout is exceeded EAGAIN/EWOULDBLOCK is returned. + UnblockKind::TimedOut => return finish.call(ecx, Err(LibcError("EWOULDBLOCK"))) + } + + match ecx.try_non_block_recv(&socket, buffer_ptr, length, should_peek)? { + Err(IoError::HostError(e)) if e.kind() == io::ErrorKind::WouldBlock => { + // We need to block the thread again as it would still block. + ecx.block_for_recv(socket, deadline, buffer_ptr, length, should_peek, finish) + }, + result => finish.call(ecx, result) + } + }), + ) + } + + /// Attempt to receive bytes from the socket in a non-blocking manner. + fn try_non_block_recv( + &mut self, + socket: &FileDescriptionRef, + buffer_ptr: Pointer, + length: u64, + should_peek: bool, + ) -> InterpResult<'tcx, Result<(u64, SocketAddr), IoError>> { + let ecx = self.eval_context_mut(); + + let host_socket = socket.socket.borrow(); + + // If the `read_from_host` below succeeds, this contains the address from where + // the data originated. Otherwise, this is `None`. + let mut origin_addr = None; + + let mut recv_from_host_socket = |buf: &mut [u8]| { + let result = + if should_peek { host_socket.peek_from(buf) } else { host_socket.recv_from(buf) }; + + result.map(|(bytes, addr)| { + // Store the origin address in `origin_addr`. We need to do this since + // `read_from_host` expects the callback to return `io::Result`. + origin_addr.replace(addr); + + // Return the amount of bytes received. + bytes + }) + }; + + // This is a *non-blocking* read/peek. + let result = ecx.read_from_host(buffer_ptr, length, |buf| { + if cfg!(windows) { + // When trying to read a message from the socket which does not fit our + // provided buffer, POSIX specifies that the provided buffer should be + // filled and the remaining bytes should be discarded. The receive operation + // should then return the amount of bytes read. Windows hosts fill the buffer + // and discard the excess bytes but return WSAEMSGSIZE instead of the bytes read. + // Since the return type of the corresponding operations in the standard library + // (and thus also in mio) is `io::Result<(usize, SocketAddr)>`, we essentially + // "lose" the address from where this data originated. + // To circumvent this, we use a temporary 64KiB buffer which fits any UDP + // datagram, receive into this temporary buffer, and then copy at most the first + // `length` bytes from the temporary buffer into `buf`. + + #[expect(clippy::as_conversions)] + let mut tmp_buf = [0u8; u16::MAX as usize]; + let result = recv_from_host_socket(&mut tmp_buf).map(|bytes| { + let bytes_received = bytes.min(usize::try_from(length).unwrap()); + buf[..bytes_received].copy_from_slice(&tmp_buf[..bytes_received]); + + // Return the actual amount of bytes written to `buf`. + bytes_received + }); + + if let Err(ref e) = result { + // Since we received into a big enough temporary buffer, we should never + // fail with WSAEMSGSIZE. + assert_ne!(e.raw_os_error(), Some(/* WSAEMSGSIZE */ 10040)) + } + + return result; + } + + recv_from_host_socket(buf) + })?; + + match result { + Err(IoError::HostError(e)) if matches!(e.kind(), io::ErrorKind::WouldBlock) => { + // We know that the source is not readable so we need to update its readiness. + socket.io_readiness.borrow_mut().readable = false; + ecx.update_fd_readiness(socket.clone(), ReadinessUpdateFlags::DEFAULT)?; + + interp_ok(Err(IoError::HostError(e))) + } + // Since `origin_addr` is only `Some` when `result` is `Ok`, it's okay to unwrap + // `origin_addr` in the mapping function of `result`. + result => interp_ok(result.map(|bytes| (bytes, origin_addr.unwrap()))), + } + } +} + impl SourceFileDescription for UdpSocket { fn with_source(&self, f: &mut dyn FnMut(&mut dyn Source) -> io::Result<()>) -> io::Result<()> { let mut socket = self.socket.borrow_mut(); diff --git a/src/tools/miri/src/shims/unix/virtual_socket.rs b/src/tools/miri/src/shims/unix/virtual_socket.rs index b6dc73970b5c3..b34fe96dc1f83 100644 --- a/src/tools/miri/src/shims/unix/virtual_socket.rs +++ b/src/tools/miri/src/shims/unix/virtual_socket.rs @@ -315,9 +315,9 @@ impl UnixSocketFileDescription for VirtualSocket { let finish = callback!( @capture<'tcx> { finish: DynMachineCallback<'tcx, Result<(u64, Option), IoError>>, - } |this, result: Result| { + } |ecx, result: Result| { // The source address of the data isn't available for stream-based sockets. - finish.call(this, result.map(|bytes| (bytes, None))) + finish.call(ecx, result.map(|bytes| (bytes, None))) } ); ecx.virtual_socket_read(self, ptr, len, is_non_block, finish) @@ -339,24 +339,24 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { is_non_block: bool, finish: DynMachineCallback<'tcx, Result>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); // Always succeed on write size 0. // ("If count is zero and fd refers to a file other than a regular file, the results are not specified.") if len == 0 { - return finish.call(this, Ok(0)); + return finish.call(ecx, Ok(0)); } // We are writing to our peer's readbuf. let Some(peer_fd) = socket.peer_fd().upgrade() else { // If the upgrade from Weak to Rc fails, it indicates that all read ends have been // closed. It is an error to write even if there would be space. - return finish.call(this, Err(ErrorKind::BrokenPipe.into())); + return finish.call(ecx, Err(ErrorKind::BrokenPipe.into())); }; let Some(writebuf) = &peer_fd.readbuf else { // Writing to the read end of a pipe. - return finish.call(this, Err(IoError::LibcError("EBADF"))); + return finish.call(ecx, Err(IoError::LibcError("EBADF"))); }; // Let's see if we can write. @@ -365,10 +365,10 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { if available_space == 0 { if socket.is_nonblock.get() || is_non_block { // Non-blocking socketpair with a full buffer. - return finish.call(this, Err(ErrorKind::WouldBlock.into())); + return finish.call(ecx, Err(ErrorKind::WouldBlock.into())); } else { - socket.blocked_write_tid.borrow_mut().push(this.active_thread()); - this.block_thread( + socket.blocked_write_tid.borrow_mut().push(ecx.active_thread()); + ecx.block_thread( BlockReason::VirtualSocket, None, callback!( @@ -390,13 +390,13 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // There is space to write! let mut writebuf = writebuf.borrow_mut(); // Remember this clock so `read` can synchronize with us. - this.release_clock(|clock| { + ecx.release_clock(|clock| { writebuf.clock.join(clock); })?; // Do full write / partial write based on the space available. let write_size = len.min(available_space); let actual_write_size = - this.write_to_host(ptr, write_size, |buf| writebuf.buf.write(buf))?.unwrap(); + ecx.write_to_host(ptr, write_size, |buf| writebuf.buf.write(buf))?.unwrap(); assert_eq!(actual_write_size, write_size); // Need to stop accessing peer_fd so that it can be notified. @@ -406,15 +406,15 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let waiting_threads = std::mem::take(&mut *peer_fd.blocked_read_tid.borrow_mut()); // FIXME: We can randomize the order of unblocking. for thread_id in waiting_threads { - this.unblock_thread(thread_id, BlockReason::VirtualSocket)?; + ecx.unblock_thread(thread_id, BlockReason::VirtualSocket)?; } // Notify readiness watchers: we might be no longer writable, peer might now be readable. // The notification to the peer seems to be always sent on Linux, even if the // FD was readable before. - this.update_fd_readiness(socket, ReadinessUpdateFlags::DEFAULT)?; - this.update_fd_readiness(peer_fd, ReadinessUpdateFlags::FORCE_EDGE)?; + ecx.update_fd_readiness(socket, ReadinessUpdateFlags::DEFAULT)?; + ecx.update_fd_readiness(peer_fd, ReadinessUpdateFlags::FORCE_EDGE)?; - return finish.call(this, Ok(write_size)); + return finish.call(ecx, Ok(write_size)); } interp_ok(()) } @@ -432,11 +432,11 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { is_non_block: bool, finish: DynMachineCallback<'tcx, Result>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); // Always succeed on read size 0. if len == 0 { - return finish.call(this, Ok(0)); + return finish.call(ecx, Ok(0)); } let Some(readbuf) = &socket.readbuf else { @@ -449,17 +449,17 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { if socket.peer_fd().upgrade().is_none() { // Socketpair with no peer and empty buffer. // 0 bytes successfully read indicates end-of-file. - return finish.call(this, Ok(0)); + return finish.call(ecx, Ok(0)); } else if socket.is_nonblock.get() || is_non_block { // Non-blocking socketpair with writer and empty buffer. // https://linux.die.net/man/2/read // EAGAIN or EWOULDBLOCK can be returned for socket, // POSIX.1-2001 allows either error to be returned for this case. // Since there is no ErrorKind for EAGAIN, WouldBlock is used. - return finish.call(this, Err(ErrorKind::WouldBlock.into())); + return finish.call(ecx, Err(ErrorKind::WouldBlock.into())); } else { - socket.blocked_read_tid.borrow_mut().push(this.active_thread()); - this.block_thread( + socket.blocked_read_tid.borrow_mut().push(ecx.active_thread()); + ecx.block_thread( BlockReason::VirtualSocket, None, callback!( @@ -483,11 +483,11 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Synchronize with all previous writes to this buffer. // FIXME: this over-synchronizes; a more precise approach would be to // only sync with the writes whose data we will read. - this.acquire_clock(&readbuf.clock)?; + ecx.acquire_clock(&readbuf.clock)?; // Do full read / partial read based on the space available. // Conveniently, `read` exists on `VecDeque` and has exactly the desired behavior. - let read_size = this.read_from_host(ptr, len, |buf| readbuf.buf.read(buf))?.unwrap(); + let read_size = ecx.read_from_host(ptr, len, |buf| readbuf.buf.read(buf))?.unwrap(); let readbuf_now_empty = readbuf.buf.is_empty(); // Need to drop before others can access the readbuf again. @@ -505,13 +505,13 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let waiting_threads = std::mem::take(&mut *peer_fd.blocked_write_tid.borrow_mut()); // FIXME: We can randomize the order of unblocking. for thread_id in waiting_threads { - this.unblock_thread(thread_id, BlockReason::VirtualSocket)?; + ecx.unblock_thread(thread_id, BlockReason::VirtualSocket)?; } // Notify readiness watchers: peer is now writable. // Linux seems to always notify the peer if the read buffer is now empty. // (Linux also does that if this was a "big" read, but to avoid some arbitrary // threshold, we do not match that.) - this.update_fd_readiness( + ecx.update_fd_readiness( peer_fd, if readbuf_now_empty { ReadinessUpdateFlags::FORCE_EDGE @@ -521,9 +521,9 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; }; // Notify readiness watchers: we might be no longer readable. - this.update_fd_readiness(socket, ReadinessUpdateFlags::DEFAULT)?; + ecx.update_fd_readiness(socket, ReadinessUpdateFlags::DEFAULT)?; - return finish.call(this, Ok(read_size)); + return finish.call(ecx, Ok(read_size)); } interp_ok(()) } @@ -540,26 +540,26 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { protocol: &OpTy<'tcx>, sv: &OpTy<'tcx>, ) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let domain = this.read_scalar(domain)?.to_i32()?; - let mut flags = this.read_scalar(type_)?.to_i32()?; - let protocol = this.read_scalar(protocol)?.to_i32()?; + let domain = ecx.read_scalar(domain)?.to_i32()?; + let mut flags = ecx.read_scalar(type_)?.to_i32()?; + let protocol = ecx.read_scalar(protocol)?.to_i32()?; // This is really a pointer to `[i32; 2]` but we use a ptr-to-first-element representation. - let sv = this.deref_pointer(sv)?; + let sv = ecx.deref_pointer(sv)?; let mut is_sock_nonblock = false; // Interpret the flag. Every flag we recognize is "subtracted" from `flags`, so // if there is anything left at the end, that's an unsupported flag. if matches!( - this.tcx.sess.target.os, + ecx.tcx.sess.target.os, Os::Linux | Os::Android | Os::FreeBsd | Os::Solaris | Os::Illumos ) { // SOCK_NONBLOCK and SOCK_CLOEXEC only exist on Linux, Android, FreeBSD, // Solaris, and Illumos targets. - let sock_nonblock = this.eval_libc_i32("SOCK_NONBLOCK"); - let sock_cloexec = this.eval_libc_i32("SOCK_CLOEXEC"); + let sock_nonblock = ecx.eval_libc_i32("SOCK_NONBLOCK"); + let sock_cloexec = ecx.eval_libc_i32("SOCK_CLOEXEC"); if flags & sock_nonblock == sock_nonblock { is_sock_nonblock = true; flags &= !sock_nonblock; @@ -572,13 +572,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Fail on unsupported input. // AF_UNIX and AF_LOCAL are synonyms, so we accept both in case // their values differ. - if domain != this.eval_libc_i32("AF_UNIX") && domain != this.eval_libc_i32("AF_LOCAL") { + if domain != ecx.eval_libc_i32("AF_UNIX") && domain != ecx.eval_libc_i32("AF_LOCAL") { throw_unsup_format!( "socketpair: domain {:#x} is unsupported, only AF_UNIX \ and AF_LOCAL are allowed", domain ); - } else if flags != this.eval_libc_i32("SOCK_STREAM") { + } else if flags != ecx.eval_libc_i32("SOCK_STREAM") { throw_unsup_format!( "socketpair: type {:#x} is unsupported, only SOCK_STREAM, \ SOCK_CLOEXEC and SOCK_NONBLOCK are allowed", @@ -592,7 +592,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } // Generate file descriptions. - let fds = &mut this.machine.fds; + let fds = &mut ecx.machine.fds; let fd0 = fds.new_ref(VirtualSocket { readbuf: Some(RefCell::new(Buffer::new())), peer_fd: OnceCell::new(), @@ -601,7 +601,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { blocked_write_tid: RefCell::new(Vec::new()), is_nonblock: Cell::new(is_sock_nonblock), fd_type: VirtualSocketType::Socketpair, - delayed_callbacks: Rc::clone(&this.machine.delayed_callbacks), + delayed_callbacks: Rc::clone(&ecx.machine.delayed_callbacks), watched: ReadinessWatched::default(), }); let fd1 = fds.new_ref(VirtualSocket { @@ -612,7 +612,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { blocked_write_tid: RefCell::new(Vec::new()), is_nonblock: Cell::new(is_sock_nonblock), fd_type: VirtualSocketType::Socketpair, - delayed_callbacks: Rc::clone(&this.machine.delayed_callbacks), + delayed_callbacks: Rc::clone(&ecx.machine.delayed_callbacks), watched: ReadinessWatched::default(), }); @@ -622,18 +622,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Insert the file description to the fd table, generating the file descriptors. let Some(sv0) = fds.insert(fd0) else { - return this.set_errno_and_return_neg1_i32(LibcError("EMFILE")); + return ecx.set_errno_and_return_neg1_i32(LibcError("EMFILE")); }; let Some(sv1) = fds.insert(fd1) else { - this.close(sv0)?; // don't leak the first FD - return this.set_errno_and_return_neg1_i32(LibcError("EMFILE")); + ecx.close(sv0)?; // don't leak the first FD + return ecx.set_errno_and_return_neg1_i32(LibcError("EMFILE")); }; // Return socketpair file descriptors to the caller. - let sv0 = Scalar::from_int(sv0, sv.layout.size); - let sv1 = Scalar::from_int(sv1, sv.layout.size); - this.write_scalar(sv0, &sv)?; - this.write_scalar(sv1, &this.project_c_array_field(&sv, 1)?)?; + ecx.write_int(sv0, &sv)?; + ecx.write_int(sv1, &ecx.project_c_array_field(&sv, 1)?)?; interp_ok(Scalar::from_i32(0)) } @@ -643,16 +641,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { pipefd: &OpTy<'tcx>, flags: Option<&OpTy<'tcx>>, ) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let pipefd = this.deref_pointer(pipefd)?; + let pipefd = ecx.deref_pointer(pipefd)?; let mut flags = match flags { - Some(flags) => this.read_scalar(flags)?.to_i32()?, + Some(flags) => ecx.read_scalar(flags)?.to_i32()?, None => 0, }; - let cloexec = this.eval_libc_i32("O_CLOEXEC"); - let o_nonblock = this.eval_libc_i32("O_NONBLOCK"); + let cloexec = ecx.eval_libc_i32("O_CLOEXEC"); + let o_nonblock = ecx.eval_libc_i32("O_NONBLOCK"); // Interpret the flag. Every flag we recognize is "subtracted" from `flags`, so // if there is anything left at the end, that's an unsupported flag. @@ -671,7 +669,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Generate file descriptions. // pipefd[0] refers to the read end of the pipe. - let fds = &mut this.machine.fds; + let fds = &mut ecx.machine.fds; let fd0 = fds.new_ref(VirtualSocket { readbuf: Some(RefCell::new(Buffer::new())), peer_fd: OnceCell::new(), @@ -680,7 +678,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { blocked_write_tid: RefCell::new(Vec::new()), is_nonblock: Cell::new(is_nonblock), fd_type: VirtualSocketType::PipeRead, - delayed_callbacks: Rc::clone(&this.machine.delayed_callbacks), + delayed_callbacks: Rc::clone(&ecx.machine.delayed_callbacks), watched: ReadinessWatched::default(), }); let fd1 = fds.new_ref(VirtualSocket { @@ -691,7 +689,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { blocked_write_tid: RefCell::new(Vec::new()), is_nonblock: Cell::new(is_nonblock), fd_type: VirtualSocketType::PipeWrite, - delayed_callbacks: Rc::clone(&this.machine.delayed_callbacks), + delayed_callbacks: Rc::clone(&ecx.machine.delayed_callbacks), watched: ReadinessWatched::default(), }); @@ -701,18 +699,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Insert the file description to the fd table, generating the file descriptors. let Some(pipefd0) = fds.insert(fd0) else { - return this.set_errno_and_return_neg1_i32(LibcError("EMFILE")); + return ecx.set_errno_and_return_neg1_i32(LibcError("EMFILE")); }; let Some(pipefd1) = fds.insert(fd1) else { - this.close(pipefd0)?; // don't leak the first FD - return this.set_errno_and_return_neg1_i32(LibcError("EMFILE")); + ecx.close(pipefd0)?; // don't leak the first FD + return ecx.set_errno_and_return_neg1_i32(LibcError("EMFILE")); }; // Return file descriptors to the caller. - let pipefd0 = Scalar::from_int(pipefd0, pipefd.layout.size); - let pipefd1 = Scalar::from_int(pipefd1, pipefd.layout.size); - this.write_scalar(pipefd0, &pipefd)?; - this.write_scalar(pipefd1, &this.project_c_array_field(&pipefd, 1)?)?; + ecx.write_int(pipefd0, &pipefd)?; + ecx.write_int(pipefd1, &ecx.project_c_array_field(&pipefd, 1)?)?; interp_ok(Scalar::from_i32(0)) } diff --git a/src/tools/miri/src/shims/unwind.rs b/src/tools/miri/src/shims/unwind.rs index dcb2ae74b8cb5..5e249c3ace67e 100644 --- a/src/tools/miri/src/shims/unwind.rs +++ b/src/tools/miri/src/shims/unwind.rs @@ -45,12 +45,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// Handles the special `miri_start_unwind` intrinsic, which is called /// by libpanic_unwind to delegate the actual unwinding process to Miri. fn handle_miri_start_unwind(&mut self, payload: &OpTy<'tcx>) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - trace!("miri_start_unwind: {:?}", this.frame().instance()); + trace!("miri_start_unwind: {:?}", ecx.frame().instance()); - let payload = this.read_immediate(payload)?; - let thread = this.active_thread_mut(); + let payload = ecx.read_immediate(payload)?; + let thread = ecx.active_thread_mut(); thread.unwind_payloads.push(payload); interp_ok(()) @@ -65,7 +65,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { dest: &PlaceTy<'tcx>, ret: Option, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); // Signature: // fn catch_unwind(try_fn: unsafe fn(*mut Data), data: *mut Data, catch_fn: unsafe fn(*mut Data, *mut u8)) -> bool @@ -79,16 +79,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // a pointer to `Box`. // Get all the arguments. - let try_fn = this.read_pointer(try_fn)?; - let data = this.read_immediate(data)?; - let catch_fn = this.read_pointer(catch_fn)?; - let dest = this.force_allocation(dest)?; // needs to be valid across fn calls + let try_fn = ecx.read_pointer(try_fn)?; + let data = ecx.read_immediate(data)?; + let catch_fn = ecx.read_pointer(catch_fn)?; + let dest = ecx.force_allocation(dest)?; // needs to be valid across fn calls // Now we make a function call, and pass `data` as first and only argument. - let f_instance = this.get_ptr_fn(try_fn)?.as_instance()?; + let f_instance = ecx.get_ptr_fn(try_fn)?.as_instance()?; trace!("try_fn: {:?}", f_instance); #[allow(clippy::cloned_ref_to_slice_refs)] // the code is clearer as-is - this.call_function( + ecx.call_function( f_instance, ExternAbi::Rust, &[data.clone()], @@ -98,13 +98,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; // We ourselves will return `0`, eventually (will be overwritten if we catch a panic). - this.write_int(0, &dest)?; + ecx.write_int(0, &dest)?; // In unwind mode, we tag this frame with the extra data needed to catch unwinding. // This lets `handle_stack_pop` (below) know that we should stop unwinding // when we pop this frame. - if this.tcx.sess.panic_strategy() == PanicStrategy::Unwind { - this.frame_mut().extra.catch_unwind = + if ecx.tcx.sess.panic_strategy() == PanicStrategy::Unwind { + ecx.frame_mut().extra.catch_unwind = Some(CatchUnwindData { catch_fn, data, dest, ret }); } @@ -116,7 +116,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { mut extra: FrameExtra<'tcx>, unwinding: bool, ) -> InterpResult<'tcx, ReturnAction> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); trace!("handle_stack_pop_unwind(extra = {:?}, unwinding = {})", extra, unwinding); // We only care about `catch_panic` if we're unwinding - if we're doing a normal @@ -126,20 +126,20 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // and we are unwinding, so we should catch that. trace!( "unwinding: found catch_panic frame during unwinding: {:?}", - this.frame().instance() + ecx.frame().instance() ); // We set the return value of `catch_unwind` to 1, since there was a panic. - this.write_scalar(Scalar::from_bool(true), &catch_unwind.dest)?; + ecx.write_scalar(Scalar::from_bool(true), &catch_unwind.dest)?; // The Thread's `panic_payload` holds what was passed to `miri_start_unwind`. // This is exactly the second argument we need to pass to `catch_fn`. - let payload = this.active_thread_mut().unwind_payloads.pop().unwrap(); + let payload = ecx.active_thread_mut().unwind_payloads.pop().unwrap(); // Push the `catch_fn` stackframe. - let f_instance = this.get_ptr_fn(catch_unwind.catch_fn)?.as_instance()?; + let f_instance = ecx.get_ptr_fn(catch_unwind.catch_fn)?.as_instance()?; trace!("catch_fn: {:?}", f_instance); - this.call_function( + ecx.call_function( f_instance, ExternAbi::Rust, &[catch_unwind.data, payload], diff --git a/src/tools/miri/src/shims/windows/foreign_items.rs b/src/tools/miri/src/shims/windows/foreign_items.rs index 7e5f545bffbfb..c9e6cc4ce7373 100644 --- a/src/tools/miri/src/shims/windows/foreign_items.rs +++ b/src/tools/miri/src/shims/windows/foreign_items.rs @@ -11,6 +11,7 @@ use rustc_target::spec::Env; use self::shims::windows::handle::{Handle, PseudoHandle}; use crate::eval::{ExitType, ProgramExitHandler}; use crate::shims::os_str::bytes_to_os_str; +use crate::shims::tls::TlsKey; use crate::shims::windows::*; use crate::*; @@ -212,7 +213,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ecx.write_scalar(result, dest)?; } "GetCurrentProcessId" => { - // FIXME: This does not have a direct test (#3179). let [] = &ecx.check_shim_sig( shim_sig!(extern "system" fn() -> u32), (link_name, abi, args), @@ -596,14 +596,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; let key = ecx.machine.tls.create_tls_key(None, dest.layout.size)?; - ecx.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?; + ecx.write_int(key, dest)?; } "TlsGetValue" => { let [key] = &ecx.check_shim_sig( shim_sig!(extern "system" fn(u32) -> *_), (link_name, abi, args), )?; - let key = u128::from(ecx.read_scalar(key)?.to_u32()?); + let key = TlsKey::from(ecx.read_scalar(key)?.to_u32()?); let active_thread = ecx.active_thread(); let ptr = ecx.machine.tls.load_tls_key(key, active_thread)?; ecx.write_pointer(ptr, dest)?; @@ -613,7 +613,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { shim_sig!(extern "system" fn(u32, *_) -> winapi::BOOL), (link_name, abi, args), )?; - let key = u128::from(ecx.read_scalar(key)?.to_u32()?); + let key = TlsKey::from(ecx.read_scalar(key)?.to_u32()?); let active_thread = ecx.active_thread(); let new_data = ecx.read_pointer(new_ptr)?; ecx.machine.tls.store_tls_key(key, active_thread, new_data)?; @@ -626,7 +626,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { shim_sig!(extern "system" fn(u32) -> winapi::BOOL), (link_name, abi, args), )?; - let key = u128::from(ecx.read_scalar(key)?.to_u32()?); + let key = TlsKey::from(ecx.read_scalar(key)?.to_u32()?); ecx.machine.tls.delete_tls_key(key)?; // Return success (`1`). @@ -653,14 +653,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }; let key = ecx.machine.tls.create_tls_key(dtor, dest.layout.size)?; - ecx.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?; + ecx.write_int(key, dest)?; } "FlsGetValue" => { let [key] = &ecx.check_shim_sig( shim_sig!(extern "system" fn(u32) -> *_), (link_name, abi, args), )?; - let key = u128::from(ecx.read_scalar(key)?.to_u32()?); + let key = TlsKey::from(ecx.read_scalar(key)?.to_u32()?); let active_thread = ecx.active_thread(); let ptr = ecx.machine.tls.load_tls_key(key, active_thread)?; ecx.write_pointer(ptr, dest)?; @@ -670,7 +670,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { shim_sig!(extern "system" fn(u32, *_) -> winapi::BOOL), (link_name, abi, args), )?; - let key = u128::from(ecx.read_scalar(key)?.to_u32()?); + let key = TlsKey::from(ecx.read_scalar(key)?.to_u32()?); let active_thread = ecx.active_thread(); let new_data = ecx.read_pointer(new_ptr)?; ecx.machine.tls.store_tls_key(key, active_thread, new_data)?; @@ -683,7 +683,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { shim_sig!(extern "system" fn(u32) -> winapi::BOOL), (link_name, abi, args), )?; - let key = u128::from(ecx.read_scalar(key)?.to_u32()?); + let key = TlsKey::from(ecx.read_scalar(key)?.to_u32()?); let tls_entry = ecx.machine.tls.delete_tls_key(key)?; // FIXME: We should run the destructor here *for all threads*. But that's non-trivial and std doesn't need it so we bail out with an "unsupported" error. diff --git a/src/tools/miri/src/shims/windows/fs.rs b/src/tools/miri/src/shims/windows/fs.rs index 6a0c00a8d3515..06bab812ca32e 100644 --- a/src/tools/miri/src/shims/windows/fs.rs +++ b/src/tools/miri/src/shims/windows/fs.rs @@ -1,4 +1,4 @@ -use std::io::SeekFrom; +use std::io::{Seek, SeekFrom}; use std::time::SystemTime; use std::{fs, io}; @@ -226,7 +226,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let mut options = fs::OpenOptions::new(); options.read(desired_read); options.write(desired_write); - let mut append = false; match creation_disposition { CreateAlways | OpenAlways => { // These two create the file if it is missing, but also succeed if it @@ -237,6 +236,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // file to not exist, we use `create_new` to fail if it does exist. if !exists_already { options.create_new(true); + // Per `create_new` documentation: + // The file must be opened with write or append access in order to create a new file. + // https://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.create_new + // So we open it for writing anyway, to make creating the file work. Write + // accesses will still be rejected because `writable` is not set on the + // `FileHandle`. + options.write(true); } if creation_disposition == CreateAlways { options.truncate(true); @@ -244,13 +250,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } CreateNew => { options.create_new(true); - // Per `create_new` documentation: - // The file must be opened with write or append access in order to create a new file. - // https://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.create_new - if !desired_write { - options.append(true); - append = true; - } + // See above for why we need to also request write access. + options.write(true); } OpenExisting => { if !desired_read && !desired_write { @@ -317,7 +318,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { file, writable: desired_write, readable: desired_read, - append, + append: false, }) else { throw_unsup_format!("we ran out of FD numbers") }; @@ -447,6 +448,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // "length" (called "EOF position") and "capacity" (called "allocation size"). // Growing the allocation size is largely a performance hint which we can // ignore -- it can also be directly queried, but we currently do not support that. + // (Linux has something equivalent, `fallocate` with `FALLOC_FL_KEEP_SIZE`, but std does + // not expose it so we cannot easily use it.) // So we only need to do something if this operation shrinks the allocation size // so far that it affects the EOF position. let place = @@ -456,8 +459,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { .to_i64()? .try_into() .unwrap(); - let old_len = match file.file.metadata() { - Ok(m) => m.len(), + let old_len = match (&file.file).stream_len() { + Ok(l) => l, Err(e) => { ecx.set_last_error(e)?; return interp_ok(ecx.eval_windows("c", "FALSE")); @@ -655,9 +658,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ecx.write_int(0, &dest) } Err(e) => { - ecx.write_int(0, &io_status_info)?; + // Native testing indicates that `io_status_block` is not written here. let status = e.into_ntstatus(); - ecx.write_int(status, &io_status)?; ecx.write_int(status, &dest) } }} @@ -755,9 +757,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ecx.write_int(0, &dest) } Err(e) => { - ecx.write_int(0, &io_status_info)?; + // Native testing indicates that `io_status_block` is not written here. let status = e.into_ntstatus(); - ecx.write_int(status, &io_status)?; ecx.write_int(status, &dest) } }} diff --git a/src/tools/miri/src/shims/windows/sync.rs b/src/tools/miri/src/shims/windows/sync.rs index 55addb2468df8..e2fd68f808725 100644 --- a/src/tools/miri/src/shims/windows/sync.rs +++ b/src/tools/miri/src/shims/windows/sync.rs @@ -20,10 +20,6 @@ impl MetaObj for WindowsInitOnce { } interp_ok(()) } - - fn opaque(&self) -> bool { - true - } } struct WindowsFutex { diff --git a/src/tools/miri/src/shims/windows/thread.rs b/src/tools/miri/src/shims/windows/thread.rs index 3307ca4f2f434..cb5810eb543bb 100644 --- a/src/tools/miri/src/shims/windows/thread.rs +++ b/src/tools/miri/src/shims/windows/thread.rs @@ -14,7 +14,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { start_op: &OpTy<'tcx>, arg_op: &OpTy<'tcx>, flags_op: &OpTy<'tcx>, - thread_op: &OpTy<'tcx>, + thread_id_op: &OpTy<'tcx>, ) -> InterpResult<'tcx, ThreadId> { let ecx = self.eval_context_mut(); @@ -24,13 +24,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let start_routine = ecx.read_pointer(start_op)?; let func_arg = ecx.read_immediate(arg_op)?; let flags = ecx.read_scalar(flags_op)?.to_u32()?; - - let thread = if ecx.ptr_is_null(ecx.read_pointer(thread_op)?)? { - None - } else { - let thread_info_place = ecx.deref_pointer(thread_op)?; - Some(thread_info_place) - }; + let thread_id_place = ecx.deref_pointer(thread_id_op)?; let stack_size_param_is_a_reservation = ecx.eval_windows_u32("c", "STACK_SIZE_PARAM_IS_A_RESERVATION"); @@ -45,13 +39,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { throw_unsup_format!("non-null `lpThreadAttributes` in `CreateThread`") } - ecx.start_regular_thread( - thread, + let thread_id = ecx.start_regular_thread( start_routine, ExternAbi::System { unwind: false }, func_arg, ecx.layout_of(ecx.tcx.types.u32)?, - ) + )?; + if !ecx.ptr_is_null(thread_id_place.ptr())? { + ecx.write_int(thread_id.to_u32(), &thread_id_place)?; + } + interp_ok(thread_id) } fn WaitForSingleObject( diff --git a/src/tools/miri/tests/deps/Cargo.toml b/src/tools/miri/tests/deps/Cargo.toml index 6b6d4a9e2f443..5f98960463d5c 100644 --- a/src/tools/miri/tests/deps/Cargo.toml +++ b/src/tools/miri/tests/deps/Cargo.toml @@ -30,6 +30,7 @@ windows-sys = { version = "0.61", features = [ "Win32_System_Threading", "Win32_Storage_FileSystem", "Win32_Security", + "Win32_Security_Cryptography", "Win32_System_IO", "Wdk_Storage_FileSystem", ] } diff --git a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_attr_double_destroy.rs b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_attr_double_destroy.rs new file mode 100644 index 0000000000000..b6b3ff07caa24 --- /dev/null +++ b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_attr_double_destroy.rs @@ -0,0 +1,17 @@ +//@ignore-target: windows # No pthreads on Windows + +/// Test that destroying a pthread_attr twice fails. + +fn main() { + unsafe { + use core::mem::MaybeUninit; + let mut attr = MaybeUninit::::uninit(); + + libc::pthread_attr_init(attr.as_mut_ptr()); + + libc::pthread_attr_destroy(attr.as_mut_ptr()); + + libc::pthread_attr_destroy(attr.as_mut_ptr()); + //~^ ERROR: has not been initialized + } +} diff --git a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_attr_double_destroy.stderr b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_attr_double_destroy.stderr new file mode 100644 index 0000000000000..b1fcb9c0abfb9 --- /dev/null +++ b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_attr_double_destroy.stderr @@ -0,0 +1,13 @@ +error: Undefined Behavior: `pthread_attr_t` has not been initialized or has been tampered with + --> tests/fail-dep/concurrency/libc_pthread_attr_double_destroy.rs:LL:CC + | +LL | libc::pthread_attr_destroy(attr.as_mut_ptr()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Undefined Behavior occurred here + | + = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior + = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to 1 previous error + diff --git a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_attr_zero_init.rs b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_attr_zero_init.rs new file mode 100644 index 0000000000000..94b0c1b6581f8 --- /dev/null +++ b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_attr_zero_init.rs @@ -0,0 +1,17 @@ +//@ignore-target: windows # No pthreads on Windows + +/// Test that using a pthread_attr that was never initialized fails. +use std::{mem, ptr}; + +extern "C" fn thread_start(_arg: *mut libc::c_void) -> *mut libc::c_void { + ptr::null_mut() +} + +fn main() { + unsafe { + let attr: libc::pthread_attr_t = mem::zeroed(); + let mut thread: libc::pthread_t = mem::zeroed(); + libc::pthread_create(&mut thread, &attr, thread_start, ptr::null_mut()); + //~^ ERROR: has not been initialized + } +} diff --git a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_attr_zero_init.stderr b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_attr_zero_init.stderr new file mode 100644 index 0000000000000..c8ff17471c17b --- /dev/null +++ b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_attr_zero_init.stderr @@ -0,0 +1,13 @@ +error: Undefined Behavior: `pthread_attr_t` has not been initialized or has been tampered with + --> tests/fail-dep/concurrency/libc_pthread_attr_zero_init.rs:LL:CC + | +LL | libc::pthread_create(&mut thread, &attr, thread_start, ptr::null_mut()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Undefined Behavior occurred here + | + = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior + = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to 1 previous error + diff --git a/src/tools/miri/tests/fail-dep/libc/abort.rs b/src/tools/miri/tests/fail-dep/libc/abort.rs new file mode 100644 index 0000000000000..cf55606012dd6 --- /dev/null +++ b/src/tools/miri/tests/fail-dep/libc/abort.rs @@ -0,0 +1,4 @@ +fn main() { + unsafe { libc::abort() }; + //~^ error: abnormal termination: the program aborted execution +} diff --git a/src/tools/miri/tests/fail-dep/libc/abort.stderr b/src/tools/miri/tests/fail-dep/libc/abort.stderr new file mode 100644 index 0000000000000..f408b08e686c5 --- /dev/null +++ b/src/tools/miri/tests/fail-dep/libc/abort.stderr @@ -0,0 +1,10 @@ +error: abnormal termination: the program aborted execution + --> tests/fail-dep/libc/abort.rs:LL:CC + | +LL | unsafe { libc::abort() }; + | ^^^^^^^^^^^^^ abnormal termination occurred here + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to 1 previous error + diff --git a/src/tools/miri/tests/fail/optimize-attribute.none.stderr b/src/tools/miri/tests/fail/optimize-attribute.none.stderr new file mode 100644 index 0000000000000..1c6aee1317890 --- /dev/null +++ b/src/tools/miri/tests/fail/optimize-attribute.none.stderr @@ -0,0 +1,13 @@ +error: Undefined Behavior: invalid metadata in wide pointer: slice is bigger than largest supported object + --> tests/fail/optimize-attribute.rs:LL:CC + | +LL | intrinsics::align_of_val(ptr); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Undefined Behavior occurred here + | + = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior + = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to 1 previous error + diff --git a/src/tools/miri/tests/fail/optimize-attribute.rs b/src/tools/miri/tests/fail/optimize-attribute.rs new file mode 100644 index 0000000000000..89d56dc820e6e --- /dev/null +++ b/src/tools/miri/tests/fail/optimize-attribute.rs @@ -0,0 +1,13 @@ +//@revisions: speed none +#![feature(core_intrinsics)] +use std::{intrinsics, mem}; + +#[cfg_attr(speed, optimize(speed))] +#[cfg_attr(none, optimize(none))] +fn main() { + unsafe { + let ptr: *const [u8] = mem::transmute((1usize, usize::MAX)); + intrinsics::align_of_val(ptr); + //~^ERROR: invalid metadata in wide pointer + } +} diff --git a/src/tools/miri/tests/fail/optimize-attribute.speed.stderr b/src/tools/miri/tests/fail/optimize-attribute.speed.stderr new file mode 100644 index 0000000000000..1c6aee1317890 --- /dev/null +++ b/src/tools/miri/tests/fail/optimize-attribute.speed.stderr @@ -0,0 +1,13 @@ +error: Undefined Behavior: invalid metadata in wide pointer: slice is bigger than largest supported object + --> tests/fail/optimize-attribute.rs:LL:CC + | +LL | intrinsics::align_of_val(ptr); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Undefined Behavior occurred here + | + = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior + = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to 1 previous error + diff --git a/src/tools/miri/tests/pass-dep/concurrency/pthread-attr.rs b/src/tools/miri/tests/pass-dep/concurrency/pthread-attr.rs new file mode 100644 index 0000000000000..27b217808cbc6 --- /dev/null +++ b/src/tools/miri/tests/pass-dep/concurrency/pthread-attr.rs @@ -0,0 +1,95 @@ +//@ignore-target: windows # No pthreads on Windows +//@run-native + +use std::mem::MaybeUninit; +use std::ptr; + +extern "C" fn thread_start(_arg: *mut libc::c_void) -> *mut libc::c_void { + ptr::null_mut() +} + +fn page_size() -> usize { + unsafe { libc::sysconf(libc::_SC_PAGESIZE).try_into().unwrap() } +} + +/// A valid stack size: at least `PTHREAD_STACK_MIN` and page-aligned. +fn normal_stack_size() -> usize { + libc::PTHREAD_STACK_MIN.next_multiple_of(page_size()) +} + +/// Spawns a thread with the given attributes, and joins it if that succeeded. +fn spawn(attr: *const libc::pthread_attr_t) -> i32 { + unsafe { + let mut thread = MaybeUninit::::uninit(); + let ret = libc::pthread_create(thread.as_mut_ptr(), attr, thread_start, ptr::null_mut()); + if ret == 0 { + assert_eq!(libc::pthread_join(thread.assume_init(), ptr::null_mut()), 0); + } + ret + } +} + +fn test_init_destroy() { + unsafe { + let mut attr = MaybeUninit::::uninit(); + assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0); + assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0); + // It can be initialized again after being destroyed. + assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0); + assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0); + } +} + +fn test_setstacksize() { + unsafe { + let mut attr = MaybeUninit::::uninit(); + assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0); + + // Too small. Round down to a page boundary so macOS cannot round it up to a valid size. + let too_small = (libc::PTHREAD_STACK_MIN / 2) / page_size() * page_size(); + assert_eq!(libc::pthread_attr_setstacksize(attr.as_mut_ptr(), too_small), libc::EINVAL); + // Not a multiple of the page size: only macOS rejects this. + let ret = libc::pthread_attr_setstacksize(attr.as_mut_ptr(), normal_stack_size() + 1); + if cfg!(target_os = "macos") { + assert_eq!(ret, libc::EINVAL); + } else { + assert_eq!(ret, 0); + } + // A normal size. + assert_eq!(libc::pthread_attr_setstacksize(attr.as_mut_ptr(), normal_stack_size()), 0); + + assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0); + } +} + +fn test_create() { + unsafe { + // Default attributes. + assert_eq!(spawn(ptr::null()), 0); + + let mut attr = MaybeUninit::::uninit(); + assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0); + // Initialized attributes without a stack size. + assert_eq!(spawn(attr.as_ptr()), 0); + // A normal stack size. + assert_eq!(libc::pthread_attr_setstacksize(attr.as_mut_ptr(), normal_stack_size()), 0); + assert_eq!(spawn(attr.as_ptr()), 0); + + // A stack that is too big to reserve. Keep it page-aligned so macOS accepts it. + let huge = if cfg!(target_pointer_width = "32") { + usize::MAX - (2 * page_size() - 1) + } else { + (1 << (usize::BITS - 1)) + page_size() + }; + assert_eq!(libc::pthread_attr_setstacksize(attr.as_mut_ptr(), huge), 0); + let ret = spawn(attr.as_ptr()); + assert_eq!(ret, libc::EAGAIN); + assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0); + } +} + +fn main() { + test_init_destroy(); + test_setstacksize(); + test_create(); +} diff --git a/src/tools/miri/tests/pass-dep/concurrency/pthread-sync.rs b/src/tools/miri/tests/pass-dep/concurrency/pthread-sync.rs index 6b1d253c2f169..47614f8bced44 100644 --- a/src/tools/miri/tests/pass-dep/concurrency/pthread-sync.rs +++ b/src/tools/miri/tests/pass-dep/concurrency/pthread-sync.rs @@ -55,6 +55,8 @@ fn main() { { test_sem(); } + + test_sched_yield(); } // We want to only use pthread APIs here for easier testing. @@ -417,3 +419,35 @@ fn test_sem() { errno_check(libc::sem_destroy(sem.ptr)); } } + +fn test_sched_yield() { + use libc_utils::errno_check; + + let bomb = AbortOnDrop; + unsafe { + let data = SyncUnsafeCell::new((libc::PTHREAD_MUTEX_INITIALIZER, false)); + let ptr = SendPtr { ptr: data.get() }; + + let t = thread::spawn(move || { + let ptr = ptr; + let mutexptr = ptr::addr_of_mut!((*ptr.ptr).0); + assert_eq!(libc::pthread_mutex_lock(mutexptr), 0); + (*ptr.ptr).1 = true; + assert_eq!(libc::pthread_mutex_unlock(mutexptr), 0); + }); + + // Let `t` go first. + errno_check(libc::sched_yield()); + + let mutexptr = ptr::addr_of_mut!((*ptr.ptr).0); + assert_eq!(libc::pthread_mutex_lock(mutexptr), 0); + // Without scheduler control, there is no guarantee that `t` went first. + if cfg!(miri) { + assert!((*ptr.ptr).1); + } + assert_eq!(libc::pthread_mutex_unlock(mutexptr), 0); + + t.join().unwrap(); + } + bomb.defuse(); +} diff --git a/src/tools/miri/tests/pass-dep/libc/blocking-io-same-fd.rs b/src/tools/miri/tests/pass-dep/libc/blocking-io-same-fd.rs index 96af64131f1d1..22c35fea749d2 100644 --- a/src/tools/miri/tests/pass-dep/libc/blocking-io-same-fd.rs +++ b/src/tools/miri/tests/pass-dep/libc/blocking-io-same-fd.rs @@ -11,7 +11,7 @@ use libc_utils::*; // same fd at the same time. fn main() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; diff --git a/src/tools/miri/tests/pass-dep/libc/env.rs b/src/tools/miri/tests/pass-dep/libc/env.rs index 53517688b222b..21b73a5b1a519 100644 --- a/src/tools/miri/tests/pass-dep/libc/env.rs +++ b/src/tools/miri/tests/pass-dep/libc/env.rs @@ -90,6 +90,29 @@ fn test_unsetenv() { assert_eq!(result, -1); } +#[cfg(target_os = "macos")] +fn test_ns_get_environ() { + unsafe { + errno_check(libc::setenv(c"MIRI_TEST_NSGETENVIRON".as_ptr(), c"test_value".as_ptr(), 1)); + + let environ = libc::_NSGetEnviron(); + assert!(!environ.is_null()); + let mut entry = *environ; + assert!(!entry.is_null()); + + let mut found = false; + while !(*entry).is_null() { + if CStr::from_ptr(*entry) == c"MIRI_TEST_NSGETENVIRON=test_value" { + found = true; + } + entry = entry.add(1); + } + assert!(found); + + errno_check(libc::unsetenv(c"MIRI_TEST_NSGETENVIRON".as_ptr())); + } +} + fn test_getcwd() { // Filling the buffer with `1` prevents the null terminator check from passing by mistake let mut buf = [1u8; libc::PATH_MAX as usize]; @@ -129,10 +152,32 @@ fn test_chdir() { assert_eq!(err.raw_os_error().unwrap(), libc::ENOENT); } +#[cfg(target_os = "macos")] +fn test_nsgetargv_argc() { + let argv = unsafe { *libc::_NSGetArgv() }; + let c_argv_0 = unsafe { CStr::from_ptr(*argv).to_bytes() }; + let argc = unsafe { *libc::_NSGetArgc() }; + let argv_argc = unsafe { *argv.add(argc as usize) }; + + // In Miri, `argv[0]` points to the path of the source file, + // whereas natively, it points to the path of the compiled program. + if cfg!(miri) { + assert_eq!(c_argv_0, file!().as_bytes()); + } + + assert_eq!(argc, 1); + + assert!(argv_argc.is_null()); +} + fn main() { test_getenv(); test_setenv(); test_unsetenv(); + #[cfg(target_os = "macos")] + test_ns_get_environ(); test_getcwd(); test_chdir(); + #[cfg(target_os = "macos")] + test_nsgetargv_argc(); } diff --git a/src/tools/miri/tests/pass-dep/libc/fs-with-isolation.rs b/src/tools/miri/tests/pass-dep/libc/fs-with-isolation.rs index 7d2d5dc888360..e1a5e0f86dcce 100644 --- a/src/tools/miri/tests/pass-dep/libc/fs-with-isolation.rs +++ b/src/tools/miri/tests/pass-dep/libc/fs-with-isolation.rs @@ -26,6 +26,19 @@ fn main() { assert_eq!(err.raw_os_error(), Some(libc::EACCES)); } + // test `unlinkat` + unsafe { + let err = errno_result(libc::unlinkat(libc::AT_FDCWD, c"foo.txt".as_ptr(), 0)).unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EACCES)); + } + + // test `mkdirat` + unsafe { + let err = + errno_result(libc::mkdirat(libc::AT_FDCWD, c"foo_dir".as_ptr(), 0o777)).unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EACCES)); + } + // test `stat` let err = fs::metadata("foo.txt").unwrap_err(); assert_eq!(err.raw_os_error(), Some(libc::EACCES)); diff --git a/src/tools/miri/tests/pass-dep/libc/fs-with-isolation.stderr b/src/tools/miri/tests/pass-dep/libc/fs-with-isolation.stderr index a3ed50bd9a65f..e12d19fb4d6d6 100644 --- a/src/tools/miri/tests/pass-dep/libc/fs-with-isolation.stderr +++ b/src/tools/miri/tests/pass-dep/libc/fs-with-isolation.stderr @@ -1,6 +1,10 @@ warning: `readlink` was made to return an error due to isolation +warning: `unlinkat` was made to return an error due to isolation + +warning: `mkdirat` was made to return an error due to isolation + warning: `$STAT` was made to return an error due to isolation -warning: 2 warnings emitted +warning: 4 warnings emitted diff --git a/src/tools/miri/tests/pass-dep/libc/fs.rs b/src/tools/miri/tests/pass-dep/libc/fs.rs index a82b6c98509a6..ec6e57bef3940 100644 --- a/src/tools/miri/tests/pass-dep/libc/fs.rs +++ b/src/tools/miri/tests/pass-dep/libc/fs.rs @@ -13,7 +13,7 @@ use std::io::Write; use std::mem::MaybeUninit; use std::os::unix::ffi::OsStrExt; use std::os::unix::io::AsRawFd; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::{env, ptr}; mod fs { @@ -36,10 +36,13 @@ fn main() { test_rename(); test_mkdir(); test_rmdir(); + test_unlink(); + test_symlink(); test_ftruncate::(libc::ftruncate); #[cfg(target_os = "linux")] test_ftruncate::(libc::ftruncate64); test_create_read_write(); + test_append_seek_read_write(); test_read_and_uninit(); test_open_args(libc::open); #[cfg(target_os = "linux")] @@ -51,6 +54,8 @@ fn main() { test_openat(libc::openat); #[cfg(target_os = "linux")] test_openat(libc::openat64); + test_unlinkat(); + test_mkdirat(); #[cfg(target_os = "linux")] test_o_tmpfile_flag(); test_posix_mkstemp(); @@ -116,6 +121,55 @@ fn main() { test_short_fs_operations(); } +fn test_append_seek_read_write() { + let path = utils::prepare_with_content("miri-pass-libc-append.txt", b"abc"); + let cpath = utils::into_c_string(path); + let fd = + errno_result(unsafe { libc::open(cpath.as_ptr(), libc::O_RDWR | libc::O_APPEND) }).unwrap(); + + unsafe { + // Reading behaves as usual. + assert_eq!(errno_result(libc::lseek(fd, 1, libc::SEEK_SET)).unwrap(), 1); + assert_eq!(libc_utils::read_exact_array::<1>(fd).unwrap(), *b"b"); + assert_eq!(errno_result(libc::lseek(fd, 0, libc::SEEK_CUR)).unwrap(), 2); + // Same for `pread`. + let mut byte = 0u8; + assert_eq!(errno_result(libc::pread(fd, (&mut byte as *mut u8).cast(), 1, 0)).unwrap(), 1); + assert_eq!(byte, b'a'); + assert_eq!(errno_result(libc::lseek(fd, 0, libc::SEEK_CUR)).unwrap(), 2); + + // But writing always adds at the end. + // The current position is 2, which would usually overwrite the `c`. + libc_utils::write_all(fd, b"d").unwrap(); + // The current position also got updated to point at the end. + assert_eq!(libc_utils::read_to_end(fd).unwrap(), b""); + // Seek to beginning to check contents of the entire file. + assert_eq!(errno_result(libc::lseek(fd, 0, libc::SEEK_SET)).unwrap(), 0); + assert_eq!(libc_utils::read_to_end(fd).unwrap(), b"abcd"); + + errno_check(libc::close(fd)); + + // Also test write-only append mode. + let fd = errno_result(libc::open(cpath.as_ptr(), libc::O_WRONLY | libc::O_APPEND)).unwrap(); + assert_eq!(errno_result(libc::lseek(fd, 1, libc::SEEK_SET)).unwrap(), 1); + let err = errno_result(libc::read(fd, (&mut byte as *mut u8).cast(), 1)).unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EBADF)); + libc_utils::write_all(fd, b"e").unwrap(); + assert_eq!(errno_result(libc::lseek(fd, 0, libc::SEEK_CUR)).unwrap(), 5); + errno_check(libc::close(fd)); + + let fd = errno_result(libc::open(cpath.as_ptr(), libc::O_RDONLY)).unwrap(); + assert_eq!(libc_utils::read_to_end(fd).unwrap(), b"abcde"); + errno_check(libc::close(fd)); + + // Read-only append works but we cannot actually write. + let fd = errno_result(libc::open(cpath.as_ptr(), libc::O_RDONLY | libc::O_APPEND)).unwrap(); + let err = libc_utils::write_all(fd, b"e").unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EBADF)); + errno_check(libc::close(fd)); + } +} + #[cfg(target_os = "linux")] #[track_caller] fn assert_statx_matches_metadata(stx: &libc::statx, meta: &fs::Metadata, expected_size: u64) { @@ -588,10 +642,123 @@ fn test_openat( errno_check(unsafe { libc::close(dirfd) }); } +fn test_unlinkat() { + let path = utils::prepare("miri_test_unlinkat"); + fs::create_dir(&path).unwrap(); + let cpath = utils::into_c_string(&path); + let dirfd = errno_result(unsafe { libc::open(cpath.as_ptr(), libc::O_DIRECTORY) }).unwrap(); + + let unlinkat = |dirfd: libc::c_int, path: &CStr, flags: libc::c_int| { + errno_result(unsafe { libc::unlinkat(dirfd, path.as_ptr(), flags) }) + }; + let errno = |res: std::io::Result| res.unwrap_err().raw_os_error().unwrap(); + + // Remove a file relative to dirfd. + fs::write(path.join("file.txt"), b"data").unwrap(); + assert_eq!(unlinkat(dirfd, c"file.txt", 0).unwrap(), 0); + assert!(!path.join("file.txt").exists()); + // Now it is gone, so removing it again fails. + assert_eq!(errno(unlinkat(dirfd, c"file.txt", 0)), libc::ENOENT); + + // Remove a file via its absolute path, can use garbage dirfd. + fs::write(path.join("file.txt"), b"data").unwrap(); + let cfile = utils::into_c_string(path.join("file.txt")); + assert_eq!(unlinkat(999, &cfile, 0).unwrap(), 0); + assert!(!path.join("file.txt").exists()); + + // With `AT_FDCWD`, a relative path is relative to the working directory, not to an FD. + let original_cwd = env::current_dir().unwrap(); + env::set_current_dir(&path).unwrap(); + let cwd_file = Path::new("miri_test_unlinkat_cwd"); + fs::write(cwd_file, b"data").unwrap(); + assert_eq!(unlinkat(libc::AT_FDCWD, c"miri_test_unlinkat_cwd", 0).unwrap(), 0,); + assert!(!cwd_file.exists()); + env::set_current_dir(original_cwd).unwrap(); + + // Remove a directory, which has to be empty. + fs::create_dir(path.join("dir")).unwrap(); + fs::write(path.join("dir/file.txt"), b"data").unwrap(); + // Test error when it is not empty. + // POSIX allows either of these errors. + let err = errno(unlinkat(dirfd, c"dir", libc::AT_REMOVEDIR)); + assert!(matches!(err, libc::ENOTEMPTY | libc::EEXIST), "unexpected errno: {err}"); + assert_eq!(unlinkat(dirfd, c"dir/file.txt", 0).unwrap(), 0); + assert_eq!(unlinkat(dirfd, c"dir", libc::AT_REMOVEDIR).unwrap(), 0); + assert!(!path.join("dir").exists()); + + // Symlinks are removed themselves, their targets are left alone. + if utils::have_symlink_permission() { + fs::write(path.join("file.txt"), b"data").unwrap(); + fs::create_dir(path.join("dir")).unwrap(); + // Check both paths relative to dirfd, and absolute paths. + for (fd, base) in [(dirfd, PathBuf::new()), (999, path.clone())] { + fs::symlink("file.txt", path.join("filelink")).unwrap(); + fs::symlink("dir", path.join("dirlink")).unwrap(); + let filelink = utils::into_c_string(base.join("filelink")); + let dirlink = utils::into_c_string(base.join("dirlink")); + + assert_eq!(unlinkat(fd, &filelink, 0).unwrap(), 0); + assert!(path.join("filelink").symlink_metadata().is_err()); + assert!(path.join("file.txt").exists()); + + // A symlink to a directory is not a directory, so `AT_REMOVEDIR` fails. + assert_eq!(errno(unlinkat(fd, &dirlink, libc::AT_REMOVEDIR)), libc::ENOTDIR); + // But it can be removed like a file. + assert_eq!(unlinkat(fd, &dirlink, 0).unwrap(), 0); + assert!(path.join("dirlink").symlink_metadata().is_err()); + assert!(path.join("dir").exists()); + } + } + + // A relative path needs a dirfd that is an open directory. + assert_eq!(errno(unlinkat(999, c"file.txt", 0)), libc::EBADF); + let file = File::create(path.join("file.txt")).unwrap(); + assert_eq!(errno(unlinkat(file.as_raw_fd(), c"file.txt", 0)), libc::ENOTDIR); + + errno_check(unsafe { libc::close(dirfd) }); +} + +fn test_mkdirat() { + let path = utils::prepare("miri_test_mkdirat"); + fs::create_dir(&path).unwrap(); + let cpath = utils::into_c_string(&path); + let dirfd = errno_result(unsafe { libc::open(cpath.as_ptr(), libc::O_DIRECTORY) }).unwrap(); + + let mkdirat = |dirfd: libc::c_int, path: &CStr, mode: libc::mode_t| { + errno_result(unsafe { libc::mkdirat(dirfd, path.as_ptr(), mode) }) + }; + let errno = |res: std::io::Result| res.unwrap_err().raw_os_error().unwrap(); + + // Make a dir relative to dirfd. + assert_eq!(mkdirat(dirfd, c"subdir", 0o777).unwrap(), 0); + assert!(path.join("subdir").is_dir()); + // It already exists; creating it again will fail. + assert_eq!(errno(mkdirat(dirfd, c"subdir", 0o777)), libc::EEXIST); + + // Make a dir via its absolute path, can use garbage dirfd. + let cdir = utils::into_c_string(path.join("abs_subdir")); + assert_eq!(mkdirat(999, &cdir, 0o777).unwrap(), 0); + assert!(path.join("abs_subdir").is_dir()); + + // With `AT_FDCWD`, a relative path is relative to the working directory, not to an FD. + let original_cwd = env::current_dir().unwrap(); + env::set_current_dir(&path).unwrap(); + assert_eq!(mkdirat(libc::AT_FDCWD, c"miri_test_mkdirat_cwd", 0o777).unwrap(), 0); + assert!(path.join("miri_test_mkdirat_cwd").is_dir()); + env::set_current_dir(original_cwd).unwrap(); + + // A relative path needs a dirfd that is an open directory. + assert_eq!(errno(mkdirat(999, c"rel_subdir", 0o777)), libc::EBADF); + let file = File::create(path.join("file.txt")).unwrap(); + assert_eq!(errno(mkdirat(file.as_raw_fd(), c"rel_subdir", 0o777)), libc::ENOTDIR); + + errno_check(unsafe { libc::close(dirfd) }); +} + fn test_create_read_write() { let content = b"hello test"; let path = utils::prepare("miri_test_create_read_write.txt"); - let cpath = utils::into_c_string(path); + let cpath = utils::into_c_string(&path); let fd = errno_result(unsafe { libc::open(cpath.as_ptr(), libc::O_WRONLY | libc::O_CREAT, 0o666) }) @@ -607,6 +774,17 @@ fn test_create_read_write() { let data = libc_utils::read_to_end(fd).unwrap(); assert_eq!(*content, *data); errno_check(unsafe { libc::close(fd) }); + + // We can also create with RDONLY. + fs::remove_file(&path).unwrap(); + let fd = + errno_result(unsafe { libc::open(cpath.as_ptr(), libc::O_RDONLY | libc::O_CREAT, 0o666) }) + .unwrap(); + let write_err = libc_utils::write_all(fd, content).unwrap_err(); + assert_eq!(write_err.raw_os_error().unwrap(), libc::EBADF, "unexpected errno: {write_err}"); + let data = libc_utils::read_to_end(fd).unwrap(); + assert!(data.is_empty()); + errno_check(unsafe { libc::close(fd) }); } fn test_dup_stdout_stderr() { @@ -775,6 +953,81 @@ fn test_rmdir() { fs::remove_file(&file_path).unwrap(); } +fn test_unlink() { + let path = utils::prepare_with_content("miri_test_libc_unlink.txt", b"hello"); + let cpath = utils::into_c_string(&path); + + // Unlinking an existing file should succeed. + errno_check(unsafe { libc::unlink(cpath.as_ptr()) }); + assert!(!path.exists()); + + // Unlinking it again should fail since it no longer exists. + let err = errno_result(unsafe { libc::unlink(cpath.as_ptr()) }).unwrap_err(); + assert_eq!(err.raw_os_error().unwrap(), libc::ENOENT); + + let dir_path = utils::prepare("miri_test_libc_unlink"); + fs::create_dir(&dir_path).unwrap(); + let c_dir_path = utils::into_c_string(&dir_path); + + // Unlinking a directory should fail since directories are removed using `rmdir`. + let err = errno_result(unsafe { libc::unlink(c_dir_path.as_ptr()) }).unwrap_err(); + // Linux `unlink` call sets errno to `EISDIR`, + // while POSIX specifies `EPERM`, which macOS returns. + assert!(matches!(err.raw_os_error().unwrap(), libc::EISDIR | libc::EPERM)); + assert!(dir_path.exists()); + fs::remove_dir(&dir_path).unwrap(); +} + +fn test_symlink() { + if !utils::have_symlink_permission() { + return; + } + let file_target = utils::prepare_with_content("miri_test_libc_symlink_target.txt", b"hello"); + let c_file_target = utils::into_c_string(&file_target); + let dir_target = utils::prepare("miri_test_libc_symlink_target_dir"); + let c_dir_target = utils::into_c_string(&dir_target); + fs::create_dir(&dir_target).unwrap(); + let link = utils::prepare("miri_test_libc_symlink_link"); + let c_link = utils::into_c_string(&link); + + // Test all four combinations: absolute/relative path, file/directory target. + // A relative target is resolved relative to the directory containing the link, + // so the file name alone works since `utils::prepare` puts all paths in the same directory. + let cases = [ + // (target, is_dir) + (file_target.as_os_str(), false), + (file_target.file_name().unwrap(), false), + (dir_target.as_os_str(), true), + (dir_target.file_name().unwrap(), true), + ]; + + for (target, is_dir) in cases { + let c_target = utils::into_c_string(target); + + // Creating a symlink should succeed and store `target` exactly as given. + errno_check(unsafe { libc::symlink(c_target.as_ptr(), c_link.as_ptr()) }); + assert_eq!(fs::read_link(&link).unwrap(), target); + + // Following the link should reach the target. + assert!(link.exists()); + assert!(if is_dir { link.is_dir() } else { link.is_file() }); + + errno_check(unsafe { libc::unlink(c_link.as_ptr()) }); + } + + // Check error when link already exists. + let err = + errno_result(unsafe { libc::symlink(c_file_target.as_ptr(), c_file_target.as_ptr()) }) + .unwrap_err(); + assert_eq!(err.raw_os_error().unwrap(), libc::EEXIST); + let err = errno_result(unsafe { libc::symlink(c_dir_target.as_ptr(), c_dir_target.as_ptr()) }) + .unwrap_err(); + assert_eq!(err.raw_os_error().unwrap(), libc::EEXIST); + + fs::remove_file(&file_target).unwrap(); + fs::remove_dir(&dir_target).unwrap(); +} + fn test_ftruncate>( ftruncate: unsafe extern "C" fn(fd: libc::c_int, length: T) -> libc::c_int, ) { @@ -1969,6 +2222,56 @@ pub fn check_stat_fields(stat: &libc::stat) { let _st_ctime_nsec = stat.st_ctime_nsec; } +/// Test reading with an offset. +fn test_pread>( + pread: unsafe extern "C" fn( + fd: libc::c_int, + buf: *mut libc::c_void, + count: libc::size_t, + offset: T, + ) -> libc::ssize_t, +) { + let file_contents = [1u8, 2, 3, 4, 5, 6]; + let path = utils::prepare_with_content("miri-pass-libc-pread.txt", &file_contents); + let cpath = utils::into_c_string(path); + let fd = errno_result(unsafe { libc::open(cpath.as_ptr(), libc::O_RDONLY) }).unwrap(); + + let mut buffer = [0u8; 2]; + + // Read with a 2 byte offset. + const OFFSET: usize = 2; + let bytes_read = unsafe { + errno_result(pread( + fd, + buffer.as_mut_ptr().cast(), + buffer.len() as libc::size_t, + T::from(OFFSET as i32), + )) + .unwrap() as usize + }; + + // We should read at least one byte. + assert!(bytes_read > 0); + // The read should start at the provided byte offset. + assert_eq!(&buffer[0..bytes_read], &file_contents[OFFSET..(bytes_read + OFFSET)]); + + // This should not affect the file position. + let data = libc_utils::read_to_end(fd).unwrap(); + assert_eq!(data, file_contents); + + // Negative offset errors with EINVAL. + let err = unsafe { + errno_result(pread( + fd, + buffer.as_mut_ptr().cast(), + buffer.len() as libc::size_t, + T::from(-1), + )) + .unwrap_err() + }; + assert_eq!(err.raw_os_error().unwrap(), libc::EINVAL); +} + /// Test vectored reads with multiple buffers. fn test_readv() { let file_contents = [1u8, 2, 3, 4, 5, 6]; @@ -2077,38 +2380,69 @@ fn test_preadv() { assert_eq!(&buffer[0..bytes_read], &file_contents[OFFSET..(bytes_read + OFFSET)]); } -/// Test reading with an offset. -fn test_pread>( - pread: unsafe extern "C" fn( +/// Test writing with an offset. +fn test_pwrite>( + pwrite: unsafe extern "C" fn( fd: libc::c_int, - buf: *mut libc::c_void, + buf: *const libc::c_void, count: libc::size_t, offset: T, ) -> libc::ssize_t, ) { - let file_contents = [1u8, 2, 3, 4, 5, 6]; - let path = utils::prepare_with_content("miri-pass-libc-pread.txt", &file_contents); + let path = utils::prepare_with_content("miri-pass-libc-pwritev.txt", &[]); let cpath = utils::into_c_string(path); - let fd = errno_result(unsafe { libc::open(cpath.as_ptr(), libc::O_RDONLY) }).unwrap(); + let fd = errno_result(unsafe { libc::open(cpath.as_ptr(), libc::O_WRONLY) }).unwrap(); - let mut buffer = [0u8; 2]; + let write_buffer = [1u8, 2, 3, 4, 5, 6]; - // Read with a 2 byte offset. + // Write with a 2 byte offset. const OFFSET: usize = 2; - let bytes_read = unsafe { - errno_result(pread( + let bytes_written = unsafe { + errno_result(pwrite( fd, - buffer.as_mut_ptr().cast(), - buffer.len() as libc::size_t, + write_buffer.as_ptr().cast(), + write_buffer.len() as libc::size_t, T::from(OFFSET as i32), )) .unwrap() as usize }; + // We should write at least one byte. + assert!(bytes_written > 0); - // We should read at least one byte. - assert!(bytes_read > 0); - // The read should start at the provided byte offset. - assert_eq!(&buffer[0..bytes_read], &file_contents[OFFSET..(bytes_read + OFFSET)]); + // This does not affect the position. + let pos = errno_result(unsafe { libc::lseek(fd, 0, libc::SEEK_CUR) }).unwrap(); + assert_eq!(pos, 0); + + // Negative offset fails wieth EINVAL. + let err = unsafe { + errno_result(pwrite( + fd, + write_buffer.as_ptr().cast(), + write_buffer.len() as libc::size_t, + T::from(-1), + )) + .unwrap_err() + }; + assert_eq!(err.raw_os_error().unwrap(), libc::EINVAL); + + // Check that the write worked correctly. + // Open the FD again in readonly mode and with an unadvanced pointer. + let fd = errno_result(unsafe { libc::open(cpath.as_ptr(), libc::O_RDONLY) }).unwrap(); + + let mut read_buffer = [0u8; 16]; + // Read offset + bytes written. + unsafe { + libc_utils::read_exact_generic( + read_buffer.as_mut_ptr().cast(), + (bytes_written + OFFSET) as libc::size_t, + libc_utils::Retry::NoRetry, + |buf, count| libc::read(fd, buf, count), + ) + .unwrap() + }; + + // The write should start at the provided byte offset. + assert_eq!(&write_buffer[0..bytes_written], &read_buffer[OFFSET..(bytes_written + OFFSET)]); } /// Test vectored writes with multiple buffers. @@ -2253,54 +2587,6 @@ fn test_pwritev() { assert_eq!(&write_buffer[0..bytes_written], &read_buffer[OFFSET..(bytes_written + OFFSET)]); } -/// Test writing with an offset. -fn test_pwrite>( - pwrite: unsafe extern "C" fn( - fd: libc::c_int, - buf: *const libc::c_void, - count: libc::size_t, - offset: T, - ) -> libc::ssize_t, -) { - let path = utils::prepare_with_content("miri-pass-libc-pwritev.txt", &[]); - let cpath = utils::into_c_string(path); - let fd = errno_result(unsafe { libc::open(cpath.as_ptr(), libc::O_WRONLY) }).unwrap(); - - let write_buffer = [1u8, 2, 3, 4, 5, 6]; - - // Write with a 2 byte offset. - const OFFSET: usize = 2; - let bytes_written = unsafe { - errno_result(pwrite( - fd, - write_buffer.as_ptr().cast(), - write_buffer.len() as libc::size_t, - T::from(OFFSET as i32), - )) - .unwrap() as usize - }; - // We should write at least one byte. - assert!(bytes_written > 0); - - // Open the FD again in readonly mode and with an unadvanced pointer. - let fd = errno_result(unsafe { libc::open(cpath.as_ptr(), libc::O_RDONLY) }).unwrap(); - - let mut read_buffer = [0u8; 16]; - // Read offset + bytes written. - unsafe { - libc_utils::read_exact_generic( - read_buffer.as_mut_ptr().cast(), - (bytes_written + OFFSET) as libc::size_t, - libc_utils::Retry::NoRetry, - |buf, count| libc::read(fd, buf, count), - ) - .unwrap() - }; - - // The write should start at the provided byte offset. - assert_eq!(&write_buffer[0..bytes_written], &read_buffer[OFFSET..(bytes_written + OFFSET)]); -} - /// Test repositioning the file offset. fn test_lseek + From + Ord + std::fmt::Debug>( lseek: unsafe extern "C" fn(fd: libc::c_int, offset: T, whence: libc::c_int) -> T, @@ -2342,7 +2628,7 @@ fn test_lseek + From + Ord + std::fmt::Debug>( let err = errno_result(unsafe { lseek(-1, T::from(2i32), libc::SEEK_SET) }).unwrap_err(); assert_eq!(err.raw_os_error().unwrap(), libc::EBADF); - // invalid offset + SEEK_SET + // negative offset + SEEK_SET let err = errno_result(unsafe { lseek(fd, T::from(-1i32), libc::SEEK_SET) }).unwrap_err(); assert_eq!(err.raw_os_error().unwrap(), libc::EINVAL); diff --git a/src/tools/miri/tests/pass-dep/libc/misc.rs b/src/tools/miri/tests/pass-dep/libc/misc.rs index c941e8b82bed1..a5872e627029c 100644 --- a/src/tools/miri/tests/pass-dep/libc/misc.rs +++ b/src/tools/miri/tests/pass-dep/libc/misc.rs @@ -78,12 +78,22 @@ fn test_geteuid() { let _val = unsafe { libc::geteuid() }; } +fn test_pthread_atfork() { + extern "C" fn prepare() {} + extern "C" fn parent() {} + extern "C" fn child() {} + + // Registering handlers should succeed. + assert_eq!(unsafe { libc::pthread_atfork(Some(prepare), Some(parent), Some(child)) }, 0); +} + fn main() { test_errno(); test_environ(); test_dlsym(); test_getuid(); test_geteuid(); + test_pthread_atfork(); #[cfg(target_os = "linux")] test_sigrt(); diff --git a/src/tools/miri/tests/pass-dep/libc/socket-tcp-no-blocking-epoll.rs b/src/tools/miri/tests/pass-dep/libc/socket-tcp-no-blocking-epoll.rs index 3032578c62449..f6512fa02e03a 100644 --- a/src/tools/miri/tests/pass-dep/libc/socket-tcp-no-blocking-epoll.rs +++ b/src/tools/miri/tests/pass-dep/libc/socket-tcp-no-blocking-epoll.rs @@ -38,7 +38,7 @@ fn main() { /// Instead of busy waiting until we no longer get ENOTCONN, we register /// the client socket to epoll and wait for a WRITABLE event. fn test_connect_nonblock() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; let epfd = errno_result(unsafe { libc::epoll_create1(0) }).unwrap(); @@ -83,7 +83,7 @@ fn test_connect_nonblock() { /// Instead of busy waiting until we no longer get EWOULDBLOCK, we add the /// server socket to an epoll instance and wait for a READABLE event. fn test_accept_nonblock() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; let epfd = errno_result(unsafe { libc::epoll_create1(0) }).unwrap(); @@ -176,7 +176,7 @@ fn test_connect_nonblock_err() { /// read from the client, we register the client socket to epoll and wait for /// READABLE events. fn test_recv_nonblock() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; let epfd = errno_result(unsafe { libc::epoll_create1(0) }).unwrap(); @@ -261,7 +261,7 @@ fn test_recv_nonblock() { /// readiness instead of busy waiting until we can /// write again. fn test_send_nonblock() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; let epfd = errno_result(unsafe { libc::epoll_create1(0) }).unwrap(); @@ -356,7 +356,7 @@ fn test_send_nonblock() { /// Test that the EPOLLHUP and EPOLLRDHUP readiness are set when both /// the read and write ends of a socket are closed. fn test_shutdown_read_write() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; let epfd = errno_result(unsafe { libc::epoll_create1(0) }).unwrap(); @@ -384,7 +384,7 @@ fn test_shutdown_read_write() { /// Test that the EPOLLRDHUP readiness is set when the read /// end of a socket is closed. fn test_shutdown_read() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; let epfd = errno_result(unsafe { libc::epoll_create1(0) }).unwrap(); @@ -408,7 +408,7 @@ fn test_shutdown_read() { /// Test that the EPOLLRDHUP readiness is set when the write /// end of the peer socket is closed. fn test_shutdown_write() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; let epfd = errno_result(unsafe { libc::epoll_create1(0) }).unwrap(); @@ -433,7 +433,7 @@ fn test_shutdown_write() { /// Test that Miri correctly removes the readable readiness or emits a new edge after a short read. fn test_readiness_after_short_read() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; let epfd = errno_result(unsafe { libc::epoll_create1(0) }).unwrap(); @@ -516,7 +516,7 @@ fn test_readiness_after_short_read() { /// Test that Miri doesn't remove the readable readiness after a short peek. fn test_readiness_after_short_peek() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -557,7 +557,7 @@ fn test_readiness_after_short_peek() { /// Test that Miri correctly removes the writable readiness or emits a new edge after a short write. fn test_readiness_after_short_write() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; let epfd = errno_result(unsafe { libc::epoll_create1(0) }).unwrap(); @@ -630,7 +630,7 @@ fn test_readiness_after_short_write() { /// Test that Miri correctly keeps the readable readiness when the read end of the client /// socket has been closed -- even after a short read. fn test_readable_after_read_shutdown_and_short_read() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; let epfd = errno_result(unsafe { libc::epoll_create1(0) }).unwrap(); @@ -712,7 +712,7 @@ fn test_readable_after_read_shutdown_and_short_read() { /// Test that the writable readiness gets set when the write end of a socket /// is closed -- even when the socket write buffer is full. fn test_writable_after_write_shutdown_with_full_buffer() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; let epfd = errno_result(unsafe { libc::epoll_create1(0) }).unwrap(); diff --git a/src/tools/miri/tests/pass-dep/libc/socket-tcp-no-blocking.rs b/src/tools/miri/tests/pass-dep/libc/socket-tcp-no-blocking.rs index 6b1d15333ec7f..f497ac9b97f42 100644 --- a/src/tools/miri/tests/pass-dep/libc/socket-tcp-no-blocking.rs +++ b/src/tools/miri/tests/pass-dep/libc/socket-tcp-no-blocking.rs @@ -30,7 +30,7 @@ fn yield_now() { } fn main() { - test_accept_nonblock(); + test_accept_nonblock(|fd, addr, len| unsafe { libc::accept(fd, addr, len).into() }); #[cfg(any( target_os = "linux", target_os = "android", @@ -38,7 +38,18 @@ fn main() { target_os = "solaris", target_os = "illumos" ))] - test_accept4_sock_nonblock_opt(); + test_accept4_sock_nonblock_opt(|fd, addr, len, flags| unsafe { + libc::accept4(fd, addr, len, flags).into() + }); + #[cfg(target_os = "linux")] + { + test_accept_nonblock(|fd, addr, len| unsafe { + libc::syscall(libc::SYS_accept4, fd, addr, len, 0 as libc::c_int) + }); + test_accept4_sock_nonblock_opt(|fd, addr, len, flags| unsafe { + libc::syscall(libc::SYS_accept4, fd, addr, len, flags) + }); + } test_connect_nonblock(); test_send_recv_nonblock(); #[cfg(any( @@ -66,8 +77,10 @@ fn main() { /// to accept when no incoming connection exists. This also tests that nonblocking server sockets /// are still able to accept incoming connections should they already exist before the `accept` or /// `accept4` syscall is called. -fn test_accept_nonblock() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); +fn test_accept_nonblock( + accept: fn(libc::c_int, *mut libc::sockaddr, *mut libc::socklen_t) -> libc::c_long, +) { + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -77,7 +90,7 @@ fn test_accept_nonblock() { } // This should fail as we don't have an incoming connection for this address. - let err = net::accept_ipv4(server_sockfd).unwrap_err(); + let err = net::sockname_ipv4(|storage, len| accept(server_sockfd, storage, len)).unwrap_err(); // Assert that either EAGAIN or EWOULDBLOCK was returned. assert_eq!(err.kind(), ErrorKind::WouldBlock); @@ -87,12 +100,16 @@ fn test_accept_nonblock() { // was called before we call the `accept` on the server. yield_now(); - net::accept_ipv4(server_sockfd).unwrap(); + net::sockname_ipv4(|storage, len| accept(server_sockfd, storage, len)).unwrap(); }); net::connect_ipv4(client_sockfd, addr).unwrap(); server_thread.join().unwrap(); + + // test bad FD + let err = net::sockname_ipv4(|storage, len| accept(-1, storage, len)).unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EBADF)); } #[cfg(any( @@ -104,17 +121,25 @@ fn test_accept_nonblock() { ))] /// Test that calling `accept4` with the SOCK_NONBLOCK flag produces /// a non-blocking peer socket. -fn test_accept4_sock_nonblock_opt() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); +fn test_accept4_sock_nonblock_opt( + accept4: fn( + libc::c_int, + *mut libc::sockaddr, + *mut libc::socklen_t, + libc::c_int, + ) -> libc::c_long, +) { + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; // Spawn the server thread. let server_thread = thread::spawn(move || { - let (peerfd, _) = net::sockname_ipv4(|storage, len| unsafe { - libc::accept4(server_sockfd, storage, len, libc::SOCK_NONBLOCK) + let (peerfd, _) = net::sockname_ipv4(|storage, len| { + accept4(server_sockfd, storage, len, libc::SOCK_NONBLOCK) }) .unwrap(); + let peerfd = libc::c_int::try_from(peerfd).unwrap(); let flags = unsafe { errno_result(libc::fcntl(peerfd, libc::F_GETFL, 0)).unwrap() }; @@ -138,7 +163,7 @@ fn test_accept4_sock_nonblock_opt() { /// Test that connecting to a server socket works when the client /// socket is non-blocking before the `connect` call. fn test_connect_nonblock() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -193,7 +218,7 @@ fn test_connect_nonblock() { /// Test sending bytes into and receiving bytes from a connected stream without blocking. fn test_send_recv_nonblock() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -310,7 +335,7 @@ fn test_send_recv_nonblock() { /// Instead of using non-blocking sockets, we test whether it works with blocking sockets /// when passing the `libc::MSG_DONTWAIT` flag to the send and receive calls. fn test_send_recv_dontwait() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -417,7 +442,7 @@ fn test_send_recv_dontwait() { /// Test writing bytes into and reading bytes from a connected stream without blocking. fn test_write_read_nonblock() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -505,7 +530,7 @@ fn test_write_read_nonblock() { /// Test that Miri's internal temporary read buffer gets correctly deallocated when the /// vectored read produces an error due to the socket read buffer being empty. fn test_readv_nonblock_err() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -542,7 +567,7 @@ fn test_readv_nonblock_err() { /// Test that Miri's internal temporary write buffer gets correctly deallocated when the /// vectored write produces an error due to the socket write buffer being full. fn test_writev_nonblock_err() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -638,7 +663,7 @@ fn test_getsockname_ipv4_connect_nonblock() { /// for a non-blocking IPv4 socket whose connection has been successfully /// established before calling the syscall. fn test_getpeername_ipv4_nonblock() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -820,7 +845,7 @@ fn test_connect_connecting() { assert_eq!(so_error, 0); // Create a socket which listens on `addr`. - let (_, addr) = net::make_listener_ipv4().unwrap(); + let (_, addr) = net::make_tcp_listener_ipv4().unwrap(); let err = net::connect_ipv4(client_sockfd, addr).unwrap_err(); // The standard library doesn't provide an error kind for EALREADY; diff --git a/src/tools/miri/tests/pass-dep/libc/socket-tcp-no-blocking.windows_host.stderr b/src/tools/miri/tests/pass-dep/libc/socket-tcp-no-blocking.windows_host.stderr index 8850a04abc6a2..632a2efe76eef 100644 --- a/src/tools/miri/tests/pass-dep/libc/socket-tcp-no-blocking.windows_host.stderr +++ b/src/tools/miri/tests/pass-dep/libc/socket-tcp-no-blocking.windows_host.stderr @@ -11,9 +11,9 @@ LL | libc::getsockname(client_sockfd, storage, len) = note: stack backtrace: 0: test_getsockname_ipv4_connect_nonblock::{closure#0} at tests/pass-dep/libc/socket-tcp-no-blocking.rs:LL:CC - 1: libc_utils::net::sockname::<{closure@tests/pass-dep/libc/socket-tcp-no-blocking.rs:LL:CC}> + 1: libc_utils::net::sockname::<{closure@tests/pass-dep/libc/socket-tcp-no-blocking.rs:LL:CC}, i32> at tests/pass-dep/libc/../../utils/libc.rs:LL:CC - 2: libc_utils::net::sockname_ipv4::<{closure@tests/pass-dep/libc/socket-tcp-no-blocking.rs:LL:CC}> + 2: libc_utils::net::sockname_ipv4::<{closure@tests/pass-dep/libc/socket-tcp-no-blocking.rs:LL:CC}, i32> at tests/pass-dep/libc/../../utils/libc.rs:LL:CC 3: test_getsockname_ipv4_connect_nonblock at tests/pass-dep/libc/socket-tcp-no-blocking.rs:LL:CC diff --git a/src/tools/miri/tests/pass-dep/libc/socket-tcp.rs b/src/tools/miri/tests/pass-dep/libc/socket-tcp.rs index 3c3f81bae9075..71df436b9806c 100644 --- a/src/tools/miri/tests/pass-dep/libc/socket-tcp.rs +++ b/src/tools/miri/tests/pass-dep/libc/socket-tcp.rs @@ -87,7 +87,7 @@ fn test_bind_twice() { /// Test that invoking `bind` on an already connected client /// TCP socket returns EINVAL. fn test_bind_connected() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -156,7 +156,7 @@ fn test_listen() { /// Test that `listen` returns EINVAL for a client TCP socket which /// is already connected to a peer socket. fn test_listen_connected() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -173,7 +173,7 @@ fn test_listen_connected() { /// Test that `listen` succeeds for a server TCP socket which is already /// listening. fn test_listen_listening() { - let (server_sockfd, _) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, _) = net::make_tcp_listener_ipv4().unwrap(); // Invoking `listen` multiple times should be allowed as it can be used to change // the backlog value. @@ -186,7 +186,7 @@ fn test_listen_listening() { /// - Connecting when the server is already accepting /// - Accepting when there is already an incoming connection fn test_accept_connect() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -238,7 +238,7 @@ fn test_accept_connect() { /// of the `accept` function is null but the `address_len` pointer is valid. /// The `accept` should succeed and the `address_len` should be left unchanged. fn test_accept_addr_nullptr() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -277,8 +277,8 @@ fn test_connect_error() { /// Test that invoking `connect` on an already connected client /// TCP socket returns EISCONN. fn test_connect_connected() { - let (server_sockfd1, addr1) = net::make_listener_ipv4().unwrap(); - let (_, addr2) = net::make_listener_ipv4().unwrap(); + let (server_sockfd1, addr1) = net::make_tcp_listener_ipv4().unwrap(); + let (_, addr2) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -295,8 +295,8 @@ fn test_connect_connected() { /// TCP socket returns EOPNOTSUPP on non-Linux-like targets and /// EISCONN on Linux-like targets. fn test_connect_listening() { - let (_, addr1) = net::make_listener_ipv4().unwrap(); - let (server_sockfd2, _) = net::make_listener_ipv4().unwrap(); + let (_, addr1) = net::make_tcp_listener_ipv4().unwrap(); + let (server_sockfd2, _) = net::make_tcp_listener_ipv4().unwrap(); let err = net::connect_ipv4(server_sockfd2, addr1).unwrap_err(); @@ -319,7 +319,7 @@ fn test_connect_listening() { /// We especially want to test that the peeking doesn't remove the bytes from /// the queue. fn test_send_peek_recv() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -327,6 +327,10 @@ fn test_send_peek_recv() { let server_thread = thread::spawn(move || { let (peerfd, _) = net::accept_ipv4(server_sockfd).unwrap(); + // Yield back to the main thread to ensure that the client + // is blocked with receiving until the server sent some data. + yield_now(); + // Write the bytes into the stream. unsafe { libc_utils::write_all_generic( @@ -379,7 +383,7 @@ fn test_send_peek_recv() { /// We want to test this because `write` and `read` should be the same as /// `send` and `recv` with zero flags. fn test_write_read() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -405,7 +409,7 @@ fn test_write_read() { /// Since TCP is a connection-mode protocol the `address` and `address_len` /// pointers should be left unchanged. fn test_recvfrom() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -467,7 +471,7 @@ fn test_recvfrom() { /// a problem since TCP is a connection-mode protocol and thus the /// destination address should be ignored. fn test_sendto() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -591,7 +595,7 @@ fn test_sendto() { /// Test vectored reads with multiple buffers on a connected socket. fn test_readv() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -626,7 +630,7 @@ fn test_readv() { /// Test vectored writes with multiple buffers on a connected socket. fn test_writev() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -662,7 +666,7 @@ fn test_writev() { /// Test the `getsockname` syscall on a connected IPv4 socket. fn test_getsockname_ipv4_connect() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -688,7 +692,7 @@ fn test_getsockname_ipv4_connect() { /// For a connected socket, the `getpeername` syscall should /// return the same address as the socket was connected to. fn test_getpeername_ipv4() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -715,7 +719,7 @@ fn test_getpeername_ipv4() { /// For a connected socket, the `getpeername` syscall should /// return the same address as the socket was connected to. fn test_getpeername_ipv6() { - let (server_sockfd, addr) = net::make_listener_ipv6().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv6().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET6, libc::SOCK_STREAM, 0)).unwrap() }; @@ -742,7 +746,7 @@ fn test_getpeername_ipv6() { /// Test shutting down TCP streams. fn test_shutdown() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -791,7 +795,7 @@ fn test_shutdown() { /// Test that a socket is still readable after the write end has /// been closed. fn test_shutdown_readable_after_write_close() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -819,7 +823,7 @@ fn test_shutdown_readable_after_write_close() { /// Test that a socket is still writable after the read end has /// been closed. fn test_shutdown_writable_after_read_close() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -842,7 +846,7 @@ fn test_shutdown_writable_after_read_close() { /// Also test that writes don't block indefinitely when we /// have a nonzero timeout. fn test_sockopt_sndtimeo() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -893,7 +897,7 @@ fn test_sockopt_sndtimeo() { /// Also test that reads don't block indefinitely when we /// have a nonzero timeout. fn test_sockopt_rcvtimeo() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -932,7 +936,7 @@ fn test_sockopt_rcvtimeo() { /// Test setting and reading the SO_REUSEADDR socket option. fn test_sockopt_reuseaddr() { - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; @@ -964,7 +968,7 @@ fn test_unblock_after_socket_close() { return; } - let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); + let (server_sockfd, addr) = net::make_tcp_listener_ipv4().unwrap(); let client_sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; diff --git a/src/tools/miri/tests/pass-dep/libc/socket-udp-no-blocking-epoll.rs b/src/tools/miri/tests/pass-dep/libc/socket-udp-no-blocking-epoll.rs index 24cb05d9ffaf5..c8132258db9d3 100644 --- a/src/tools/miri/tests/pass-dep/libc/socket-udp-no-blocking-epoll.rs +++ b/src/tools/miri/tests/pass-dep/libc/socket-udp-no-blocking-epoll.rs @@ -5,11 +5,17 @@ #[path = "../../utils/libc.rs"] mod libc_utils; +use std::io::ErrorKind; + use libc_utils::epoll::*; use libc_utils::*; +const TEST_BYTES: &[u8] = b"these are some test bytes!"; + fn main() { test_epoll_udp_socket(); + test_recv_nonblock(); + test_initial_readiness(); } /// Test creating a non-blocking UDP socket and adding it to an epoll instance. @@ -29,3 +35,62 @@ fn test_epoll_udp_socket() { // The socket should always be writable. check_epoll_wait_noblock(epfd, &[Ev { events: EPOLLOUT, data: sockfd }]); } + +/// Test receiving bytes from a UDP socket without blocking. +/// Instead of busy waiting until we no longer receive EWOULDBLOCK when trying to +/// read from the client, we register the client socket to epoll and wait for +/// READABLE events. +fn test_recv_nonblock() { + let (rx_sockfd, addr) = net::make_local_ipv4(libc::SOCK_DGRAM).unwrap(); + let tx_sockfd = + unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0)).unwrap() }; + let epfd = errno_result(unsafe { libc::epoll_create1(0) }).unwrap(); + + unsafe { + // Change both sockets to be non-blocking. + errno_check(libc::fcntl(rx_sockfd, libc::F_SETFL, libc::O_NONBLOCK)); + errno_check(libc::fcntl(tx_sockfd, libc::F_SETFL, libc::O_NONBLOCK)); + } + + // Set the default destination address of the transmitting socket. + net::connect_ipv4(tx_sockfd, addr).unwrap(); + + // Add the receiving socket with a READABLE interest to epoll. + epoll_ctl_add(epfd, rx_sockfd, EPOLLIN | EPOLLET | EPOLLERR).unwrap(); + + // Write some data into the transmitting socket. + unsafe { + errno_result(libc::write(tx_sockfd, TEST_BYTES.as_ptr().cast(), TEST_BYTES.len())).unwrap(); + } + + // Ensure that the EPOLLIN readiness is set on the receiving socket. + check_epoll_wait_noblock(epfd, &[Ev { events: EPOLLIN, data: rx_sockfd }]); + + let mut buffer = [0; TEST_BYTES.len()]; + + unsafe { + errno_result(libc::read(rx_sockfd, buffer.as_mut_ptr().cast(), buffer.len())).unwrap(); + } + assert_eq!(&buffer, TEST_BYTES); + + // There should be no data left to read in the socket; a read should thus + // fail with EWOULDBLOCK. + let err = unsafe { + errno_result(libc::read(rx_sockfd, buffer.as_mut_ptr().cast(), buffer.len())).unwrap_err() + }; + assert_eq!(err.kind(), ErrorKind::WouldBlock); + + // Ensure that the EPOLLIN readiness is no longer set on the receiving + // socket since we just read everything from it. + assert_eq!(current_epoll_readiness(rx_sockfd, EPOLLIN | EPOLLET), 0); +} + +/// Test that a socket reports the EPOLLOUT readiness directly after being created. +fn test_initial_readiness() { + let sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0)) }.unwrap(); + let epfd = errno_result(unsafe { libc::epoll_create1(0) }).unwrap(); + + epoll_ctl_add(epfd, sockfd, EPOLLOUT | EPOLLIN | EPOLLHUP | EPOLLRDHUP).unwrap(); + + check_epoll_wait(epfd, &[Ev { events: EPOLLOUT, data: sockfd }], -1); +} diff --git a/src/tools/miri/tests/pass-dep/libc/socket-udp-no-blocking.rs b/src/tools/miri/tests/pass-dep/libc/socket-udp-no-blocking.rs new file mode 100644 index 0000000000000..a429d3729b4a4 --- /dev/null +++ b/src/tools/miri/tests/pass-dep/libc/socket-udp-no-blocking.rs @@ -0,0 +1,536 @@ +//@ignore-target: windows # No libc socket on Windows +//@compile-flags: -Zmiri-disable-isolation +//@run-native + +//@revisions: bsd_host other_host +//@[bsd_host] only-host: macos freebsd +//@[other_host] ignore-host: macos freebsd + +#[path = "../../utils/libc.rs"] +mod libc_utils; + +use std::io::ErrorKind; +use std::time::Duration; +use std::{ptr, thread}; + +use libc_utils::*; + +const TEST_BYTES: &[u8] = b"these are some test bytes!"; + +fn main() { + test_send_peek_recv_nonblock(); + #[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "freebsd", + target_os = "solaris", + target_os = "illumos" + ))] + test_send_recv_dontwait(); + test_write_read_nonblock(); + test_send_not_connected(); + test_send_message_too_big(); + test_recv_discard_excess(); + test_sendto_recvfrom(); + test_sendto_implicit_bind(); +} + +/// Test sending bytes into an UDP socket and peeking and receiving them from another UDP socket +/// without blocking. +fn test_send_peek_recv_nonblock() { + let (rx_sockfd, addr) = net::make_local_ipv4(libc::SOCK_DGRAM).unwrap(); + let tx_sockfd = + unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0)).unwrap() }; + + unsafe { + // Change both sockets to be non-blocking. + errno_check(libc::fcntl(rx_sockfd, libc::F_SETFL, libc::O_NONBLOCK)); + errno_check(libc::fcntl(tx_sockfd, libc::F_SETFL, libc::O_NONBLOCK)); + } + + // Set the default destination address of the transmitting socket. + net::connect_ipv4(tx_sockfd, addr).unwrap(); + + let mut buffer = [0; TEST_BYTES.len()]; + + // Receiving from a socket when no data is available is not possible without blocking. + let err = unsafe { + errno_result(libc::recv(rx_sockfd, buffer.as_mut_ptr().cast(), buffer.len(), 0)) + .unwrap_err() + }; + assert_eq!(err.kind(), ErrorKind::WouldBlock); + + // Write `TEST_BYTES` into the transmitting socket. + let bytes_sent = unsafe { + errno_result(libc::send(tx_sockfd, TEST_BYTES.as_ptr().cast(), TEST_BYTES.len(), 0)) + .unwrap() + }; + assert_eq!(bytes_sent as usize, TEST_BYTES.len()); + + // Peek `TEST_BYTES` from the receiving socket. + // On BSDs, UDP sockets appear to be asynchronous, so we have a loop that waits for the packets + // that we just sent above. + loop { + let result = unsafe { + errno_result(libc::recv( + rx_sockfd, + buffer.as_mut_ptr().cast(), + buffer.len(), + libc::MSG_PEEK, + )) + }; + match result { + Ok(bytes_received) => { + assert_eq!(bytes_received as usize, buffer.len()); + break; + } + Err(e) if e.kind() == ErrorKind::WouldBlock => thread::sleep(Duration::from_millis(10)), + Err(e) => panic!("error while receiving: {e}"), + } + } + assert_eq!(&buffer, TEST_BYTES); + + // The peek shouldn't have removed the data from the socket; we should + // thus be able to read it again. + + let mut buffer = [0; TEST_BYTES.len()]; + + // Read `TEST_BYTES` from the receiving socket. + let bytes_received = unsafe { + errno_result(libc::recv(rx_sockfd, buffer.as_mut_ptr().cast(), buffer.len(), 0)).unwrap() + }; + assert_eq!(bytes_received as usize, TEST_BYTES.len()); + assert_eq!(&buffer, TEST_BYTES); +} + +#[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "freebsd", + target_os = "solaris", + target_os = "illumos" +))] +/// Test sending bytes into an UDP socket and receiving them from another UDP socket without blocking. +/// In this case, the sockets are blocking sockets, however, all `recv` and `send` operations have +/// the `libc::MSG_DONTWAIT` flag set which means that those operations should be performed in a +/// non-blocking manner. +fn test_send_recv_dontwait() { + let (rx_sockfd, addr) = net::make_local_ipv4(libc::SOCK_DGRAM).unwrap(); + let tx_sockfd = + unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0)).unwrap() }; + + // Set the default destination address of the transmitting socket. + net::connect_ipv4(tx_sockfd, addr).unwrap(); + + let mut buffer = [0; TEST_BYTES.len()]; + + // Write `TEST_BYTES` into the transmitting socket. + let bytes_sent = unsafe { + errno_result(libc::send( + tx_sockfd, + TEST_BYTES.as_ptr().cast(), + TEST_BYTES.len(), + libc::MSG_DONTWAIT, + )) + .unwrap() + }; + assert_eq!(bytes_sent as usize, TEST_BYTES.len()); + + // Read `TEST_BYTES` from the receiving socket. + // On BSDs, UDP sockets appear to be asynchronous, so we have a loop that waits for the packets + // that we just sent above. + loop { + let result = unsafe { + errno_result(libc::recv( + rx_sockfd, + buffer.as_mut_ptr().cast(), + buffer.len(), + libc::MSG_DONTWAIT, + )) + }; + match result { + Ok(bytes_received) => { + assert_eq!(bytes_received as usize, TEST_BYTES.len()); + break; + } + Err(e) if e.kind() == ErrorKind::WouldBlock => thread::sleep(Duration::from_millis(10)), + Err(e) => panic!("error while reading: {e}"), + } + } + assert_eq!(&buffer, TEST_BYTES); +} + +/// Test writing bytes into an UDP socket and reading them from another UDP socket without +/// blocking. +fn test_write_read_nonblock() { + let (rx_sockfd, addr) = net::make_local_ipv4(libc::SOCK_DGRAM).unwrap(); + let tx_sockfd = + unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0)).unwrap() }; + + unsafe { + // Change both sockets to be non-blocking. + errno_check(libc::fcntl(rx_sockfd, libc::F_SETFL, libc::O_NONBLOCK)); + errno_check(libc::fcntl(tx_sockfd, libc::F_SETFL, libc::O_NONBLOCK)); + } + + // Set the default destination address of the transmitting socket. + net::connect_ipv4(tx_sockfd, addr).unwrap(); + + let mut buffer = [0; TEST_BYTES.len()]; + + // Reading from a socket when no data is available is not possible without blocking. + let err = unsafe { + errno_result(libc::read(rx_sockfd, buffer.as_mut_ptr().cast(), buffer.len())).unwrap_err() + }; + assert_eq!(err.kind(), ErrorKind::WouldBlock); + + // Write `TEST_BYTES` into the transmitting socket. + let bytes_written = unsafe { + errno_result(libc::write(tx_sockfd, TEST_BYTES.as_ptr().cast(), TEST_BYTES.len())).unwrap() + }; + assert_eq!(bytes_written as usize, TEST_BYTES.len()); + + // Read `TEST_BYTES` from the receiving socket. + // On BSDs, UDP sockets appear to be asynchronous, so we have a loop that waits for the packets + // that we just sent above. + loop { + let result = unsafe { + errno_result(libc::read(rx_sockfd, buffer.as_mut_ptr().cast(), buffer.len())) + }; + match result { + Ok(bytes_read) => { + assert_eq!(bytes_read as usize, TEST_BYTES.len()); + break; + } + Err(e) if e.kind() == ErrorKind::WouldBlock => thread::sleep(Duration::from_millis(10)), + Err(e) => panic!("error while reading: {e}"), + } + } + assert_eq!(&buffer, TEST_BYTES); +} + +/// Test sending bytes into a UDP socket with `send` but there hasn't been set a +/// default destination using the `connect` function. This should fail with EDESTADDRREQ. +fn test_send_not_connected() { + let sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0)).unwrap() }; + + unsafe { + // Change the socket to be non-blocking. + errno_check(libc::fcntl(sockfd, libc::F_SETFL, libc::O_NONBLOCK)); + } + + // Attempt to write `TEST_BYTES` into the socket. + let err = unsafe { + errno_result(libc::send(sockfd, TEST_BYTES.as_ptr().cast(), TEST_BYTES.len(), 0)) + .unwrap_err() + }; + if cfg!(miri) { + // On Windows hosts the `send` fails with ENOTCONN while on Unix-like hosts + // it fails with EDESTADDRREQ since the socket has no default destination address + // set. We don't explicitly remap the errors and thus accept both here. + assert!(matches!(err.raw_os_error().unwrap(), libc::EDESTADDRREQ | libc::ENOTCONN)); + } else { + // On Unix-like systems the `send` should fail with EDESTADDRREQ since + // the socket has no default destination address set. + assert_eq!(err.raw_os_error().unwrap(), libc::EDESTADDRREQ); + } +} + +/// Test sending a UDP message which doesn't fit into a single UDP datagram. +/// The `send` operation should fail with EMSGSIZE. +fn test_send_message_too_big() { + let (_rx_sockfd, addr) = net::make_local_ipv4(libc::SOCK_DGRAM).unwrap(); + let tx_sockfd = + unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0)).unwrap() }; + + unsafe { + // Change the transmitting socket to be non-blocking. + errno_check(libc::fcntl(tx_sockfd, libc::F_SETFL, libc::O_NONBLOCK)); + } + + // Set the default destination address of the transmitting socket. + net::connect_ipv4(tx_sockfd, addr).unwrap(); + + // The maximum UDP packet size is `u16::MAX` which is less than 70'000 bytes. + let buffer = [1u8; 70_000]; + + let err = unsafe { + errno_result(libc::send(tx_sockfd, buffer.as_ptr().cast(), buffer.len(), 0)).unwrap_err() + }; + // `send` should fail with EMSGSIZE since the message doesn't fit into a single UDP datagram. + assert_eq!(err.raw_os_error(), Some(libc::EMSGSIZE)); +} + +/// Test that reading a partial message discards the remaining bytes of the message +/// i.e. they cannot be read by a subsequent `recv`. +fn test_recv_discard_excess() { + let (rx_sockfd, addr) = net::make_local_ipv4(libc::SOCK_DGRAM).unwrap(); + let tx_sockfd = + unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0)).unwrap() }; + + unsafe { + // Change both sockets to be non-blocking. + errno_check(libc::fcntl(rx_sockfd, libc::F_SETFL, libc::O_NONBLOCK)); + errno_check(libc::fcntl(tx_sockfd, libc::F_SETFL, libc::O_NONBLOCK)); + } + + // Set the default destination address of the transmitting socket. + net::connect_ipv4(tx_sockfd, addr).unwrap(); + + let mut buffer = [0u8; TEST_BYTES.len() / 2]; + + // Write `TEST_BYTES` into the transmitting socket. + unsafe { + errno_result(libc::write(tx_sockfd, TEST_BYTES.as_ptr().cast(), TEST_BYTES.len())).unwrap(); + } + + // Read `TEST_BYTES` partially from the receiving socket. + // On BSDs, UDP sockets appear to be asynchronous, so we have a loop that waits for the packets + // that we just sent above. + loop { + let result = unsafe { + errno_result(libc::recv(rx_sockfd, buffer.as_mut_ptr().cast(), buffer.len(), 0)) + }; + match result { + Ok(bytes_received) => { + assert_eq!(bytes_received as usize, buffer.len()); + break; + } + Err(e) if e.kind() == ErrorKind::WouldBlock => thread::sleep(Duration::from_millis(10)), + Err(e) => panic!("error while receiving: {e}"), + } + } + assert_eq!(&buffer, &TEST_BYTES[0..buffer.len()]); + + // The bytes from the message which didn't fit into the buffer are discarded. + // The read buffer should thus now be empty. + let err = unsafe { + errno_result(libc::recv(rx_sockfd, buffer.as_mut_ptr().cast(), buffer.len(), 0)) + .unwrap_err() + }; + assert_eq!(err.kind(), ErrorKind::WouldBlock); +} + +/// Test `sendto` and `recvfrom` with various combinations for the destination/origin address +/// pointer. +/// - `sendto` where the destination address is a nullptr and without a default destination address: +/// Should fail with EDESTADDRREQ. +/// - `sendto` where the destination address is valid and the default destination address is unavailable: +/// Should succeed on non-BSD targets since the `sendto` address should overwrite the default destination address. +/// Should fail with EISCONN on BSD targets. +/// - `sendto` where the destination address is a nullptr and with a default destination address: +/// Should succeed. +/// - `sendto` where the destination address is valid address: +/// Should succeed. +/// - `recvfrom` where the origin address pointer is a nullptr: +/// Should succeed. +/// - `recvfrom` where the origin address pointer is a valid pointer: +/// Should succeed. +fn test_sendto_recvfrom() { + let (rx_sockfd, rx_addr) = net::make_local_ipv4(libc::SOCK_DGRAM).unwrap(); + let (tx_sockfd, tx_addr) = net::make_local_ipv4(libc::SOCK_DGRAM).unwrap(); + let other_tx_sockfd = + unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0)).unwrap() }; + + unsafe { + // Change all sockets to be non-blocking. + errno_check(libc::fcntl(rx_sockfd, libc::F_SETFL, libc::O_NONBLOCK)); + errno_check(libc::fcntl(tx_sockfd, libc::F_SETFL, libc::O_NONBLOCK)); + errno_check(libc::fcntl(other_tx_sockfd, libc::F_SETFL, libc::O_NONBLOCK)); + } + + // Write `TEST_BYTES` without specifying an explicit destination address + // and without having a default destination address configured. + // This should fail with EDESTADDRREQ. + let err = unsafe { + errno_result(libc::sendto( + tx_sockfd, + TEST_BYTES.as_ptr().cast(), + TEST_BYTES.len(), + /* flags */ 0, + ptr::null::().cast(), + size_of::() as libc::socklen_t, + )) + .unwrap_err() + }; + assert_eq!(err.raw_os_error().unwrap(), libc::EDESTADDRREQ); + + // Send `TEST_BYTES` from the transmitting socket to the receiving socket + // by specifying `rx_addr` as the destination address of `sendto`. + let bytes_sent = unsafe { + errno_result(libc::sendto( + tx_sockfd, + TEST_BYTES.as_ptr().cast(), + TEST_BYTES.len(), + /* flags */ 0, + (&rx_addr as *const libc::sockaddr_in).cast(), + size_of::() as libc::socklen_t, + )) + .unwrap() + }; + assert_eq!(bytes_sent as usize, TEST_BYTES.len()); + + // Set default destination address to `rx_addr`. + net::connect_ipv4(tx_sockfd, rx_addr).unwrap(); + + // When a default destination address is specified using `connect`, then + // a `sendto` with a nullptr destination address falls back to the default + // destination address. + let bytes_sent = unsafe { + errno_result(libc::sendto( + tx_sockfd, + TEST_BYTES.as_ptr().cast(), + TEST_BYTES.len(), + /* flags */ 0, + ptr::null::(), + size_of::() as libc::socklen_t, + )) + .unwrap() + }; + assert_eq!(bytes_sent as usize, TEST_BYTES.len()); + + // Set default destination address to some bogus address that is not available. + // Since we cannot use `connect` multiple times on `tx_sockfd` we use `other_tx_sockfd` + // for this. + let bogus_addr = net::sock_addr_ipv4([127, 0, 3, 1], 5124); + net::connect_ipv4(other_tx_sockfd, bogus_addr).unwrap(); + + if !cfg!(any(bsd_host, target_os = "freebsd", target_vendor = "apple")) { + // We're on a non-BSD host and on a non-BSD target. + + // A `sendto` with the destination address of `rx_addr` should overwrite the + // bogus default destination address and thus `TEST_BYTES` should be transmitted + // successfully from the transmitting socket to the receiving socket. + let bytes_sent = unsafe { + errno_result(libc::sendto( + other_tx_sockfd, + TEST_BYTES.as_ptr().cast(), + TEST_BYTES.len(), + /* flags */ 0, + (&rx_addr as *const libc::sockaddr_in).cast(), + size_of::() as libc::socklen_t, + )) + .unwrap() + }; + assert_eq!(bytes_sent as usize, TEST_BYTES.len()); + } else if cfg!(any(target_os = "freebsd", target_vendor = "apple")) { + // We're on a BSD target. + + // A `sendto` with a non-null destination address and a configured default + // destination address should return EISCONN. + let err = unsafe { + errno_result(libc::sendto( + other_tx_sockfd, + TEST_BYTES.as_ptr().cast(), + TEST_BYTES.len(), + /* flags */ 0, + (&rx_addr as *const libc::sockaddr_in).cast(), + size_of::() as libc::socklen_t, + )) + .unwrap_err() + }; + assert_eq!(err.raw_os_error().unwrap(), libc::EISCONN); + } + + let mut buffer = [0u8; TEST_BYTES.len()]; + + // Read `TEST_BYTES` from the receiving socket using `recvfrom` and ensure that the origin + // address matches `tx_addr`. + // On BSDs, UDP sockets appear to be asynchronous, so we have a loop that waits for the packets + // that we just sent above. + loop { + let result = net::sockname_ipv4(|storage, len| unsafe { + libc::recvfrom( + rx_sockfd, + buffer.as_mut_ptr().cast(), + buffer.len(), + /* flags */ 0, + storage, + len, + ) + }); + match result { + Ok((bytes_received, origin_addr)) => { + assert_eq!(bytes_received as usize, TEST_BYTES.len()); + assert_eq!(origin_addr.sin_family, tx_addr.sin_family); + assert_eq!(origin_addr.sin_port, tx_addr.sin_port); + assert_eq!(origin_addr.sin_addr.s_addr, tx_addr.sin_addr.s_addr); + break; + } + Err(e) if e.kind() == ErrorKind::WouldBlock => thread::sleep(Duration::from_millis(10)), + Err(e) => panic!("error while reading: {e}"), + } + } + assert_eq!(&buffer, TEST_BYTES); + + let mut buffer = [0u8; TEST_BYTES.len()]; + + // Read `TEST_BYTES` from the receiving socket using `recvfrom` but with a nullptr address pointer. + // This indicates that we don't care about the origin address and thus it should still succeed. + // On BSDs, UDP sockets appear to be asynchronous, so we have a loop that waits for the packets + // that we just sent above. + loop { + let result = unsafe { + errno_result(libc::recvfrom( + rx_sockfd, + buffer.as_mut_ptr().cast(), + buffer.len(), + /* flags */ 0, + ptr::null_mut::(), + ptr::null_mut::(), + )) + }; + match result { + Ok(bytes_received) => { + assert_eq!(bytes_received as usize, TEST_BYTES.len()); + break; + } + Err(e) if e.kind() == ErrorKind::WouldBlock => thread::sleep(Duration::from_millis(10)), + Err(e) => panic!("error while reading: {e}"), + } + } + assert_eq!(&buffer, TEST_BYTES); +} + +/// Test that a UDP socket gets implicitly bound to a local address after +/// the first `sendto` has been invoked on it. +fn test_sendto_implicit_bind() { + let (rx_sockfd, rx_addr) = net::make_local_ipv4(libc::SOCK_DGRAM).unwrap(); + let tx_sockfd = + unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0)).unwrap() }; + + unsafe { + // Change both sockets to be non-blocking. + errno_check(libc::fcntl(rx_sockfd, libc::F_SETFL, libc::O_NONBLOCK)); + errno_check(libc::fcntl(tx_sockfd, libc::F_SETFL, libc::O_NONBLOCK)); + } + + let bytes_sent = unsafe { + errno_result(libc::sendto( + tx_sockfd, + TEST_BYTES.as_ptr().cast(), + TEST_BYTES.len(), + /* flags */ 0, + (&rx_addr as *const libc::sockaddr_in).cast(), + size_of::() as libc::socklen_t, + )) + .unwrap() + }; + assert_eq!(bytes_sent as usize, TEST_BYTES.len()); + + // After the first `sendto` the `tx_sockfd` should be implicitly bound to a local address. + // This means `sock_addr.sin_port` should be non-zero. A zero port would indicate that + // the socket hasn't been bound. + let (_, sock_addr) = + net::sockname_ipv4(|storage, len| unsafe { libc::getsockname(tx_sockfd, storage, len) }) + .unwrap(); + + // Libc representation of an unspecified IPv4 address with zero port. + let addr = net::sock_addr_ipv4([0, 0, 0, 0], 0); + + // Ensure that the socket got implicitly bound to the unspecified + // local address with a non-zero port. + assert!(sock_addr.sin_port > 0); + assert_eq!(addr.sin_family, sock_addr.sin_family); + assert_eq!(addr.sin_addr.s_addr, sock_addr.sin_addr.s_addr); +} diff --git a/src/tools/miri/tests/pass-dep/libc/socket-udp.rs b/src/tools/miri/tests/pass-dep/libc/socket-udp.rs index 6bdfb2e72b3cc..2243e4c695336 100644 --- a/src/tools/miri/tests/pass-dep/libc/socket-udp.rs +++ b/src/tools/miri/tests/pass-dep/libc/socket-udp.rs @@ -1,5 +1,5 @@ //@ignore-target: windows # No libc socket on Windows -//@compile-flags: -Zmiri-disable-isolation +//@compile-flags: -Zmiri-disable-isolation -Zmiri-fixed-schedule //@run-native #[path = "../../utils/libc.rs"] @@ -7,15 +7,95 @@ mod libc_utils; #[path = "../../utils/mod.rs"] mod utils; +use std::thread; +use std::time::Duration; + use libc_utils::*; +const TEST_BYTES: &[u8] = b"these are some test bytes!"; + +fn yield_now() { + if cfg!(miri) { + // We control the scheduler so we know this is enough. + thread::yield_now(); + } else { + // Without scheduler control, we hope that sleeping a bit is enough. + thread::sleep(Duration::from_millis(20)); + } +} + fn main() { + test_send_peek_recv(); + test_getsockname_ipv4_connect(); test_getpeername_ipv4(); test_getpeername_ipv6(); } +/// Test sending bytes into a transmitting UDP socket and then peeking and receiving +/// them from the receiving UDP socket. +/// We especially want to test that the peeking doesn't remove the bytes from +/// the queue. +fn test_send_peek_recv() { + let (rx_sockfd, addr) = net::make_local_ipv4(libc::SOCK_DGRAM).unwrap(); + let tx_sockfd = + unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0)).unwrap() }; + + // Set the default destination address of the transmitting socket. + net::connect_ipv4(tx_sockfd, addr).unwrap(); + + // Spawn the transmitter thread. + let tx_thread = thread::spawn(move || { + // Yield back to the main thread to ensure that the receiver + // is blocked on the sender. + yield_now(); + + // Write the bytes into the stream. + let bytes_sent = unsafe { + errno_result(libc::send( + tx_sockfd, + TEST_BYTES.as_ptr().cast(), + TEST_BYTES.len(), + /* flags */ 0, + )) + .unwrap() + }; + assert_eq!(bytes_sent as usize, TEST_BYTES.len()); + }); + + let mut buffer = [0; TEST_BYTES.len()]; + let bytes_received = unsafe { + errno_result(libc::recv( + rx_sockfd, + buffer.as_mut_ptr().cast(), + buffer.len(), + libc::MSG_PEEK, + )) + .unwrap() + } as usize; + assert_eq!(bytes_received as usize, TEST_BYTES.len()); + assert_eq!(&buffer, TEST_BYTES); + + // Since the bytes aren't removed from the queue by peeking, we should be + // able to read the same bytes again into a new buffer. + + let mut buffer = [0; TEST_BYTES.len()]; + let bytes_received = unsafe { + errno_result(libc::recv( + rx_sockfd, + buffer.as_mut_ptr().cast(), + buffer.len(), + /* flags */ 0, + )) + .unwrap() + } as usize; + assert_eq!(bytes_received as usize, TEST_BYTES.len()); + assert_eq!(&buffer, TEST_BYTES); + + tx_thread.join().unwrap(); +} + /// Test the `getsockname` syscall on a IPv4 UDP socket for which the default /// destination address has been set using `connect` but which has not been /// explicitly bound to a local address. diff --git a/src/tools/miri/tests/pass-dep/windows-fs.rs b/src/tools/miri/tests/pass-dep/windows/fs.rs similarity index 80% rename from src/tools/miri/tests/pass-dep/windows-fs.rs rename to src/tools/miri/tests/pass-dep/windows/fs.rs index 71910ca92ec58..38c4ee805879d 100644 --- a/src/tools/miri/tests/pass-dep/windows-fs.rs +++ b/src/tools/miri/tests/pass-dep/windows/fs.rs @@ -10,7 +10,7 @@ use std::os::windows::io::{AsRawHandle, FromRawHandle}; use std::path::Path; use std::{fs, mem, ptr}; -#[path = "../utils/mod.rs"] +#[path = "../../utils/mod.rs"] mod utils; use windows_sys::Wdk::Storage::FileSystem::{NtReadFile, NtWriteFile}; @@ -114,7 +114,25 @@ unsafe fn test_create_normal_file() { panic!("Failed to close file") }; - // Creating the file again should fail due to CREATE_NEW. + // Try again, this time without asking for any file access. + // That should still work. + fs::remove_file(&temp).unwrap(); // let's create the file again + let handle = CreateFileW( + raw_path.as_ptr(), + /* desired_access */ 0, + FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, + ptr::null_mut(), + CREATE_NEW, + FILE_FLAG_OPEN_REPARSE_POINT, // std also sets this + ptr::null_mut(), + ); + assert_ne!(handle.addr(), usize::MAX, "CreateFileW Failed: {}", GetLastError()); + assert_eq!(GetLastError(), 0); + if CloseHandle(handle) == 0 { + panic!("Failed to close file") + }; + + // Creating the file when it already exists should fail due to CREATE_NEW. let handle = CreateFileW( raw_path.as_ptr(), GENERIC_READ | GENERIC_WRITE, @@ -143,6 +161,22 @@ unsafe fn test_create_normal_file() { panic!("Failed to get file information: {}", GetLastError()) }; assert!(info.dwFileAttributes & REGULAR_FILE != 0); + // Even reading should fail. (Under the hood we did actually open the file for reading, + // so this checks that we do still reject read requests.) + let mut status = std::mem::zeroed::(); + let mut buffer = vec![0; 13]; + let out = NtReadFile( + handle, + ptr::null_mut(), + None, + ptr::null_mut(), + &mut status, + buffer.as_mut_ptr().cast(), + buffer.len() as u32, + ptr::null_mut(), + ptr::null_mut(), + ); + assert_eq!(out, STATUS_ACCESS_DENIED); if CloseHandle(handle) == 0 { panic!("Failed to close file") }; @@ -154,7 +188,7 @@ unsafe fn test_create_always_twice() { let raw_path = to_wide_cstr(&temp); let handle = CreateFileW( raw_path.as_ptr(), - GENERIC_READ | GENERIC_WRITE, + /* desired_access */ GENERIC_READ, // should work even without write access FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, ptr::null_mut(), CREATE_ALWAYS, @@ -163,6 +197,22 @@ unsafe fn test_create_always_twice() { ); assert_ne!(handle.addr(), usize::MAX, "CreateFileW Failed: {}", GetLastError()); assert_eq!(GetLastError(), 0); + // Writing should fail as we did not request write access. (This is tricky because under the + // hood we actually do request write access to be able to create the file.) + let text = b"Example text!"; + let mut status = std::mem::zeroed::(); + let out = NtWriteFile( + handle, + ptr::null_mut(), + None, + ptr::null_mut(), + &mut status, + text.as_ptr().cast(), + text.len() as u32, + ptr::null_mut(), + ptr::null_mut(), + ); + assert_eq!(out, STATUS_ACCESS_DENIED); if CloseHandle(handle) == 0 { panic!("Failed to close file") }; @@ -285,17 +335,37 @@ unsafe fn test_file_read_write() { ptr::null_mut(), ptr::null_mut(), ); - - assert_eq!(out, status.Anonymous.Status); assert_eq!(out, STATUS_SUCCESS); + assert_eq!(status.Anonymous.Status, STATUS_SUCCESS); + assert_eq!(status.Information, text.len()); + // GetLastError was not touched. + assert_eq!(GetLastError(), 1234); + + // Reading would fail as the file was opened write-only. + status.Anonymous.Status = 1234; + status.Information = 1234; + let mut buffer = vec![0; 13]; + let out = NtReadFile( + handle, + ptr::null_mut(), + None, + ptr::null_mut(), + &mut status, + buffer.as_mut_ptr().cast(), + buffer.len() as u32, + ptr::null_mut(), + ptr::null_mut(), + ); + assert_eq!(out, STATUS_ACCESS_DENIED); + // The rest was not touched. + assert_eq!(status.Information, 1234); + assert_eq!(status.Anonymous.Status, 1234); assert_eq!(GetLastError(), 1234); + // Open for reading to also test that. let file = fs::File::open(&temp).unwrap(); + SetLastError(1234); // needs reset after opening file let handle = file.as_raw_handle(); - - // Testing NtReadFile doesn't clobber the error - SetLastError(1234); - let mut buffer = vec![0; 13]; let out = NtReadFile( handle, @@ -308,10 +378,31 @@ unsafe fn test_file_read_write() { ptr::null_mut(), ptr::null_mut(), ); - - assert_eq!(out, status.Anonymous.Status); assert_eq!(out, STATUS_SUCCESS); + assert_eq!(status.Anonymous.Status, STATUS_SUCCESS); + assert_eq!(status.Information, text.len()); assert_eq!(buffer, text); + // GetLastError was not touched + assert_eq!(GetLastError(), 1234); + + // Writing fails as the file was opened read-only. + status.Anonymous.Status = 1234; + status.Information = 1234; + let out = NtWriteFile( + handle, + ptr::null_mut(), + None, + ptr::null_mut(), + &mut status, + text.as_ptr().cast(), + text.len() as u32, + ptr::null_mut(), + ptr::null_mut(), + ); + assert_eq!(out, STATUS_ACCESS_DENIED); + // The rest was not touched. + assert_eq!(status.Information, 1234); + assert_eq!(status.Anonymous.Status, 1234); assert_eq!(GetLastError(), 1234); } diff --git a/src/tools/miri/tests/pass-dep/windows/process.rs b/src/tools/miri/tests/pass-dep/windows/process.rs new file mode 100644 index 0000000000000..244b933e6c503 --- /dev/null +++ b/src/tools/miri/tests/pass-dep/windows/process.rs @@ -0,0 +1,18 @@ +//@only-target: windows # this directly tests windows-only functions +//@revisions: with_isolation without_isolation +//@[without_isolation] compile-flags: -Zmiri-disable-isolation +//@run-native + +use windows_sys::Win32::System::Threading::GetCurrentProcessId; + +fn main() { + let pid = unsafe { GetCurrentProcessId() }; + assert_ne!(pid, 0); + assert_eq!(pid, std::process::id()); + + std::thread::spawn(move || { + assert_eq!(unsafe { GetCurrentProcessId() }, pid); + }) + .join() + .unwrap(); +} diff --git a/src/tools/miri/tests/pass/shims/windows-rand.rs b/src/tools/miri/tests/pass-dep/windows/rand.rs similarity index 50% rename from src/tools/miri/tests/pass/shims/windows-rand.rs rename to src/tools/miri/tests/pass-dep/windows/rand.rs index 079d743b46150..7da2cb1126629 100644 --- a/src/tools/miri/tests/pass/shims/windows-rand.rs +++ b/src/tools/miri/tests/pass-dep/windows/rand.rs @@ -5,35 +5,16 @@ use core::ffi::c_void; use core::mem::size_of_val; use core::ptr::null_mut; -// Windows API definitions. -type NTSTATUS = i32; -type BOOLEAN = u8; -type BOOL = i32; // yes, seriously, BOOL and BOOLEAN are very different... -const BCRYPT_USE_SYSTEM_PREFERRED_RNG: u32 = 0x00000002; -const BCRYPT_RNG_ALG_HANDLE: *mut c_void = 0x81 as *mut c_void; -#[link(name = "bcrypt")] -extern "system" { - fn BCryptGenRandom( - halgorithm: *mut c_void, - pbbuffer: *mut u8, - cbbuffer: u32, - dwflags: u32, - ) -> NTSTATUS; -} +use windows_sys::Win32::Security::Cryptography::{ + BCRYPT_RNG_ALG_HANDLE, BCRYPT_USE_SYSTEM_PREFERRED_RNG, BCryptGenRandom, ProcessPrng, +}; + +// FIXME: `windows-sys` declares the return type as bool. The SDK declares it as BOOLEAN (u8). +// https://github.com/microsoft/windows-rs/issues/5437 #[link(name = "advapi32")] -extern "system" { +unsafe extern "system" { #[link_name = "SystemFunction036"] - fn RtlGenRandom(RandomBuffer: *mut u8, RandomBufferLength: u32) -> BOOLEAN; -} -#[cfg(target_arch = "x86")] -#[link(name = "bcryptprimitives", kind = "raw-dylib", import_name_type = "undecorated")] -extern "system" { - fn ProcessPrng(pbdata: *mut u8, cbdata: usize) -> BOOL; -} -#[cfg(not(target_arch = "x86"))] -#[link(name = "bcryptprimitives", kind = "raw-dylib")] -extern "system" { - fn ProcessPrng(pbdata: *mut u8, cbdata: usize) -> BOOL; + fn RtlGenRandom(buffer: *mut c_void, len: u32) -> u8; } fn main() { @@ -48,7 +29,7 @@ fn main() { let ret = unsafe { BCryptGenRandom(BCRYPT_RNG_ALG_HANDLE, key.as_mut_ptr(), len, 0) }; assert!(ret >= 0); - let ret = unsafe { RtlGenRandom(key.as_mut_ptr(), len) }; + let ret = unsafe { RtlGenRandom(key.as_mut_ptr().cast(), len) }; // RtlGenRandom returns a BOOLEAN where 0 indicates an error assert_ne!(ret, 0); diff --git a/src/tools/miri/tests/pass/shims/windows-threadname.rs b/src/tools/miri/tests/pass-dep/windows/threadname.rs similarity index 69% rename from src/tools/miri/tests/pass/shims/windows-threadname.rs rename to src/tools/miri/tests/pass-dep/windows/threadname.rs index e5abe673a9ee9..ba463e69c4fca 100644 --- a/src/tools/miri/tests/pass/shims/windows-threadname.rs +++ b/src/tools/miri/tests/pass-dep/windows/threadname.rs @@ -1,20 +1,13 @@ //@only-target: windows # this directly tests windows-only functions //@run-native -use core::ffi::c_void; use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; -type HANDLE = *mut c_void; -type PWSTR = *mut u16; -type PCWSTR = *const u16; -type HRESULT = i32; -type HLOCAL = *mut ::core::ffi::c_void; -extern "system" { - fn GetCurrentThread() -> HANDLE; - fn GetThreadDescription(hthread: HANDLE, lpthreaddescription: *mut PWSTR) -> HRESULT; - fn SetThreadDescription(hthread: HANDLE, lpthreaddescription: PCWSTR) -> HRESULT; - fn LocalFree(hmem: HLOCAL) -> HLOCAL; -} + +use windows_sys::Win32::Foundation::LocalFree; +use windows_sys::Win32::System::Threading::{ + GetCurrentThread, GetThreadDescription, SetThreadDescription, +}; fn to_u16s>(s: S) -> Vec { let mut result: Vec<_> = s.as_ref().encode_wide().collect(); diff --git a/src/tools/miri/tests/pass/tls/windows-tls.in_thread.stdout b/src/tools/miri/tests/pass-dep/windows/tls.in_thread.stderr similarity index 100% rename from src/tools/miri/tests/pass/tls/windows-tls.in_thread.stdout rename to src/tools/miri/tests/pass-dep/windows/tls.in_thread.stderr diff --git a/src/tools/miri/tests/pass/tls/windows-tls.rs b/src/tools/miri/tests/pass-dep/windows/tls.rs similarity index 73% rename from src/tools/miri/tests/pass/tls/windows-tls.rs rename to src/tools/miri/tests/pass-dep/windows/tls.rs index 13e479d2d0fd6..274dbea047804 100644 --- a/src/tools/miri/tests/pass/tls/windows-tls.rs +++ b/src/tools/miri/tests/pass-dep/windows/tls.rs @@ -5,48 +5,16 @@ use std::ffi::c_void; use std::ptr; -pub type BOOL = i32; -pub const FALSE: BOOL = 0i32; -pub const TRUE: BOOL = 1i32; - -extern "system" { - fn TlsAlloc() -> u32; - fn TlsSetValue(key: u32, val: *mut c_void) -> BOOL; - fn TlsGetValue(key: u32) -> *mut c_void; - fn TlsFree(key: u32) -> BOOL; - - fn FlsAlloc(lpcallback: Option) -> u32; - fn FlsSetValue(key: u32, val: *mut c_void) -> BOOL; - fn FlsGetValue(key: u32) -> *mut c_void; - fn FlsFree(key: u32) -> BOOL; - - fn IsThreadAFiber() -> BOOL; -} +use windows_sys::Win32::Foundation::{FALSE, TRUE}; +use windows_sys::Win32::System::Threading::{ + FlsAlloc, FlsFree, FlsGetValue, FlsSetValue, IsThreadAFiber, TlsAlloc, TlsFree, TlsGetValue, + TlsSetValue, +}; -extern "system" fn dtor_unreachable(_val: *mut c_void) { +extern "system" fn dtor_unreachable(_val: *const c_void) { unreachable!() } -// Printing without touching the Rust runtime. -fn print_safe(msg: &str) { - use std::io::Write; - use std::os::windows::io::FromRawHandle; - use std::{ffi, fs, mem}; - - pub const STD_OUTPUT_HANDLE: u32 = 4294967285; - - #[link(name = "kernel32")] - unsafe extern "system" { - fn GetStdHandle(which: u32) -> *mut ffi::c_void; - } - - unsafe { - let handle = GetStdHandle(STD_OUTPUT_HANDLE); - let mut handle = mem::ManuallyDrop::new(fs::File::from_raw_handle(handle)); - handle.write_all(msg.as_bytes()).unwrap(); - } -} - fn fls_0_zero_value_does_not_run() { let key = unsafe { FlsAlloc(Some(dtor_unreachable)) }; @@ -56,9 +24,9 @@ fn fls_0_zero_value_does_not_run() { } fn fls_1_dtor_simple() { - extern "system" fn dtor(val: *mut c_void) { + extern "system" fn dtor(val: *const c_void) { assert!(!val.is_null()); - print_safe("fls_1_dtor_simple\n"); + eprintln!("fls_1_dtor_simple"); // Keys are freed in-order. Without a dtor, the early key's value is not zeroed out. let early_key = val as u32; @@ -80,13 +48,13 @@ fn fls_1_dtor_simple() { } fn fls_2_dtor_update_value_ignored() { - extern "system" fn early_dtor(val: *mut c_void) { + extern "system" fn early_dtor(val: *const c_void) { assert!(!val.is_null()); - print_safe("fls_2.1_early_dtor\n"); + eprintln!("fls_2.1_early_dtor"); } - extern "system" fn later_dtor(val: *mut c_void) { - print_safe("fls_2.2_later_dtor\n"); + extern "system" fn later_dtor(val: *const c_void) { + eprintln!("fls_2.2_later_dtor"); // Updating a different fls slot's value doesn't cause their dtor to run, if it already did. let early_key = val as u32; @@ -98,7 +66,7 @@ fn fls_2_dtor_update_value_ignored() { // Registering new fls slots in a dtor is always possible, // but their dtor might not get called. - extern "system" fn new_in_dtor(_val: *mut c_void) {} + extern "system" fn new_in_dtor(_val: *const c_void) {} let a_new_key_in_dtor = unsafe { FlsAlloc(Some(new_in_dtor)) }; assert_eq!(unsafe { FlsSetValue(a_new_key_in_dtor, ptr::without_provenance_mut(1)) }, TRUE); assert_eq!(unsafe { FlsGetValue(a_new_key_in_dtor).addr() }, 1); @@ -114,8 +82,8 @@ fn fls_2_dtor_update_value_ignored() { } fn fls_3_dtor_update_value_skipped_ignored() { - extern "system" fn later_dtor(val: *mut c_void) { - print_safe("fls_3_later_dtor\n"); + extern "system" fn later_dtor(val: *const c_void) { + eprintln!("fls_3_later_dtor"); // Updating a different fls slot's value doesn't cause their dtor to run, if it was already skipped. let early_key = val as u32; @@ -132,16 +100,16 @@ fn fls_3_dtor_update_value_skipped_ignored() { } fn fls_4_dtor_update_value_used() { - extern "system" fn early_dtor(val: *mut c_void) { - print_safe("fls_4.1_early_dtor\n"); + extern "system" fn early_dtor(val: *const c_void) { + eprintln!("fls_4.1_early_dtor"); // Updating a different fls slot's value affect their dtor, if it hasn't yet run. let later_key = val as u32; assert_eq!(unsafe { FlsSetValue(later_key, ptr::without_provenance_mut(1)) }, TRUE); } - extern "system" fn later_dtor(_val: *mut c_void) { - print_safe("fls_4.2_later_dtor\n"); + extern "system" fn later_dtor(_val: *const c_void) { + eprintln!("fls_4.2_later_dtor"); } let early_key = unsafe { FlsAlloc(Some(early_dtor)) }; @@ -156,13 +124,13 @@ fn fls_4_dtor_update_value_used() { } fn fls_5_dtor_value() { - extern "system" fn dtor(val: *mut c_void) { + extern "system" fn dtor(val: *const c_void) { assert!(!val.is_null()); - print_safe("fls_5_dtor_value\n"); + eprintln!("fls_5_dtor_value"); // When the key's dtor run, the key's value equals the destructor argument. let key = val as u32; - assert_eq!(unsafe { FlsGetValue(key) }, val); + assert_eq!(unsafe { FlsGetValue(key) }.cast_const(), val); } let key = unsafe { FlsAlloc(Some(dtor)) }; @@ -171,8 +139,8 @@ fn fls_5_dtor_value() { } fn fls_6_no_dtor_does_not_zero_value() { - extern "system" fn later_dtor(val: *mut c_void) { - print_safe("fls_6_later_dtor\n"); + extern "system" fn later_dtor(val: *const c_void) { + eprintln!("fls_6_later_dtor"); // If an earlier fls slot doesn't have a dtor, the key's value is _not_ zeroed out. let early_key = val as u32; @@ -190,8 +158,8 @@ fn fls_6_no_dtor_does_not_zero_value() { fn fls_7_free() { // This dtor is not expected to be called. - extern "system" fn dtor_for_freed_key(_val: *mut c_void) { - print_safe("dtor_for_freed_key\n"); + extern "system" fn dtor_for_freed_key(_val: *const c_void) { + eprintln!("dtor_for_freed_key"); } let key_with_dtor = unsafe { FlsAlloc(Some(dtor_for_freed_key)) }; assert_eq!(unsafe { FlsSetValue(key_with_dtor, ptr::without_provenance_mut(0)) }, TRUE); @@ -222,7 +190,7 @@ fn the_test() { assert_eq!(unsafe { TlsFree(key) }, TRUE); fls(); - print_safe("exiting thread\n"); + eprintln!("exiting thread"); } fn main() { diff --git a/src/tools/miri/tests/pass/tls/windows-tls.with_exit.stdout b/src/tools/miri/tests/pass-dep/windows/tls.with_exit.stderr similarity index 100% rename from src/tools/miri/tests/pass/tls/windows-tls.with_exit.stdout rename to src/tools/miri/tests/pass-dep/windows/tls.with_exit.stderr diff --git a/src/tools/miri/tests/pass/tls/windows-tls.without_exit.stdout b/src/tools/miri/tests/pass-dep/windows/tls.without_exit.stderr similarity index 100% rename from src/tools/miri/tests/pass/tls/windows-tls.without_exit.stdout rename to src/tools/miri/tests/pass-dep/windows/tls.without_exit.stderr diff --git a/src/tools/miri/tests/pass/concurrency/apple-dispatch-semaphore.rs b/src/tools/miri/tests/pass/concurrency/apple-dispatch-semaphore.rs index 95df515abea00..3371695f554c9 100644 --- a/src/tools/miri/tests/pass/concurrency/apple-dispatch-semaphore.rs +++ b/src/tools/miri/tests/pass/concurrency/apple-dispatch-semaphore.rs @@ -81,7 +81,7 @@ fn main() { let res = dispatch_semaphore_wait(sem.ptr, timeout); assert_eq!(res, 49); // KERN_OPERATION_TIMED_OUT let elapsed_time = before_time.elapsed().as_millis(); - assert!(10 <= elapsed_time && elapsed_time <= 100); + assert!(10 <= elapsed_time && elapsed_time <= 200, "elapsed time: {elapsed_time}ms"); // Need to get the value back up to at least 1 before destroying it. // Higher values are also fine. diff --git a/src/tools/miri/tests/pass/concurrency/spawn_stack_size_too_large.rs b/src/tools/miri/tests/pass/concurrency/spawn_stack_size_too_large.rs new file mode 100644 index 0000000000000..23ddccbc34037 --- /dev/null +++ b/src/tools/miri/tests/pass/concurrency/spawn_stack_size_too_large.rs @@ -0,0 +1,13 @@ +//@ignore-target: windows # FIXME: `CreateThread` shim ignores the stack size +//@run-native + +use std::thread; + +fn main() { + // A stack this big can never be reserved, so spawning must fail instead of panicking. + let result = thread::Builder::new().stack_size(usize::MAX).spawn(|| {}); + assert!(result.is_err()); + + // A normal stack size still works. + thread::Builder::new().stack_size(1 << 20).spawn(|| {}).unwrap().join().unwrap(); +} diff --git a/src/tools/miri/tests/pass/float.rs b/src/tools/miri/tests/pass/float.rs index f94840f1ef246..babec9e9e770c 100644 --- a/src/tools/miri/tests/pass/float.rs +++ b/src/tools/miri/tests/pass/float.rs @@ -1063,6 +1063,7 @@ fn mul_add() { assert_eq!(f.to_bits(), f32::to_bits(-0.0)); } +// FIXME(f128): add tests when supported fn libm() { fn ldexp(a: f64, b: i32) -> f64 { extern "C" { @@ -1245,14 +1246,16 @@ fn libm() { let pi_f32 = f32_consts::PI; let pi_f64 = f64_consts::PI; for _ in 0..64 { - // sin() should be clamped to [-1, 1] so asin() can never return NaN - assert!(!halve_pi_f16.sin().asin().is_nan()); - assert!(!halve_pi_f32.sin().asin().is_nan()); - assert!(!halve_pi_f64.sin().asin().is_nan()); - // cos() should be clamped to [-1, 1] so acos() can never return NaN - assert!(!pi_f16.cos().acos().is_nan()); - assert!(!pi_f32.cos().acos().is_nan()); - assert!(!pi_f64.cos().acos().is_nan()); + // sin() should be clamped to [-1, 1] so asin() can never return NaN. + // asin() should itself be clamped to [-Ï€/2, Ï€/2]. + assert!((-halve_pi_f16..=halve_pi_f16).contains(&halve_pi_f16.sin().asin())); + assert!((-halve_pi_f32..=halve_pi_f32).contains(&halve_pi_f32.sin().asin())); + assert!((-halve_pi_f64..=halve_pi_f64).contains(&halve_pi_f64.sin().asin())); + // cos() should be clamped to [-1, 1] so acos() can never return NaN. + // acos() should itself be clamped to [0, Ï€]. + assert!((0.0..=pi_f16).contains(&pi_f16.cos().acos())); + assert!((0.0..=pi_f32).contains(&pi_f32.cos().acos())); + assert!((0.0..=pi_f64).contains(&pi_f64.cos().acos())); } assert_eq!(0f16.cos(), 1f16); @@ -1301,6 +1304,7 @@ fn libm() { // Associated items cannot be brought into scope with a `use`, hence the `const`s. const INFINITY: $float_type = <$float_type>::INFINITY; const NEG_INFINITY: $float_type = <$float_type>::NEG_INFINITY; + const NAN: $float_type = <$float_type>::NAN; // atan2(±0,−0) = ±π. assert_eq!($float_type::atan2(0.0, -0.0), PI, "atan2(0,−0) = Ï€"); @@ -1333,6 +1337,10 @@ fn libm() { // atan2(±∞, +∞) = ±π/4 assert_eq!($float_type::atan2(INFINITY, INFINITY), FRAC_PI_4, "atan2(+∞, +∞) = Ï€/4"); assert_eq!($float_type::atan2(NEG_INFINITY, INFINITY), -FRAC_PI_4, "atan2(-∞, +∞) = -Ï€/4"); + + // We should never mask a NaN though, which we used to get wrong. + assert!($float_type::atan2(NAN, NEG_INFINITY).is_nan()); + assert!($float_type::atan2(NAN, 0.0).is_nan()); }} } fixed_atan2_cases!(f16); @@ -1680,6 +1688,7 @@ fn test_non_determinism() { } fn test_operations_f128(a: f128, b: f128) { test_operations_f!(a, b); + // FIXME(f128): add more operations when supported } test_operations_f16(3., 5.); diff --git a/src/tools/miri/tests/pass/global_allocator.stdout b/src/tools/miri/tests/pass/global_allocator.default.stdout similarity index 100% rename from src/tools/miri/tests/pass/global_allocator.stdout rename to src/tools/miri/tests/pass/global_allocator.default.stdout diff --git a/src/tools/miri/tests/pass/global_allocator.rs b/src/tools/miri/tests/pass/global_allocator.rs index 788c58a3c54c0..a08811782e119 100644 --- a/src/tools/miri/tests/pass/global_allocator.rs +++ b/src/tools/miri/tests/pass/global_allocator.rs @@ -1,3 +1,6 @@ +//@revisions: default symbolic +//@[symbolic]compile-flags: -Zmiri-symbolic-alignment-check + #![feature(slice_ptr_get)] use std::alloc::{Allocator as _, Global, GlobalAlloc, Layout, System}; diff --git a/src/tools/miri/tests/pass/global_allocator.symbolic.stdout b/src/tools/miri/tests/pass/global_allocator.symbolic.stdout new file mode 100644 index 0000000000000..30c61946407c9 --- /dev/null +++ b/src/tools/miri/tests/pass/global_allocator.symbolic.stdout @@ -0,0 +1,2 @@ +Allocated! +Deallocated! diff --git a/src/tools/miri/tests/pass/heap_allocator.rs b/src/tools/miri/tests/pass/heap_allocator.rs index dcd8515ab99f6..e18a3c3ffe398 100644 --- a/src/tools/miri/tests/pass/heap_allocator.rs +++ b/src/tools/miri/tests/pass/heap_allocator.rs @@ -1,3 +1,6 @@ +//@revisions: default symbolic +//@[symbolic]compile-flags: -Zmiri-symbolic-alignment-check + #![feature(slice_ptr_get)] use std::alloc::{Allocator, Global, Layout, System}; diff --git a/src/tools/miri/tests/pass/intrinsics/portable-simd.rs b/src/tools/miri/tests/pass/intrinsics/portable-simd.rs index c16bc21636f78..c5b4e9a75faa7 100644 --- a/src/tools/miri/tests/pass/intrinsics/portable-simd.rs +++ b/src/tools/miri/tests/pass/intrinsics/portable-simd.rs @@ -21,6 +21,10 @@ use std::ptr; use std::simd::StdFloat; use std::simd::prelude::*; +#[path = "../../utils/mod.rs"] +mod utils; +use utils::check_nondet; + // small hack to make type inference better macro_rules! assert_eq { ($a:expr, $b:expr $(,$t:tt)* $(,)?) => {{ @@ -147,6 +151,22 @@ fn test_simd_ops_f16() { assert_eq!(simd_reduce_min(f16x2::from_array([0.0, f16::NAN])), 0.0f16); assert_eq!(simd_reduce_min(f16x2::from_array([f16::NAN, 0.0])), 0.0f16); } + + // Ensure we do use non-deterministic NaN generation. + // Non-determinism tests do not make sense natively. + if cfg!(miri) { + let a = f16x2::splat(0.0); + let b = f16x2::splat(0.0); + let nan = f16x2::splat(f16::NAN); + check_nondet(|| { + let result = a / b; + result[0].to_bits() == result[1].to_bits() + }); + check_nondet(|| { + let result = a + nan; + result[0].to_bits() == result[1].to_bits() + }); + } } fn test_simd_ops_f32() { @@ -221,6 +241,22 @@ fn test_simd_ops_f32() { assert_eq!(simd_reduce_min(f32x2::from_array([0.0, f32::NAN])), 0.0f32); assert_eq!(simd_reduce_min(f32x2::from_array([f32::NAN, 0.0])), 0.0f32); } + + // Ensure we do use non-deterministic NaN generation. + // Non-determinism tests do not make sense natively. + if cfg!(miri) { + let a = f32x2::splat(0.0); + let b = f32x2::splat(0.0); + let nan = f32x2::splat(f32::NAN); + check_nondet(|| { + let result = a / b; + result[0].to_bits() == result[1].to_bits() + }); + check_nondet(|| { + let result = a + nan; + result[0].to_bits() == result[1].to_bits() + }); + } } fn test_simd_ops_f64() { @@ -295,6 +331,22 @@ fn test_simd_ops_f64() { assert_eq!(simd_reduce_min(f64x2::from_array([0.0, f64::NAN])), 0.0f64); assert_eq!(simd_reduce_min(f64x2::from_array([f64::NAN, 0.0])), 0.0f64); } + + // Ensure we do use non-deterministic NaN generation. + // Non-determinism tests do not make sense natively. + if cfg!(miri) { + let a = f64x2::splat(0.0); + let b = f64x2::splat(0.0); + let nan = f64x2::splat(f64::NAN); + check_nondet(|| { + let result = a / b; + result[0].to_bits() == result[1].to_bits() + }); + check_nondet(|| { + let result = a + nan; + result[0].to_bits() == result[1].to_bits() + }); + } } #[cfg(any(miri, target_has_reliable_f128_math))] @@ -382,6 +434,22 @@ fn test_simd_ops_f128() { assert_eq!(simd_reduce_min(f128x2::from_array([0.0, f128::NAN])), 0.0f128); assert_eq!(simd_reduce_min(f128x2::from_array([f128::NAN, 0.0])), 0.0f128); } + + // Ensure we do use non-deterministic NaN generation. + // Non-determinism tests do not make sense natively. + if cfg!(miri) { + let a = f128x2::splat(0.0); + let b = f128x2::splat(0.0); + let nan = f128x2::splat(f128::NAN); + check_nondet(|| { + let result = simd_div(a, b).into_array(); + result[0].to_bits() == result[1].to_bits() + }); + check_nondet(|| { + let result = simd_add(a, nan).into_array(); + result[0].to_bits() == result[1].to_bits() + }); + } } } @@ -984,17 +1052,24 @@ fn test_simd_intrinsics() { } fn test_simd_float_intrinsics() { + if !cfg!(miri) { + // The non-determinism tests don't work natively. + return; + } + // These are just smoke tests to ensure the intrinsics can be called. unsafe { - let a = f16x8::splat(10.0); + let a = f16x2::splat(10.0); simd_fsqrt(a); - simd_fsin(a); - simd_fcos(a); - simd_fexp(a); - simd_fexp2(a); - simd_flog(a); - simd_flog2(a); - simd_flog10(a); + // These ones are non-deterministic. + let elems_eq = |x: f16x2| x[0] == x[1]; + check_nondet(|| elems_eq(simd_fsin(a))); + check_nondet(|| elems_eq(simd_fcos(a))); + check_nondet(|| elems_eq(simd_fexp(a))); + check_nondet(|| elems_eq(simd_fexp2(a))); + check_nondet(|| elems_eq(simd_flog(a))); + check_nondet(|| elems_eq(simd_flog2(a))); + check_nondet(|| elems_eq(simd_flog10(a))); } unsafe { diff --git a/src/tools/miri/tests/pass/miri_start_with_std.rs b/src/tools/miri/tests/pass/miri_start_with_std.rs index 510b9d4196226..e58f3746b6ce1 100644 --- a/src/tools/miri/tests/pass/miri_start_with_std.rs +++ b/src/tools/miri/tests/pass/miri_start_with_std.rs @@ -1,7 +1,11 @@ #![no_main] #[no_mangle] -fn miri_start(_argc: isize, _argv: *const *const u8) -> isize { +fn miri_start(argc: isize, argv: *const *const u8) -> isize { + // Ensure argument array is null-terminated. + assert!(unsafe { (*argv.add(argc as usize)).is_null() }); + + // Ensure basic std functionality works. let _b = Box::new(0); println!("hello, world!"); 0 diff --git a/src/tools/miri/tests/pass/shims/fs.rs b/src/tools/miri/tests/pass/shims/fs.rs index bd2758b663df2..5c79ab3af4390 100644 --- a/src/tools/miri/tests/pass/shims/fs.rs +++ b/src/tools/miri/tests/pass/shims/fs.rs @@ -64,6 +64,7 @@ fn main() { } // Windows file handling is very incomplete. if cfg!(not(windows)) || cfg!(not(miri)) { + test_append(); test_fs_set_permissions(); test_file_set_permissions(); @@ -261,6 +262,31 @@ fn test_seek() { remove_file(&path).unwrap(); } +fn test_append() { + let bytes = b"Hello"; + let path = utils::prepare_with_content("miri_test_fs_append.txt", bytes); + + let mut file = OpenOptions::new().append(true).open(&path).unwrap(); + file.write_all(b" World").unwrap(); + file.seek(SeekFrom::Start(0)).unwrap(); + file.write_all(b"!\n").unwrap(); + drop(file); + assert_eq!(fs::read(&path).unwrap(), b"Hello World!\n"); + + // Also try combining this with reading. + let mut file = OpenOptions::new().read(true).append(true).open(&path).unwrap(); + let mut buf = [0u8; 2]; + file.read_exact(&mut buf).unwrap(); + assert_eq!(&buf, b"He"); + file.write_all(b"Next?").unwrap(); + file.seek(SeekFrom::Current(-6)).unwrap(); + file.read_exact(&mut buf).unwrap(); + assert_eq!(&buf, b"\nN"); + drop(file); + + remove_file(&path).unwrap(); +} + fn check_metadata(bytes: &[u8], path: &Path) -> Result<()> { // Test that the file metadata is correct. let metadata = path.metadata()?; @@ -845,8 +871,17 @@ fn test_directory_handle() { .unwrap_err(); assert_eq!(err.kind(), ErrorKind::AlreadyExists); - fs::create_dir(dirname.join("subdir")).unwrap(); - let _subdir = dir.open_dir("subdir").unwrap(); + dir.create_dir("subdir").unwrap(); + let subdir = dir.open_dir("subdir").unwrap(); + + // Delete subdir. + // Close the handles first, Windows hosts may refuse to remove things that are still open. + drop(file); + drop(subdir); + dir.remove_file("file.txt").unwrap(); + assert!(!filename.exists()); + dir.remove_dir("subdir").unwrap(); + assert!(!dirname.join("subdir").exists()); } fn test_fs_set_permissions() { diff --git a/src/tools/miri/tests/pass/shims/socket-tcp.rs b/src/tools/miri/tests/pass/shims/socket-tcp.rs index 13de45a6a7b09..9e692cb4e02fa 100644 --- a/src/tools/miri/tests/pass/shims/socket-tcp.rs +++ b/src/tools/miri/tests/pass/shims/socket-tcp.rs @@ -230,14 +230,22 @@ fn test_sockopt_read_timeout() { // By default, reads on blocking sockets should block indefinitely. assert_eq!(stream.read_timeout().unwrap(), None); - let short_read_timeout = Some(Duration::from_millis(40)); - stream.set_read_timeout(short_read_timeout).unwrap(); - assert_eq!(stream.read_timeout().unwrap(), short_read_timeout); + let short_read_timeout = Duration::from_millis(40); + stream.set_read_timeout(Some(short_read_timeout)).unwrap(); + assert_eq!(stream.read_timeout().unwrap(), Some(short_read_timeout)); let mut buffer = [0u8; 128]; + let before = Instant::now(); // This should not block indefinitely and instead return EAGAIN/EWOULDBLOCK. let err = stream.read(&mut buffer).unwrap_err(); assert_eq!(err.kind(), ErrorKind::WouldBlock); + // Ensure that we blocked at least for `short_read_timeout`. The upper bound on the + // blocking time is pessimistic to account for slow CI runners. + let duration = before.elapsed(); + assert!( + duration >= short_read_timeout && duration < short_read_timeout * 20, + "operation blocked for {duration:?}" + ); } /// Test setting and reading the RCVTIMEO socket option. @@ -253,21 +261,29 @@ fn test_sockopt_write_timeout() { // By default, writes on blocking sockets should block indefinitely. assert_eq!(stream.write_timeout().unwrap(), None); - let short_write_timeout = Some(Duration::from_millis(40)); - stream.set_write_timeout(short_write_timeout).unwrap(); - assert_eq!(stream.write_timeout().unwrap(), short_write_timeout); + let short_write_timeout = Duration::from_millis(40); + stream.set_write_timeout(Some(short_write_timeout)).unwrap(); + assert_eq!(stream.write_timeout().unwrap(), Some(short_write_timeout)); let fill_buffer = [1u8; 1024]; - loop { + let before = loop { + let before = Instant::now(); match stream.write_all(&fill_buffer) { Ok(_) => { /* continue to fill up buffer */ } // When we get an EAGAIN/EWOULDBLOCK when writing into a blocking socket, // we know it's because of the write timeout exceeding because the write // buffer is full. - Err(err) if err.kind() == ErrorKind::WouldBlock => break, + Err(err) if err.kind() == ErrorKind::WouldBlock => break before, Err(err) => panic!("unexpected error whilst filling up buffer: {err}"), } - } + }; + // Ensure that we blocked at least for `short_write_timeout`. The upper bound on the + // blocking time is pessimistic to account for slow CI runners. + let duration = before.elapsed(); + assert!( + duration >= short_write_timeout && duration < short_write_timeout * 20, + "operation blocked for {duration:?}" + ); } /// Test setting and reading the SO_LINGER socket option. diff --git a/src/tools/miri/tests/pass/shims/socket-udp-no-blocking.rs b/src/tools/miri/tests/pass/shims/socket-udp-no-blocking.rs new file mode 100644 index 0000000000000..92eb38cae4768 --- /dev/null +++ b/src/tools/miri/tests/pass/shims/socket-udp-no-blocking.rs @@ -0,0 +1,41 @@ +//@ignore-target: windows # No libc socket on Windows +//@compile-flags: -Zmiri-disable-isolation + +use std::io::ErrorKind; +use std::net::UdpSocket; + +const TEST_BYTES: &[u8] = b"these are some test bytes!"; + +fn main() { + test_send_recv_nonblock(); +} + +/// Test sending bytes into one UDP socket and receiving them from another UDP socket +/// without blocking. +fn test_send_recv_nonblock() { + let sock_rx = UdpSocket::bind("127.0.0.1:0").unwrap(); + sock_rx.set_nonblocking(true).unwrap(); + + let sock_tx = UdpSocket::bind("127.0.0.1:0").unwrap(); + sock_tx.set_nonblocking(true).unwrap(); + + // Get local address with randomized port to know where + // we need to send the bytes to. + let address_rx = sock_rx.local_addr().unwrap(); + + // Set the default destination address of the transmitting UDP socket + // to the address where the receiving UDP socket is bound to. + sock_tx.connect(address_rx).unwrap(); + + let mut buffer = [0u8; 1024]; + // Receiving when no data is available should fail with EWOULDBLOCK. + let err = sock_rx.recv(&mut buffer).unwrap_err(); + assert_eq!(err.kind(), ErrorKind::WouldBlock); + + let bytes_sent = sock_tx.send(TEST_BYTES).unwrap(); + assert_eq!(bytes_sent, TEST_BYTES.len()); + + let bytes_received = sock_rx.recv(&mut buffer).unwrap(); + assert_eq!(bytes_received, TEST_BYTES.len()); + assert_eq!(&buffer[0..bytes_received], TEST_BYTES); +} diff --git a/src/tools/miri/tests/pass/shims/socket-udp.rs b/src/tools/miri/tests/pass/shims/socket-udp.rs index bd4e8aee28321..2490d6db50298 100644 --- a/src/tools/miri/tests/pass/shims/socket-udp.rs +++ b/src/tools/miri/tests/pass/shims/socket-udp.rs @@ -2,13 +2,19 @@ //@compile-flags: -Zmiri-disable-isolation //@run-native +use std::io::ErrorKind; use std::net::UdpSocket; -use std::time::Duration; +use std::thread; +use std::time::{Duration, Instant}; + +const TEST_BYTES: &[u8] = b"these are some test bytes!"; fn main() { test_create_ipv4(); test_create_ipv6(); test_connect(); + test_read_write(); + test_peek(); test_sockopt_ttl(); test_sockopt_read_timeout(); test_sockopt_write_timeout(); @@ -28,6 +34,67 @@ fn test_connect() { socket.connect("127.0.1.1:8080").unwrap() } +/// Test reading and writing into two connected sockets and ensuring +/// that the other side receives the correct bytes. +fn test_read_write() { + let tx_socket = UdpSocket::bind("127.0.0.1:0").unwrap(); + let rx_socket = UdpSocket::bind("127.0.0.1:0").unwrap(); + + // Get local address with randomized port to know where we + // need to send the data to. + let address = rx_socket.local_addr().unwrap(); + + // Set the default destination address of the transmitting socket + // to the address of the receiving socket. + tx_socket.connect(address).unwrap(); + + let handle = thread::spawn(move || { + let bytes_sent = tx_socket.send(TEST_BYTES).unwrap(); + assert_eq!(bytes_sent, TEST_BYTES.len()); + }); + + let mut buffer = [0; TEST_BYTES.len()]; + let bytes_received = rx_socket.recv(&mut buffer).unwrap(); + assert_eq!(bytes_received, TEST_BYTES.len()); + assert_eq!(&buffer, TEST_BYTES); + + handle.join().unwrap(); +} + +/// Test that peeking on a receiving socket doesn't remove the bytes +/// from the queue. +fn test_peek() { + let tx_socket = UdpSocket::bind("127.0.0.1:0").unwrap(); + let rx_socket = UdpSocket::bind("127.0.0.1:0").unwrap(); + + // Get local address with randomized port to know where we + // need to send the data to. + let address = rx_socket.local_addr().unwrap(); + + // Set the default destination address of the transmitting socket + // to the address of the receiving socket. + tx_socket.connect(address).unwrap(); + + let handle = thread::spawn(move || { + let bytes_sent = tx_socket.send(TEST_BYTES).unwrap(); + assert_eq!(bytes_sent, TEST_BYTES.len()); + }); + + let mut buffer = [0; TEST_BYTES.len()]; + let bytes_peeked = rx_socket.peek(&mut buffer).unwrap(); + assert_eq!(bytes_peeked, TEST_BYTES.len()); + assert_eq!(&buffer, &TEST_BYTES); + + // Since the peek shouldn't remove the bytes from the queue, + // we should be able to read them again. + let mut buffer = [0; TEST_BYTES.len()]; + let bytes_received = rx_socket.recv(&mut buffer).unwrap(); + assert_eq!(bytes_received, TEST_BYTES.len()); + assert_eq!(&buffer, TEST_BYTES); + + handle.join().unwrap(); +} + // Test setting and reading the TTL socket option. fn test_sockopt_ttl() { let socket = UdpSocket::bind("127.0.0.1:0").unwrap(); @@ -44,18 +111,22 @@ fn test_sockopt_read_timeout() { // By default, reads on blocking sockets should block indefinitely. assert_eq!(socket.read_timeout().unwrap(), None); - let short_read_timeout = Some(Duration::from_millis(40)); - socket.set_read_timeout(short_read_timeout).unwrap(); - assert_eq!(socket.read_timeout().unwrap(), short_read_timeout); - - /* - TODO: Once UDP sockets support reading. + let short_read_timeout = Duration::from_millis(40); + socket.set_read_timeout(Some(short_read_timeout)).unwrap(); + assert_eq!(socket.read_timeout().unwrap(), Some(short_read_timeout)); let mut buffer = [0u8; 128]; + let before = Instant::now(); // This should not block indefinitely and instead return EAGAIN/EWOULDBLOCK. - let err = socket.read(&mut buffer).unwrap_err(); + let err = socket.recv(&mut buffer).unwrap_err(); assert_eq!(err.kind(), ErrorKind::WouldBlock); - */ + // Ensure that we blocked at least for `short_read_timeout`. The upper bound on the + // blocking time is pessimistic to account for slow CI runners. + let duration = before.elapsed(); + assert!( + duration >= short_read_timeout && duration < short_read_timeout * 20, + "operation blocked for {duration:?}" + ); } /// Test setting and reading the RCVTIMEO socket option. @@ -71,19 +142,8 @@ fn test_sockopt_write_timeout() { socket.set_write_timeout(short_write_timeout).unwrap(); assert_eq!(socket.write_timeout().unwrap(), short_write_timeout); - /* - TODO: Once UDP sockets support writing. - - let fill_buffer = [1u8; 1024]; - loop { - match socket.write_all(&fill_buffer) { - Ok(_) => { /* continue to fill up buffer */ } - // When we get an EAGAIN/EWOULDBLOCK when writing into a blocking socket, - // we know it's because of the write timeout exceeding because the write - // buffer is full. - Err(err) if err.kind() == ErrorKind::WouldBlock => break, - Err(err) => panic!("unexpected error whilst filling up buffer: {err}"), - } - } - */ + // We cannot test "filling up" the UDP socket buffer since UDP is unreliable. + // This means the kernel can report to us that it sent the entire datagram but + // on the receiving end it just gets discarded should the buffer be full without + // notifying the sender. } diff --git a/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx.rs b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx.rs index 8709a17e8aeb4..8811737487e12 100644 --- a/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx.rs +++ b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx.rs @@ -474,6 +474,17 @@ unsafe fn test_avx() { let r = _mm256_dp_ps::<0xFF>(a, b); let e = _mm256_setr_ps(200., 200., 200., 200., 2387., 2387., 2387., 2387.); assert_eq_m256(r, e); + + // Each 128-bit half has its own reduction and uses the same masks. + let a = _mm256_setr_ps(1e20, 1.0, -1e20, 1.0, -0.0, -0.0, -0.0, -0.0); + let b = _mm256_set1_ps(1.0); + let r: [u32; 8] = transmute(_mm256_dp_ps::<0xff>(a, b)); + let neg_zero = (-0.0f32).to_bits(); + assert_eq!(r, [0, 0, 0, 0, neg_zero, neg_zero, neg_zero, neg_zero]); + let r: [u32; 8] = transmute(_mm256_dp_ps::<0xf5>(a, b)); + assert_eq!(r, [0, 0, 0, 0, neg_zero, 0, neg_zero, 0]); + let r: [f32; 8] = transmute(_mm256_dp_ps::<0x2f>(a, b)); + assert_eq!(r.map(f32::to_bits), [1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0].map(f32::to_bits)); } test_mm256_dp_ps(); diff --git a/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx2.rs b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx2.rs index f75eae9fd8d25..6c52437657ef4 100644 --- a/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx2.rs +++ b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx2.rs @@ -632,6 +632,14 @@ unsafe fn test_avx2() { // A multiplier of 4 is word-addressing let r = _mm_i64gather_epi32::<4>(arr.as_ptr(), _mm_setr_epi64x(0, 16)); assert_eq_m128i(r, _mm_setr_epi32(0, 16, 0, 0)); + + let arr: [i32; 128] = core::array::from_fn(|i| i as i32); + // `offset * scale` overflows and wraps around to 16 * 4 and 32 * 4 + let r = _mm_i64gather_epi32::<4>( + arr.as_ptr(), + _mm_setr_epi64x(i64::MIN + 16, i64::MIN / 2 + 32), + ); + assert_eq_m128i(r, _mm_setr_epi32(16, 32, 0, 0)); } test_mm_i64gather_epi32(); diff --git a/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx512.rs b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx512.rs index 2c05fdbd3a21d..530e5736ef49b 100644 --- a/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx512.rs +++ b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx512.rs @@ -38,7 +38,7 @@ fn main() { } } -#[target_feature(enable = "avx512f")] +#[target_feature(enable = "avx512bw")] unsafe fn test_avx512_shifts() { let a = transmute([1u64, u64::MAX, u64::MAX, u64::MAX, u64::MAX, u64::MAX, u64::MAX, u64::MAX]); let counts = transmute([0u64, 1, 63, 64, 65, 256, 1 << 32, u64::MAX]); @@ -50,6 +50,115 @@ unsafe fn test_avx512_shifts() { transmute::<_, [u64; 8]>(_mm512_srlv_epi64(a, counts)), [1, u64::MAX >> 1, 1, 0, 0, 0, 0, 0], ); + + // Test large (greater than u32::MAX) shift values for 64-bit arithmetic shifts. + // Only the lowest 64bits of this matter: this is a shift by (2^48). + let shift = _mm_set_epi64x(0, 1 << 48); + let values = _mm_set_epi64x(-100, 100); + assert_eq!(transmute::<_, [i64; 2]>(_mm_sra_epi64(values, shift)), [0i64, -1]); + + // Only the lowest 64 bits of this matter: this is a shift by 4. + let shift = _mm_set_epi64x(0, 4); + + // Test _mm_sra_epi64. + let values = _mm_set_epi64x(-32, -16); + assert_eq!(transmute::<_, [i64; 2]>(_mm_sra_epi64(values, shift)), [-1i64, -2]); + + // Test _mm256_sra_epi64. + let values = _mm256_setr_epi64x(-16, -32, -64, -128); + assert_eq!(transmute::<_, [i64; 4]>(_mm256_sra_epi64(values, shift)), [-1i64, -2, -4, -8]); + + // Test _mm512_{sll, srl, sra}_epi64. + let values = _mm512_setr_epi64(1, 2, 4, 8, 16, 32, 64, 128); + assert_eq!( + transmute::<_, [u64; 8]>(_mm512_sll_epi64(values, shift)), + [16u64, 32, 64, 128, 256, 512, 1024, 2048], + ); + let values = _mm512_setr_epi64(1, 2, 4, 8, 16, 32, 64, 128); + assert_eq!( + transmute::<_, [u64; 8]>(_mm512_srl_epi64(values, shift)), + [0u64, 0, 0, 0, 1, 2, 4, 8], + ); + let values = _mm512_setr_epi64(-1, -2, -4, -8, -16, -32, -64, -128); + assert_eq!( + transmute::<_, [i64; 8]>(_mm512_sra_epi64(values, shift)), + [-1i64, -1, -1, -1, -1, -2, -4, -8], + ); + + // Only the lowest 64 bits of this matter: this is a shift by 2. + let shift = _mm_set_epi64x(0, 2); + + // Test _mm512_{sll, srl, sra}_epi32 + #[rustfmt::skip] + let values = _mm512_setr_epi32( + 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + ); + assert_eq!( + transmute::<_, [u32; 16]>(_mm512_sll_epi32(values, shift)), + [0u32, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60], + ); + #[rustfmt::skip] + let values = _mm512_setr_epi32( + 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + ); + assert_eq!( + transmute::<_, [u32; 16]>(_mm512_srl_epi32(values, shift)), + [0u32, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3], + ); + #[rustfmt::skip] + let values = _mm512_setr_epi32( + 0, 1, 2, 3, 4, 5, 6, 7, + -1, -2, -4, -8, -16, -32, -64, -128, + ); + assert_eq!( + transmute::<_, [i32; 16]>(_mm512_sra_epi32(values, shift)), + [0i32, 0, 0, 0, 1, 1, 1, 1, -1, -1, -1, -2, -4, -8, -16, -32], + ); + + // Test _mm512_{sll, srl, sra}_epi16 + #[rustfmt::skip] + let values = _mm512_set_epi16( + 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, + 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, + ); + #[rustfmt::skip] + assert_eq!( + transmute::<_, [u16; 32]>(_mm512_sll_epi16(values, shift)), + [ + 0u16, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, + 64, 68, 72, 76, 80, 84, 88, 92, 96, 100, 104, 108, 112, 116, 120, 124, + ], + ); + #[rustfmt::skip] + let values = _mm512_set_epi16( + 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, + 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, + ); + #[rustfmt::skip] + assert_eq!( + transmute::<_, [u16; 32]>(_mm512_srl_epi16(values, shift)), + [ + 0u16, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, + 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, + ], + ); + #[rustfmt::skip] + let values = _mm512_set_epi16( + -1, -16384, -8192, -4096, -2048, -1024, -512, -256, + 15, 14, 13, 12, 11, 10, 9, 8, + -128, -64, -32, -16, -8, -4, -2, -1, + 7, 6, 5, 4, 3, 2, 1, 0, + ); + #[rustfmt::skip] + assert_eq!( + transmute::<_, [i16; 32]>(_mm512_sra_epi16(values, shift)), + [ + 0i16, 0, 0, 0, 1, 1, 1, 1, -1, -1, -1, -2, -4, -8, -16, -32, + 2i16, 2, 2, 2, 3, 3, 3, 3, -64, -128, -256, -512, -1024, -2048, -4096, -1, + ], + ); } #[target_feature(enable = "avx512f")] diff --git a/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-sse41.rs b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-sse41.rs index 48510b46ff327..994b785db3a45 100644 --- a/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-sse41.rs +++ b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-sse41.rs @@ -54,6 +54,17 @@ unsafe fn test_sse41() { let b = _mm_setr_pd(1.0, 4.0); let e = _mm_setr_pd(14.0, 0.0); assert_eq_m128d(_mm_dp_pd::<0b00110001>(a, b), e); + + let a = _mm_set1_pd(-0.0); + let b = _mm_set1_pd(1.0); + // Bits 7:6 and 3:2 are ignored; no extra zeros may enter the sum. + let r: [u64; 2] = transmute(_mm_dp_pd::<0xff>(a, b)); + assert_eq!(r, [(-0.0f64).to_bits(); 2]); + let r: [u64; 2] = transmute(_mm_dp_pd::<0x31>(a, b)); + assert_eq!(r, [(-0.0f64).to_bits(), 0]); + // A masked-out product contributes +0.0. + let r: [u64; 2] = transmute(_mm_dp_pd::<0x13>(a, b)); + assert_eq!(r, [0; 2]); } test_mm_dp_pd(); @@ -63,6 +74,29 @@ unsafe fn test_sse41() { let b = _mm_setr_ps(1.0, 4.0, 0.5, 10.0); let e = _mm_setr_ps(14.5, 0.0, 14.5, 0.0); assert_eq_m128(_mm_dp_ps::<0b01110101>(a, b), e); + + // Adjacent pairs are added first, with rounding at each step. + let b = _mm_set1_ps(1.0); + for a in [_mm_setr_ps(1e20, 1.0, -1e20, 1.0), _mm_setr_ps(1.0, 1e20, 1.0, -1e20)] { + let r: [u32; 4] = transmute(_mm_dp_ps::<0xff>(a, b)); + assert_eq!(r, [0; 4]); + } + + let a = _mm_set1_ps(-0.0); + let r: [u32; 4] = transmute(_mm_dp_ps::<0xff>(a, b)); + assert_eq!(r, [(-0.0f32).to_bits(); 4]); + let r: [u32; 4] = transmute(_mm_dp_ps::<0xf5>(a, b)); + assert_eq!(r, [(-0.0f32).to_bits(), 0, (-0.0f32).to_bits(), 0]); + let r: [u32; 4] = transmute(_mm_dp_ps::<0x7f>(a, b)); + assert_eq!(r, [0; 4]); + + // Masked-out products and destination lanes are +0.0, even for NaNs. + let a = _mm_setr_ps(f32::NAN, 2.0, f32::INFINITY, 3.0); + assert_eq_m128(_mm_dp_ps::<0xaf>(a, b), _mm_set1_ps(5.0)); + let r: [u32; 4] = transmute(_mm_dp_ps::<0x0f>(a, b)); + assert_eq!(r, [0; 4]); + let r: [u32; 4] = transmute(_mm_dp_ps::<0xf0>(a, b)); + assert_eq!(r, [0; 4]); } test_mm_dp_ps(); diff --git a/src/tools/miri/tests/pass/tls/win_thread_atexit.rs b/src/tools/miri/tests/pass/tls/win_thread_atexit.rs index 65fd24d65b7b9..377ef4e5db4df 100644 --- a/src/tools/miri/tests/pass/tls/win_thread_atexit.rs +++ b/src/tools/miri/tests/pass/tls/win_thread_atexit.rs @@ -4,33 +4,13 @@ // run-native does not work properly. It randomly sometimes calls the hook 3 times. I guess there's // sometimes another thread appearing from somewhere. -// Printing without touching the Rust runtime. -fn print_safe(msg: &str) { - use std::io::Write; - use std::os::windows::io::FromRawHandle; - use std::{ffi, fs, mem}; - - pub const STD_OUTPUT_HANDLE: u32 = 4294967285; - - #[link(name = "kernel32")] - unsafe extern "system" { - fn GetStdHandle(which: u32) -> *mut ffi::c_void; - } - - unsafe { - let handle = GetStdHandle(STD_OUTPUT_HANDLE); - let mut handle = mem::ManuallyDrop::new(fs::File::from_raw_handle(handle)); - handle.write_all(msg.as_bytes()).unwrap(); - } -} - #[link_section = ".CRT$XLB"] #[used] // Miri only considers explicitly `#[used]` statics for `lookup_link_section` pub static CALLBACK: unsafe extern "system" fn(*const (), u32, *const ()) = tls_callback; unsafe extern "system" fn tls_callback(_h: *const (), _dw_reason: u32, _pv: *const ()) { // Do not call into std as it has already been shut down. That means we cannot run natively. - print_safe("in tls_callback\n"); + eprintln!("in tls_callback"); } fn main() { diff --git a/src/tools/miri/tests/pass/tls/win_thread_atexit.with_exit.stdout b/src/tools/miri/tests/pass/tls/win_thread_atexit.with_exit.stderr similarity index 100% rename from src/tools/miri/tests/pass/tls/win_thread_atexit.with_exit.stdout rename to src/tools/miri/tests/pass/tls/win_thread_atexit.with_exit.stderr diff --git a/src/tools/miri/tests/pass/tls/win_thread_atexit.without_exit.stdout b/src/tools/miri/tests/pass/tls/win_thread_atexit.without_exit.stderr similarity index 100% rename from src/tools/miri/tests/pass/tls/win_thread_atexit.without_exit.stdout rename to src/tools/miri/tests/pass/tls/win_thread_atexit.without_exit.stderr diff --git a/src/tools/miri/tests/utils/libc.rs b/src/tools/miri/tests/utils/libc.rs index acfc301923427..f865fb7a2975f 100644 --- a/src/tools/miri/tests/utils/libc.rs +++ b/src/tools/miri/tests/utils/libc.rs @@ -315,10 +315,12 @@ pub mod net { } } - /// Create an IPv4 TCP socket which listens on a random port at the localhost address. - /// Returns the socket file descriptor and the actual socket address the socket is listening on. - pub fn make_listener_ipv4() -> io::Result<(libc::c_int, libc::sockaddr_in)> { - let sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0))? }; + /// Create an IPv4 socket of type `socket_type` which is bound to a random port on the local interface. + /// Returns the socket file descriptor and the actual socket address the socket is bound to. + pub fn make_local_ipv4( + socket_type: libc::c_int, + ) -> io::Result<(libc::c_int, libc::sockaddr_in)> { + let sockfd = unsafe { errno_result(libc::socket(libc::AF_INET, socket_type, 0))? }; // Turn address into socket address with a random free port. let addr = sock_addr_ipv4(IPV4_LOCALHOST, 0); unsafe { @@ -329,10 +331,6 @@ pub mod net { ))?; } - unsafe { - errno_result(libc::listen(sockfd, 16))?; - } - // Retrieve actual listener address because we used a randomized port. let (_, addr_with_port) = sockname_ipv4(|storage, len| unsafe { libc::getsockname(sockfd, storage, len) })?; @@ -340,10 +338,22 @@ pub mod net { Ok((sockfd, addr_with_port)) } - /// Create an IPv6 TCP socket which listens on a random port at the localhost address. + /// Create an IPv4 TCP socket which listens on a random port at the localhost address. /// Returns the socket file descriptor and the actual socket address the socket is listening on. - pub fn make_listener_ipv6() -> io::Result<(libc::c_int, libc::sockaddr_in6)> { - let sockfd = unsafe { errno_result(libc::socket(libc::AF_INET6, libc::SOCK_STREAM, 0))? }; + pub fn make_tcp_listener_ipv4() -> io::Result<(libc::c_int, libc::sockaddr_in)> { + let (sockfd, addr_with_port) = make_local_ipv4(libc::SOCK_STREAM)?; + + unsafe { errno_result(libc::listen(sockfd, 16))? }; + + Ok((sockfd, addr_with_port)) + } + + /// Create an IPv6 socket of type `socket_type` which is bound to a random port on the local interface. + /// Returns the socket file descriptor and the actual socket address the socket is bound to. + pub fn make_local_ipv6( + socket_type: libc::c_int, + ) -> io::Result<(libc::c_int, libc::sockaddr_in6)> { + let sockfd = unsafe { errno_result(libc::socket(libc::AF_INET6, socket_type, 0))? }; // Turn address into socket address with a random free port. let addr = sock_addr_ipv6(IPV6_LOCALHOST, 0); unsafe { @@ -354,10 +364,6 @@ pub mod net { ))?; } - unsafe { - errno_result(libc::listen(sockfd, 16))?; - } - // Retrieve actual listener address because we used a randomized port. let (_, addr_with_port) = sockname_ipv6(|storage, len| unsafe { libc::getsockname(sockfd, storage, len) })?; @@ -365,6 +371,16 @@ pub mod net { Ok((sockfd, addr_with_port)) } + /// Create an IPv6 TCP socket which listens on a random port at the localhost address. + /// Returns the socket file descriptor and the actual socket address the socket is listening on. + pub fn make_tcp_listener_ipv6() -> io::Result<(libc::c_int, libc::sockaddr_in6)> { + let (sockfd, addr_with_port) = make_local_ipv6(libc::SOCK_STREAM)?; + + unsafe { errno_result(libc::listen(sockfd, 16))? }; + + Ok((sockfd, addr_with_port)) + } + /// Accept an incoming IPv4 connection. pub fn accept_ipv4(sockfd: libc::c_int) -> io::Result<(libc::c_int, libc::sockaddr_in)> { sockname_ipv4(|storage, len| unsafe { libc::accept(sockfd, storage, len) }) @@ -456,9 +472,10 @@ pub mod net { /// Wraps a call to a platform function that returns an IPv4 socket address. /// Returns a tuple containing the actual return value of the performed /// syscall and the written address of it. - pub fn sockname_ipv4(f: F) -> io::Result<(libc::c_int, libc::sockaddr_in)> + pub fn sockname_ipv4(f: F) -> io::Result<(V, libc::sockaddr_in)> where - F: FnOnce(*mut libc::sockaddr, *mut libc::socklen_t) -> libc::c_int, + F: FnOnce(*mut libc::sockaddr, *mut libc::socklen_t) -> V, + V: From + Ord, { let (result, addr) = sockname(f)?; let LibcSocketAddr::V4(addr) = addr else { panic!("expected IPv4 address") }; @@ -469,9 +486,10 @@ pub mod net { /// Wraps a call to a platform function that returns an IPv6 socket address. /// Returns a tuple containing the actual return value of the performed /// syscall and the written address of it. - pub fn sockname_ipv6(f: F) -> io::Result<(libc::c_int, libc::sockaddr_in6)> + pub fn sockname_ipv6(f: F) -> io::Result<(V, libc::sockaddr_in6)> where - F: FnOnce(*mut libc::sockaddr, *mut libc::socklen_t) -> libc::c_int, + F: FnOnce(*mut libc::sockaddr, *mut libc::socklen_t) -> V, + V: From + Ord, { let (result, addr) = sockname(f)?; let LibcSocketAddr::V6(addr) = addr else { panic!("expected IPv6 address") }; @@ -489,9 +507,10 @@ pub mod net { /// standard library implementation. /// Returns a tuple containing the actual return value of the performed /// syscall and the written address of it. - fn sockname(f: F) -> io::Result<(libc::c_int, LibcSocketAddr)> + fn sockname(f: F) -> io::Result<(V, LibcSocketAddr)> where - F: FnOnce(*mut libc::sockaddr, *mut libc::socklen_t) -> libc::c_int, + F: FnOnce(*mut libc::sockaddr, *mut libc::socklen_t) -> V, + V: From + Ord, { let mut storage = std::mem::MaybeUninit::::zeroed(); let mut len = size_of::() as libc::socklen_t; diff --git a/src/tools/miri/triagebot.toml b/src/tools/miri/triagebot.toml index b02fa19882f66..9d5607829a6ce 100644 --- a/src/tools/miri/triagebot.toml +++ b/src/tools/miri/triagebot.toml @@ -16,15 +16,11 @@ allow-unauthenticated = [ # Enables assigning users to issues and PRs. [assign] warn_non_default_branch = true -# These are entirely ignored, unfortunately. contributing_url = "https://github.com/rust-lang/miri/blob/master/CONTRIBUTING.md#pr-review-process" llm_policy_url = "https://github.com/rust-lang/miri/blob/master/CONTRIBUTING.md#ai-policy" [assign.custom_messages] -auto-assign-someone = "(unused)" -auto-assign-no-one = """ -Thank you for contributing to Miri! A reviewer will take a look at your PR, typically within a week or two. - -Please take a look at our [LLM policy](https://github.com/rust-lang/miri/blob/master/CONTRIBUTING.md#ai-policy) and make sure you understand our [review process](https://github.com/rust-lang/miri/blob/master/CONTRIBUTING.md#pr-review-process). +auto-assign-no-one-welcome = """ +Welcome, and thank you for contributing to Miri! A reviewer will take a look at your PR, typically within a week or two. """ [no-merges] @@ -53,6 +49,9 @@ new_pr = true [autolabel."S-waiting-on-author"] new_draft = true +# Post a comment when a PR gets un-drafted. +[undraft-comment] + # Canonicalize issue numbers to avoid closing the wrong issue when upstreaming this subtree. [canonicalize-issue-links] @@ -61,3 +60,7 @@ new_draft = true # Add link to the review body to review changes since posting it. [review-changes-since] + +# Allow 'rustbot merge'. +[merge] +type = "merge-queue" diff --git a/tests/assembly-llvm/s390x-backchain-toggle.rs b/tests/assembly-llvm/s390x-backchain-toggle.rs index baf7104727833..bc602d1baec8c 100644 --- a/tests/assembly-llvm/s390x-backchain-toggle.rs +++ b/tests/assembly-llvm/s390x-backchain-toggle.rs @@ -3,8 +3,8 @@ //@ assembly-output: emit-asm //@ compile-flags: -Copt-level=3 --crate-type=lib --target=s390x-unknown-linux-gnu //@ needs-llvm-components: systemz -//@[enable-backchain] compile-flags: -Ctarget-feature=+backchain -//@[disable-backchain] compile-flags: -Ctarget-feature=-backchain +//@[enable-backchain] compile-flags: -Cforce-frame-pointers +//@[disable-backchain] compile-flags: -Cforce-frame-pointers=no #![feature(no_core, lang_items)] #![no_std] #![no_core] @@ -31,20 +31,7 @@ extern "C" fn test_backchain() -> i32 { unsafe { extern_func(); } - // enable-backchain-NEXT: brasl %r{{.*}}, extern_func@PLT - // disable-backchain: brasl %r{{.*}}, extern_func@PLT - - // Make sure that the expected return value is written into %r2 (return register): - // enable-backchain-NEXT: lghi %r2, 1 - // disable-backchain: lghi %r2, 0 - // default-backchain: lghi %r2, 0 - #[cfg(target_feature = "backchain")] - { - 1 - } - #[cfg(not(target_feature = "backchain"))] - { - 0 - } + // NEXT: brasl %r{{.*}}, extern_func@PLT + 1 // CHECK: br %r{{.*}} } diff --git a/tests/codegen-llvm/backchain.rs b/tests/codegen-llvm/backchain.rs index fae494dcad1b4..1cb01f3cf0032 100644 --- a/tests/codegen-llvm/backchain.rs +++ b/tests/codegen-llvm/backchain.rs @@ -1,5 +1,6 @@ //@ add-minicore -//@ compile-flags: -Copt-level=3 --crate-type=lib --target=s390x-unknown-linux-gnu -Ctarget-feature=+backchain +//@ compile-flags: -Copt-level=3 --crate-type=lib --target=s390x-unknown-linux-gnu +//@ compile-flags: -Cforce-frame-pointers=yes //@ needs-llvm-components: systemz #![crate_type = "lib"] #![feature(no_core, lang_items)] @@ -12,4 +13,4 @@ use minicore::*; pub fn test_backchain() { // CHECK: @test_backchain() unnamed_addr #0 } -// CHECK: attributes #0 = { {{.*}}"target-features"="{{[^"]*}}+backchain{{.*}} } +// CHECK: attributes #0 = { {{.*}}"backchain"{{.*}} } diff --git a/tests/codegen-llvm/force-frame-pointers.rs b/tests/codegen-llvm/force-frame-pointers.rs index 2cdc37e691115..1d7cb2bea60aa 100644 --- a/tests/codegen-llvm/force-frame-pointers.rs +++ b/tests/codegen-llvm/force-frame-pointers.rs @@ -9,6 +9,9 @@ //@ [NonLeaf] ignore-x86_64-apple-darwin //@ [NonLeaf] ignore-windows-gnu //@ [NonLeaf] ignore-thumb +// On s390x, -Cforce-frame-pointers emits `"backchain"` not `"frame-pointer"`. +// Since this test passes -Zunstable-options globally, it must be skipped on s390x. +//@ ignore-s390x // result is platform-dependent based on platform's frame pointer settings #![crate_type = "lib"] diff --git a/tests/codegen-llvm/frame-pointer-cli-control.rs b/tests/codegen-llvm/frame-pointer-cli-control.rs index 79cdfc70f1ad7..47b2464bcd07c 100644 --- a/tests/codegen-llvm/frame-pointer-cli-control.rs +++ b/tests/codegen-llvm/frame-pointer-cli-control.rs @@ -2,6 +2,7 @@ //@ compile-flags: --crate-type=rlib -Copt-level=0 //@ revisions: force-on aarch64-apple aarch64-apple-on aarch64-apple-off //@ [force-on] compile-flags: -Cforce-frame-pointers=on +//@ [force-on] ignore-s390x //@ [aarch64-apple] needs-llvm-components: aarch64 //@ [aarch64-apple] compile-flags: --target=aarch64-apple-darwin //@ [aarch64-apple-on] needs-llvm-components: aarch64 @@ -39,6 +40,9 @@ Specific cases where platforms or tools rely on frame pointers for sound or corr - openbsd: - i686-msvc - i686-mingw: + +S390x is a special case because on this platform framepointers cannot be use for unwinding. +On s390x `-Cforce-frame-pointers=on' will emit a 'backchain' attribute which is tested elsewhere. */ #![feature(no_core, lang_items)] #![no_core] diff --git a/tests/mir-opt/building/match/aggregate_array_eq.array_match.built.after.panic-abort.mir b/tests/mir-opt/building/match/aggregate_array_eq.array_match.built.after.panic-abort.mir new file mode 100644 index 0000000000000..71641a2679605 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.array_match.built.after.panic-abort.mir @@ -0,0 +1,47 @@ +// MIR for `array_match` after built + +fn array_match(_1: [u8; 4]) -> bool { + debug x => _1; + let mut _0: bool; + let mut _2: &[u8; 4]; + let mut _3: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + _2 = &_1; + _3 = raw_eq::<[u8; 4]>(copy _2, const &*b"\x01\x02\x03\x04") -> [return: bb4, unwind unreachable]; + } + + bb1: { + _0 = const false; + goto -> bb7; + } + + bb2: { + falseEdge -> [real: bb6, imaginary: bb1]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + switchInt(move _3) -> [0: bb1, otherwise: bb2]; + } + + bb5: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb6: { + _0 = const true; + goto -> bb7; + } + + bb7: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.array_match.built.after.panic-unwind.mir b/tests/mir-opt/building/match/aggregate_array_eq.array_match.built.after.panic-unwind.mir new file mode 100644 index 0000000000000..71641a2679605 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.array_match.built.after.panic-unwind.mir @@ -0,0 +1,47 @@ +// MIR for `array_match` after built + +fn array_match(_1: [u8; 4]) -> bool { + debug x => _1; + let mut _0: bool; + let mut _2: &[u8; 4]; + let mut _3: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + _2 = &_1; + _3 = raw_eq::<[u8; 4]>(copy _2, const &*b"\x01\x02\x03\x04") -> [return: bb4, unwind unreachable]; + } + + bb1: { + _0 = const false; + goto -> bb7; + } + + bb2: { + falseEdge -> [real: bb6, imaginary: bb1]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + switchInt(move _3) -> [0: bb1, otherwise: bb2]; + } + + bb5: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb6: { + _0 = const true; + goto -> bb7; + } + + bb7: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.char_slice_match.built.after.panic-abort.mir b/tests/mir-opt/building/match/aggregate_array_eq.char_slice_match.built.after.panic-abort.mir new file mode 100644 index 0000000000000..75d5cb4e6d74f --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.char_slice_match.built.after.panic-abort.mir @@ -0,0 +1,73 @@ +// MIR for `char_slice_match` after built + +fn char_slice_match(_1: &[char]) -> bool { + debug x => _1; + let mut _0: bool; + let mut _2: &[char]; + let mut _3: *const [char]; + let mut _4: *const u8; + let mut _5: *const [char]; + let mut _6: *const u8; + let mut _7: usize; + let mut _8: i32; + let mut _9: usize; + let mut _10: usize; + let mut _11: usize; + let mut _12: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + _10 = PtrMetadata(copy _1); + _9 = move _10; + _11 = const 4_usize; + _12 = Eq(move _9, move _11); + switchInt(move _12) -> [0: bb1, otherwise: bb2]; + } + + bb1: { + _0 = const false; + goto -> bb9; + } + + bb2: { + _2 = const &Branch(['a', 'b', 'c', 'd']): [char]; + _3 = &raw const (*_1); + _4 = move _3 as *const u8 (PtrToPtr); + _5 = &raw const (*_2); + _6 = move _5 as *const u8 (PtrToPtr); + _7 = const 16_usize; + _8 = compare_bytes(move _4, move _6, move _7) -> [return: bb6, unwind unreachable]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + falseEdge -> [real: bb8, imaginary: bb1]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + switchInt(move _8) -> [0: bb4, otherwise: bb3]; + } + + bb7: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb8: { + _0 = const true; + goto -> bb9; + } + + bb9: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.char_slice_match.built.after.panic-unwind.mir b/tests/mir-opt/building/match/aggregate_array_eq.char_slice_match.built.after.panic-unwind.mir new file mode 100644 index 0000000000000..75d5cb4e6d74f --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.char_slice_match.built.after.panic-unwind.mir @@ -0,0 +1,73 @@ +// MIR for `char_slice_match` after built + +fn char_slice_match(_1: &[char]) -> bool { + debug x => _1; + let mut _0: bool; + let mut _2: &[char]; + let mut _3: *const [char]; + let mut _4: *const u8; + let mut _5: *const [char]; + let mut _6: *const u8; + let mut _7: usize; + let mut _8: i32; + let mut _9: usize; + let mut _10: usize; + let mut _11: usize; + let mut _12: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + _10 = PtrMetadata(copy _1); + _9 = move _10; + _11 = const 4_usize; + _12 = Eq(move _9, move _11); + switchInt(move _12) -> [0: bb1, otherwise: bb2]; + } + + bb1: { + _0 = const false; + goto -> bb9; + } + + bb2: { + _2 = const &Branch(['a', 'b', 'c', 'd']): [char]; + _3 = &raw const (*_1); + _4 = move _3 as *const u8 (PtrToPtr); + _5 = &raw const (*_2); + _6 = move _5 as *const u8 (PtrToPtr); + _7 = const 16_usize; + _8 = compare_bytes(move _4, move _6, move _7) -> [return: bb6, unwind unreachable]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + falseEdge -> [real: bb8, imaginary: bb1]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + switchInt(move _8) -> [0: bb4, otherwise: bb3]; + } + + bb7: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb8: { + _0 = const true; + goto -> bb9; + } + + bb9: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.const_array_match.built.after.panic-abort.mir b/tests/mir-opt/building/match/aggregate_array_eq.const_array_match.built.after.panic-abort.mir new file mode 100644 index 0000000000000..c785ea537e9c9 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.const_array_match.built.after.panic-abort.mir @@ -0,0 +1,64 @@ +// MIR for `const_array_match` after built + +fn const_array_match(_1: [u8; 4]) -> bool { + debug x => _1; + let mut _0: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + switchInt(copy _1[0 of 4]) -> [1: bb2, otherwise: bb1]; + } + + bb1: { + _0 = const false; + goto -> bb12; + } + + bb2: { + switchInt(copy _1[1 of 4]) -> [2: bb4, otherwise: bb3]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + switchInt(copy _1[2 of 4]) -> [3: bb6, otherwise: bb5]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + switchInt(copy _1[3 of 4]) -> [4: bb8, otherwise: bb7]; + } + + bb7: { + goto -> bb5; + } + + bb8: { + falseEdge -> [real: bb11, imaginary: bb1]; + } + + bb9: { + goto -> bb7; + } + + bb10: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb11: { + _0 = const true; + goto -> bb12; + } + + bb12: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.const_array_match.built.after.panic-unwind.mir b/tests/mir-opt/building/match/aggregate_array_eq.const_array_match.built.after.panic-unwind.mir new file mode 100644 index 0000000000000..c785ea537e9c9 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.const_array_match.built.after.panic-unwind.mir @@ -0,0 +1,64 @@ +// MIR for `const_array_match` after built + +fn const_array_match(_1: [u8; 4]) -> bool { + debug x => _1; + let mut _0: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + switchInt(copy _1[0 of 4]) -> [1: bb2, otherwise: bb1]; + } + + bb1: { + _0 = const false; + goto -> bb12; + } + + bb2: { + switchInt(copy _1[1 of 4]) -> [2: bb4, otherwise: bb3]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + switchInt(copy _1[2 of 4]) -> [3: bb6, otherwise: bb5]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + switchInt(copy _1[3 of 4]) -> [4: bb8, otherwise: bb7]; + } + + bb7: { + goto -> bb5; + } + + bb8: { + falseEdge -> [real: bb11, imaginary: bb1]; + } + + bb9: { + goto -> bb7; + } + + bb10: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb11: { + _0 = const true; + goto -> bb12; + } + + bb12: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.const_try_from_matched.built.after.panic-abort.mir b/tests/mir-opt/building/match/aggregate_array_eq.const_try_from_matched.built.after.panic-abort.mir new file mode 100644 index 0000000000000..4b105ec6d5d01 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.const_try_from_matched.built.after.panic-abort.mir @@ -0,0 +1,197 @@ +// MIR for `const_try_from_matched` after built + +fn const_try_from_matched(_1: [u8; 4]) -> Result { + debug value => _1; + let mut _0: std::result::Result; + let mut _2: &[u8; 4]; + let mut _3: MyEnum; + let mut _4: MyEnum; + let mut _5: MyEnum; + let mut _6: MyEnum; + let mut _7: (); + + bb0: { + StorageLive(_2); + _2 = &_1; + PlaceMention(_2); + switchInt(copy (*_2)[0 of 4]) -> [65: bb2, 69: bb10, 73: bb18, 77: bb26, otherwise: bb1]; + } + + bb1: { + StorageLive(_7); + _7 = (); + _0 = Result::::Err(move _7); + StorageDead(_7); + goto -> bb39; + } + + bb2: { + switchInt(copy (*_2)[1 of 4]) -> [66: bb4, otherwise: bb3]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + switchInt(copy (*_2)[2 of 4]) -> [67: bb6, otherwise: bb5]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + switchInt(copy (*_2)[3 of 4]) -> [68: bb8, otherwise: bb7]; + } + + bb7: { + goto -> bb5; + } + + bb8: { + falseEdge -> [real: bb38, imaginary: bb10]; + } + + bb9: { + goto -> bb7; + } + + bb10: { + switchInt(copy (*_2)[1 of 4]) -> [70: bb12, otherwise: bb11]; + } + + bb11: { + goto -> bb1; + } + + bb12: { + switchInt(copy (*_2)[2 of 4]) -> [71: bb14, otherwise: bb13]; + } + + bb13: { + goto -> bb11; + } + + bb14: { + switchInt(copy (*_2)[3 of 4]) -> [72: bb16, otherwise: bb15]; + } + + bb15: { + goto -> bb13; + } + + bb16: { + falseEdge -> [real: bb37, imaginary: bb18]; + } + + bb17: { + goto -> bb15; + } + + bb18: { + switchInt(copy (*_2)[1 of 4]) -> [74: bb20, otherwise: bb19]; + } + + bb19: { + goto -> bb1; + } + + bb20: { + switchInt(copy (*_2)[2 of 4]) -> [75: bb22, otherwise: bb21]; + } + + bb21: { + goto -> bb19; + } + + bb22: { + switchInt(copy (*_2)[3 of 4]) -> [76: bb24, otherwise: bb23]; + } + + bb23: { + goto -> bb21; + } + + bb24: { + falseEdge -> [real: bb36, imaginary: bb26]; + } + + bb25: { + goto -> bb23; + } + + bb26: { + switchInt(copy (*_2)[1 of 4]) -> [78: bb28, otherwise: bb27]; + } + + bb27: { + goto -> bb1; + } + + bb28: { + switchInt(copy (*_2)[2 of 4]) -> [79: bb30, otherwise: bb29]; + } + + bb29: { + goto -> bb27; + } + + bb30: { + switchInt(copy (*_2)[3 of 4]) -> [80: bb32, otherwise: bb31]; + } + + bb31: { + goto -> bb29; + } + + bb32: { + falseEdge -> [real: bb35, imaginary: bb1]; + } + + bb33: { + goto -> bb31; + } + + bb34: { + FakeRead(ForMatchedPlace(None), _2); + unreachable; + } + + bb35: { + StorageLive(_6); + _6 = MyEnum::D; + _0 = Result::::Ok(move _6); + StorageDead(_6); + goto -> bb39; + } + + bb36: { + StorageLive(_5); + _5 = MyEnum::C; + _0 = Result::::Ok(move _5); + StorageDead(_5); + goto -> bb39; + } + + bb37: { + StorageLive(_4); + _4 = MyEnum::B; + _0 = Result::::Ok(move _4); + StorageDead(_4); + goto -> bb39; + } + + bb38: { + StorageLive(_3); + _3 = MyEnum::A; + _0 = Result::::Ok(move _3); + StorageDead(_3); + goto -> bb39; + } + + bb39: { + StorageDead(_2); + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.const_try_from_matched.built.after.panic-unwind.mir b/tests/mir-opt/building/match/aggregate_array_eq.const_try_from_matched.built.after.panic-unwind.mir new file mode 100644 index 0000000000000..4b105ec6d5d01 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.const_try_from_matched.built.after.panic-unwind.mir @@ -0,0 +1,197 @@ +// MIR for `const_try_from_matched` after built + +fn const_try_from_matched(_1: [u8; 4]) -> Result { + debug value => _1; + let mut _0: std::result::Result; + let mut _2: &[u8; 4]; + let mut _3: MyEnum; + let mut _4: MyEnum; + let mut _5: MyEnum; + let mut _6: MyEnum; + let mut _7: (); + + bb0: { + StorageLive(_2); + _2 = &_1; + PlaceMention(_2); + switchInt(copy (*_2)[0 of 4]) -> [65: bb2, 69: bb10, 73: bb18, 77: bb26, otherwise: bb1]; + } + + bb1: { + StorageLive(_7); + _7 = (); + _0 = Result::::Err(move _7); + StorageDead(_7); + goto -> bb39; + } + + bb2: { + switchInt(copy (*_2)[1 of 4]) -> [66: bb4, otherwise: bb3]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + switchInt(copy (*_2)[2 of 4]) -> [67: bb6, otherwise: bb5]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + switchInt(copy (*_2)[3 of 4]) -> [68: bb8, otherwise: bb7]; + } + + bb7: { + goto -> bb5; + } + + bb8: { + falseEdge -> [real: bb38, imaginary: bb10]; + } + + bb9: { + goto -> bb7; + } + + bb10: { + switchInt(copy (*_2)[1 of 4]) -> [70: bb12, otherwise: bb11]; + } + + bb11: { + goto -> bb1; + } + + bb12: { + switchInt(copy (*_2)[2 of 4]) -> [71: bb14, otherwise: bb13]; + } + + bb13: { + goto -> bb11; + } + + bb14: { + switchInt(copy (*_2)[3 of 4]) -> [72: bb16, otherwise: bb15]; + } + + bb15: { + goto -> bb13; + } + + bb16: { + falseEdge -> [real: bb37, imaginary: bb18]; + } + + bb17: { + goto -> bb15; + } + + bb18: { + switchInt(copy (*_2)[1 of 4]) -> [74: bb20, otherwise: bb19]; + } + + bb19: { + goto -> bb1; + } + + bb20: { + switchInt(copy (*_2)[2 of 4]) -> [75: bb22, otherwise: bb21]; + } + + bb21: { + goto -> bb19; + } + + bb22: { + switchInt(copy (*_2)[3 of 4]) -> [76: bb24, otherwise: bb23]; + } + + bb23: { + goto -> bb21; + } + + bb24: { + falseEdge -> [real: bb36, imaginary: bb26]; + } + + bb25: { + goto -> bb23; + } + + bb26: { + switchInt(copy (*_2)[1 of 4]) -> [78: bb28, otherwise: bb27]; + } + + bb27: { + goto -> bb1; + } + + bb28: { + switchInt(copy (*_2)[2 of 4]) -> [79: bb30, otherwise: bb29]; + } + + bb29: { + goto -> bb27; + } + + bb30: { + switchInt(copy (*_2)[3 of 4]) -> [80: bb32, otherwise: bb31]; + } + + bb31: { + goto -> bb29; + } + + bb32: { + falseEdge -> [real: bb35, imaginary: bb1]; + } + + bb33: { + goto -> bb31; + } + + bb34: { + FakeRead(ForMatchedPlace(None), _2); + unreachable; + } + + bb35: { + StorageLive(_6); + _6 = MyEnum::D; + _0 = Result::::Ok(move _6); + StorageDead(_6); + goto -> bb39; + } + + bb36: { + StorageLive(_5); + _5 = MyEnum::C; + _0 = Result::::Ok(move _5); + StorageDead(_5); + goto -> bb39; + } + + bb37: { + StorageLive(_4); + _4 = MyEnum::B; + _0 = Result::::Ok(move _4); + StorageDead(_4); + goto -> bb39; + } + + bb38: { + StorageLive(_3); + _3 = MyEnum::A; + _0 = Result::::Ok(move _3); + StorageDead(_3); + goto -> bb39; + } + + bb39: { + StorageDead(_2); + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.custom_element_array_match.built.after.panic-abort.mir b/tests/mir-opt/building/match/aggregate_array_eq.custom_element_array_match.built.after.panic-abort.mir new file mode 100644 index 0000000000000..252b4858d2b62 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.custom_element_array_match.built.after.panic-abort.mir @@ -0,0 +1,64 @@ +// MIR for `custom_element_array_match` after built + +fn custom_element_array_match(_1: [Element; 4]) -> bool { + debug x => _1; + let mut _0: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + switchInt(copy (_1[0 of 4].0: u8)) -> [1: bb2, otherwise: bb1]; + } + + bb1: { + _0 = const false; + goto -> bb12; + } + + bb2: { + switchInt(copy (_1[1 of 4].0: u8)) -> [2: bb4, otherwise: bb3]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + switchInt(copy (_1[2 of 4].0: u8)) -> [3: bb6, otherwise: bb5]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + switchInt(copy (_1[3 of 4].0: u8)) -> [4: bb8, otherwise: bb7]; + } + + bb7: { + goto -> bb5; + } + + bb8: { + falseEdge -> [real: bb11, imaginary: bb1]; + } + + bb9: { + goto -> bb7; + } + + bb10: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb11: { + _0 = const true; + goto -> bb12; + } + + bb12: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.custom_element_array_match.built.after.panic-unwind.mir b/tests/mir-opt/building/match/aggregate_array_eq.custom_element_array_match.built.after.panic-unwind.mir new file mode 100644 index 0000000000000..252b4858d2b62 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.custom_element_array_match.built.after.panic-unwind.mir @@ -0,0 +1,64 @@ +// MIR for `custom_element_array_match` after built + +fn custom_element_array_match(_1: [Element; 4]) -> bool { + debug x => _1; + let mut _0: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + switchInt(copy (_1[0 of 4].0: u8)) -> [1: bb2, otherwise: bb1]; + } + + bb1: { + _0 = const false; + goto -> bb12; + } + + bb2: { + switchInt(copy (_1[1 of 4].0: u8)) -> [2: bb4, otherwise: bb3]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + switchInt(copy (_1[2 of 4].0: u8)) -> [3: bb6, otherwise: bb5]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + switchInt(copy (_1[3 of 4].0: u8)) -> [4: bb8, otherwise: bb7]; + } + + bb7: { + goto -> bb5; + } + + bb8: { + falseEdge -> [real: bb11, imaginary: bb1]; + } + + bb9: { + goto -> bb7; + } + + bb10: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb11: { + _0 = const true; + goto -> bb12; + } + + bb12: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.handwritten_array_match.built.after.panic-abort.mir b/tests/mir-opt/building/match/aggregate_array_eq.handwritten_array_match.built.after.panic-abort.mir new file mode 100644 index 0000000000000..7f2e610b412a2 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.handwritten_array_match.built.after.panic-abort.mir @@ -0,0 +1,64 @@ +// MIR for `handwritten_array_match` after built + +fn handwritten_array_match(_1: [u8; 4]) -> bool { + debug x => _1; + let mut _0: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + switchInt(copy _1[0 of 4]) -> [1: bb2, otherwise: bb1]; + } + + bb1: { + _0 = const false; + goto -> bb12; + } + + bb2: { + switchInt(copy _1[1 of 4]) -> [2: bb4, otherwise: bb3]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + switchInt(copy _1[2 of 4]) -> [3: bb6, otherwise: bb5]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + switchInt(copy _1[3 of 4]) -> [4: bb8, otherwise: bb7]; + } + + bb7: { + goto -> bb5; + } + + bb8: { + falseEdge -> [real: bb11, imaginary: bb1]; + } + + bb9: { + goto -> bb7; + } + + bb10: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb11: { + _0 = const true; + goto -> bb12; + } + + bb12: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.handwritten_array_match.built.after.panic-unwind.mir b/tests/mir-opt/building/match/aggregate_array_eq.handwritten_array_match.built.after.panic-unwind.mir new file mode 100644 index 0000000000000..7f2e610b412a2 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.handwritten_array_match.built.after.panic-unwind.mir @@ -0,0 +1,64 @@ +// MIR for `handwritten_array_match` after built + +fn handwritten_array_match(_1: [u8; 4]) -> bool { + debug x => _1; + let mut _0: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + switchInt(copy _1[0 of 4]) -> [1: bb2, otherwise: bb1]; + } + + bb1: { + _0 = const false; + goto -> bb12; + } + + bb2: { + switchInt(copy _1[1 of 4]) -> [2: bb4, otherwise: bb3]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + switchInt(copy _1[2 of 4]) -> [3: bb6, otherwise: bb5]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + switchInt(copy _1[3 of 4]) -> [4: bb8, otherwise: bb7]; + } + + bb7: { + goto -> bb5; + } + + bb8: { + falseEdge -> [real: bb11, imaginary: bb1]; + } + + bb9: { + goto -> bb7; + } + + bb10: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb11: { + _0 = const true; + goto -> bb12; + } + + bb12: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.nested_array_match.built.after.panic-abort.mir b/tests/mir-opt/building/match/aggregate_array_eq.nested_array_match.built.after.panic-abort.mir new file mode 100644 index 0000000000000..bce03b76013d1 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.nested_array_match.built.after.panic-abort.mir @@ -0,0 +1,92 @@ +// MIR for `nested_array_match` after built + +fn nested_array_match(_1: [[u8; 4]; 4]) -> bool { + debug x => _1; + let mut _0: bool; + let mut _2: &[u8; 4]; + let mut _3: bool; + let mut _4: &[u8; 4]; + let mut _5: bool; + let mut _6: &[u8; 4]; + let mut _7: bool; + let mut _8: &[u8; 4]; + let mut _9: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + _8 = &_1[0 of 4]; + _9 = raw_eq::<[u8; 4]>(copy _8, const &*b"\x01\x02\x03\x04") -> [return: bb13, unwind unreachable]; + } + + bb1: { + _0 = const false; + goto -> bb16; + } + + bb2: { + _6 = &_1[1 of 4]; + _7 = raw_eq::<[u8; 4]>(copy _6, const &*b"\x05\x06\x07\x08") -> [return: bb12, unwind unreachable]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + _4 = &_1[2 of 4]; + _5 = raw_eq::<[u8; 4]>(copy _4, const &*b"\t\n\x0b\x0c") -> [return: bb11, unwind unreachable]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + _2 = &_1[3 of 4]; + _3 = raw_eq::<[u8; 4]>(copy _2, const &*b"\r\x0e\x0f\x10") -> [return: bb10, unwind unreachable]; + } + + bb7: { + goto -> bb5; + } + + bb8: { + falseEdge -> [real: bb15, imaginary: bb1]; + } + + bb9: { + goto -> bb7; + } + + bb10: { + switchInt(move _3) -> [0: bb7, otherwise: bb8]; + } + + bb11: { + switchInt(move _5) -> [0: bb5, otherwise: bb6]; + } + + bb12: { + switchInt(move _7) -> [0: bb3, otherwise: bb4]; + } + + bb13: { + switchInt(move _9) -> [0: bb1, otherwise: bb2]; + } + + bb14: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb15: { + _0 = const true; + goto -> bb16; + } + + bb16: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.nested_array_match.built.after.panic-unwind.mir b/tests/mir-opt/building/match/aggregate_array_eq.nested_array_match.built.after.panic-unwind.mir new file mode 100644 index 0000000000000..bce03b76013d1 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.nested_array_match.built.after.panic-unwind.mir @@ -0,0 +1,92 @@ +// MIR for `nested_array_match` after built + +fn nested_array_match(_1: [[u8; 4]; 4]) -> bool { + debug x => _1; + let mut _0: bool; + let mut _2: &[u8; 4]; + let mut _3: bool; + let mut _4: &[u8; 4]; + let mut _5: bool; + let mut _6: &[u8; 4]; + let mut _7: bool; + let mut _8: &[u8; 4]; + let mut _9: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + _8 = &_1[0 of 4]; + _9 = raw_eq::<[u8; 4]>(copy _8, const &*b"\x01\x02\x03\x04") -> [return: bb13, unwind unreachable]; + } + + bb1: { + _0 = const false; + goto -> bb16; + } + + bb2: { + _6 = &_1[1 of 4]; + _7 = raw_eq::<[u8; 4]>(copy _6, const &*b"\x05\x06\x07\x08") -> [return: bb12, unwind unreachable]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + _4 = &_1[2 of 4]; + _5 = raw_eq::<[u8; 4]>(copy _4, const &*b"\t\n\x0b\x0c") -> [return: bb11, unwind unreachable]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + _2 = &_1[3 of 4]; + _3 = raw_eq::<[u8; 4]>(copy _2, const &*b"\r\x0e\x0f\x10") -> [return: bb10, unwind unreachable]; + } + + bb7: { + goto -> bb5; + } + + bb8: { + falseEdge -> [real: bb15, imaginary: bb1]; + } + + bb9: { + goto -> bb7; + } + + bb10: { + switchInt(move _3) -> [0: bb7, otherwise: bb8]; + } + + bb11: { + switchInt(move _5) -> [0: bb5, otherwise: bb6]; + } + + bb12: { + switchInt(move _7) -> [0: bb3, otherwise: bb4]; + } + + bb13: { + switchInt(move _9) -> [0: bb1, otherwise: bb2]; + } + + bb14: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb15: { + _0 = const true; + goto -> bb16; + } + + bb16: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.rs b/tests/mir-opt/building/match/aggregate_array_eq.rs new file mode 100644 index 0000000000000..06ff9d8a9e8f9 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.rs @@ -0,0 +1,191 @@ +// EMIT_MIR_FOR_EACH_PANIC_STRATEGY +//@ compile-flags: -Zmir-opt-level=0 + +// Verify that matching against an array/slice pattern of a bytewise-comparable +// primitive type that was expanded from a constant (a named constant or a +// byte-string literal) produces a single call to the `raw_eq` or `compare_bytes` +// intrinsic rather than element-by-element comparisons. The call must be marked +// as non-unwinding. +// +// Hand-written patterns and patterns in const contexts are still compared +// element by element. + +#![crate_type = "lib"] + +// EMIT_MIR aggregate_array_eq.array_match.built.after.mir +pub fn array_match(x: [u8; 4]) -> bool { + // CHECK-LABEL: fn array_match( + // CHECK-NOT: _1[ + // CHECK: raw_eq::<[u8; 4]>( + // CHECK-SAME: unwind unreachable + // CHECK-NOT: _1[ + const EXPECTED: [u8; 4] = [1, 2, 3, 4]; + matches!(x, EXPECTED) +} + +// EMIT_MIR aggregate_array_eq.handwritten_array_match.built.after.mir +pub fn handwritten_array_match(x: [u8; 4]) -> bool { + // CHECK-LABEL: fn handwritten_array_match( + // CHECK-NOT: raw_eq + // CHECK: switchInt(copy _1[0 of 4]) + // CHECK: switchInt(copy _1[1 of 4]) + // CHECK: switchInt(copy _1[2 of 4]) + // CHECK: switchInt(copy _1[3 of 4]) + matches!(x, [1, 2, 3, 4]) +} + +// Below a length threshold, constants are still compared element by element. +// EMIT_MIR aggregate_array_eq.short_array_match.built.after.mir +pub fn short_array_match(x: [u8; 3]) -> bool { + // CHECK-LABEL: fn short_array_match( + // CHECK-NOT: raw_eq + // CHECK: switchInt(copy _1[0 of 3]) + // CHECK: switchInt(copy _1[1 of 3]) + // CHECK: switchInt(copy _1[2 of 3]) + const EXPECTED: [u8; 3] = [1, 2, 3]; + matches!(x, EXPECTED) +} + +#[derive(PartialEq, Eq)] +pub struct Element(u8); + +// The aggregate comparison is limited to bytewise-comparable primitive element +// types, whose bytes are equal if and only if their values are. +// EMIT_MIR aggregate_array_eq.custom_element_array_match.built.after.mir +pub fn custom_element_array_match(x: [Element; 4]) -> bool { + // CHECK-LABEL: fn custom_element_array_match( + // CHECK-NOT: raw_eq + // CHECK: switchInt(copy (_1[0 of 4].0: u8)) + // CHECK: switchInt(copy (_1[1 of 4].0: u8)) + // CHECK: switchInt(copy (_1[2 of 4].0: u8)) + // CHECK: switchInt(copy (_1[3 of 4].0: u8)) + const EXPECTED: [Element; 4] = [Element(1), Element(2), Element(3), Element(4)]; + matches!(x, EXPECTED) +} + +// Arrays of bytewise-comparable elements are not themselves treated as +// bytewise-comparable, so only the inner arrays are compared in one go. +// EMIT_MIR aggregate_array_eq.nested_array_match.built.after.mir +pub fn nested_array_match(x: [[u8; 4]; 4]) -> bool { + // CHECK-LABEL: fn nested_array_match( + // CHECK-NOT: raw_eq::<{{\[\[}}u8; 4]; 4]> + // CHECK: = &_1[0 of 4]; + // CHECK: raw_eq::<[u8; 4]>( + // CHECK: = &_1[1 of 4]; + // CHECK: raw_eq::<[u8; 4]>( + // CHECK: = &_1[2 of 4]; + // CHECK: raw_eq::<[u8; 4]>( + // CHECK: = &_1[3 of 4]; + // CHECK: raw_eq::<[u8; 4]>( + // CHECK-NOT: raw_eq::<{{\[\[}}u8; 4]; 4]> + const EXPECTED: [[u8; 4]; 4] = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]; + matches!(x, EXPECTED) +} + +// Slice patterns of the same length share a single length check. +// EMIT_MIR aggregate_array_eq.slice_match.built.after.mir +pub fn slice_match(x: &[u8]) -> u32 { + // CHECK-LABEL: fn slice_match( + // CHECK: PtrMetadata(copy _1); + // CHECK-NOT: PtrMetadata + // CHECK-NOT: (*_1)[ + // CHECK: compare_bytes( + // CHECK-SAME: unwind unreachable + // CHECK-NOT: PtrMetadata + // CHECK-NOT: (*_1)[ + // CHECK: compare_bytes( + // CHECK-SAME: unwind unreachable + // CHECK-NOT: PtrMetadata + // CHECK-NOT: (*_1)[ + match x { + b"ABCD" => 1, + b"EFGH" => 2, + _ => 0, + } +} + +// EMIT_MIR aggregate_array_eq.short_slice_match.built.after.mir +pub fn short_slice_match(x: &[u8]) -> bool { + // CHECK-LABEL: fn short_slice_match( + // CHECK-NOT: compare_bytes + // CHECK: PtrMetadata(copy _1); + // CHECK: switchInt(copy (*_1)[0 of 3]) + // CHECK: switchInt(copy (*_1)[1 of 3]) + // CHECK: switchInt(copy (*_1)[2 of 3]) + matches!(x, b"ABC") +} + +// `compare_bytes` is given the length in bytes, not in elements. +// EMIT_MIR aggregate_array_eq.u16_slice_match.built.after.mir +pub fn u16_slice_match(x: &[u16]) -> bool { + // CHECK-LABEL: fn u16_slice_match( + // CHECK: [[BYTES:_[0-9]+]] = const 8_usize; + // CHECK: compare_bytes({{.*}}, move [[BYTES]]) + const EXPECTED: &[u16] = &[1, 2, 3, 4]; + matches!(x, EXPECTED) +} + +// EMIT_MIR aggregate_array_eq.char_slice_match.built.after.mir +pub fn char_slice_match(x: &[char]) -> bool { + // CHECK-LABEL: fn char_slice_match( + // CHECK: [[BYTES:_[0-9]+]] = const 16_usize; + // CHECK: compare_bytes({{.*}}, move [[BYTES]]) + const EXPECTED: &[char] = &['a', 'b', 'c', 'd']; + matches!(x, EXPECTED) +} + +pub enum MyEnum { + A, + B, + C, + D, +} + +// Regression test for https://github.com/rust-lang/rust/issues/103073. +// EMIT_MIR aggregate_array_eq.try_from_matched.built.after.mir +pub fn try_from_matched(value: [u8; 4]) -> Result { + // CHECK-LABEL: fn try_from_matched( + // CHECK: [[SCRUTINEE:_[0-9]+]] = &_1; + // CHECK-NOT: (*[[SCRUTINEE]])[ + // CHECK: raw_eq::<[u8; 4]>( + // CHECK-NOT: (*[[SCRUTINEE]])[ + match &value { + b"ABCD" => Ok(MyEnum::A), + b"EFGH" => Ok(MyEnum::B), + b"IJKL" => Ok(MyEnum::C), + b"MNOP" => Ok(MyEnum::D), + _ => Err(()), + } +} + +// In a const fn, the aggregate comparison must not be used because the +// `compare_bytes` intrinsic is not const-stable. +// EMIT_MIR aggregate_array_eq.const_array_match.built.after.mir +pub const fn const_array_match(x: [u8; 4]) -> bool { + // CHECK-LABEL: fn const_array_match( + // CHECK-NOT: raw_eq + // CHECK: switchInt(copy _1[0 of 4]) + // CHECK: switchInt(copy _1[1 of 4]) + // CHECK: switchInt(copy _1[2 of 4]) + // CHECK: switchInt(copy _1[3 of 4]) + const EXPECTED: [u8; 4] = [1, 2, 3, 4]; + matches!(x, EXPECTED) +} + +// EMIT_MIR aggregate_array_eq.const_try_from_matched.built.after.mir +pub const fn const_try_from_matched(value: [u8; 4]) -> Result { + // CHECK-LABEL: fn const_try_from_matched( + // CHECK-NOT: raw_eq + // CHECK: [[SCRUTINEE:_[0-9]+]] = &_1; + // CHECK: switchInt(copy (*[[SCRUTINEE]])[0 of 4]) + // CHECK: switchInt(copy (*[[SCRUTINEE]])[1 of 4]) + // CHECK: switchInt(copy (*[[SCRUTINEE]])[2 of 4]) + // CHECK: switchInt(copy (*[[SCRUTINEE]])[3 of 4]) + match &value { + b"ABCD" => Ok(MyEnum::A), + b"EFGH" => Ok(MyEnum::B), + b"IJKL" => Ok(MyEnum::C), + b"MNOP" => Ok(MyEnum::D), + _ => Err(()), + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.short_array_match.built.after.panic-abort.mir b/tests/mir-opt/building/match/aggregate_array_eq.short_array_match.built.after.panic-abort.mir new file mode 100644 index 0000000000000..8789bdf13a5f9 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.short_array_match.built.after.panic-abort.mir @@ -0,0 +1,56 @@ +// MIR for `short_array_match` after built + +fn short_array_match(_1: [u8; 3]) -> bool { + debug x => _1; + let mut _0: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + switchInt(copy _1[0 of 3]) -> [1: bb2, otherwise: bb1]; + } + + bb1: { + _0 = const false; + goto -> bb10; + } + + bb2: { + switchInt(copy _1[1 of 3]) -> [2: bb4, otherwise: bb3]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + switchInt(copy _1[2 of 3]) -> [3: bb6, otherwise: bb5]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + falseEdge -> [real: bb9, imaginary: bb1]; + } + + bb7: { + goto -> bb5; + } + + bb8: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb9: { + _0 = const true; + goto -> bb10; + } + + bb10: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.short_array_match.built.after.panic-unwind.mir b/tests/mir-opt/building/match/aggregate_array_eq.short_array_match.built.after.panic-unwind.mir new file mode 100644 index 0000000000000..8789bdf13a5f9 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.short_array_match.built.after.panic-unwind.mir @@ -0,0 +1,56 @@ +// MIR for `short_array_match` after built + +fn short_array_match(_1: [u8; 3]) -> bool { + debug x => _1; + let mut _0: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + switchInt(copy _1[0 of 3]) -> [1: bb2, otherwise: bb1]; + } + + bb1: { + _0 = const false; + goto -> bb10; + } + + bb2: { + switchInt(copy _1[1 of 3]) -> [2: bb4, otherwise: bb3]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + switchInt(copy _1[2 of 3]) -> [3: bb6, otherwise: bb5]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + falseEdge -> [real: bb9, imaginary: bb1]; + } + + bb7: { + goto -> bb5; + } + + bb8: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb9: { + _0 = const true; + goto -> bb10; + } + + bb10: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.short_slice_match.built.after.panic-abort.mir b/tests/mir-opt/building/match/aggregate_array_eq.short_slice_match.built.after.panic-abort.mir new file mode 100644 index 0000000000000..a3bdcea638803 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.short_slice_match.built.after.panic-abort.mir @@ -0,0 +1,72 @@ +// MIR for `short_slice_match` after built + +fn short_slice_match(_1: &[u8]) -> bool { + debug x => _1; + let mut _0: bool; + let mut _2: usize; + let mut _3: usize; + let mut _4: usize; + let mut _5: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + _3 = PtrMetadata(copy _1); + _2 = move _3; + _4 = const 3_usize; + _5 = Eq(move _2, move _4); + switchInt(move _5) -> [0: bb1, otherwise: bb2]; + } + + bb1: { + _0 = const false; + goto -> bb12; + } + + bb2: { + switchInt(copy (*_1)[0 of 3]) -> [65: bb4, otherwise: bb3]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + switchInt(copy (*_1)[1 of 3]) -> [66: bb6, otherwise: bb5]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + switchInt(copy (*_1)[2 of 3]) -> [67: bb8, otherwise: bb7]; + } + + bb7: { + goto -> bb5; + } + + bb8: { + falseEdge -> [real: bb11, imaginary: bb1]; + } + + bb9: { + goto -> bb7; + } + + bb10: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb11: { + _0 = const true; + goto -> bb12; + } + + bb12: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.short_slice_match.built.after.panic-unwind.mir b/tests/mir-opt/building/match/aggregate_array_eq.short_slice_match.built.after.panic-unwind.mir new file mode 100644 index 0000000000000..a3bdcea638803 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.short_slice_match.built.after.panic-unwind.mir @@ -0,0 +1,72 @@ +// MIR for `short_slice_match` after built + +fn short_slice_match(_1: &[u8]) -> bool { + debug x => _1; + let mut _0: bool; + let mut _2: usize; + let mut _3: usize; + let mut _4: usize; + let mut _5: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + _3 = PtrMetadata(copy _1); + _2 = move _3; + _4 = const 3_usize; + _5 = Eq(move _2, move _4); + switchInt(move _5) -> [0: bb1, otherwise: bb2]; + } + + bb1: { + _0 = const false; + goto -> bb12; + } + + bb2: { + switchInt(copy (*_1)[0 of 3]) -> [65: bb4, otherwise: bb3]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + switchInt(copy (*_1)[1 of 3]) -> [66: bb6, otherwise: bb5]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + switchInt(copy (*_1)[2 of 3]) -> [67: bb8, otherwise: bb7]; + } + + bb7: { + goto -> bb5; + } + + bb8: { + falseEdge -> [real: bb11, imaginary: bb1]; + } + + bb9: { + goto -> bb7; + } + + bb10: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb11: { + _0 = const true; + goto -> bb12; + } + + bb12: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.slice_match.built.after.panic-abort.mir b/tests/mir-opt/building/match/aggregate_array_eq.slice_match.built.after.panic-abort.mir new file mode 100644 index 0000000000000..7b6b939241ebf --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.slice_match.built.after.panic-abort.mir @@ -0,0 +1,109 @@ +// MIR for `slice_match` after built + +fn slice_match(_1: &[u8]) -> u32 { + debug x => _1; + let mut _0: u32; + let mut _2: &[u8]; + let mut _3: *const [u8]; + let mut _4: *const u8; + let mut _5: *const [u8]; + let mut _6: *const u8; + let mut _7: usize; + let mut _8: i32; + let mut _9: &[u8]; + let mut _10: *const [u8]; + let mut _11: *const u8; + let mut _12: *const [u8]; + let mut _13: *const u8; + let mut _14: usize; + let mut _15: i32; + let mut _16: usize; + let mut _17: usize; + let mut _18: usize; + let mut _19: bool; + + bb0: { + PlaceMention(_1); + _17 = PtrMetadata(copy _1); + _16 = move _17; + _18 = const 4_usize; + _19 = Eq(move _16, move _18); + switchInt(move _19) -> [0: bb1, otherwise: bb2]; + } + + bb1: { + _0 = const 0_u32; + goto -> bb15; + } + + bb2: { + _9 = const b"ABCD"; + _10 = &raw const (*_1); + _11 = move _10 as *const u8 (PtrToPtr); + _12 = &raw const (*_9); + _13 = move _12 as *const u8 (PtrToPtr); + _14 = const 4_usize; + _15 = compare_bytes(move _11, move _13, move _14) -> [return: bb11, unwind unreachable]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + falseEdge -> [real: bb14, imaginary: bb6]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + _2 = const b"EFGH"; + _3 = &raw const (*_1); + _4 = move _3 as *const u8 (PtrToPtr); + _5 = &raw const (*_2); + _6 = move _5 as *const u8 (PtrToPtr); + _7 = const 4_usize; + _8 = compare_bytes(move _4, move _6, move _7) -> [return: bb10, unwind unreachable]; + } + + bb7: { + goto -> bb3; + } + + bb8: { + falseEdge -> [real: bb13, imaginary: bb1]; + } + + bb9: { + goto -> bb7; + } + + bb10: { + switchInt(move _8) -> [0: bb8, otherwise: bb7]; + } + + bb11: { + switchInt(move _15) -> [0: bb4, otherwise: bb6]; + } + + bb12: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb13: { + _0 = const 2_u32; + goto -> bb15; + } + + bb14: { + _0 = const 1_u32; + goto -> bb15; + } + + bb15: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.slice_match.built.after.panic-unwind.mir b/tests/mir-opt/building/match/aggregate_array_eq.slice_match.built.after.panic-unwind.mir new file mode 100644 index 0000000000000..7b6b939241ebf --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.slice_match.built.after.panic-unwind.mir @@ -0,0 +1,109 @@ +// MIR for `slice_match` after built + +fn slice_match(_1: &[u8]) -> u32 { + debug x => _1; + let mut _0: u32; + let mut _2: &[u8]; + let mut _3: *const [u8]; + let mut _4: *const u8; + let mut _5: *const [u8]; + let mut _6: *const u8; + let mut _7: usize; + let mut _8: i32; + let mut _9: &[u8]; + let mut _10: *const [u8]; + let mut _11: *const u8; + let mut _12: *const [u8]; + let mut _13: *const u8; + let mut _14: usize; + let mut _15: i32; + let mut _16: usize; + let mut _17: usize; + let mut _18: usize; + let mut _19: bool; + + bb0: { + PlaceMention(_1); + _17 = PtrMetadata(copy _1); + _16 = move _17; + _18 = const 4_usize; + _19 = Eq(move _16, move _18); + switchInt(move _19) -> [0: bb1, otherwise: bb2]; + } + + bb1: { + _0 = const 0_u32; + goto -> bb15; + } + + bb2: { + _9 = const b"ABCD"; + _10 = &raw const (*_1); + _11 = move _10 as *const u8 (PtrToPtr); + _12 = &raw const (*_9); + _13 = move _12 as *const u8 (PtrToPtr); + _14 = const 4_usize; + _15 = compare_bytes(move _11, move _13, move _14) -> [return: bb11, unwind unreachable]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + falseEdge -> [real: bb14, imaginary: bb6]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + _2 = const b"EFGH"; + _3 = &raw const (*_1); + _4 = move _3 as *const u8 (PtrToPtr); + _5 = &raw const (*_2); + _6 = move _5 as *const u8 (PtrToPtr); + _7 = const 4_usize; + _8 = compare_bytes(move _4, move _6, move _7) -> [return: bb10, unwind unreachable]; + } + + bb7: { + goto -> bb3; + } + + bb8: { + falseEdge -> [real: bb13, imaginary: bb1]; + } + + bb9: { + goto -> bb7; + } + + bb10: { + switchInt(move _8) -> [0: bb8, otherwise: bb7]; + } + + bb11: { + switchInt(move _15) -> [0: bb4, otherwise: bb6]; + } + + bb12: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb13: { + _0 = const 2_u32; + goto -> bb15; + } + + bb14: { + _0 = const 1_u32; + goto -> bb15; + } + + bb15: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.try_from_matched.built.after.panic-abort.mir b/tests/mir-opt/building/match/aggregate_array_eq.try_from_matched.built.after.panic-abort.mir new file mode 100644 index 0000000000000..fda8a9d2bc859 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.try_from_matched.built.after.panic-abort.mir @@ -0,0 +1,153 @@ +// MIR for `try_from_matched` after built + +fn try_from_matched(_1: [u8; 4]) -> Result { + debug value => _1; + let mut _0: std::result::Result; + let mut _2: &[u8; 4]; + let mut _3: &[u8; 4]; + let mut _4: bool; + let mut _5: &[u8; 4]; + let mut _6: bool; + let mut _7: &[u8; 4]; + let mut _8: bool; + let mut _9: &[u8; 4]; + let mut _10: bool; + let mut _11: MyEnum; + let mut _12: MyEnum; + let mut _13: MyEnum; + let mut _14: MyEnum; + let mut _15: (); + + bb0: { + StorageLive(_2); + _2 = &_1; + PlaceMention(_2); + _9 = &(*_2); + _10 = raw_eq::<[u8; 4]>(copy _9, const &*b"ABCD") -> [return: bb19, unwind unreachable]; + } + + bb1: { + StorageLive(_15); + _15 = (); + _0 = Result::::Err(move _15); + StorageDead(_15); + goto -> bb25; + } + + bb2: { + falseEdge -> [real: bb24, imaginary: bb4]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + _7 = &(*_2); + _8 = raw_eq::<[u8; 4]>(copy _7, const &*b"EFGH") -> [return: bb18, unwind unreachable]; + } + + bb5: { + goto -> bb1; + } + + bb6: { + falseEdge -> [real: bb23, imaginary: bb8]; + } + + bb7: { + goto -> bb5; + } + + bb8: { + _5 = &(*_2); + _6 = raw_eq::<[u8; 4]>(copy _5, const &*b"IJKL") -> [return: bb17, unwind unreachable]; + } + + bb9: { + goto -> bb5; + } + + bb10: { + falseEdge -> [real: bb22, imaginary: bb12]; + } + + bb11: { + goto -> bb9; + } + + bb12: { + _3 = &(*_2); + _4 = raw_eq::<[u8; 4]>(copy _3, const &*b"MNOP") -> [return: bb16, unwind unreachable]; + } + + bb13: { + goto -> bb9; + } + + bb14: { + falseEdge -> [real: bb21, imaginary: bb1]; + } + + bb15: { + goto -> bb13; + } + + bb16: { + switchInt(move _4) -> [0: bb13, otherwise: bb14]; + } + + bb17: { + switchInt(move _6) -> [0: bb12, otherwise: bb10]; + } + + bb18: { + switchInt(move _8) -> [0: bb8, otherwise: bb6]; + } + + bb19: { + switchInt(move _10) -> [0: bb4, otherwise: bb2]; + } + + bb20: { + FakeRead(ForMatchedPlace(None), _2); + unreachable; + } + + bb21: { + StorageLive(_14); + _14 = MyEnum::D; + _0 = Result::::Ok(move _14); + StorageDead(_14); + goto -> bb25; + } + + bb22: { + StorageLive(_13); + _13 = MyEnum::C; + _0 = Result::::Ok(move _13); + StorageDead(_13); + goto -> bb25; + } + + bb23: { + StorageLive(_12); + _12 = MyEnum::B; + _0 = Result::::Ok(move _12); + StorageDead(_12); + goto -> bb25; + } + + bb24: { + StorageLive(_11); + _11 = MyEnum::A; + _0 = Result::::Ok(move _11); + StorageDead(_11); + goto -> bb25; + } + + bb25: { + StorageDead(_2); + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.try_from_matched.built.after.panic-unwind.mir b/tests/mir-opt/building/match/aggregate_array_eq.try_from_matched.built.after.panic-unwind.mir new file mode 100644 index 0000000000000..fda8a9d2bc859 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.try_from_matched.built.after.panic-unwind.mir @@ -0,0 +1,153 @@ +// MIR for `try_from_matched` after built + +fn try_from_matched(_1: [u8; 4]) -> Result { + debug value => _1; + let mut _0: std::result::Result; + let mut _2: &[u8; 4]; + let mut _3: &[u8; 4]; + let mut _4: bool; + let mut _5: &[u8; 4]; + let mut _6: bool; + let mut _7: &[u8; 4]; + let mut _8: bool; + let mut _9: &[u8; 4]; + let mut _10: bool; + let mut _11: MyEnum; + let mut _12: MyEnum; + let mut _13: MyEnum; + let mut _14: MyEnum; + let mut _15: (); + + bb0: { + StorageLive(_2); + _2 = &_1; + PlaceMention(_2); + _9 = &(*_2); + _10 = raw_eq::<[u8; 4]>(copy _9, const &*b"ABCD") -> [return: bb19, unwind unreachable]; + } + + bb1: { + StorageLive(_15); + _15 = (); + _0 = Result::::Err(move _15); + StorageDead(_15); + goto -> bb25; + } + + bb2: { + falseEdge -> [real: bb24, imaginary: bb4]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + _7 = &(*_2); + _8 = raw_eq::<[u8; 4]>(copy _7, const &*b"EFGH") -> [return: bb18, unwind unreachable]; + } + + bb5: { + goto -> bb1; + } + + bb6: { + falseEdge -> [real: bb23, imaginary: bb8]; + } + + bb7: { + goto -> bb5; + } + + bb8: { + _5 = &(*_2); + _6 = raw_eq::<[u8; 4]>(copy _5, const &*b"IJKL") -> [return: bb17, unwind unreachable]; + } + + bb9: { + goto -> bb5; + } + + bb10: { + falseEdge -> [real: bb22, imaginary: bb12]; + } + + bb11: { + goto -> bb9; + } + + bb12: { + _3 = &(*_2); + _4 = raw_eq::<[u8; 4]>(copy _3, const &*b"MNOP") -> [return: bb16, unwind unreachable]; + } + + bb13: { + goto -> bb9; + } + + bb14: { + falseEdge -> [real: bb21, imaginary: bb1]; + } + + bb15: { + goto -> bb13; + } + + bb16: { + switchInt(move _4) -> [0: bb13, otherwise: bb14]; + } + + bb17: { + switchInt(move _6) -> [0: bb12, otherwise: bb10]; + } + + bb18: { + switchInt(move _8) -> [0: bb8, otherwise: bb6]; + } + + bb19: { + switchInt(move _10) -> [0: bb4, otherwise: bb2]; + } + + bb20: { + FakeRead(ForMatchedPlace(None), _2); + unreachable; + } + + bb21: { + StorageLive(_14); + _14 = MyEnum::D; + _0 = Result::::Ok(move _14); + StorageDead(_14); + goto -> bb25; + } + + bb22: { + StorageLive(_13); + _13 = MyEnum::C; + _0 = Result::::Ok(move _13); + StorageDead(_13); + goto -> bb25; + } + + bb23: { + StorageLive(_12); + _12 = MyEnum::B; + _0 = Result::::Ok(move _12); + StorageDead(_12); + goto -> bb25; + } + + bb24: { + StorageLive(_11); + _11 = MyEnum::A; + _0 = Result::::Ok(move _11); + StorageDead(_11); + goto -> bb25; + } + + bb25: { + StorageDead(_2); + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.u16_slice_match.built.after.panic-abort.mir b/tests/mir-opt/building/match/aggregate_array_eq.u16_slice_match.built.after.panic-abort.mir new file mode 100644 index 0000000000000..a9c89902d29f3 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.u16_slice_match.built.after.panic-abort.mir @@ -0,0 +1,73 @@ +// MIR for `u16_slice_match` after built + +fn u16_slice_match(_1: &[u16]) -> bool { + debug x => _1; + let mut _0: bool; + let mut _2: &[u16]; + let mut _3: *const [u16]; + let mut _4: *const u8; + let mut _5: *const [u16]; + let mut _6: *const u8; + let mut _7: usize; + let mut _8: i32; + let mut _9: usize; + let mut _10: usize; + let mut _11: usize; + let mut _12: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + _10 = PtrMetadata(copy _1); + _9 = move _10; + _11 = const 4_usize; + _12 = Eq(move _9, move _11); + switchInt(move _12) -> [0: bb1, otherwise: bb2]; + } + + bb1: { + _0 = const false; + goto -> bb9; + } + + bb2: { + _2 = const &Branch([1_u16, 2_u16, 3_u16, 4_u16]): [u16]; + _3 = &raw const (*_1); + _4 = move _3 as *const u8 (PtrToPtr); + _5 = &raw const (*_2); + _6 = move _5 as *const u8 (PtrToPtr); + _7 = const 8_usize; + _8 = compare_bytes(move _4, move _6, move _7) -> [return: bb6, unwind unreachable]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + falseEdge -> [real: bb8, imaginary: bb1]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + switchInt(move _8) -> [0: bb4, otherwise: bb3]; + } + + bb7: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb8: { + _0 = const true; + goto -> bb9; + } + + bb9: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq.u16_slice_match.built.after.panic-unwind.mir b/tests/mir-opt/building/match/aggregate_array_eq.u16_slice_match.built.after.panic-unwind.mir new file mode 100644 index 0000000000000..a9c89902d29f3 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq.u16_slice_match.built.after.panic-unwind.mir @@ -0,0 +1,73 @@ +// MIR for `u16_slice_match` after built + +fn u16_slice_match(_1: &[u16]) -> bool { + debug x => _1; + let mut _0: bool; + let mut _2: &[u16]; + let mut _3: *const [u16]; + let mut _4: *const u8; + let mut _5: *const [u16]; + let mut _6: *const u8; + let mut _7: usize; + let mut _8: i32; + let mut _9: usize; + let mut _10: usize; + let mut _11: usize; + let mut _12: bool; + scope 1 { + } + + bb0: { + PlaceMention(_1); + _10 = PtrMetadata(copy _1); + _9 = move _10; + _11 = const 4_usize; + _12 = Eq(move _9, move _11); + switchInt(move _12) -> [0: bb1, otherwise: bb2]; + } + + bb1: { + _0 = const false; + goto -> bb9; + } + + bb2: { + _2 = const &Branch([1_u16, 2_u16, 3_u16, 4_u16]): [u16]; + _3 = &raw const (*_1); + _4 = move _3 as *const u8 (PtrToPtr); + _5 = &raw const (*_2); + _6 = move _5 as *const u8 (PtrToPtr); + _7 = const 8_usize; + _8 = compare_bytes(move _4, move _6, move _7) -> [return: bb6, unwind unreachable]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + falseEdge -> [real: bb8, imaginary: bb1]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + switchInt(move _8) -> [0: bb4, otherwise: bb3]; + } + + bb7: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb8: { + _0 = const true; + goto -> bb9; + } + + bb9: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq_no_core.array_match.built.after.mir b/tests/mir-opt/building/match/aggregate_array_eq_no_core.array_match.built.after.mir new file mode 100644 index 0000000000000..3539c573a68ea --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq_no_core.array_match.built.after.mir @@ -0,0 +1,62 @@ +// MIR for `array_match` after built + +fn array_match(_1: [u8; 4]) -> bool { + debug x => _1; + let mut _0: bool; + + bb0: { + PlaceMention(_1); + switchInt(copy _1[0 of 4]) -> [1: bb2, otherwise: bb1]; + } + + bb1: { + _0 = const false; + goto -> bb12; + } + + bb2: { + switchInt(copy _1[1 of 4]) -> [2: bb4, otherwise: bb3]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + switchInt(copy _1[2 of 4]) -> [3: bb6, otherwise: bb5]; + } + + bb5: { + goto -> bb3; + } + + bb6: { + switchInt(copy _1[3 of 4]) -> [4: bb8, otherwise: bb7]; + } + + bb7: { + goto -> bb5; + } + + bb8: { + falseEdge -> [real: bb11, imaginary: bb1]; + } + + bb9: { + goto -> bb7; + } + + bb10: { + FakeRead(ForMatchedPlace(None), _1); + unreachable; + } + + bb11: { + _0 = const true; + goto -> bb12; + } + + bb12: { + return; + } +} diff --git a/tests/mir-opt/building/match/aggregate_array_eq_no_core.rs b/tests/mir-opt/building/match/aggregate_array_eq_no_core.rs new file mode 100644 index 0000000000000..cd7a5a2fd67d6 --- /dev/null +++ b/tests/mir-opt/building/match/aggregate_array_eq_no_core.rs @@ -0,0 +1,52 @@ +//@ add-minicore +//@ compile-flags: -Zmir-opt-level=0 + +// Verify that a `#![no_core]` crate that does not define the `raw_eq` and +// `compare_bytes` lang items still compares an array pattern expanded from a +// constant element by element, rather than failing to find the intrinsics. + +#![crate_type = "lib"] +#![feature(no_core, lang_items)] +#![no_std] +#![no_core] + +extern crate minicore; +use minicore::*; + +// Constant patterns require `PartialEq` and `StructuralPartialEq`, which +// minicore does not provide. Only the MIR is checked, so the impls do not need +// meaningful bodies. +#[lang = "partial_eq"] +pub trait PartialEq { + fn eq(&self, other: &Rhs) -> bool; +} + +#[lang = "structural_peq"] +pub trait StructuralPartialEq {} + +impl PartialEq for u8 { + fn eq(&self, _: &u8) -> bool { + true + } +} + +impl PartialEq for [u8; 4] { + fn eq(&self, _: &[u8; 4]) -> bool { + true + } +} + +// EMIT_MIR aggregate_array_eq_no_core.array_match.built.after.mir +pub fn array_match(x: [u8; 4]) -> bool { + // CHECK-LABEL: fn array_match( + // CHECK-NOT: raw_eq + // CHECK: switchInt(copy _1[0 of 4]) + // CHECK: switchInt(copy _1[1 of 4]) + // CHECK: switchInt(copy _1[2 of 4]) + // CHECK: switchInt(copy _1[3 of 4]) + const EXPECTED: [u8; 4] = [1, 2, 3, 4]; + match x { + EXPECTED => true, + _ => false, + } +} diff --git a/tests/rustdoc-json/attrs/repr_combination.rs b/tests/rustdoc-json/attrs/repr_combination.rs index bd4a8563b6f27..d7f4c08f624b9 100644 --- a/tests/rustdoc-json/attrs/repr_combination.rs +++ b/tests/rustdoc-json/attrs/repr_combination.rs @@ -5,20 +5,20 @@ //@ is "$.index[?(@.name=='ReprCI8')].attrs" '[{"repr":{"align":null,"int":"i8","kind":"c","packed":null}}]' #[repr(C, i8)] pub enum ReprCI8 { - First, + First(usize), } //@ is "$.index[?(@.name=='SeparateReprCI16')].attrs" '[{"repr":{"align":null,"int":"i16","kind":"c","packed":null}}]' #[repr(C)] #[repr(i16)] pub enum SeparateReprCI16 { - First, + First(usize), } //@ is "$.index[?(@.name=='ReversedReprCUsize')].attrs" '[{"repr":{"align":null,"int":"usize","kind":"c","packed":null}}]' #[repr(usize, C)] pub enum ReversedReprCUsize { - First, + First(usize), } //@ is "$.index[?(@.name=='ReprCPacked')].attrs" '[{"repr":{"align":null,"int":null,"kind":"c","packed":1}}]' @@ -68,13 +68,13 @@ pub struct ReversedReprCAlign { //@ is "$.index[?(@.name=='AlignedExplicitRepr')].attrs" '[{"repr":{"align":16,"int":"isize","kind":"c","packed":null}}]' #[repr(C, align(16), isize)] pub enum AlignedExplicitRepr { - First, + First(usize), } //@ is "$.index[?(@.name=='ReorderedAlignedExplicitRepr')].attrs" '[{"repr":{"align":16,"int":"isize","kind":"c","packed":null}}]' #[repr(isize, C, align(16))] pub enum ReorderedAlignedExplicitRepr { - First, + First(usize), } //@ is "$.index[?(@.name=='Transparent')].attrs" '[{"repr":{"align":null,"int":null,"kind":"transparent","packed":null}}]' diff --git a/tests/rustdoc-ui/2024-doctests-crate-attribute.rs b/tests/rustdoc-ui/doctest/2024-doctests-crate-attribute.rs similarity index 100% rename from tests/rustdoc-ui/2024-doctests-crate-attribute.rs rename to tests/rustdoc-ui/doctest/2024-doctests-crate-attribute.rs diff --git a/tests/rustdoc-ui/2024-doctests-crate-attribute.stdout b/tests/rustdoc-ui/doctest/2024-doctests-crate-attribute.stdout similarity index 100% rename from tests/rustdoc-ui/2024-doctests-crate-attribute.stdout rename to tests/rustdoc-ui/doctest/2024-doctests-crate-attribute.stdout diff --git a/tests/rustdoc-ui/lints/check-attr.rs b/tests/rustdoc-ui/doctest/check-attr.rs similarity index 100% rename from tests/rustdoc-ui/lints/check-attr.rs rename to tests/rustdoc-ui/doctest/check-attr.rs diff --git a/tests/rustdoc-ui/lints/check-attr.stderr b/tests/rustdoc-ui/doctest/check-attr.stderr similarity index 100% rename from tests/rustdoc-ui/lints/check-attr.stderr rename to tests/rustdoc-ui/doctest/check-attr.stderr diff --git a/tests/rustdoc-ui/check-doc-alias-attr-location.rs b/tests/rustdoc-ui/lints/check-doc-alias-attr-location.rs similarity index 100% rename from tests/rustdoc-ui/check-doc-alias-attr-location.rs rename to tests/rustdoc-ui/lints/check-doc-alias-attr-location.rs diff --git a/tests/rustdoc-ui/check-doc-alias-attr-location.stderr b/tests/rustdoc-ui/lints/check-doc-alias-attr-location.stderr similarity index 100% rename from tests/rustdoc-ui/check-doc-alias-attr-location.stderr rename to tests/rustdoc-ui/lints/check-doc-alias-attr-location.stderr diff --git a/tests/rustdoc-ui/check-doc-alias-attr.rs b/tests/rustdoc-ui/lints/check-doc-alias-attr.rs similarity index 100% rename from tests/rustdoc-ui/check-doc-alias-attr.rs rename to tests/rustdoc-ui/lints/check-doc-alias-attr.rs diff --git a/tests/rustdoc-ui/check-doc-alias-attr.stderr b/tests/rustdoc-ui/lints/check-doc-alias-attr.stderr similarity index 100% rename from tests/rustdoc-ui/check-doc-alias-attr.stderr rename to tests/rustdoc-ui/lints/check-doc-alias-attr.stderr diff --git a/tests/rustdoc-ui/deprecated-attrs.rs b/tests/rustdoc-ui/lints/deprecated-attrs.rs similarity index 100% rename from tests/rustdoc-ui/deprecated-attrs.rs rename to tests/rustdoc-ui/lints/deprecated-attrs.rs diff --git a/tests/rustdoc-ui/deprecated-attrs.stderr b/tests/rustdoc-ui/lints/deprecated-attrs.stderr similarity index 100% rename from tests/rustdoc-ui/deprecated-attrs.stderr rename to tests/rustdoc-ui/lints/deprecated-attrs.stderr diff --git a/tests/rustdoc-ui/doc-attribute-unsupported.rs b/tests/rustdoc-ui/lints/doc-attribute-unsupported.rs similarity index 100% rename from tests/rustdoc-ui/doc-attribute-unsupported.rs rename to tests/rustdoc-ui/lints/doc-attribute-unsupported.rs diff --git a/tests/rustdoc-ui/doc-attribute-unsupported.stderr b/tests/rustdoc-ui/lints/doc-attribute-unsupported.stderr similarity index 100% rename from tests/rustdoc-ui/doc-attribute-unsupported.stderr rename to tests/rustdoc-ui/lints/doc-attribute-unsupported.stderr diff --git a/tests/rustdoc-ui/invalid-attribute.rs b/tests/rustdoc-ui/lints/invalid-attribute.rs similarity index 100% rename from tests/rustdoc-ui/invalid-attribute.rs rename to tests/rustdoc-ui/lints/invalid-attribute.rs diff --git a/tests/rustdoc-ui/invalid-attribute.stderr b/tests/rustdoc-ui/lints/invalid-attribute.stderr similarity index 100% rename from tests/rustdoc-ui/invalid-attribute.stderr rename to tests/rustdoc-ui/lints/invalid-attribute.stderr diff --git a/tests/rustdoc-ui/extract-doctests-result.rs b/tests/rustdoc-ui/output-format/extract-doctests-result.rs similarity index 100% rename from tests/rustdoc-ui/extract-doctests-result.rs rename to tests/rustdoc-ui/output-format/extract-doctests-result.rs diff --git a/tests/rustdoc-ui/extract-doctests-result.stdout b/tests/rustdoc-ui/output-format/extract-doctests-result.stdout similarity index 100% rename from tests/rustdoc-ui/extract-doctests-result.stdout rename to tests/rustdoc-ui/output-format/extract-doctests-result.stdout diff --git a/tests/rustdoc-ui/extract-doctests.rs b/tests/rustdoc-ui/output-format/extract-doctests.rs similarity index 100% rename from tests/rustdoc-ui/extract-doctests.rs rename to tests/rustdoc-ui/output-format/extract-doctests.rs diff --git a/tests/rustdoc-ui/extract-doctests.stdout b/tests/rustdoc-ui/output-format/extract-doctests.stdout similarity index 100% rename from tests/rustdoc-ui/extract-doctests.stdout rename to tests/rustdoc-ui/output-format/extract-doctests.stdout diff --git a/tests/rustdoc-ui/output-format-doctest-emit.dep-info.stderr b/tests/rustdoc-ui/output-format/output-format-doctest-emit.dep-info.stderr similarity index 100% rename from tests/rustdoc-ui/output-format-doctest-emit.dep-info.stderr rename to tests/rustdoc-ui/output-format/output-format-doctest-emit.dep-info.stderr diff --git a/tests/rustdoc-ui/output-format-doctest-emit.html-static-files.stderr b/tests/rustdoc-ui/output-format/output-format-doctest-emit.html-static-files.stderr similarity index 100% rename from tests/rustdoc-ui/output-format-doctest-emit.html-static-files.stderr rename to tests/rustdoc-ui/output-format/output-format-doctest-emit.html-static-files.stderr diff --git a/tests/rustdoc-ui/output-format-doctest-emit.rs b/tests/rustdoc-ui/output-format/output-format-doctest-emit.rs similarity index 100% rename from tests/rustdoc-ui/output-format-doctest-emit.rs rename to tests/rustdoc-ui/output-format/output-format-doctest-emit.rs diff --git a/tests/rustdoc-ui/output-format-doctests-unstable.rs b/tests/rustdoc-ui/output-format/output-format-doctests-unstable.rs similarity index 100% rename from tests/rustdoc-ui/output-format-doctests-unstable.rs rename to tests/rustdoc-ui/output-format/output-format-doctests-unstable.rs diff --git a/tests/rustdoc-ui/output-format-doctests-unstable.stderr b/tests/rustdoc-ui/output-format/output-format-doctests-unstable.stderr similarity index 100% rename from tests/rustdoc-ui/output-format-doctests-unstable.stderr rename to tests/rustdoc-ui/output-format/output-format-doctests-unstable.stderr diff --git a/tests/rustdoc-ui/output-format-html-stable.rs b/tests/rustdoc-ui/output-format/output-format-html-stable.rs similarity index 100% rename from tests/rustdoc-ui/output-format-html-stable.rs rename to tests/rustdoc-ui/output-format/output-format-html-stable.rs diff --git a/tests/rustdoc-ui/output-format-irjson-emit-depinfo.rs b/tests/rustdoc-ui/output-format/output-format-irjson-emit-depinfo.rs similarity index 100% rename from tests/rustdoc-ui/output-format-irjson-emit-depinfo.rs rename to tests/rustdoc-ui/output-format/output-format-irjson-emit-depinfo.rs diff --git a/tests/rustdoc-ui/output-format-irjson-unstable.rs b/tests/rustdoc-ui/output-format/output-format-irjson-unstable.rs similarity index 100% rename from tests/rustdoc-ui/output-format-irjson-unstable.rs rename to tests/rustdoc-ui/output-format/output-format-irjson-unstable.rs diff --git a/tests/rustdoc-ui/output-format-irjson-unstable.stderr b/tests/rustdoc-ui/output-format/output-format-irjson-unstable.stderr similarity index 100% rename from tests/rustdoc-ui/output-format-irjson-unstable.stderr rename to tests/rustdoc-ui/output-format/output-format-irjson-unstable.stderr diff --git a/tests/rustdoc-ui/output-format-unknown.rs b/tests/rustdoc-ui/output-format/output-format-unknown.rs similarity index 100% rename from tests/rustdoc-ui/output-format-unknown.rs rename to tests/rustdoc-ui/output-format/output-format-unknown.rs diff --git a/tests/rustdoc-ui/output-format-unknown.stderr b/tests/rustdoc-ui/output-format/output-format-unknown.stderr similarity index 100% rename from tests/rustdoc-ui/output-format-unknown.stderr rename to tests/rustdoc-ui/output-format/output-format-unknown.stderr diff --git a/tests/rustdoc-ui/remap-path-prefix-failed-doctest-output.stdout b/tests/rustdoc-ui/remap-path-prefix-failed-doctest-output.stdout deleted file mode 100644 index 08f7a4ddd3a64..0000000000000 --- a/tests/rustdoc-ui/remap-path-prefix-failed-doctest-output.stdout +++ /dev/null @@ -1,22 +0,0 @@ - -running 1 test -test remapped_path/remap-path-prefix-failed-doctest-output.rs - SomeStruct (line 11) ... FAILED - -failures: - ----- remapped_path/remap-path-prefix-failed-doctest-output.rs - SomeStruct (line 11) stdout ---- -Test executable failed (exit status: 101). - -stderr: - -thread 'main' ($TID) panicked at remapped_path/remap-path-prefix-failed-doctest-output.rs:3:1: -oh no -note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace - - - -failures: - remapped_path/remap-path-prefix-failed-doctest-output.rs - SomeStruct (line 11) - -test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME - diff --git a/tests/rustdoc-ui/remap-path-prefix-invalid-doctest.stdout b/tests/rustdoc-ui/remap-path-prefix-invalid-doctest.stdout deleted file mode 100644 index c0d2515998f23..0000000000000 --- a/tests/rustdoc-ui/remap-path-prefix-invalid-doctest.stdout +++ /dev/null @@ -1,22 +0,0 @@ - -running 1 test -test remapped_path/remap-path-prefix-invalid-doctest.rs - SomeStruct (line 10) ... FAILED - -failures: - ----- remapped_path/remap-path-prefix-invalid-doctest.rs - SomeStruct (line 10) stdout ---- -error: expected one of `!` or `::`, found `is` - --> remapped_path/remap-path-prefix-invalid-doctest.rs:11:6 - | -LL | this is not real code - | ^^ expected one of `!` or `::` - -error: aborting due to 1 previous error - -Couldn't compile the test. - -failures: - remapped_path/remap-path-prefix-invalid-doctest.rs - SomeStruct (line 10) - -test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME - diff --git a/tests/rustdoc-ui/remap-path-prefix-doctest.rs b/tests/rustdoc-ui/remap-path/remap-path-prefix-doctest.rs similarity index 100% rename from tests/rustdoc-ui/remap-path-prefix-doctest.rs rename to tests/rustdoc-ui/remap-path/remap-path-prefix-doctest.rs diff --git a/tests/rustdoc-ui/remap-path-prefix-doctest.with-diag-scope.stdout b/tests/rustdoc-ui/remap-path/remap-path-prefix-doctest.with-diag-scope.stdout similarity index 50% rename from tests/rustdoc-ui/remap-path-prefix-doctest.with-diag-scope.stdout rename to tests/rustdoc-ui/remap-path/remap-path-prefix-doctest.with-diag-scope.stdout index 248f7734652fa..8767f66d23d84 100644 --- a/tests/rustdoc-ui/remap-path-prefix-doctest.with-diag-scope.stdout +++ b/tests/rustdoc-ui/remap-path/remap-path-prefix-doctest.with-diag-scope.stdout @@ -1,12 +1,12 @@ running 1 test -test remapped_path/remap-path-prefix-doctest.rs - SomeStruct (line 19) ... FAILED +test remapped_path/remap-path/remap-path-prefix-doctest.rs - SomeStruct (line 19) ... FAILED failures: ----- remapped_path/remap-path-prefix-doctest.rs - SomeStruct (line 19) stdout ---- +---- remapped_path/remap-path/remap-path-prefix-doctest.rs - SomeStruct (line 19) stdout ---- error: this file contains an unclosed delimiter - --> remapped_path/remap-path-prefix-doctest.rs:20:12 + --> remapped_path/remap-path/remap-path-prefix-doctest.rs:20:12 | LL | fn invalid( | -^ @@ -18,7 +18,7 @@ error: aborting due to 1 previous error Couldn't compile the test. failures: - remapped_path/remap-path-prefix-doctest.rs - SomeStruct (line 19) + remapped_path/remap-path/remap-path-prefix-doctest.rs - SomeStruct (line 19) test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME diff --git a/tests/rustdoc-ui/remap-path-prefix-doctest.with-doc-scope.stdout b/tests/rustdoc-ui/remap-path/remap-path-prefix-doctest.with-doc-scope.stdout similarity index 100% rename from tests/rustdoc-ui/remap-path-prefix-doctest.with-doc-scope.stdout rename to tests/rustdoc-ui/remap-path/remap-path-prefix-doctest.with-doc-scope.stdout diff --git a/tests/rustdoc-ui/remap-path-prefix-doctest.with-macro-scope.stdout b/tests/rustdoc-ui/remap-path/remap-path-prefix-doctest.with-macro-scope.stdout similarity index 100% rename from tests/rustdoc-ui/remap-path-prefix-doctest.with-macro-scope.stdout rename to tests/rustdoc-ui/remap-path/remap-path-prefix-doctest.with-macro-scope.stdout diff --git a/tests/rustdoc-ui/remap-path-prefix-doctest.with-object-scope.stdout b/tests/rustdoc-ui/remap-path/remap-path-prefix-doctest.with-object-scope.stdout similarity index 100% rename from tests/rustdoc-ui/remap-path-prefix-doctest.with-object-scope.stdout rename to tests/rustdoc-ui/remap-path/remap-path-prefix-doctest.with-object-scope.stdout diff --git a/tests/rustdoc-ui/remap-path-prefix-doctest.without-scope.stdout b/tests/rustdoc-ui/remap-path/remap-path-prefix-doctest.without-scope.stdout similarity index 50% rename from tests/rustdoc-ui/remap-path-prefix-doctest.without-scope.stdout rename to tests/rustdoc-ui/remap-path/remap-path-prefix-doctest.without-scope.stdout index 248f7734652fa..8767f66d23d84 100644 --- a/tests/rustdoc-ui/remap-path-prefix-doctest.without-scope.stdout +++ b/tests/rustdoc-ui/remap-path/remap-path-prefix-doctest.without-scope.stdout @@ -1,12 +1,12 @@ running 1 test -test remapped_path/remap-path-prefix-doctest.rs - SomeStruct (line 19) ... FAILED +test remapped_path/remap-path/remap-path-prefix-doctest.rs - SomeStruct (line 19) ... FAILED failures: ----- remapped_path/remap-path-prefix-doctest.rs - SomeStruct (line 19) stdout ---- +---- remapped_path/remap-path/remap-path-prefix-doctest.rs - SomeStruct (line 19) stdout ---- error: this file contains an unclosed delimiter - --> remapped_path/remap-path-prefix-doctest.rs:20:12 + --> remapped_path/remap-path/remap-path-prefix-doctest.rs:20:12 | LL | fn invalid( | -^ @@ -18,7 +18,7 @@ error: aborting due to 1 previous error Couldn't compile the test. failures: - remapped_path/remap-path-prefix-doctest.rs - SomeStruct (line 19) + remapped_path/remap-path/remap-path-prefix-doctest.rs - SomeStruct (line 19) test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME diff --git a/tests/rustdoc-ui/remap-path-prefix-failed-doctest-output.rs b/tests/rustdoc-ui/remap-path/remap-path-prefix-failed-doctest-output.rs similarity index 100% rename from tests/rustdoc-ui/remap-path-prefix-failed-doctest-output.rs rename to tests/rustdoc-ui/remap-path/remap-path-prefix-failed-doctest-output.rs diff --git a/tests/rustdoc-ui/remap-path/remap-path-prefix-failed-doctest-output.stdout b/tests/rustdoc-ui/remap-path/remap-path-prefix-failed-doctest-output.stdout new file mode 100644 index 0000000000000..2f2dd88eaf8eb --- /dev/null +++ b/tests/rustdoc-ui/remap-path/remap-path-prefix-failed-doctest-output.stdout @@ -0,0 +1,22 @@ + +running 1 test +test remapped_path/remap-path/remap-path-prefix-failed-doctest-output.rs - SomeStruct (line 11) ... FAILED + +failures: + +---- remapped_path/remap-path/remap-path-prefix-failed-doctest-output.rs - SomeStruct (line 11) stdout ---- +Test executable failed (exit status: 101). + +stderr: + +thread 'main' ($TID) panicked at remapped_path/remap-path/remap-path-prefix-failed-doctest-output.rs:3:1: +oh no +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace + + + +failures: + remapped_path/remap-path/remap-path-prefix-failed-doctest-output.rs - SomeStruct (line 11) + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME + diff --git a/tests/rustdoc-ui/remap-path-prefix-file.all_scope.stdout b/tests/rustdoc-ui/remap-path/remap-path-prefix-file.all_scope.stdout similarity index 60% rename from tests/rustdoc-ui/remap-path-prefix-file.all_scope.stdout rename to tests/rustdoc-ui/remap-path/remap-path-prefix-file.all_scope.stdout index 910e5a362cabb..f4e9ae57d51c0 100644 --- a/tests/rustdoc-ui/remap-path-prefix-file.all_scope.stdout +++ b/tests/rustdoc-ui/remap-path/remap-path-prefix-file.all_scope.stdout @@ -1,6 +1,6 @@ running 1 test -test /REMAPPED/remap-path-prefix-file.rs - f (line 24) ... ok +test /REMAPPED/remap-path/remap-path-prefix-file.rs - f (line 24) ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME diff --git a/tests/rustdoc-ui/remap-path-prefix-file.debuginfo_scope.stdout b/tests/rustdoc-ui/remap-path/remap-path-prefix-file.debuginfo_scope.stdout similarity index 100% rename from tests/rustdoc-ui/remap-path-prefix-file.debuginfo_scope.stdout rename to tests/rustdoc-ui/remap-path/remap-path-prefix-file.debuginfo_scope.stdout diff --git a/tests/rustdoc-ui/remap-path-prefix-file.diagnostics_scope.stdout b/tests/rustdoc-ui/remap-path/remap-path-prefix-file.diagnostics_scope.stdout similarity index 60% rename from tests/rustdoc-ui/remap-path-prefix-file.diagnostics_scope.stdout rename to tests/rustdoc-ui/remap-path/remap-path-prefix-file.diagnostics_scope.stdout index 910e5a362cabb..f4e9ae57d51c0 100644 --- a/tests/rustdoc-ui/remap-path-prefix-file.diagnostics_scope.stdout +++ b/tests/rustdoc-ui/remap-path/remap-path-prefix-file.diagnostics_scope.stdout @@ -1,6 +1,6 @@ running 1 test -test /REMAPPED/remap-path-prefix-file.rs - f (line 24) ... ok +test /REMAPPED/remap-path/remap-path-prefix-file.rs - f (line 24) ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME diff --git a/tests/rustdoc-ui/remap-path-prefix-file.documentation_scope.stdout b/tests/rustdoc-ui/remap-path/remap-path-prefix-file.documentation_scope.stdout similarity index 100% rename from tests/rustdoc-ui/remap-path-prefix-file.documentation_scope.stdout rename to tests/rustdoc-ui/remap-path/remap-path-prefix-file.documentation_scope.stdout diff --git a/tests/rustdoc-ui/remap-path-prefix-file.macro_scope.stdout b/tests/rustdoc-ui/remap-path/remap-path-prefix-file.macro_scope.stdout similarity index 100% rename from tests/rustdoc-ui/remap-path-prefix-file.macro_scope.stdout rename to tests/rustdoc-ui/remap-path/remap-path-prefix-file.macro_scope.stdout diff --git a/tests/rustdoc-ui/remap-path-prefix-file.no_scopes.stdout b/tests/rustdoc-ui/remap-path/remap-path-prefix-file.no_scopes.stdout similarity index 60% rename from tests/rustdoc-ui/remap-path-prefix-file.no_scopes.stdout rename to tests/rustdoc-ui/remap-path/remap-path-prefix-file.no_scopes.stdout index 910e5a362cabb..f4e9ae57d51c0 100644 --- a/tests/rustdoc-ui/remap-path-prefix-file.no_scopes.stdout +++ b/tests/rustdoc-ui/remap-path/remap-path-prefix-file.no_scopes.stdout @@ -1,6 +1,6 @@ running 1 test -test /REMAPPED/remap-path-prefix-file.rs - f (line 24) ... ok +test /REMAPPED/remap-path/remap-path-prefix-file.rs - f (line 24) ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME diff --git a/tests/rustdoc-ui/remap-path-prefix-file.object_scope.stdout b/tests/rustdoc-ui/remap-path/remap-path-prefix-file.object_scope.stdout similarity index 100% rename from tests/rustdoc-ui/remap-path-prefix-file.object_scope.stdout rename to tests/rustdoc-ui/remap-path/remap-path-prefix-file.object_scope.stdout diff --git a/tests/rustdoc-ui/remap-path-prefix-file.rs b/tests/rustdoc-ui/remap-path/remap-path-prefix-file.rs similarity index 100% rename from tests/rustdoc-ui/remap-path-prefix-file.rs rename to tests/rustdoc-ui/remap-path/remap-path-prefix-file.rs diff --git a/tests/rustdoc-ui/remap-path-prefix-invalid-doctest.rs b/tests/rustdoc-ui/remap-path/remap-path-prefix-invalid-doctest.rs similarity index 100% rename from tests/rustdoc-ui/remap-path-prefix-invalid-doctest.rs rename to tests/rustdoc-ui/remap-path/remap-path-prefix-invalid-doctest.rs diff --git a/tests/rustdoc-ui/remap-path/remap-path-prefix-invalid-doctest.stdout b/tests/rustdoc-ui/remap-path/remap-path-prefix-invalid-doctest.stdout new file mode 100644 index 0000000000000..4c413cad70e30 --- /dev/null +++ b/tests/rustdoc-ui/remap-path/remap-path-prefix-invalid-doctest.stdout @@ -0,0 +1,22 @@ + +running 1 test +test remapped_path/remap-path/remap-path-prefix-invalid-doctest.rs - SomeStruct (line 10) ... FAILED + +failures: + +---- remapped_path/remap-path/remap-path-prefix-invalid-doctest.rs - SomeStruct (line 10) stdout ---- +error: expected one of `!` or `::`, found `is` + --> remapped_path/remap-path/remap-path-prefix-invalid-doctest.rs:11:6 + | +LL | this is not real code + | ^^ expected one of `!` or `::` + +error: aborting due to 1 previous error + +Couldn't compile the test. + +failures: + remapped_path/remap-path/remap-path-prefix-invalid-doctest.rs - SomeStruct (line 10) + +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME + diff --git a/tests/rustdoc-ui/remap-path-prefix-macro-138520.rs b/tests/rustdoc-ui/remap-path/remap-path-prefix-macro-138520.rs similarity index 100% rename from tests/rustdoc-ui/remap-path-prefix-macro-138520.rs rename to tests/rustdoc-ui/remap-path/remap-path-prefix-macro-138520.rs diff --git a/tests/rustdoc-ui/remap-path-prefix-passed-doctest-output.rs b/tests/rustdoc-ui/remap-path/remap-path-prefix-passed-doctest-output.rs similarity index 100% rename from tests/rustdoc-ui/remap-path-prefix-passed-doctest-output.rs rename to tests/rustdoc-ui/remap-path/remap-path-prefix-passed-doctest-output.rs diff --git a/tests/rustdoc-ui/remap-path-prefix-passed-doctest-output.stdout b/tests/rustdoc-ui/remap-path/remap-path-prefix-passed-doctest-output.stdout similarity index 52% rename from tests/rustdoc-ui/remap-path-prefix-passed-doctest-output.stdout rename to tests/rustdoc-ui/remap-path/remap-path-prefix-passed-doctest-output.stdout index 8ffb569488563..366de986296d9 100644 --- a/tests/rustdoc-ui/remap-path-prefix-passed-doctest-output.stdout +++ b/tests/rustdoc-ui/remap-path/remap-path-prefix-passed-doctest-output.stdout @@ -1,6 +1,6 @@ running 1 test -test remapped_path/remap-path-prefix-passed-doctest-output.rs - SomeStruct (line 11) ... ok +test remapped_path/remap-path/remap-path-prefix-passed-doctest-output.rs - SomeStruct (line 11) ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME diff --git a/tests/rustdoc-ui/remap-path-prefix.rs b/tests/rustdoc-ui/remap-path/remap-path-prefix.rs similarity index 100% rename from tests/rustdoc-ui/remap-path-prefix.rs rename to tests/rustdoc-ui/remap-path/remap-path-prefix.rs diff --git a/tests/rustdoc-ui/remap-path-prefix.with-debuginfo-scope.stderr b/tests/rustdoc-ui/remap-path/remap-path-prefix.with-debuginfo-scope.stderr similarity index 100% rename from tests/rustdoc-ui/remap-path-prefix.with-debuginfo-scope.stderr rename to tests/rustdoc-ui/remap-path/remap-path-prefix.with-debuginfo-scope.stderr diff --git a/tests/rustdoc-ui/remap-path-prefix.with-diag-scope.stderr b/tests/rustdoc-ui/remap-path/remap-path-prefix.with-diag-scope.stderr similarity index 78% rename from tests/rustdoc-ui/remap-path-prefix.with-diag-scope.stderr rename to tests/rustdoc-ui/remap-path/remap-path-prefix.with-diag-scope.stderr index a51ff5dce4a38..19b3593685e2c 100644 --- a/tests/rustdoc-ui/remap-path-prefix.with-diag-scope.stderr +++ b/tests/rustdoc-ui/remap-path/remap-path-prefix.with-diag-scope.stderr @@ -1,5 +1,5 @@ error: file!() = $DIR/remap-path-prefix.rs - --> remapped/remap-path-prefix.rs:21:1 + --> remapped/remap-path/remap-path-prefix.rs:21:1 | LL | compile_error!(concat!("file!() = ", file!())); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/rustdoc-ui/remap-path-prefix.with-doc-scope.stderr b/tests/rustdoc-ui/remap-path/remap-path-prefix.with-doc-scope.stderr similarity index 100% rename from tests/rustdoc-ui/remap-path-prefix.with-doc-scope.stderr rename to tests/rustdoc-ui/remap-path/remap-path-prefix.with-doc-scope.stderr diff --git a/tests/rustdoc-ui/remap-path-prefix.with-macro-scope.stderr b/tests/rustdoc-ui/remap-path/remap-path-prefix.with-macro-scope.stderr similarity index 76% rename from tests/rustdoc-ui/remap-path-prefix.with-macro-scope.stderr rename to tests/rustdoc-ui/remap-path/remap-path-prefix.with-macro-scope.stderr index 2ac0fb513a9cd..05fe8b28fa047 100644 --- a/tests/rustdoc-ui/remap-path-prefix.with-macro-scope.stderr +++ b/tests/rustdoc-ui/remap-path/remap-path-prefix.with-macro-scope.stderr @@ -1,4 +1,4 @@ -error: file!() = remapped/remap-path-prefix.rs +error: file!() = remapped/remap-path/remap-path-prefix.rs --> $DIR/remap-path-prefix.rs:21:1 | LL | compile_error!(concat!("file!() = ", file!())); diff --git a/tests/rustdoc-ui/remap-path-prefix.without-remap.stderr b/tests/rustdoc-ui/remap-path/remap-path-prefix.without-remap.stderr similarity index 100% rename from tests/rustdoc-ui/remap-path-prefix.without-remap.stderr rename to tests/rustdoc-ui/remap-path/remap-path-prefix.without-remap.stderr diff --git a/tests/rustdoc-ui/remap-path-prefix.without-scopes.stderr b/tests/rustdoc-ui/remap-path/remap-path-prefix.without-scopes.stderr similarity index 58% rename from tests/rustdoc-ui/remap-path-prefix.without-scopes.stderr rename to tests/rustdoc-ui/remap-path/remap-path-prefix.without-scopes.stderr index 8564703e74dcc..5e483522fda55 100644 --- a/tests/rustdoc-ui/remap-path-prefix.without-scopes.stderr +++ b/tests/rustdoc-ui/remap-path/remap-path-prefix.without-scopes.stderr @@ -1,5 +1,5 @@ -error: file!() = remapped/remap-path-prefix.rs - --> remapped/remap-path-prefix.rs:21:1 +error: file!() = remapped/remap-path/remap-path-prefix.rs + --> remapped/remap-path/remap-path-prefix.rs:21:1 | LL | compile_error!(concat!("file!() = ", file!())); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/rustdoc-ui/remap-path-scope-invalid.foo.stderr b/tests/rustdoc-ui/remap-path/remap-path-scope-invalid.foo.stderr similarity index 100% rename from tests/rustdoc-ui/remap-path-scope-invalid.foo.stderr rename to tests/rustdoc-ui/remap-path/remap-path-scope-invalid.foo.stderr diff --git a/tests/rustdoc-ui/remap-path-scope-invalid.rs b/tests/rustdoc-ui/remap-path/remap-path-scope-invalid.rs similarity index 100% rename from tests/rustdoc-ui/remap-path-scope-invalid.rs rename to tests/rustdoc-ui/remap-path/remap-path-scope-invalid.rs diff --git a/tests/rustdoc-ui/remap-path-scope-invalid.underscore.stderr b/tests/rustdoc-ui/remap-path/remap-path-scope-invalid.underscore.stderr similarity index 100% rename from tests/rustdoc-ui/remap-path-scope-invalid.underscore.stderr rename to tests/rustdoc-ui/remap-path/remap-path-scope-invalid.underscore.stderr diff --git a/tests/rustdoc-ui/remap-path-scope-unstable.rs b/tests/rustdoc-ui/remap-path/remap-path-scope-unstable.rs similarity index 100% rename from tests/rustdoc-ui/remap-path-scope-unstable.rs rename to tests/rustdoc-ui/remap-path/remap-path-scope-unstable.rs diff --git a/tests/rustdoc-ui/remap-path-scope-unstable.stderr b/tests/rustdoc-ui/remap-path/remap-path-scope-unstable.stderr similarity index 100% rename from tests/rustdoc-ui/remap-path-scope-unstable.stderr rename to tests/rustdoc-ui/remap-path/remap-path-scope-unstable.stderr diff --git a/tests/ui/abi/numbers-arithmetic/i128-ffi.rs b/tests/ui/abi/numbers-arithmetic/i128-ffi.rs index 26d65e8bbf853..2248e9a75b04b 100644 --- a/tests/ui/abi/numbers-arithmetic/i128-ffi.rs +++ b/tests/ui/abi/numbers-arithmetic/i128-ffi.rs @@ -12,7 +12,7 @@ extern "C" { fn identity(f: u128) -> u128; fn square(f: i128) -> i128; - fn sub(f: i128, f: i128) -> i128; + fn sub(f1: i128, f2: i128) -> i128; } fn main() { diff --git a/tests/ui/argument-suggestions/extern-fn-arg-names.stderr b/tests/ui/argument-suggestions/extern-fn-arg-names.stderr index e4183e6d519ef..8204d53733aad 100644 --- a/tests/ui/argument-suggestions/extern-fn-arg-names.stderr +++ b/tests/ui/argument-suggestions/extern-fn-arg-names.stderr @@ -14,7 +14,7 @@ note: function defined here --> $DIR/extern-fn-arg-names.rs:2:8 | LL | fn dstfn(src: i32, dst: err); - | ^^^^^ --- + | ^^^^^ -------- help: provide the argument | LL | dstfn(1, /* dst */); diff --git a/tests/ui/c-variadic/variadic-ffi-1.stderr b/tests/ui/c-variadic/variadic-ffi-1.stderr index b7182887cfb78..e600bea41246e 100644 --- a/tests/ui/c-variadic/variadic-ffi-1.stderr +++ b/tests/ui/c-variadic/variadic-ffi-1.stderr @@ -20,7 +20,7 @@ note: function defined here --> $DIR/variadic-ffi-1.rs:22:8 | LL | fn foo(f: isize, x: u8, ...); - | ^^^ - - + | ^^^ -------- ----- help: provide the arguments | LL | foo(/* isize */, /* u8 */); @@ -36,7 +36,7 @@ note: function defined here --> $DIR/variadic-ffi-1.rs:22:8 | LL | fn foo(f: isize, x: u8, ...); - | ^^^ - + | ^^^ ----- help: provide the argument | LL | foo(1, /* u8 */); diff --git a/tests/ui/check-cfg/target_feature.stderr b/tests/ui/check-cfg/target_feature.stderr index 8250fc1f1d498..5f79f3d533e15 100644 --- a/tests/ui/check-cfg/target_feature.stderr +++ b/tests/ui/check-cfg/target_feature.stderr @@ -56,7 +56,6 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `avxvnniint16` `avxvnniint8` `b` -`backchain` `bf16` `bmi1` `bmi2` diff --git a/tests/ui/error-codes/E0060.stderr b/tests/ui/error-codes/E0060.stderr index 7065b623ad325..9bb5e6edbfef6 100644 --- a/tests/ui/error-codes/E0060.stderr +++ b/tests/ui/error-codes/E0060.stderr @@ -8,7 +8,7 @@ note: function defined here --> $DIR/E0060.rs:2:8 | LL | fn printf(_: *const u8, ...) -> u32; - | ^^^^^^ - + | ^^^^^^ ------------ help: provide the argument | LL | unsafe { printf(/* *const u8 */); } diff --git a/tests/ui/feature-gates/feature-gate-repr-simd.rs b/tests/ui/feature-gates/feature-gate-repr-simd.rs index e73ad1e536aa3..228c8e4941a7e 100644 --- a/tests/ui/feature-gates/feature-gate-repr-simd.rs +++ b/tests/ui/feature-gates/feature-gate-repr-simd.rs @@ -2,7 +2,6 @@ struct Foo([u64; 2]); #[repr(C)] //~ ERROR conflicting representation hints -//~^ WARN this was previously accepted #[repr(simd)] //~ ERROR: SIMD types are experimental struct Bar([u64; 2]); diff --git a/tests/ui/feature-gates/feature-gate-repr-simd.stderr b/tests/ui/feature-gates/feature-gate-repr-simd.stderr index 95936212ce1cd..8675a67a54eb6 100644 --- a/tests/ui/feature-gates/feature-gate-repr-simd.stderr +++ b/tests/ui/feature-gates/feature-gate-repr-simd.stderr @@ -9,7 +9,7 @@ LL | #[repr(simd)] = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error[E0658]: SIMD types are experimental and possibly buggy - --> $DIR/feature-gate-repr-simd.rs:6:8 + --> $DIR/feature-gate-repr-simd.rs:5:8 | LL | #[repr(simd)] | ^^^^ @@ -19,7 +19,7 @@ LL | #[repr(simd)] = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error[E0658]: SIMD types are experimental and possibly buggy - --> $DIR/feature-gate-repr-simd.rs:9:8 + --> $DIR/feature-gate-repr-simd.rs:8:8 | LL | #[repr(simd)] | ^^^^ @@ -29,7 +29,7 @@ LL | #[repr(simd)] = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error: the `repr(simd)` attribute cannot be used on unions - --> $DIR/feature-gate-repr-simd.rs:9:3 + --> $DIR/feature-gate-repr-simd.rs:8:3 | LL | #[repr(simd)] | ^^^^^^^^^^ @@ -39,7 +39,7 @@ LL | union U {f: u32} = help: the `repr(simd)` attribute can only be applied to structs error[E0658]: SIMD types are experimental and possibly buggy - --> $DIR/feature-gate-repr-simd.rs:13:8 + --> $DIR/feature-gate-repr-simd.rs:12:8 | LL | #[repr(simd)] | ^^^^ @@ -49,7 +49,7 @@ LL | #[repr(simd)] = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error: the `repr(simd)` attribute cannot be used on enums - --> $DIR/feature-gate-repr-simd.rs:13:3 + --> $DIR/feature-gate-repr-simd.rs:12:3 | LL | #[repr(simd)] | ^^^^^^^^^^ @@ -63,29 +63,10 @@ error[E0566]: conflicting representation hints | LL | #[repr(C)] | ^ -LL | LL | #[repr(simd)] | ^^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 - = note: `#[deny(conflicting_repr_hints)]` (part of `#[deny(future_incompatible)]`) on by default error: aborting due to 7 previous errors Some errors have detailed explanations: E0566, E0658. For more information about an error, try `rustc --explain E0566`. -Future incompatibility report: Future breakage diagnostic: -error[E0566]: conflicting representation hints - --> $DIR/feature-gate-repr-simd.rs:4:8 - | -LL | #[repr(C)] - | ^ -LL | -LL | #[repr(simd)] - | ^^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 - = note: `#[deny(conflicting_repr_hints)]` (part of `#[deny(future_incompatible)]`) on by default - diff --git a/tests/ui/fn/fn-ptr-pattern.rs b/tests/ui/fn/fn-ptr-pattern.rs index 465fa9f9e20b5..ff78c9ac36055 100644 --- a/tests/ui/fn/fn-ptr-pattern.rs +++ b/tests/ui/fn/fn-ptr-pattern.rs @@ -5,6 +5,7 @@ fn allowed( f3: fn(String, msg: String), f4: fn(msg: String, String), f5: fn(duplicate_name: bool, duplicate_name: bool), + //~^ WARN identifier `duplicate_name` is bound more than once in this parameter list ) { } @@ -46,6 +47,7 @@ fn semantics( variadics: extern "C" fn(...), duplicate_names: fn(x: usize, x: usize), + //~^ WARN identifier `x` is bound more than once in this parameter list ) { } // Patterns are also syntactically rejected, but restricted patterns are not diff --git a/tests/ui/fn/fn-ptr-pattern.stderr b/tests/ui/fn/fn-ptr-pattern.stderr index bf99fd06cf184..78c3b96c0327a 100644 --- a/tests/ui/fn/fn-ptr-pattern.stderr +++ b/tests/ui/fn/fn-ptr-pattern.stderr @@ -1,5 +1,5 @@ error[E0642]: patterns aren't allowed in function pointer types - --> $DIR/fn-ptr-pattern.rs:13:14 + --> $DIR/fn-ptr-pattern.rs:14:14 | LL | pat1: fn(1..3: bool), | ^^^^ @@ -11,7 +11,7 @@ LL + pat1: fn(_: bool), | error[E0642]: patterns aren't allowed in function pointer types - --> $DIR/fn-ptr-pattern.rs:15:14 + --> $DIR/fn-ptr-pattern.rs:16:14 | LL | pat2: fn((x, y): (bool, bool)), | ^^^^^^ @@ -23,7 +23,7 @@ LL + pat2: fn(_: (bool, bool)), | error[E0642]: patterns aren't allowed in function pointer types - --> $DIR/fn-ptr-pattern.rs:17:14 + --> $DIR/fn-ptr-pattern.rs:18:14 | LL | pat3: fn(Thing { a, b }: Thing), | ^^^^^^^^^^^^^^ @@ -35,7 +35,7 @@ LL + pat3: fn(_: Thing), | error[E0642]: patterns aren't allowed in function pointer types - --> $DIR/fn-ptr-pattern.rs:19:14 + --> $DIR/fn-ptr-pattern.rs:20:14 | LL | pat4: fn(NoThing { a, b }: NoThing), | ^^^^^^^^^^^^^^^^ @@ -47,7 +47,7 @@ LL + pat4: fn(_: NoThing), | error[E0642]: patterns aren't allowed in function pointer types - --> $DIR/fn-ptr-pattern.rs:22:14 + --> $DIR/fn-ptr-pattern.rs:23:14 | LL | pat5: fn((((((x))))): bool), | ^^^^^^^^^^^ @@ -59,19 +59,19 @@ LL + pat5: fn(_: bool), | error: unexpected `self` parameter in function - --> $DIR/fn-ptr-pattern.rs:27:21 + --> $DIR/fn-ptr-pattern.rs:28:21 | LL | self2: fn(self, self), | ^^^^ must be the first parameter of an associated function error: unexpected `self` parameter in function - --> $DIR/fn-ptr-pattern.rs:30:21 + --> $DIR/fn-ptr-pattern.rs:31:21 | LL | self3: fn(bool, self), | ^^^^ must be the first parameter of an associated function error[E0642]: patterns aren't allowed in function pointer types - --> $DIR/fn-ptr-pattern.rs:54:14 + --> $DIR/fn-ptr-pattern.rs:56:14 | LL | pat1: fn(1..3: bool), | ^^^^ @@ -83,7 +83,7 @@ LL + pat1: fn(_: bool), | error[E0642]: patterns aren't allowed in function pointer types - --> $DIR/fn-ptr-pattern.rs:56:14 + --> $DIR/fn-ptr-pattern.rs:58:14 | LL | pat2: fn((x, y): (bool, bool)), | ^^^^^^ @@ -95,7 +95,7 @@ LL + pat2: fn(_: (bool, bool)), | error[E0642]: patterns aren't allowed in function pointer types - --> $DIR/fn-ptr-pattern.rs:58:14 + --> $DIR/fn-ptr-pattern.rs:60:14 | LL | pat3: fn(Thing { a, b }: Thing), | ^^^^^^^^^^^^^^ @@ -107,7 +107,7 @@ LL + pat3: fn(_: Thing), | error[E0642]: patterns aren't allowed in function pointer types - --> $DIR/fn-ptr-pattern.rs:60:14 + --> $DIR/fn-ptr-pattern.rs:62:14 | LL | pat4: fn(NoThing { a, b }: NoThing), | ^^^^^^^^^^^^^^^^ @@ -119,7 +119,7 @@ LL + pat4: fn(_: NoThing), | error[E0642]: patterns aren't allowed in function pointer types - --> $DIR/fn-ptr-pattern.rs:62:14 + --> $DIR/fn-ptr-pattern.rs:64:14 | LL | pat5: fn((((((x))))): bool), | ^^^^^^^^^^^ @@ -131,19 +131,19 @@ LL + pat5: fn(_: bool), | error: unexpected `self` parameter in function - --> $DIR/fn-ptr-pattern.rs:66:21 + --> $DIR/fn-ptr-pattern.rs:68:21 | LL | self2: fn(self, self), | ^^^^ must be the first parameter of an associated function error: unexpected `self` parameter in function - --> $DIR/fn-ptr-pattern.rs:68:21 + --> $DIR/fn-ptr-pattern.rs:70:21 | LL | self3: fn(bool, self), | ^^^^ must be the first parameter of an associated function error: `self` parameter is only allowed in associated functions - --> $DIR/fn-ptr-pattern.rs:25:15 + --> $DIR/fn-ptr-pattern.rs:26:15 | LL | self1: fn(self), | ^^^^ not semantically valid as function parameter @@ -151,7 +151,7 @@ LL | self1: fn(self), = note: associated functions are those in `impl` or `trait` definitions error: `self` parameter is only allowed in associated functions - --> $DIR/fn-ptr-pattern.rs:27:15 + --> $DIR/fn-ptr-pattern.rs:28:15 | LL | self2: fn(self, self), | ^^^^ not semantically valid as function parameter @@ -159,49 +159,49 @@ LL | self2: fn(self, self), = note: associated functions are those in `impl` or `trait` definitions error[E0561]: patterns aren't allowed in function pointer types - --> $DIR/fn-ptr-pattern.rs:33:25 + --> $DIR/fn-ptr-pattern.rs:34:25 | LL | restricted_pat1: fn(mut x: ()), | ^^^^^ error[E0561]: patterns aren't allowed in function pointer types - --> $DIR/fn-ptr-pattern.rs:35:25 + --> $DIR/fn-ptr-pattern.rs:36:25 | LL | restricted_pat2: fn(&x: ()), | ^^ error[E0561]: patterns aren't allowed in function pointer types - --> $DIR/fn-ptr-pattern.rs:37:25 + --> $DIR/fn-ptr-pattern.rs:38:25 | LL | restricted_pat3: fn(&&x: ()), | ^^^ error[E0561]: patterns aren't allowed in function pointer types - --> $DIR/fn-ptr-pattern.rs:39:25 + --> $DIR/fn-ptr-pattern.rs:40:25 | LL | restricted_pat4: fn(false: ()), | ^^^^^ error[E0561]: patterns aren't allowed in function pointer types - --> $DIR/fn-ptr-pattern.rs:41:25 + --> $DIR/fn-ptr-pattern.rs:42:25 | LL | restricted_pat5: fn(&_: ()), | ^^ error[E0561]: patterns aren't allowed in function pointer types - --> $DIR/fn-ptr-pattern.rs:43:25 + --> $DIR/fn-ptr-pattern.rs:44:25 | LL | restricted_pat6: fn(&true: ()), | ^^^^^ error[E0425]: cannot find type `NoThing` in this scope - --> $DIR/fn-ptr-pattern.rs:19:32 + --> $DIR/fn-ptr-pattern.rs:20:32 | LL | pat4: fn(NoThing { a, b }: NoThing), | ^^^^^^^ not found in this scope | note: similarly named struct `Thing` defined here - --> $DIR/fn-ptr-pattern.rs:81:1 + --> $DIR/fn-ptr-pattern.rs:83:1 | LL | struct Thing { a: bool, b: bool } | ^^^^^^^^^^^^ @@ -211,7 +211,25 @@ LL - pat4: fn(NoThing { a, b }: NoThing), LL + pat4: fn(NoThing { a, b }: Thing), | -error: aborting due to 23 previous errors +warning: identifier `duplicate_name` is bound more than once in this parameter list + --> $DIR/fn-ptr-pattern.rs:7:34 + | +LL | f5: fn(duplicate_name: bool, duplicate_name: bool), + | -------------- ^^^^^^^^^^^^^^ used as parameter more than once + | | + | used here already + | + = note: `#[warn(duplicate_parameter_names)]` on by default + +warning: identifier `x` is bound more than once in this parameter list + --> $DIR/fn-ptr-pattern.rs:49:35 + | +LL | duplicate_names: fn(x: usize, x: usize), + | - ^ used as parameter more than once + | | + | used here already + +error: aborting due to 23 previous errors; 2 warnings emitted Some errors have detailed explanations: E0425, E0561, E0642. For more information about an error, try `rustc --explain E0425`. diff --git a/tests/ui/fn/named-fn-trait-parameters.rs b/tests/ui/fn/named-fn-trait-parameters.rs index fd9ce5559fe01..0e81b1339c011 100644 --- a/tests/ui/fn/named-fn-trait-parameters.rs +++ b/tests/ui/fn/named-fn-trait-parameters.rs @@ -7,6 +7,7 @@ fn allowed( f3: impl Fn(String, msg: String), f4: impl Fn(msg: String, String), f5: impl Fn(duplicate_name: bool, duplicate_name: bool), + //~^ WARN identifier `duplicate_name` is bound more than once in this parameter list fg: F ) where F: Fn(msg: String) { } @@ -57,6 +58,7 @@ fn semantics( //~^ ERROR C-variadic parameters aren't allowed in parenthesized argument lists duplicate_names: impl Fn(x: usize, x: usize), + //~^ WARN identifier `x` is bound more than once in this parameter list ) { } // Patterns are also syntactically rejected, but restricted patterns are not diff --git a/tests/ui/fn/named-fn-trait-parameters.stderr b/tests/ui/fn/named-fn-trait-parameters.stderr index dfdf4cd6c3fb4..ba01a3e64b299 100644 --- a/tests/ui/fn/named-fn-trait-parameters.stderr +++ b/tests/ui/fn/named-fn-trait-parameters.stderr @@ -1,5 +1,5 @@ error[E0642]: patterns aren't allowed in parenthesized argument list - --> $DIR/named-fn-trait-parameters.rs:17:19 + --> $DIR/named-fn-trait-parameters.rs:18:19 | LL | pat1: impl Fn(1..3: bool), | ^^^^ @@ -11,7 +11,7 @@ LL + pat1: impl Fn(_: bool), | error[E0642]: patterns aren't allowed in parenthesized argument list - --> $DIR/named-fn-trait-parameters.rs:19:19 + --> $DIR/named-fn-trait-parameters.rs:20:19 | LL | pat2: impl Fn((x, y): (bool, bool)), | ^^^^^^ @@ -23,7 +23,7 @@ LL + pat2: impl Fn(_: (bool, bool)), | error[E0642]: patterns aren't allowed in parenthesized argument list - --> $DIR/named-fn-trait-parameters.rs:21:19 + --> $DIR/named-fn-trait-parameters.rs:22:19 | LL | pat3: impl Fn(Thing { a, b }: Thing), | ^^^^^^^^^^^^^^ @@ -35,7 +35,7 @@ LL + pat3: impl Fn(_: Thing), | error[E0642]: patterns aren't allowed in parenthesized argument list - --> $DIR/named-fn-trait-parameters.rs:23:19 + --> $DIR/named-fn-trait-parameters.rs:24:19 | LL | pat4: impl Fn(NoThing { a, b }: NoThing), | ^^^^^^^^^^^^^^^^ @@ -47,7 +47,7 @@ LL + pat4: impl Fn(_: NoThing), | error[E0642]: patterns aren't allowed in parenthesized argument list - --> $DIR/named-fn-trait-parameters.rs:26:19 + --> $DIR/named-fn-trait-parameters.rs:27:19 | LL | pat5: impl Fn((((((x))))): bool), | ^^^^^^^^^^^ @@ -59,19 +59,19 @@ LL + pat5: impl Fn(_: bool), | error: unexpected `self` parameter in function - --> $DIR/named-fn-trait-parameters.rs:31:26 + --> $DIR/named-fn-trait-parameters.rs:32:26 | LL | self2: impl Fn(self, self), | ^^^^ must be the first parameter of an associated function error: unexpected `self` parameter in function - --> $DIR/named-fn-trait-parameters.rs:34:26 + --> $DIR/named-fn-trait-parameters.rs:35:26 | LL | self3: impl Fn(bool, self), | ^^^^ must be the first parameter of an associated function error[E0642]: patterns aren't allowed in parenthesized argument list - --> $DIR/named-fn-trait-parameters.rs:65:19 + --> $DIR/named-fn-trait-parameters.rs:67:19 | LL | pat1: impl Fn(1..3: bool), | ^^^^ @@ -83,7 +83,7 @@ LL + pat1: impl Fn(_: bool), | error[E0642]: patterns aren't allowed in parenthesized argument list - --> $DIR/named-fn-trait-parameters.rs:67:19 + --> $DIR/named-fn-trait-parameters.rs:69:19 | LL | pat2: impl Fn((x, y): (bool, bool)), | ^^^^^^ @@ -95,7 +95,7 @@ LL + pat2: impl Fn(_: (bool, bool)), | error[E0642]: patterns aren't allowed in parenthesized argument list - --> $DIR/named-fn-trait-parameters.rs:69:19 + --> $DIR/named-fn-trait-parameters.rs:71:19 | LL | pat3: impl Fn(Thing { a, b }: Thing), | ^^^^^^^^^^^^^^ @@ -107,7 +107,7 @@ LL + pat3: impl Fn(_: Thing), | error[E0642]: patterns aren't allowed in parenthesized argument list - --> $DIR/named-fn-trait-parameters.rs:71:19 + --> $DIR/named-fn-trait-parameters.rs:73:19 | LL | pat4: impl Fn(NoThing { a, b }: NoThing), | ^^^^^^^^^^^^^^^^ @@ -119,7 +119,7 @@ LL + pat4: impl Fn(_: NoThing), | error[E0642]: patterns aren't allowed in parenthesized argument list - --> $DIR/named-fn-trait-parameters.rs:73:19 + --> $DIR/named-fn-trait-parameters.rs:75:19 | LL | pat5: impl Fn((((((x))))): bool), | ^^^^^^^^^^^ @@ -131,19 +131,19 @@ LL + pat5: impl Fn(_: bool), | error: unexpected `self` parameter in function - --> $DIR/named-fn-trait-parameters.rs:77:26 + --> $DIR/named-fn-trait-parameters.rs:79:26 | LL | self2: impl Fn(self, self), | ^^^^ must be the first parameter of an associated function error: unexpected `self` parameter in function - --> $DIR/named-fn-trait-parameters.rs:79:26 + --> $DIR/named-fn-trait-parameters.rs:81:26 | LL | self3: impl Fn(bool, self), | ^^^^ must be the first parameter of an associated function error: `self` parameter is only allowed in associated functions - --> $DIR/named-fn-trait-parameters.rs:29:20 + --> $DIR/named-fn-trait-parameters.rs:30:20 | LL | self1: impl Fn(self), | ^^^^ not semantically valid as function parameter @@ -151,7 +151,7 @@ LL | self1: impl Fn(self), = note: associated functions are those in `impl` or `trait` definitions error: `self` parameter is only allowed in associated functions - --> $DIR/named-fn-trait-parameters.rs:31:20 + --> $DIR/named-fn-trait-parameters.rs:32:20 | LL | self2: impl Fn(self, self), | ^^^^ not semantically valid as function parameter @@ -159,43 +159,43 @@ LL | self2: impl Fn(self, self), = note: associated functions are those in `impl` or `trait` definitions error[E0561]: patterns aren't allowed in parenthesized argument lists - --> $DIR/named-fn-trait-parameters.rs:37:30 + --> $DIR/named-fn-trait-parameters.rs:38:30 | LL | restricted_pat1: impl Fn(mut x: ()), | ^^^^^ error[E0561]: patterns aren't allowed in parenthesized argument lists - --> $DIR/named-fn-trait-parameters.rs:39:30 + --> $DIR/named-fn-trait-parameters.rs:40:30 | LL | restricted_pat2: impl Fn(&x: ()), | ^^ error[E0561]: patterns aren't allowed in parenthesized argument lists - --> $DIR/named-fn-trait-parameters.rs:41:30 + --> $DIR/named-fn-trait-parameters.rs:42:30 | LL | restricted_pat3: impl Fn(&&x: ()), | ^^^ error[E0561]: patterns aren't allowed in parenthesized argument lists - --> $DIR/named-fn-trait-parameters.rs:43:30 + --> $DIR/named-fn-trait-parameters.rs:44:30 | LL | restricted_pat4: impl Fn(false: ()), | ^^^^^ error[E0561]: patterns aren't allowed in parenthesized argument lists - --> $DIR/named-fn-trait-parameters.rs:45:30 + --> $DIR/named-fn-trait-parameters.rs:46:30 | LL | restricted_pat5: impl Fn(&_: ()), | ^^ error[E0561]: patterns aren't allowed in parenthesized argument lists - --> $DIR/named-fn-trait-parameters.rs:47:30 + --> $DIR/named-fn-trait-parameters.rs:48:30 | LL | restricted_pat6: impl Fn(&true: ()), | ^^^^^ error: C-variadic parameters aren't allowed in parenthesized argument lists - --> $DIR/named-fn-trait-parameters.rs:50:29 + --> $DIR/named-fn-trait-parameters.rs:51:29 | LL | variadics1: impl Fn(a1: ...), | ----^^^ @@ -203,7 +203,7 @@ LL | variadics1: impl Fn(a1: ...), | help: remove the C-variadics error: C-variadic parameters aren't allowed in parenthesized argument lists - --> $DIR/named-fn-trait-parameters.rs:52:29 + --> $DIR/named-fn-trait-parameters.rs:53:29 | LL | variadics2: impl Fn(a1: ...), | ----^^^ @@ -211,7 +211,7 @@ LL | variadics2: impl Fn(a1: ...), | help: remove the C-variadics error: C-variadic parameters aren't allowed in parenthesized argument lists - --> $DIR/named-fn-trait-parameters.rs:54:40 + --> $DIR/named-fn-trait-parameters.rs:55:40 | LL | variadics3: impl Fn(a1: usize, a2: ...), | ----^^^ @@ -219,19 +219,19 @@ LL | variadics3: impl Fn(a1: usize, a2: ...), | help: remove the C-variadics error: C-variadic parameters aren't allowed in parenthesized argument lists - --> $DIR/named-fn-trait-parameters.rs:56:29 + --> $DIR/named-fn-trait-parameters.rs:57:29 | LL | variadics4: impl Fn(a1: ..., a2: usize), | ----^^^-- help: remove the C-variadics error[E0425]: cannot find type `NoThing` in this scope - --> $DIR/named-fn-trait-parameters.rs:23:37 + --> $DIR/named-fn-trait-parameters.rs:24:37 | LL | pat4: impl Fn(NoThing { a, b }: NoThing), | ^^^^^^^ not found in this scope | note: similarly named struct `Thing` defined here - --> $DIR/named-fn-trait-parameters.rs:93:1 + --> $DIR/named-fn-trait-parameters.rs:95:1 | LL | struct Thing { a: bool, b: bool } | ^^^^^^^^^^^^ @@ -241,7 +241,25 @@ LL - pat4: impl Fn(NoThing { a, b }: NoThing), LL + pat4: impl Fn(NoThing { a, b }: Thing), | -error: aborting due to 27 previous errors +warning: identifier `duplicate_name` is bound more than once in this parameter list + --> $DIR/named-fn-trait-parameters.rs:9:39 + | +LL | f5: impl Fn(duplicate_name: bool, duplicate_name: bool), + | -------------- ^^^^^^^^^^^^^^ used as parameter more than once + | | + | used here already + | + = note: `#[warn(duplicate_parameter_names)]` on by default + +warning: identifier `x` is bound more than once in this parameter list + --> $DIR/named-fn-trait-parameters.rs:60:40 + | +LL | duplicate_names: impl Fn(x: usize, x: usize), + | - ^ used as parameter more than once + | | + | used here already + +error: aborting due to 27 previous errors; 2 warnings emitted Some errors have detailed explanations: E0425, E0561, E0642. For more information about an error, try `rustc --explain E0425`. diff --git a/tests/ui/fn/param-mismatch-foreign.stderr b/tests/ui/fn/param-mismatch-foreign.stderr index 835e0a3343e9a..ae994bb658f25 100644 --- a/tests/ui/fn/param-mismatch-foreign.stderr +++ b/tests/ui/fn/param-mismatch-foreign.stderr @@ -8,7 +8,7 @@ note: function defined here --> $DIR/param-mismatch-foreign.rs:2:8 | LL | fn foo(x: i32, y: u32, z: i32); - | ^^^ - + | ^^^ ------ help: provide the argument | LL | foo(1i32, /* u32 */, 2i32); diff --git a/tests/ui/lint/duplicate-parameter-names.rs b/tests/ui/lint/duplicate-parameter-names.rs new file mode 100644 index 0000000000000..422fa8d5caa94 --- /dev/null +++ b/tests/ui/lint/duplicate-parameter-names.rs @@ -0,0 +1,63 @@ +// Functions without bodies, function pointers, and parenthesized generic args +// should lint against parameters with duplicate names + +#![allow(unused)] +#![feature(named_fn_trait_parameters)] + +trait Test { + fn trait_fn(x: usize, x: usize); + //~^ WARN identifier `x` is bound more than once in this parameter list + + // Functions with a body should hard error, and should not show a warning + fn fn_with_body(x: usize, x: u64) {} + //~^ ERROR identifier `x` is bound more than once in this parameter list + + fn three_args(x: usize, x: usize, x: u8); + //~^ WARN identifier `x` is bound more than once in this parameter list + //~| WARN identifier `x` is bound more than once in this parameter list + + fn underscore(_: bool, _: bool); +} + +unsafe extern "C" { + fn extern_fn(x: usize, x: usize); + //~^ WARN identifier `x` is bound more than once in this parameter list +} + +type FnPointer = fn(x: usize, x: u64); +//~^ WARN identifier `x` is bound more than once in this parameter list + +fn generic_type() +//~^ WARN identifier `x` is bound more than once in this parameter list + where U: FnOnce(x: usize, x: usize) +//~^ WARN identifier `x` is bound more than once in this parameter list + {} + +fn impl_trait(f: impl FnOnce(x: usize, x: usize)) {} +//~^ WARN identifier `x` is bound more than once in this parameter list + +fn main() {} + +// Functions with a body already hard error if they have duplicated parameter names, +// so they shouldn't warn on top of the error +fn fn_with_body(x: usize, x: u64) {} +//~^ ERROR identifier `x` is bound more than once in this parameter list + +// Patterns aren't allowed, so they shouldn't show a warning on top of the error +trait Error { + fn pattern_in_args((x, x): usize, x: impl Fn((a, a): (bool, bool)), f: fn((b, b): (u64, u64))); + //~^ ERROR patterns aren't allowed in methods without bodies + //~| ERROR patterns aren't allowed in function pointer types + //~| ERROR patterns aren't allowed in parenthesized argument list +} + +// Free fns throw an error, but it's unrelated so we do warn +fn free_fn_without_body(x: u8, x: u8); +//~^ ERROR free function without a body +//~| WARN identifier `x` is bound more than once in this parameter list + +// The warning should respect hygiene +macro_rules! decl { + ($p:ident) => { trait T { fn decl(x: u8, $p: u8); } }; +} +decl!(x); diff --git a/tests/ui/lint/duplicate-parameter-names.stderr b/tests/ui/lint/duplicate-parameter-names.stderr new file mode 100644 index 0000000000000..87128ec15c3f4 --- /dev/null +++ b/tests/ui/lint/duplicate-parameter-names.stderr @@ -0,0 +1,132 @@ +error[E0642]: patterns aren't allowed in methods without bodies + --> $DIR/duplicate-parameter-names.rs:48:24 + | +LL | fn pattern_in_args((x, x): usize, x: impl Fn((a, a): (bool, bool)), f: fn((b, b): (u64, u64))); + | ^^^^^^ + | +help: give this argument a name or use an underscore to ignore it + | +LL - fn pattern_in_args((x, x): usize, x: impl Fn((a, a): (bool, bool)), f: fn((b, b): (u64, u64))); +LL + fn pattern_in_args(_: usize, x: impl Fn((a, a): (bool, bool)), f: fn((b, b): (u64, u64))); + | + +error[E0642]: patterns aren't allowed in parenthesized argument list + --> $DIR/duplicate-parameter-names.rs:48:50 + | +LL | fn pattern_in_args((x, x): usize, x: impl Fn((a, a): (bool, bool)), f: fn((b, b): (u64, u64))); + | ^^^^^^ + | +help: give this argument a name or use an underscore to ignore it + | +LL - fn pattern_in_args((x, x): usize, x: impl Fn((a, a): (bool, bool)), f: fn((b, b): (u64, u64))); +LL + fn pattern_in_args((x, x): usize, x: impl Fn(_: (bool, bool)), f: fn((b, b): (u64, u64))); + | + +error[E0642]: patterns aren't allowed in function pointer types + --> $DIR/duplicate-parameter-names.rs:48:79 + | +LL | fn pattern_in_args((x, x): usize, x: impl Fn((a, a): (bool, bool)), f: fn((b, b): (u64, u64))); + | ^^^^^^ + | +help: give this argument a name or use an underscore to ignore it + | +LL - fn pattern_in_args((x, x): usize, x: impl Fn((a, a): (bool, bool)), f: fn((b, b): (u64, u64))); +LL + fn pattern_in_args((x, x): usize, x: impl Fn((a, a): (bool, bool)), f: fn(_: (u64, u64))); + | + +error: free function without a body + --> $DIR/duplicate-parameter-names.rs:55:1 + | +LL | fn free_fn_without_body(x: u8, x: u8); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- + | | + | help: provide a definition for the function: `{ }` + +error[E0415]: identifier `x` is bound more than once in this parameter list + --> $DIR/duplicate-parameter-names.rs:12:31 + | +LL | fn fn_with_body(x: usize, x: u64) {} + | ^ used as parameter more than once + +error[E0415]: identifier `x` is bound more than once in this parameter list + --> $DIR/duplicate-parameter-names.rs:43:27 + | +LL | fn fn_with_body(x: usize, x: u64) {} + | ^ used as parameter more than once + +warning: identifier `x` is bound more than once in this parameter list + --> $DIR/duplicate-parameter-names.rs:8:27 + | +LL | fn trait_fn(x: usize, x: usize); + | - ^ used as parameter more than once + | | + | used here already + | + = note: `#[warn(duplicate_parameter_names)]` on by default + +warning: identifier `x` is bound more than once in this parameter list + --> $DIR/duplicate-parameter-names.rs:15:29 + | +LL | fn three_args(x: usize, x: usize, x: u8); + | - ^ used as parameter more than once + | | + | used here already + +warning: identifier `x` is bound more than once in this parameter list + --> $DIR/duplicate-parameter-names.rs:15:39 + | +LL | fn three_args(x: usize, x: usize, x: u8); + | - used here already ^ used as parameter more than once + +warning: identifier `x` is bound more than once in this parameter list + --> $DIR/duplicate-parameter-names.rs:23:28 + | +LL | fn extern_fn(x: usize, x: usize); + | - ^ used as parameter more than once + | | + | used here already + +warning: identifier `x` is bound more than once in this parameter list + --> $DIR/duplicate-parameter-names.rs:27:31 + | +LL | type FnPointer = fn(x: usize, x: u64); + | - ^ used as parameter more than once + | | + | used here already + +warning: identifier `x` is bound more than once in this parameter list + --> $DIR/duplicate-parameter-names.rs:30:33 + | +LL | fn generic_type() + | - ^ used as parameter more than once + | | + | used here already + +warning: identifier `x` is bound more than once in this parameter list + --> $DIR/duplicate-parameter-names.rs:32:31 + | +LL | where U: FnOnce(x: usize, x: usize) + | - ^ used as parameter more than once + | | + | used here already + +warning: identifier `x` is bound more than once in this parameter list + --> $DIR/duplicate-parameter-names.rs:36:40 + | +LL | fn impl_trait(f: impl FnOnce(x: usize, x: usize)) {} + | - ^ used as parameter more than once + | | + | used here already + +warning: identifier `x` is bound more than once in this parameter list + --> $DIR/duplicate-parameter-names.rs:55:32 + | +LL | fn free_fn_without_body(x: u8, x: u8); + | - ^ used as parameter more than once + | | + | used here already + +error: aborting due to 6 previous errors; 9 warnings emitted + +Some errors have detailed explanations: E0415, E0642. +For more information about an error, try `rustc --explain E0415`. diff --git a/tests/ui/lint/lint-check-params.rs b/tests/ui/lint/lint-check-params.rs new file mode 100644 index 0000000000000..5af0144e9f136 --- /dev/null +++ b/tests/ui/lint/lint-check-params.rs @@ -0,0 +1,13 @@ +// Checks that a lint-check attribute applied to a foreign function parameter, +// only applies to that parameter + +#![deny(dead_code)] + +unsafe extern "C" { + //~v ERROR function `unused_foreign` is never used + fn unused_foreign( + #[allow(dead_code)] arg: i32, + ); +} + +fn main() {} diff --git a/tests/ui/lint/lint-check-params.stderr b/tests/ui/lint/lint-check-params.stderr new file mode 100644 index 0000000000000..0a4d19f5e9679 --- /dev/null +++ b/tests/ui/lint/lint-check-params.stderr @@ -0,0 +1,14 @@ +error: function `unused_foreign` is never used + --> $DIR/lint-check-params.rs:8:8 + | +LL | fn unused_foreign( + | ^^^^^^^^^^^^^^ + | +note: the lint level is defined here + --> $DIR/lint-check-params.rs:4:9 + | +LL | #![deny(dead_code)] + | ^^^^^^^^^ + +error: aborting due to 1 previous error + diff --git a/tests/ui/lint/lint-strict-provenance-no_std.rs b/tests/ui/lint/lint-strict-provenance-no_std.rs new file mode 100644 index 0000000000000..6b0aaf6db22fe --- /dev/null +++ b/tests/ui/lint/lint-strict-provenance-no_std.rs @@ -0,0 +1,16 @@ +//@ check-pass + +#![no_std] +#![crate_type = "lib"] +#![feature(strict_provenance_lints)] +#![warn(implicit_provenance_casts)] + +pub fn int2ptr() -> *const u8 { + 16_usize as *const u8 + //~^ WARN cast from `usize` to `*const u8` implicitly relies on exposed provenance +} + +pub fn ptr2int(ptr: *const u8) -> usize { + ptr as usize + //~^ WARN cast from `*const u8` to `usize` implicitly exposes pointer provenance +} diff --git a/tests/ui/lint/lint-strict-provenance-no_std.stderr b/tests/ui/lint/lint-strict-provenance-no_std.stderr new file mode 100644 index 0000000000000..58492acd91c59 --- /dev/null +++ b/tests/ui/lint/lint-strict-provenance-no_std.stderr @@ -0,0 +1,32 @@ +warning: cast from `usize` to `*const u8` implicitly relies on exposed provenance + --> $DIR/lint-strict-provenance-no_std.rs:9:5 + | +LL | 16_usize as *const u8 + | ^^^^^^^^^^^^^^^^^^^^^ + | + = help: if conforming to strict provenance is not possible, use `core::ptr::with_exposed_provenance()` + = note: for more information, visit +note: the lint level is defined here + --> $DIR/lint-strict-provenance-no_std.rs:6:9 + | +LL | #![warn(implicit_provenance_casts)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^ +help: use `.with_addr()` to adjust the address of a valid pointer in the same allocation + | +LL - 16_usize as *const u8 +LL + (...).with_addr(16_usize) + | + +warning: cast from `*const u8` to `usize` implicitly exposes pointer provenance + --> $DIR/lint-strict-provenance-no_std.rs:14:5 + | +LL | ptr as usize + | ^^^--------- + | | + | help: use `.addr()` to obtain the address of a pointer: `.addr()` + | + = help: if conforming to strict provenance is not possible, use `.expose_provenance()` + = note: for more information, visit + +warning: 2 warnings emitted + diff --git a/tests/ui/lint/non-snake-case/non-snake-foreign-fn-params.rs b/tests/ui/lint/non-snake-case/non-snake-foreign-fn-params.rs new file mode 100644 index 0000000000000..ebb6b1d3a7837 --- /dev/null +++ b/tests/ui/lint/non-snake-case/non-snake-foreign-fn-params.rs @@ -0,0 +1,9 @@ +//@ check-pass + +#![deny(non_snake_case)] + +extern "C" { + fn test(X: usize); // OK +} + +fn main() {} diff --git a/tests/ui/match/aggregate-array-eq-guard-drop-order.rs b/tests/ui/match/aggregate-array-eq-guard-drop-order.rs new file mode 100644 index 0000000000000..aa9a0b8aa378b --- /dev/null +++ b/tests/ui/match/aggregate-array-eq-guard-drop-order.rs @@ -0,0 +1,32 @@ +//! The aggregate `raw_eq`/`compare_bytes` comparison emitted for constant array/slice +//! patterns must be marked as non-unwinding. If it could unwind, this program +//! would fail borrow-checking in edition 2021: the unwind path from the guard +//! would require the scrutinee temporary, which borrows `referent`, to be +//! dropped in a different order relative to `referent` than on the ordinary +//! path. An explicit `slice == b"ABCD"` guard, which is an unwinding call, +//! still errors here. +//@ check-pass +//@ edition: 2021 + +struct Referent; +impl Drop for Referent { + fn drop(&mut self) {} +} + +struct DropMeFirst<'a>(&'a Referent); +impl Drop for DropMeFirst<'_> { + fn drop(&mut self) {} +} + +fn foo(slice: &[u8]) -> u32 { + let referent = Referent; + match DropMeFirst(&referent) { + _dropped_first if matches!(slice, b"ABCD") => 0, + _dropped_first => 1, + } +} + +fn main() { + assert_eq!(foo(b"ABCD"), 0); + assert_eq!(foo(b"ZZZZ"), 1); +} diff --git a/tests/ui/match/aggregate-array-eq.rs b/tests/ui/match/aggregate-array-eq.rs new file mode 100644 index 0000000000000..9cad70d4dc996 --- /dev/null +++ b/tests/ui/match/aggregate-array-eq.rs @@ -0,0 +1,149 @@ +//! Verify that matching against array/slice patterns expanded from constants +//! produces correct results at runtime, complementing the MIR test in +//! `tests/mir-opt/building/match/aggregate_array_eq.rs` which checks that +//! a single aggregate `raw_eq` or `compare_bytes` call is emitted. +//! +//! Also verify that the variants which fall back to element-by-element +//! comparison (hand-written patterns and const contexts) produce the same +//! results. +//@ run-pass + +const EXPECTED: [u8; 4] = [1, 2, 3, 4]; + +fn array_match(x: [u8; 4]) -> bool { + matches!(x, EXPECTED) +} + +fn handwritten_array_match(x: [u8; 4]) -> bool { + matches!(x, [1, 2, 3, 4]) +} + +fn slice_match(x: &[u8]) -> bool { + matches!(x, b"ABCD") +} + +fn multi_slice_match(x: &[u8]) -> u32 { + match x { + b"ABCD" => 1, + b"EFGH" => 2, + b"IJKLM" => 3, + _ => 0, + } +} + +const U16_SLICE: &[u16] = &[1, 2, 3, 0x1234]; + +fn u16_slice_match(x: &[u16]) -> bool { + matches!(x, U16_SLICE) +} + +const CHAR_SLICE: &[char] = &['a', 'b', 'c', '\u{1F980}']; + +fn char_slice_match(x: &[char]) -> bool { + matches!(x, CHAR_SLICE) +} + +const NESTED: [[u8; 4]; 4] = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]; + +fn nested_array_match(x: [[u8; 4]; 4]) -> bool { + matches!(x, NESTED) +} + +#[derive(Debug, PartialEq)] +enum MyEnum { + A, + B, + C, + D, +} + +// Regression test for https://github.com/rust-lang/rust/issues/103073. +fn try_from_matched(value: [u8; 4]) -> Result { + match &value { + b"ABCD" => Ok(MyEnum::A), + b"EFGH" => Ok(MyEnum::B), + b"IJKL" => Ok(MyEnum::C), + b"MNOP" => Ok(MyEnum::D), + _ => Err(()), + } +} + +// Const fn variants use element-by-element comparison because the +// `compare_bytes` intrinsic is not const-stable. +const fn const_array_match(x: [u8; 4]) -> bool { + matches!(x, EXPECTED) +} + +const fn const_try_from_matched(value: [u8; 4]) -> Result { + match &value { + b"ABCD" => Ok(MyEnum::A), + b"EFGH" => Ok(MyEnum::B), + b"IJKL" => Ok(MyEnum::C), + b"MNOP" => Ok(MyEnum::D), + _ => Err(()), + } +} + +fn main() { + // In this loop and the `try_from_matched` one below, the const fn variants + // are called at runtime. + for check in [array_match, handwritten_array_match, const_array_match] { + assert!(check([1, 2, 3, 4])); + assert!(!check([1, 2, 3, 5])); + assert!(!check([0, 0, 0, 0])); + assert!(!check([4, 3, 2, 1])); + } + + assert!(slice_match(b"ABCD")); + assert!(!slice_match(b"ABCE")); + assert!(!slice_match(b"ABC")); + assert!(!slice_match(b"ABCDE")); + assert!(!slice_match(b"")); + + assert_eq!(multi_slice_match(b"ABCD"), 1); + assert_eq!(multi_slice_match(b"EFGH"), 2); + assert_eq!(multi_slice_match(b"IJKLM"), 3); + assert_eq!(multi_slice_match(b"IJKL"), 0); + assert_eq!(multi_slice_match(b"EFGHI"), 0); + assert_eq!(multi_slice_match(b"ABC"), 0); + assert_eq!(multi_slice_match(b""), 0); + + assert!(u16_slice_match(&[1, 2, 3, 0x1234])); + assert!(!u16_slice_match(&[1, 2, 3, 0x1235])); + // Equal in the first half of the bytes, which would wrongly match if the + // length passed to `compare_bytes` were in elements rather than bytes. + assert!(!u16_slice_match(&[1, 2, 4, 0x1234])); + assert!(!u16_slice_match(&[1, 2, 3])); + assert!(!u16_slice_match(&[1, 2, 3, 0x1234, 5])); + + assert!(char_slice_match(&['a', 'b', 'c', '\u{1F980}'])); + assert!(!char_slice_match(&['a', 'b', 'c', '\u{1F981}'])); + assert!(!char_slice_match(&['a', 'b', 'd', '\u{1F980}'])); + assert!(!char_slice_match(&['a', 'b', 'c'])); + + assert!(nested_array_match(NESTED)); + assert!(!nested_array_match([[0; 4]; 4])); + assert!(!nested_array_match([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 0]])); + + for check in [try_from_matched, const_try_from_matched] { + assert_eq!(check(*b"ABCD"), Ok(MyEnum::A)); + assert_eq!(check(*b"EFGH"), Ok(MyEnum::B)); + assert_eq!(check(*b"IJKL"), Ok(MyEnum::C)); + assert_eq!(check(*b"MNOP"), Ok(MyEnum::D)); + assert_eq!(check(*b"ZZZZ"), Err(())); + assert_eq!(check(*b"ABCE"), Err(())); + } + + // Const fn variants evaluated at compile time. + const MATCH_TRUE: bool = const_array_match([1, 2, 3, 4]); + const MATCH_FALSE: bool = const_array_match([1, 2, 3, 5]); + assert!(MATCH_TRUE); + assert!(!MATCH_FALSE); + + const FROM_ABCD: Result = const_try_from_matched(*b"ABCD"); + const FROM_MNOP: Result = const_try_from_matched(*b"MNOP"); + const FROM_ZZZZ: Result = const_try_from_matched(*b"ZZZZ"); + assert_eq!(FROM_ABCD, Ok(MyEnum::A)); + assert_eq!(FROM_MNOP, Ok(MyEnum::D)); + assert_eq!(FROM_ZZZZ, Err(())); +} diff --git a/tests/ui/mismatched_types/issue-26480.stderr b/tests/ui/mismatched_types/issue-26480.stderr index ec91caed5e940..8e2683850c5f1 100644 --- a/tests/ui/mismatched_types/issue-26480.stderr +++ b/tests/ui/mismatched_types/issue-26480.stderr @@ -15,7 +15,7 @@ note: function defined here --> $DIR/issue-26480.rs:2:8 | LL | fn write(fildes: i32, buf: *const i8, nbyte: u64) -> i64; - | ^^^^^ ----- + | ^^^^^ ---------- help: you can convert a `usize` to a `u64` and panic if the converted value doesn't fit | LL | ($arr.len() * size_of($arr[0])).try_into().unwrap()); diff --git a/tests/ui/repr/conflicting-repr-enum-attrs.rs b/tests/ui/repr/conflicting-repr-enum-attrs.rs index d7e629d230c02..9aa598e820cf2 100644 --- a/tests/ui/repr/conflicting-repr-enum-attrs.rs +++ b/tests/ui/repr/conflicting-repr-enum-attrs.rs @@ -3,14 +3,12 @@ //! when there are multiple repr attributes. #[repr(C, u8)] //~ ERROR conflicting representation hints -//~^ WARN this was previously accepted enum Foo { A, B, } #[repr(C)] //~ ERROR conflicting representation hints -//~^ WARN this was previously accepted #[repr(u8)] enum Bar { A, diff --git a/tests/ui/repr/conflicting-repr-enum-attrs.stderr b/tests/ui/repr/conflicting-repr-enum-attrs.stderr index 6810a2a2a1171..e2a534fd6bd6d 100644 --- a/tests/ui/repr/conflicting-repr-enum-attrs.stderr +++ b/tests/ui/repr/conflicting-repr-enum-attrs.stderr @@ -3,48 +3,15 @@ error[E0566]: conflicting representation hints | LL | #[repr(C, u8)] | ^ ^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 - = note: `#[deny(conflicting_repr_hints)]` (part of `#[deny(future_incompatible)]`) on by default error[E0566]: conflicting representation hints - --> $DIR/conflicting-repr-enum-attrs.rs:12:8 + --> $DIR/conflicting-repr-enum-attrs.rs:11:8 | LL | #[repr(C)] | ^ -LL | LL | #[repr(u8)] | ^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0566`. -Future incompatibility report: Future breakage diagnostic: -error[E0566]: conflicting representation hints - --> $DIR/conflicting-repr-enum-attrs.rs:5:8 - | -LL | #[repr(C, u8)] - | ^ ^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 - = note: `#[deny(conflicting_repr_hints)]` (part of `#[deny(future_incompatible)]`) on by default - -Future breakage diagnostic: -error[E0566]: conflicting representation hints - --> $DIR/conflicting-repr-enum-attrs.rs:12:8 - | -LL | #[repr(C)] - | ^ -LL | -LL | #[repr(u8)] - | ^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 - = note: `#[deny(conflicting_repr_hints)]` (part of `#[deny(future_incompatible)]`) on by default - diff --git a/tests/ui/repr/conflicting-repr-hints.rs b/tests/ui/repr/conflicting-repr-hints.rs index 6a265e13ad93d..bd554d6e8db5d 100644 --- a/tests/ui/repr/conflicting-repr-hints.rs +++ b/tests/ui/repr/conflicting-repr-hints.rs @@ -12,13 +12,11 @@ enum B { } #[repr(C, u64)] //~ ERROR conflicting representation hints -//~^ WARN this was previously accepted enum C { C, } #[repr(u32, u64)] //~ ERROR conflicting representation hints -//~^ WARN this was previously accepted enum D { D, } diff --git a/tests/ui/repr/conflicting-repr-hints.stderr b/tests/ui/repr/conflicting-repr-hints.stderr index 2a81610e85f99..094ab4a55754a 100644 --- a/tests/ui/repr/conflicting-repr-hints.stderr +++ b/tests/ui/repr/conflicting-repr-hints.stderr @@ -3,22 +3,15 @@ error[E0566]: conflicting representation hints | LL | #[repr(C, u64)] | ^ ^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 - = note: `#[deny(conflicting_repr_hints)]` (part of `#[deny(future_incompatible)]`) on by default error[E0566]: conflicting representation hints - --> $DIR/conflicting-repr-hints.rs:20:8 + --> $DIR/conflicting-repr-hints.rs:19:8 | LL | #[repr(u32, u64)] | ^^^ ^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 warning: `#[repr(..)]` attribute is specified more than once - --> $DIR/conflicting-repr-hints.rs:47:8 + --> $DIR/conflicting-repr-hints.rs:45:8 | LL | #[repr(packed, packed(1))] | ^^^^^^ ^^^^^^^^^ @@ -27,61 +20,61 @@ LL | #[repr(packed, packed(1))] = note: requested on the command line with `-W repeated-reprs` error[E0587]: type has conflicting packed and align representation hints - --> $DIR/conflicting-repr-hints.rs:30:1 + --> $DIR/conflicting-repr-hints.rs:28:1 | LL | struct F(i32); | ^^^^^^^^ error[E0587]: type has conflicting packed and align representation hints - --> $DIR/conflicting-repr-hints.rs:34:1 + --> $DIR/conflicting-repr-hints.rs:32:1 | LL | struct G(i32); | ^^^^^^^^ error[E0587]: type has conflicting packed and align representation hints - --> $DIR/conflicting-repr-hints.rs:38:1 + --> $DIR/conflicting-repr-hints.rs:36:1 | LL | struct H(i32); | ^^^^^^^^ error[E0634]: type has conflicting packed representation hints - --> $DIR/conflicting-repr-hints.rs:41:1 + --> $DIR/conflicting-repr-hints.rs:39:1 | LL | struct I(i32); | ^^^^^^^^ error[E0634]: type has conflicting packed representation hints - --> $DIR/conflicting-repr-hints.rs:45:1 + --> $DIR/conflicting-repr-hints.rs:43:1 | LL | struct J(i32); | ^^^^^^^^ error[E0587]: type has conflicting packed and align representation hints - --> $DIR/conflicting-repr-hints.rs:51:1 + --> $DIR/conflicting-repr-hints.rs:49:1 | LL | union X { | ^^^^^^^ error[E0587]: type has conflicting packed and align representation hints - --> $DIR/conflicting-repr-hints.rs:58:1 + --> $DIR/conflicting-repr-hints.rs:56:1 | LL | union Y { | ^^^^^^^ error[E0587]: type has conflicting packed and align representation hints - --> $DIR/conflicting-repr-hints.rs:65:1 + --> $DIR/conflicting-repr-hints.rs:63:1 | LL | union Z { | ^^^^^^^ error[E0587]: type has conflicting packed and align representation hints - --> $DIR/conflicting-repr-hints.rs:71:1 + --> $DIR/conflicting-repr-hints.rs:69:1 | LL | pub struct S(u16); | ^^^^^^^^^^^^ error[E0587]: type has conflicting packed and align representation hints - --> $DIR/conflicting-repr-hints.rs:74:1 + --> $DIR/conflicting-repr-hints.rs:72:1 | LL | pub union U { | ^^^^^^^^^^^ @@ -90,25 +83,3 @@ error: aborting due to 12 previous errors; 1 warning emitted Some errors have detailed explanations: E0566, E0587, E0634. For more information about an error, try `rustc --explain E0566`. -Future incompatibility report: Future breakage diagnostic: -error[E0566]: conflicting representation hints - --> $DIR/conflicting-repr-hints.rs:14:8 - | -LL | #[repr(C, u64)] - | ^ ^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 - = note: `#[deny(conflicting_repr_hints)]` (part of `#[deny(future_incompatible)]`) on by default - -Future breakage diagnostic: -error[E0566]: conflicting representation hints - --> $DIR/conflicting-repr-hints.rs:20:8 - | -LL | #[repr(u32, u64)] - | ^^^ ^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 - = note: `#[deny(conflicting_repr_hints)]` (part of `#[deny(future_incompatible)]`) on by default - diff --git a/tests/ui/repr/repr-repeated-attrs.rs b/tests/ui/repr/repr-repeated-attrs.rs index 122eb9b7485ef..560a9d95b4b7d 100644 --- a/tests/ui/repr/repr-repeated-attrs.rs +++ b/tests/ui/repr/repr-repeated-attrs.rs @@ -22,14 +22,12 @@ struct SeveralC(u8); #[repr(u8, u8)] //~ WARN `#[repr(..)]` attribute is specified more than once [repeated_reprs] //~^ ERROR conflicting representation hints -//~| WARN this was previously accepted enum SeveralPrimitiveRerprs { Variant, } #[repr(C, C, u8)] //~ WARN `#[repr(..)]` attribute is specified more than once [repeated_reprs] //~^ ERROR conflicting representation hints -//~| WARN this was previously accepted #[repr(C, u8, u8)] enum SeveralCAndPrims { Variant(u8), @@ -38,14 +36,12 @@ enum SeveralCAndPrims { #[repr(Rust, u8, u8)] //~ WARN `#[repr(..)]` attribute is specified more than once [repeated_reprs] //~^ ERROR conflicting representation hints //~^^ ERROR conflicting representation hints -//~| WARN this was previously accepted enum RustAndPrimDisallowed { Variant(u8), } #[repr(u8, u8)] //~ WARN `#[repr(..)]` attribute is specified more than once [repeated_reprs] //~^ ERROR conflicting representation hints -//~| WARN this was previously accepted #[repr(u16)] enum ConflictingPrimReprs { Variant, @@ -53,7 +49,6 @@ enum ConflictingPrimReprs { #[repr(C, u8)] //~^ ERROR conflicting representation hints -//~| WARN this was previously accepted enum CWithIntsCausesFCW1 { A, B, @@ -61,7 +56,6 @@ enum CWithIntsCausesFCW1 { #[repr(C, C, u8, u8, u8)] //~ WARN `#[repr(..)]` attribute is specified more than once [repeated_reprs] //~^ ERROR conflicting representation hints -//~| WARN this was previously accepted enum CWithIntsCausesFCW2 { A, B, diff --git a/tests/ui/repr/repr-repeated-attrs.stderr b/tests/ui/repr/repr-repeated-attrs.stderr index a1e54f6218889..9ac5508b240d8 100644 --- a/tests/ui/repr/repr-repeated-attrs.stderr +++ b/tests/ui/repr/repr-repeated-attrs.stderr @@ -71,36 +71,29 @@ error[E0566]: conflicting representation hints | LL | #[repr(u8, u8)] | ^^ ^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 - = note: `#[deny(conflicting_repr_hints)]` (part of `#[deny(future_incompatible)]`) on by default warning: `#[repr(..)]` attribute is specified more than once - --> $DIR/repr-repeated-attrs.rs:30:8 + --> $DIR/repr-repeated-attrs.rs:29:8 | LL | #[repr(C, C, u8)] | ^ ^ ^^ -... +LL | LL | #[repr(C, u8, u8)] | ^ ^^ ^^ | = note: for consistency, only specify the representation once error[E0566]: conflicting representation hints - --> $DIR/repr-repeated-attrs.rs:30:8 + --> $DIR/repr-repeated-attrs.rs:29:8 | LL | #[repr(C, C, u8)] | ^ ^ ^^ -... +LL | LL | #[repr(C, u8, u8)] | ^ ^^ ^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 warning: `#[repr(..)]` attribute is specified more than once - --> $DIR/repr-repeated-attrs.rs:38:14 + --> $DIR/repr-repeated-attrs.rs:36:14 | LL | #[repr(Rust, u8, u8)] | ^^ ^^ @@ -108,22 +101,21 @@ LL | #[repr(Rust, u8, u8)] = note: for consistency, only specify the representation once error[E0566]: conflicting representation hints - --> $DIR/repr-repeated-attrs.rs:38:8 + --> $DIR/repr-repeated-attrs.rs:36:8 | LL | #[repr(Rust, u8, u8)] | ^^^^ ^^ ^^ error[E0566]: conflicting representation hints - --> $DIR/repr-repeated-attrs.rs:38:8 + --> $DIR/repr-repeated-attrs.rs:36:8 | LL | #[repr(Rust, u8, u8)] | ^^^^ ^^ ^^ | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` warning: `#[repr(..)]` attribute is specified more than once - --> $DIR/repr-repeated-attrs.rs:46:8 + --> $DIR/repr-repeated-attrs.rs:43:8 | LL | #[repr(u8, u8)] | ^^ ^^ @@ -131,28 +123,22 @@ LL | #[repr(u8, u8)] = note: for consistency, only specify the representation once error[E0566]: conflicting representation hints - --> $DIR/repr-repeated-attrs.rs:46:8 + --> $DIR/repr-repeated-attrs.rs:43:8 | LL | #[repr(u8, u8)] | ^^ ^^ -... +LL | LL | #[repr(u16)] | ^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 error[E0566]: conflicting representation hints - --> $DIR/repr-repeated-attrs.rs:54:8 + --> $DIR/repr-repeated-attrs.rs:50:8 | LL | #[repr(C, u8)] | ^ ^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 warning: `#[repr(..)]` attribute is specified more than once - --> $DIR/repr-repeated-attrs.rs:62:8 + --> $DIR/repr-repeated-attrs.rs:57:8 | LL | #[repr(C, C, u8, u8, u8)] | ^ ^ ^^ ^^ ^^ @@ -160,87 +146,12 @@ LL | #[repr(C, C, u8, u8, u8)] = note: for consistency, only specify the representation once error[E0566]: conflicting representation hints - --> $DIR/repr-repeated-attrs.rs:62:8 + --> $DIR/repr-repeated-attrs.rs:57:8 | LL | #[repr(C, C, u8, u8, u8)] | ^ ^ ^^ ^^ ^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 error: aborting due to 9 previous errors; 9 warnings emitted Some errors have detailed explanations: E0566, E0692. For more information about an error, try `rustc --explain E0566`. -Future incompatibility report: Future breakage diagnostic: -error[E0566]: conflicting representation hints - --> $DIR/repr-repeated-attrs.rs:23:8 - | -LL | #[repr(u8, u8)] - | ^^ ^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 - = note: `#[deny(conflicting_repr_hints)]` (part of `#[deny(future_incompatible)]`) on by default - -Future breakage diagnostic: -error[E0566]: conflicting representation hints - --> $DIR/repr-repeated-attrs.rs:30:8 - | -LL | #[repr(C, C, u8)] - | ^ ^ ^^ -... -LL | #[repr(C, u8, u8)] - | ^ ^^ ^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 - = note: `#[deny(conflicting_repr_hints)]` (part of `#[deny(future_incompatible)]`) on by default - -Future breakage diagnostic: -error[E0566]: conflicting representation hints - --> $DIR/repr-repeated-attrs.rs:38:8 - | -LL | #[repr(Rust, u8, u8)] - | ^^^^ ^^ ^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 - = note: `#[deny(conflicting_repr_hints)]` (part of `#[deny(future_incompatible)]`) on by default - -Future breakage diagnostic: -error[E0566]: conflicting representation hints - --> $DIR/repr-repeated-attrs.rs:46:8 - | -LL | #[repr(u8, u8)] - | ^^ ^^ -... -LL | #[repr(u16)] - | ^^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 - = note: `#[deny(conflicting_repr_hints)]` (part of `#[deny(future_incompatible)]`) on by default - -Future breakage diagnostic: -error[E0566]: conflicting representation hints - --> $DIR/repr-repeated-attrs.rs:54:8 - | -LL | #[repr(C, u8)] - | ^ ^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 - = note: `#[deny(conflicting_repr_hints)]` (part of `#[deny(future_incompatible)]`) on by default - -Future breakage diagnostic: -error[E0566]: conflicting representation hints - --> $DIR/repr-repeated-attrs.rs:62:8 - | -LL | #[repr(C, C, u8, u8, u8)] - | ^ ^ ^^ ^^ ^^ - | - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - = note: for more information, see issue #68585 - = note: `#[deny(conflicting_repr_hints)]` (part of `#[deny(future_incompatible)]`) on by default - diff --git a/tests/ui/resolve/name-collision-in-trait-fn-sig.rs b/tests/ui/resolve/name-collision-in-trait-fn-sig.rs deleted file mode 100644 index f405ab5c59dd5..0000000000000 --- a/tests/ui/resolve/name-collision-in-trait-fn-sig.rs +++ /dev/null @@ -1,11 +0,0 @@ -//@ check-pass -// This is currently stable behavior, which was almost accidentally made an -// error in #102161 since there is no test exercising it. I am not sure if -// this _should_ be the desired behavior, but at least we should know if it -// changes. - -fn main() {} - -trait Foo { - fn fn_with_type_named_same_as_local_in_param(b: i32, b: i32); -} diff --git a/tests/ui/stats/input-stats.stderr b/tests/ui/stats/input-stats.stderr index 420b01102e41e..be15fb0df6a9c 100644 --- a/tests/ui/stats/input-stats.stderr +++ b/tests/ui/stats/input-stats.stderr @@ -86,10 +86,10 @@ hir-stats - Ptr 48 (NN.N%) 1 hir-stats - Ref 48 (NN.N%) 1 hir-stats - Path 624 (NN.N%) 13 hir-stats Generics 560 (NN.N%) 10 56 -hir-stats Pat 400 (NN.N%) 5 80 +hir-stats Pat 480 (NN.N%) 6 80 hir-stats - Struct 80 (NN.N%) 1 hir-stats - Wild 80 (NN.N%) 1 -hir-stats - Binding 240 (NN.N%) 3 +hir-stats - Binding 320 (NN.N%) 4 hir-stats GenericParam 400 (NN.N%) 5 80 hir-stats Block 288 (NN.N%) 6 48 hir-stats GenericBound 256 (NN.N%) 4 64 @@ -103,12 +103,12 @@ hir-stats Stmt 96 (NN.N%) 3 32 hir-stats - Expr 32 (NN.N%) 1 hir-stats - Let 32 (NN.N%) 1 hir-stats - Semi 32 (NN.N%) 1 +hir-stats Param 96 (NN.N%) 3 32 hir-stats Arm 80 (NN.N%) 2 40 hir-stats WherePredicate 72 (NN.N%) 3 24 hir-stats - BoundPredicate 72 (NN.N%) 3 hir-stats InlineAsm 72 (NN.N%) 1 72 hir-stats Body 72 (NN.N%) 3 24 -hir-stats Param 64 (NN.N%) 2 32 hir-stats Local 64 (NN.N%) 1 64 hir-stats GenericArg 64 (NN.N%) 4 16 hir-stats - Type 16 (NN.N%) 1 @@ -120,5 +120,5 @@ hir-stats TraitItemId 8 (NN.N%) 2 4 hir-stats ImplItemId 8 (NN.N%) 2 4 hir-stats ForeignItemId 4 (NN.N%) 1 4 hir-stats ---------------------------------------------------------------- -hir-stats Total 8_592 172 +hir-stats Total 8_704 174 hir-stats ================================================================ diff --git a/tests/ui/suggestions/suggest-null-ptr.stderr b/tests/ui/suggestions/suggest-null-ptr.stderr index 5be33d47237d2..bdc625c49c5b1 100644 --- a/tests/ui/suggestions/suggest-null-ptr.stderr +++ b/tests/ui/suggestions/suggest-null-ptr.stderr @@ -12,7 +12,7 @@ note: function defined here --> $DIR/suggest-null-ptr.rs:7:8 | LL | fn foo(ptr: *const u8); - | ^^^ --- + | ^^^ -------------- help: if you meant to create a null pointer, use `std::ptr::null()` | LL - foo(0); @@ -33,7 +33,7 @@ note: function defined here --> $DIR/suggest-null-ptr.rs:9:8 | LL | fn foo_mut(ptr: *mut u8); - | ^^^^^^^ --- + | ^^^^^^^ ------------ help: if you meant to create a null pointer, use `std::ptr::null_mut()` | LL - foo_mut(0); @@ -54,7 +54,7 @@ note: function defined here --> $DIR/suggest-null-ptr.rs:11:8 | LL | fn usize(ptr: *const usize); - | ^^^^^ --- + | ^^^^^ ----------------- help: if you meant to create a null pointer, use `std::ptr::null()` | LL - usize(0); @@ -75,7 +75,7 @@ note: function defined here --> $DIR/suggest-null-ptr.rs:13:8 | LL | fn usize_mut(ptr: *mut usize); - | ^^^^^^^^^ --- + | ^^^^^^^^^ --------------- help: if you meant to create a null pointer, use `std::ptr::null_mut()` | LL - usize_mut(0); diff --git a/tests/ui/target-feature/forbidden-target-feature-backchain.rs b/tests/ui/target-feature/forbidden-target-feature-backchain.rs new file mode 100644 index 0000000000000..b868352321e6c --- /dev/null +++ b/tests/ui/target-feature/forbidden-target-feature-backchain.rs @@ -0,0 +1,10 @@ +//! Ensure `backchain` cannot be enabled via `-Ctarget-feature` on s390x. +//@ compile-flags: --crate-type=lib --target=s390x-unknown-linux-gnu +//@ compile-flags: -Ctarget-feature=+backchain +//@ needs-llvm-components: systemz +//@ ignore-backends: gcc + +#![feature(no_core)] +#![no_core] + +//~? ERROR target feature `backchain` cannot be enabled with `-Ctarget-feature`: use `-Cforce-frame-pointers` compiler flag instead diff --git a/tests/ui/target-feature/forbidden-target-feature-backchain.stderr b/tests/ui/target-feature/forbidden-target-feature-backchain.stderr new file mode 100644 index 0000000000000..38847e3d8fe4e --- /dev/null +++ b/tests/ui/target-feature/forbidden-target-feature-backchain.stderr @@ -0,0 +1,4 @@ +error: target feature `backchain` cannot be enabled with `-Ctarget-feature`: use `-Cforce-frame-pointers` compiler flag instead + +error: aborting due to 1 previous error + diff --git a/tests/ui/target-feature/packedstack-combinations.backchain_attr.stderr b/tests/ui/target-feature/packedstack-combinations.backchain_attr.stderr deleted file mode 100644 index 6270e43e93255..0000000000000 --- a/tests/ui/target-feature/packedstack-combinations.backchain_attr.stderr +++ /dev/null @@ -1,6 +0,0 @@ -error: `-Zpacked-stack` is incompatible with `backchain` target feature - | - = note: enabling both `-Zpacked-stack` and the `backchain` target feature is incompatible with the default s390x ABI. Switch to s390x-unknown-none-softfloat if you need both attributes - -error: aborting due to 1 previous error - diff --git a/tests/ui/target-feature/packedstack-combinations.need_softfloat.stderr b/tests/ui/target-feature/packedstack-combinations.need_softfloat.stderr deleted file mode 100644 index 6f4531945ee07..0000000000000 --- a/tests/ui/target-feature/packedstack-combinations.need_softfloat.stderr +++ /dev/null @@ -1,10 +0,0 @@ -warning: unstable feature specified for `-Ctarget-feature`: `backchain` - | - = note: this feature is not stably supported; its behavior can change in the future - -error: packedstack with backchain needs softfloat - | - = note: enabling both `-Zpacked-stack` and the `backchain` target feature is incompatible with the default s390x ABI. Switch to s390x-unknown-none-softfloat if you need both attributes - -error: aborting due to 1 previous error; 1 warning emitted - diff --git a/tests/ui/target-feature/packedstack-combinations.rs b/tests/ui/target-feature/packedstack-combinations.rs index fab2820169d3f..e58c00c970bf5 100644 --- a/tests/ui/target-feature/packedstack-combinations.rs +++ b/tests/ui/target-feature/packedstack-combinations.rs @@ -1,5 +1,6 @@ +// backchain on s390x is enabled with -Cforce-frame-pointers //@ add-minicore -//@ revisions: wrong_arch only_packedstack backchain_attr backchain_cli with_softfloat +//@ revisions: wrong_arch only_packedstack backchain_cli with_softfloat //@ compile-flags: -Zpacked-stack --crate-type=rlib //@ [wrong_arch] compile-flags: --target=x86_64-unknown-linux-gnu @@ -10,32 +11,26 @@ //@ [only_packedstack] build-pass //@ [only_packedstack] needs-llvm-components: systemz -//@ [backchain_attr] compile-flags: --target=s390x-unknown-linux-gnu -//@ [backchain_attr] build-fail -//@ [backchain_attr] needs-llvm-components: systemz - -//@ [backchain_cli] compile-flags: -Ctarget-feature=+backchain --target=s390x-unknown-linux-gnu +//@ [backchain_cli] compile-flags: --target=s390x-unknown-linux-gnu +//@ [backchain_cli] compile-flags: -Cforce-frame-pointers //@ [backchain_cli] should-fail //@ [backchain_cli] needs-llvm-components: systemz -//@ [with_softfloat] compile-flags: -Ctarget-feature=+backchain +//@ [with_softfloat] compile-flags: -Cforce-frame-pointers //@ [with_softfloat] compile-flags: --target=s390x-unknown-none-softfloat //@ [with_softfloat] build-pass //@ [with_softfloat] needs-llvm-components: systemz #![feature(s390x_target_feature)] #![crate_type = "rlib"] -#![feature(no_core,lang_items)] +#![feature(no_core, lang_items)] #![no_core] extern crate minicore; use minicore::*; #[no_mangle] -#[cfg_attr(backchain_attr,target_feature(enable = "backchain"))] -pub fn test() { -} +pub fn test() {} //[wrong_arch]~? ERROR `-Zpacked-stack` is only supported on s390x -//[backchain_cli]~? ERROR `-Zpacked-stack` is incompatible with `backchain` target feature -//[backchain_attr]~? ERROR `-Zpacked-stack` is incompatible with `backchain` target feature +//[backchain_cli]~? ERROR `-Zpacked-stack` is incompatible with `-Cforce-frame-pointers` (backchain) diff --git a/tests/ui/thir-print/const-array-slice-patterns.rs b/tests/ui/thir-print/const-array-slice-patterns.rs new file mode 100644 index 0000000000000..c630388555d5a --- /dev/null +++ b/tests/ui/thir-print/const-array-slice-patterns.rs @@ -0,0 +1,25 @@ +#![crate_type = "rlib"] +//@ edition: 2024 +//@ compile-flags: -Zunpretty=thir-flat +//@ check-pass + +// Snapshot test capturing the original constant value recorded on array and +// slice pattern nodes expanded from constants by `const_to_pat`, which match +// lowering uses to compare the scrutinee against the constant as a whole. + +const ARRAY: [u8; 4] = [1, 2, 3, 4]; +const SLICE: &[u8] = b"ABCD"; + +pub fn array(x: [u8; 4]) { + match x { + ARRAY => {} + _ => {} + } +} + +pub fn slice(x: &[u8]) { + match x { + SLICE => {} + _ => {} + } +} diff --git a/tests/ui/thir-print/const-array-slice-patterns.stdout b/tests/ui/thir-print/const-array-slice-patterns.stdout new file mode 100644 index 0000000000000..be8be57fa1a79 --- /dev/null +++ b/tests/ui/thir-print/const-array-slice-patterns.stdout @@ -0,0 +1,864 @@ +DefId(0:3 ~ const_array_slice_patterns[8ec1]::ARRAY): +Thir { + body_type: Const( + [u8; 4_usize], + ), + loop_hint_attrs: {}, + arms: [], + blocks: [], + exprs: [ + Expr { + kind: Literal { + lit: Spanned { + node: Int( + Pu128( + 1, + ), + Unsuffixed, + ), + span: $DIR/const-array-slice-patterns.rs:10:25: 10:26 (#0), + }, + neg: false, + }, + ty: u8, + temp_scope_id: 8, + span: $DIR/const-array-slice-patterns.rs:10:25: 10:26 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(8), + hir_id: HirId(DefId(0:3 ~ const_array_slice_patterns[8ec1]::ARRAY).8), + value: e0, + }, + ty: u8, + temp_scope_id: 8, + span: $DIR/const-array-slice-patterns.rs:10:25: 10:26 (#0), + }, + Expr { + kind: Literal { + lit: Spanned { + node: Int( + Pu128( + 2, + ), + Unsuffixed, + ), + span: $DIR/const-array-slice-patterns.rs:10:28: 10:29 (#0), + }, + neg: false, + }, + ty: u8, + temp_scope_id: 9, + span: $DIR/const-array-slice-patterns.rs:10:28: 10:29 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(9), + hir_id: HirId(DefId(0:3 ~ const_array_slice_patterns[8ec1]::ARRAY).9), + value: e2, + }, + ty: u8, + temp_scope_id: 9, + span: $DIR/const-array-slice-patterns.rs:10:28: 10:29 (#0), + }, + Expr { + kind: Literal { + lit: Spanned { + node: Int( + Pu128( + 3, + ), + Unsuffixed, + ), + span: $DIR/const-array-slice-patterns.rs:10:31: 10:32 (#0), + }, + neg: false, + }, + ty: u8, + temp_scope_id: 10, + span: $DIR/const-array-slice-patterns.rs:10:31: 10:32 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(10), + hir_id: HirId(DefId(0:3 ~ const_array_slice_patterns[8ec1]::ARRAY).10), + value: e4, + }, + ty: u8, + temp_scope_id: 10, + span: $DIR/const-array-slice-patterns.rs:10:31: 10:32 (#0), + }, + Expr { + kind: Literal { + lit: Spanned { + node: Int( + Pu128( + 4, + ), + Unsuffixed, + ), + span: $DIR/const-array-slice-patterns.rs:10:34: 10:35 (#0), + }, + neg: false, + }, + ty: u8, + temp_scope_id: 11, + span: $DIR/const-array-slice-patterns.rs:10:34: 10:35 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(11), + hir_id: HirId(DefId(0:3 ~ const_array_slice_patterns[8ec1]::ARRAY).11), + value: e6, + }, + ty: u8, + temp_scope_id: 11, + span: $DIR/const-array-slice-patterns.rs:10:34: 10:35 (#0), + }, + Expr { + kind: Array { + fields: [ + e1, + e3, + e5, + e7, + ], + }, + ty: [u8; 4_usize], + temp_scope_id: 7, + span: $DIR/const-array-slice-patterns.rs:10:24: 10:36 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(7), + hir_id: HirId(DefId(0:3 ~ const_array_slice_patterns[8ec1]::ARRAY).7), + value: e8, + }, + ty: [u8; 4_usize], + temp_scope_id: 7, + span: $DIR/const-array-slice-patterns.rs:10:24: 10:36 (#0), + }, + ], + stmts: [], + params: [], +} + +DefId(0:4 ~ const_array_slice_patterns[8ec1]::ARRAY::{constant#0}): +Thir { + body_type: Const( + usize, + ), + loop_hint_attrs: {}, + arms: [], + blocks: [], + exprs: [ + Expr { + kind: Literal { + lit: Spanned { + node: Int( + Pu128( + 4, + ), + Unsuffixed, + ), + span: $DIR/const-array-slice-patterns.rs:10:19: 10:20 (#0), + }, + neg: false, + }, + ty: usize, + temp_scope_id: 4, + span: $DIR/const-array-slice-patterns.rs:10:19: 10:20 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(4), + hir_id: HirId(DefId(0:3 ~ const_array_slice_patterns[8ec1]::ARRAY).4), + value: e0, + }, + ty: usize, + temp_scope_id: 4, + span: $DIR/const-array-slice-patterns.rs:10:19: 10:20 (#0), + }, + ], + stmts: [], + params: [], +} + +DefId(0:5 ~ const_array_slice_patterns[8ec1]::SLICE): +Thir { + body_type: Const( + &'{erased} [u8], + ), + loop_hint_attrs: {}, + arms: [], + blocks: [], + exprs: [ + Expr { + kind: Literal { + lit: Spanned { + node: ByteStr( + [ + 65, + 66, + 67, + 68, + ], + Cooked, + ), + span: $DIR/const-array-slice-patterns.rs:11:22: 11:29 (#0), + }, + neg: false, + }, + ty: &'{erased} [u8; 4_usize], + temp_scope_id: 6, + span: $DIR/const-array-slice-patterns.rs:11:22: 11:29 (#0), + }, + Expr { + kind: Deref { + arg: e0, + }, + ty: [u8; 4_usize], + temp_scope_id: 6, + span: $DIR/const-array-slice-patterns.rs:11:22: 11:29 (#0), + }, + Expr { + kind: Borrow { + borrow_kind: Shared, + arg: e1, + }, + ty: &'{erased} [u8; 4_usize], + temp_scope_id: 6, + span: $DIR/const-array-slice-patterns.rs:11:22: 11:29 (#0), + }, + Expr { + kind: PointerCoercion { + cast: Unsize, + source: e2, + is_from_as_cast: false, + }, + ty: &'{erased} [u8], + temp_scope_id: 6, + span: $DIR/const-array-slice-patterns.rs:11:22: 11:29 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(6), + hir_id: HirId(DefId(0:5 ~ const_array_slice_patterns[8ec1]::SLICE).6), + value: e3, + }, + ty: &'{erased} [u8], + temp_scope_id: 6, + span: $DIR/const-array-slice-patterns.rs:11:22: 11:29 (#0), + }, + ], + stmts: [], + params: [], +} + +DefId(0:6 ~ const_array_slice_patterns[8ec1]::array): +Thir { + body_type: Fn( + fn([u8; 4_usize]), + ), + loop_hint_attrs: {}, + arms: [ + Arm { + pattern: Pat { + ty: [u8; 4_usize], + span: $DIR/const-array-slice-patterns.rs:15:9: 15:14 (#0), + extra: Some( + PatExtra { + expanded_const: Some( + Free { + def_id: DefId(0:3 ~ const_array_slice_patterns[8ec1]::ARRAY), + }, + ), + expanded_const_value: Some( + Value { + ty: [u8; 4_usize], + valtree: Branch( + [ + 1_u8, + 2_u8, + 3_u8, + 4_u8, + ], + ), + }, + ), + ascriptions: [], + }, + ), + kind: Array { + prefix: [ + Pat { + ty: u8, + span: $DIR/const-array-slice-patterns.rs:15:9: 15:14 (#0), + extra: None, + kind: Constant { + value: Value { + ty: u8, + valtree: Leaf( + 0x01, + ), + }, + }, + }, + Pat { + ty: u8, + span: $DIR/const-array-slice-patterns.rs:15:9: 15:14 (#0), + extra: None, + kind: Constant { + value: Value { + ty: u8, + valtree: Leaf( + 0x02, + ), + }, + }, + }, + Pat { + ty: u8, + span: $DIR/const-array-slice-patterns.rs:15:9: 15:14 (#0), + extra: None, + kind: Constant { + value: Value { + ty: u8, + valtree: Leaf( + 0x03, + ), + }, + }, + }, + Pat { + ty: u8, + span: $DIR/const-array-slice-patterns.rs:15:9: 15:14 (#0), + extra: None, + kind: Constant { + value: Value { + ty: u8, + valtree: Leaf( + 0x04, + ), + }, + }, + }, + ], + slice: None, + suffix: [], + }, + }, + guard: None, + body: e3, + hir_id: HirId(DefId(0:6 ~ const_array_slice_patterns[8ec1]::array).10), + scope: Node(10), + span: $DIR/const-array-slice-patterns.rs:15:9: 15:20 (#0), + }, + Arm { + pattern: Pat { + ty: [u8; 4_usize], + span: $DIR/const-array-slice-patterns.rs:16:9: 16:10 (#0), + extra: None, + kind: Wild, + }, + guard: None, + body: e5, + hir_id: HirId(DefId(0:6 ~ const_array_slice_patterns[8ec1]::array).14), + scope: Node(14), + span: $DIR/const-array-slice-patterns.rs:16:9: 16:16 (#0), + }, + ], + blocks: [ + Block { + targeted_by_break: false, + region_scope: Node(12), + span: $DIR/const-array-slice-patterns.rs:15:18: 15:20 (#0), + stmts: [], + expr: None, + safety_mode: Safe, + }, + Block { + targeted_by_break: false, + region_scope: Node(16), + span: $DIR/const-array-slice-patterns.rs:16:14: 16:16 (#0), + stmts: [], + expr: None, + safety_mode: Safe, + }, + Block { + targeted_by_break: false, + region_scope: Node(3), + span: $DIR/const-array-slice-patterns.rs:13:26: 18:2 (#0), + stmts: [], + expr: Some( + e7, + ), + safety_mode: Safe, + }, + ], + exprs: [ + Expr { + kind: VarRef { + id: LocalVarId( + HirId(DefId(0:6 ~ const_array_slice_patterns[8ec1]::array).2), + ), + }, + ty: [u8; 4_usize], + temp_scope_id: 5, + span: $DIR/const-array-slice-patterns.rs:14:11: 14:12 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(5), + hir_id: HirId(DefId(0:6 ~ const_array_slice_patterns[8ec1]::array).5), + value: e0, + }, + ty: [u8; 4_usize], + temp_scope_id: 5, + span: $DIR/const-array-slice-patterns.rs:14:11: 14:12 (#0), + }, + Expr { + kind: Block { + block: b0, + }, + ty: (), + temp_scope_id: 11, + span: $DIR/const-array-slice-patterns.rs:15:18: 15:20 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(11), + hir_id: HirId(DefId(0:6 ~ const_array_slice_patterns[8ec1]::array).11), + value: e2, + }, + ty: (), + temp_scope_id: 11, + span: $DIR/const-array-slice-patterns.rs:15:18: 15:20 (#0), + }, + Expr { + kind: Block { + block: b1, + }, + ty: (), + temp_scope_id: 15, + span: $DIR/const-array-slice-patterns.rs:16:14: 16:16 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(15), + hir_id: HirId(DefId(0:6 ~ const_array_slice_patterns[8ec1]::array).15), + value: e4, + }, + ty: (), + temp_scope_id: 15, + span: $DIR/const-array-slice-patterns.rs:16:14: 16:16 (#0), + }, + Expr { + kind: Match { + scrutinee: e1, + arms: [ + a0, + a1, + ], + match_source: Normal, + }, + ty: (), + temp_scope_id: 4, + span: $DIR/const-array-slice-patterns.rs:14:5: 17:6 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(4), + hir_id: HirId(DefId(0:6 ~ const_array_slice_patterns[8ec1]::array).4), + value: e6, + }, + ty: (), + temp_scope_id: 4, + span: $DIR/const-array-slice-patterns.rs:14:5: 17:6 (#0), + }, + Expr { + kind: Block { + block: b2, + }, + ty: (), + temp_scope_id: 17, + span: $DIR/const-array-slice-patterns.rs:13:26: 18:2 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(17), + hir_id: HirId(DefId(0:6 ~ const_array_slice_patterns[8ec1]::array).17), + value: e8, + }, + ty: (), + temp_scope_id: 17, + span: $DIR/const-array-slice-patterns.rs:13:26: 18:2 (#0), + }, + ], + stmts: [], + params: [ + Param { + pat: Some( + Pat { + ty: [u8; 4_usize], + span: $DIR/const-array-slice-patterns.rs:13:14: 13:15 (#0), + extra: None, + kind: Binding { + name: "x", + mode: BindingMode( + No, + Not, + ), + var: LocalVarId( + HirId(DefId(0:6 ~ const_array_slice_patterns[8ec1]::array).2), + ), + ty: [u8; 4_usize], + subpattern: None, + is_primary: true, + is_shorthand: false, + }, + }, + ), + ty: [u8; 4_usize], + ty_span: Some( + $DIR/const-array-slice-patterns.rs:13:17: 13:24 (#0), + ), + self_kind: None, + hir_id: Some( + HirId(DefId(0:6 ~ const_array_slice_patterns[8ec1]::array).1), + ), + }, + ], +} + +DefId(0:7 ~ const_array_slice_patterns[8ec1]::array::{constant#0}): +Thir { + body_type: Const( + usize, + ), + loop_hint_attrs: {}, + arms: [], + blocks: [], + exprs: [ + Expr { + kind: Literal { + lit: Spanned { + node: Int( + Pu128( + 4, + ), + Unsuffixed, + ), + span: $DIR/const-array-slice-patterns.rs:13:22: 13:23 (#0), + }, + neg: false, + }, + ty: usize, + temp_scope_id: 21, + span: $DIR/const-array-slice-patterns.rs:13:22: 13:23 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(21), + hir_id: HirId(DefId(0:6 ~ const_array_slice_patterns[8ec1]::array).21), + value: e0, + }, + ty: usize, + temp_scope_id: 21, + span: $DIR/const-array-slice-patterns.rs:13:22: 13:23 (#0), + }, + ], + stmts: [], + params: [], +} + +DefId(0:8 ~ const_array_slice_patterns[8ec1]::slice): +Thir { + body_type: Fn( + fn(&'{erased} [u8]), + ), + loop_hint_attrs: {}, + arms: [ + Arm { + pattern: Pat { + ty: &'{erased} [u8], + span: $DIR/const-array-slice-patterns.rs:22:9: 22:14 (#0), + extra: Some( + PatExtra { + expanded_const: Some( + Free { + def_id: DefId(0:5 ~ const_array_slice_patterns[8ec1]::SLICE), + }, + ), + expanded_const_value: None, + ascriptions: [], + }, + ), + kind: Deref { + pin: Not, + subpattern: Pat { + ty: [u8], + span: $DIR/const-array-slice-patterns.rs:22:9: 22:14 (#0), + extra: Some( + PatExtra { + expanded_const: None, + expanded_const_value: Some( + Value { + ty: [u8], + valtree: Branch( + [ + 65_u8, + 66_u8, + 67_u8, + 68_u8, + ], + ), + }, + ), + ascriptions: [], + }, + ), + kind: Slice { + prefix: [ + Pat { + ty: u8, + span: $DIR/const-array-slice-patterns.rs:22:9: 22:14 (#0), + extra: None, + kind: Constant { + value: Value { + ty: u8, + valtree: Leaf( + 0x41, + ), + }, + }, + }, + Pat { + ty: u8, + span: $DIR/const-array-slice-patterns.rs:22:9: 22:14 (#0), + extra: None, + kind: Constant { + value: Value { + ty: u8, + valtree: Leaf( + 0x42, + ), + }, + }, + }, + Pat { + ty: u8, + span: $DIR/const-array-slice-patterns.rs:22:9: 22:14 (#0), + extra: None, + kind: Constant { + value: Value { + ty: u8, + valtree: Leaf( + 0x43, + ), + }, + }, + }, + Pat { + ty: u8, + span: $DIR/const-array-slice-patterns.rs:22:9: 22:14 (#0), + extra: None, + kind: Constant { + value: Value { + ty: u8, + valtree: Leaf( + 0x44, + ), + }, + }, + }, + ], + slice: None, + suffix: [], + }, + }, + }, + }, + guard: None, + body: e3, + hir_id: HirId(DefId(0:8 ~ const_array_slice_patterns[8ec1]::slice).10), + scope: Node(10), + span: $DIR/const-array-slice-patterns.rs:22:9: 22:20 (#0), + }, + Arm { + pattern: Pat { + ty: &'{erased} [u8], + span: $DIR/const-array-slice-patterns.rs:23:9: 23:10 (#0), + extra: None, + kind: Wild, + }, + guard: None, + body: e5, + hir_id: HirId(DefId(0:8 ~ const_array_slice_patterns[8ec1]::slice).14), + scope: Node(14), + span: $DIR/const-array-slice-patterns.rs:23:9: 23:16 (#0), + }, + ], + blocks: [ + Block { + targeted_by_break: false, + region_scope: Node(12), + span: $DIR/const-array-slice-patterns.rs:22:18: 22:20 (#0), + stmts: [], + expr: None, + safety_mode: Safe, + }, + Block { + targeted_by_break: false, + region_scope: Node(16), + span: $DIR/const-array-slice-patterns.rs:23:14: 23:16 (#0), + stmts: [], + expr: None, + safety_mode: Safe, + }, + Block { + targeted_by_break: false, + region_scope: Node(3), + span: $DIR/const-array-slice-patterns.rs:20:24: 25:2 (#0), + stmts: [], + expr: Some( + e7, + ), + safety_mode: Safe, + }, + ], + exprs: [ + Expr { + kind: VarRef { + id: LocalVarId( + HirId(DefId(0:8 ~ const_array_slice_patterns[8ec1]::slice).2), + ), + }, + ty: &'{erased} [u8], + temp_scope_id: 5, + span: $DIR/const-array-slice-patterns.rs:21:11: 21:12 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(5), + hir_id: HirId(DefId(0:8 ~ const_array_slice_patterns[8ec1]::slice).5), + value: e0, + }, + ty: &'{erased} [u8], + temp_scope_id: 5, + span: $DIR/const-array-slice-patterns.rs:21:11: 21:12 (#0), + }, + Expr { + kind: Block { + block: b0, + }, + ty: (), + temp_scope_id: 11, + span: $DIR/const-array-slice-patterns.rs:22:18: 22:20 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(11), + hir_id: HirId(DefId(0:8 ~ const_array_slice_patterns[8ec1]::slice).11), + value: e2, + }, + ty: (), + temp_scope_id: 11, + span: $DIR/const-array-slice-patterns.rs:22:18: 22:20 (#0), + }, + Expr { + kind: Block { + block: b1, + }, + ty: (), + temp_scope_id: 15, + span: $DIR/const-array-slice-patterns.rs:23:14: 23:16 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(15), + hir_id: HirId(DefId(0:8 ~ const_array_slice_patterns[8ec1]::slice).15), + value: e4, + }, + ty: (), + temp_scope_id: 15, + span: $DIR/const-array-slice-patterns.rs:23:14: 23:16 (#0), + }, + Expr { + kind: Match { + scrutinee: e1, + arms: [ + a0, + a1, + ], + match_source: Normal, + }, + ty: (), + temp_scope_id: 4, + span: $DIR/const-array-slice-patterns.rs:21:5: 24:6 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(4), + hir_id: HirId(DefId(0:8 ~ const_array_slice_patterns[8ec1]::slice).4), + value: e6, + }, + ty: (), + temp_scope_id: 4, + span: $DIR/const-array-slice-patterns.rs:21:5: 24:6 (#0), + }, + Expr { + kind: Block { + block: b2, + }, + ty: (), + temp_scope_id: 17, + span: $DIR/const-array-slice-patterns.rs:20:24: 25:2 (#0), + }, + Expr { + kind: Scope { + region_scope: Node(17), + hir_id: HirId(DefId(0:8 ~ const_array_slice_patterns[8ec1]::slice).17), + value: e8, + }, + ty: (), + temp_scope_id: 17, + span: $DIR/const-array-slice-patterns.rs:20:24: 25:2 (#0), + }, + ], + stmts: [], + params: [ + Param { + pat: Some( + Pat { + ty: &'{erased} [u8], + span: $DIR/const-array-slice-patterns.rs:20:14: 20:15 (#0), + extra: None, + kind: Binding { + name: "x", + mode: BindingMode( + No, + Not, + ), + var: LocalVarId( + HirId(DefId(0:8 ~ const_array_slice_patterns[8ec1]::slice).2), + ), + ty: &'{erased} [u8], + subpattern: None, + is_primary: true, + is_shorthand: false, + }, + }, + ), + ty: &'{erased} [u8], + ty_span: Some( + $DIR/const-array-slice-patterns.rs:20:17: 20:22 (#0), + ), + self_kind: None, + hir_id: Some( + HirId(DefId(0:8 ~ const_array_slice_patterns[8ec1]::slice).1), + ), + }, + ], +} + diff --git a/tests/ui/thir-print/str-patterns.stdout b/tests/ui/thir-print/str-patterns.stdout index f943eb03675ab..138b3a0096044 100644 --- a/tests/ui/thir-print/str-patterns.stdout +++ b/tests/ui/thir-print/str-patterns.stdout @@ -50,6 +50,7 @@ Thir { def_id: DefId(0:4 ~ str_patterns[fc71]::CONSTANT), }, ), + expanded_const_value: None, ascriptions: [], }, ), diff --git a/tests/ui/thir-print/thir-tree-array-index.stdout b/tests/ui/thir-print/thir-tree-array-index.stdout index 4e40bcbbf4e07..b167169ca87fa 100644 --- a/tests/ui/thir-print/thir-tree-array-index.stdout +++ b/tests/ui/thir-print/thir-tree-array-index.stdout @@ -129,6 +129,7 @@ body: span: $DIR/thir-tree-array-index.rs:7:7: 7:9 (#0) extra: PatExtra { expanded_const: None + expanded_const_value: None ascriptions: [ Ascription { annotation: CanonicalUserTypeAnnotation { user_ty: Canonical { value: UserType { kind: Ty([usize; 5_usize]), bounds: [] }, max_universe: U0, var_kinds: [] }, span: $DIR/thir-tree-array-index.rs:7:11: 7:21 (#0), inferred_ty: [usize; 5_usize] }, variance: + } ] @@ -279,6 +280,7 @@ body: span: $DIR/thir-tree-array-index.rs:8:7: 8:9 (#0) extra: PatExtra { expanded_const: None + expanded_const_value: None ascriptions: [ Ascription { annotation: CanonicalUserTypeAnnotation { user_ty: Canonical { value: UserType { kind: Ty([usize; 5_usize]), bounds: [] }, max_universe: U0, var_kinds: [] }, span: $DIR/thir-tree-array-index.rs:8:11: 8:21 (#0), inferred_ty: [usize; 5_usize] }, variance: + } ] diff --git a/tests/ui/thir-print/thir-tree-match-for.stdout b/tests/ui/thir-print/thir-tree-match-for.stdout index 72dd2c578e446..8abba07559261 100644 --- a/tests/ui/thir-print/thir-tree-match-for.stdout +++ b/tests/ui/thir-print/thir-tree-match-for.stdout @@ -171,6 +171,7 @@ body: span: $DIR/thir-tree-match-for.rs:10:5: 10:9 (#0) extra: PatExtra { expanded_const: None + expanded_const_value: None ascriptions: [] } kind: PatKind {