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_attr_parsing/src/interface.rs b/compiler/rustc_attr_parsing/src/interface.rs index 8510b54aa6446..4274c21ffd26f 100644 --- a/compiler/rustc_attr_parsing/src/interface.rs +++ b/compiler/rustc_attr_parsing/src/interface.rs @@ -372,14 +372,20 @@ impl<'sess> AttributeParser<'sess> { let inner_span = lower_span(n.item.span); let accepter = ATTRIBUTE_PARSERS.accepters.get(parts.as_slice()); + + self.check_attribute_safety( + &attr_path, + inner_span, + n.item.unsafety, + if let Some(accept) = accepter { + accept.safety + } else { + AttributeSafety::Normal + }, + &mut emit_lint, + ); + if let Some(accept) = accepter { - self.check_attribute_safety( - &attr_path, - inner_span, - n.item.unsafety, - accept.safety, - &mut emit_lint, - ); self.check_attribute_stability(&attr_path, attr_span, accept.stability); if let [part] = parts.as_slice() { debug_assert!(BUILTIN_ATTRIBUTE_SET.contains(part)); @@ -491,14 +497,6 @@ impl<'sess> AttributeParser<'sess> { span: attr_span, }; - self.check_attribute_safety( - &attr_path, - inner_span, - n.item.unsafety, - AttributeSafety::Normal, - &mut emit_lint, - ); - if !matches!(self.should_emit, ShouldEmit::Nothing) && Target::from_ast_target(&ast_target) == Target::Crate { diff --git a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs index f1f281b5509cd..2bd58ce8620a1 100644 --- a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs +++ b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs @@ -33,7 +33,6 @@ pub(crate) fn expand( return vec![orig_item]; }; - // Generate a bunch of new items using the AllocFnFactory let span = ecx.with_def_site_ctxt(item.span); // Generate item statements for the allocator methods. @@ -42,7 +41,7 @@ pub(crate) fn expand( // Generate anonymous constant serving as container for the allocator methods. let const_item = ecx.item_const_underscore(span, ecx.block(span, stmts)); let const_item = if is_stmt { - Annotatable::Stmt(Box::new(ecx.stmt_item(span, const_item))) + Annotatable::Stmt(ecx.stmt_item(span, const_item)) } else { Annotatable::Item(const_item) }; diff --git a/compiler/rustc_builtin_macros/src/autodiff.rs b/compiler/rustc_builtin_macros/src/autodiff.rs index cc79eb29b68ab..da53a770cdc1a 100644 --- a/compiler/rustc_builtin_macros/src/autodiff.rs +++ b/compiler/rustc_builtin_macros/src/autodiff.rs @@ -14,8 +14,8 @@ mod llvm_enzyme { use rustc_ast::tokenstream::*; use rustc_ast::visit::AssocCtxt::*; use rustc_ast::{ - self as ast, FnRetTy, FnSig, GenericArg, GenericParamKind, Generics, ItemKind, - MetaItemInner, PatKind, TyKind, Visibility, + self as ast, FnRetTy, FnSig, GenericParamKind, Generics, ItemKind, MetaItemInner, PatKind, + TyKind, Visibility, }; use rustc_attr_ir::RustcAutodiff; use rustc_expand::base::{Annotatable, ExtCtxt}; @@ -24,6 +24,7 @@ mod llvm_enzyme { use tracing::{debug, trace}; use crate::diagnostics; + use crate::util::generic_param_to_arg; pub(crate) fn outer_normal_attr( kind: &Box, @@ -449,7 +450,7 @@ mod llvm_enzyme { Annotatable::Stmt(_) => { let mut d_fn = ecx.item(span, d_attrs, ItemKind::Fn(d_fn)); d_fn.vis = vis; - Annotatable::Stmt(Box::new(ecx.stmt_item(span, d_fn))) + Annotatable::Stmt(ecx.stmt_item(span, d_fn)) } _ => { unreachable!("item kind checked previously") @@ -577,16 +578,8 @@ mod llvm_enzyme { .params .iter() .filter_map(|p| match &p.kind { - GenericParamKind::Type { .. } => { - let path = ast::Path::from_ident(p.ident); - let ty = ecx.ty_path(path); - Some(GenericArg::Type(ty)) - } - GenericParamKind::Const { .. } => { - let anon_const = ecx.const_ident(span, p.ident); - Some(GenericArg::Const(anon_const)) - } GenericParamKind::Lifetime => None, + _ => Some(generic_param_to_arg(ecx, p, span)), }) .collect::>(); diff --git a/compiler/rustc_builtin_macros/src/cfg_eval.rs b/compiler/rustc_builtin_macros/src/cfg_eval.rs index 210b9ee895c0f..00c8dd52da6a2 100644 --- a/compiler/rustc_builtin_macros/src/cfg_eval.rs +++ b/compiler/rustc_builtin_macros/src/cfg_eval.rs @@ -126,7 +126,7 @@ impl CfgEval<'_> { Annotatable::Stmt(_) => { let stmt = parser.parse_stmt_without_recovery(false, ForceCollect::Yes, false)?; - self.flat_map_stmt(stmt).pop().map(|stmt| Annotatable::Stmt(Box::new(stmt))) + self.flat_map_stmt(stmt).pop().map(Annotatable::Stmt) } Annotatable::Expr(_) => { let mut expr = parser.parse_expr_force_collect()?; diff --git a/compiler/rustc_builtin_macros/src/cfg_select.rs b/compiler/rustc_builtin_macros/src/cfg_select.rs index 69c3802ceafae..1c33f9d95c99d 100644 --- a/compiler/rustc_builtin_macros/src/cfg_select.rs +++ b/compiler/rustc_builtin_macros/src/cfg_select.rs @@ -29,11 +29,7 @@ fn tts_to_mac_result<'cx, 'sess>( tts: TokenStream, span: Span, ) -> Box { - match ExpandResult::from_tts(ecx, tts, site_span, span, Ident::with_dummy_span(sym::cfg_select)) - { - ExpandResult::Ready(x) => x, - _ => unreachable!("from_tts always returns Ready"), - } + ExpandResult::from_tts(ecx, tts, site_span, span, Ident::with_dummy_span(sym::cfg_select)) } macro_rules! forward_to_parser_any_macro { diff --git a/compiler/rustc_builtin_macros/src/deriving/clone.rs b/compiler/rustc_builtin_macros/src/deriving/clone.rs index 669b89801ee45..19992c2b69481 100644 --- a/compiler/rustc_builtin_macros/src/deriving/clone.rs +++ b/compiler/rustc_builtin_macros/src/deriving/clone.rs @@ -28,7 +28,7 @@ pub(crate) fn expand_derive_clone( // enough. Whether Clone is implemented for fields is irrelevant so we // don't assert it.) let bounds; - let body: MethodBodyFunc<'_>; + let body; let is_simple; match &item.kind { ItemKind::Struct(_, Generics { params, .. }, _) @@ -42,16 +42,22 @@ pub(crate) fn expand_derive_clone( .any(|param| matches!(param.kind, ast::GenericParamKind::Type { .. })) { is_simple = true; - body = Box::new(|c, s, sub| clone_simple_body(c, s, sub, false)); + body = MethodBody::Directly(clone_simple_body(cx, span, item, false)); } else { is_simple = false; - body = Box::new(|c, s, sub| clone_body(c, s, sub, item.kind.ident().unwrap())); + body = MethodBody::SubstructureFunc { + body_func: Box::new(|c, s, sub| { + clone_body(c, s, sub, item.kind.ident().unwrap()) + }), + strategy: FieldlessVariantsStrategy::Default, + has_other_selflike_arg: false, + }; } } ItemKind::Union(..) => { bounds = smallvec![path_std!(cx, span, marker::Copy)]; is_simple = true; - body = Box::new(|c, s, sub| clone_simple_body(c, s, sub, true)); + body = MethodBody::Directly(clone_simple_body(cx, span, item, true)); } _ => cx.dcx().span_bug(span, "`derive(Clone)` on wrong item kind"), } @@ -86,28 +92,25 @@ pub(crate) fn expand_derive_clone( methods: smallvec![MethodDef { name: sym::clone, generics: cx.empty_generics(span), - explicit_self: true, - nonself_args: SmallVec::new(), - has_other_selflike_arg: false, + args: thin_vec![cx.param_self_ref(span)], ret_ty: cx.ty_self(span), attributes: thin_vec![ cx.generated_attr(span, ast::GeneratedAttr::Inline), cx.generated_attr(span, ast::GeneratedAttr::RustcTrivialFieldReads) ], - fieldless_variants_strategy: FieldlessVariantsStrategy::Default, body, }], is_const, .. }; - trait_def.expand_ext(cx, item, push, is_simple) + trait_def.expand(cx, item, push); } fn clone_simple_body( cx: &ExtCtxt<'_>, trait_span: Span, - substr: Substructure<'_>, + item: &ast::Item, is_union: bool, ) -> BlockOrExpr { let mut stmts = ThinVec::new(); @@ -148,16 +151,16 @@ fn clone_simple_body( &[sym::clone, sym::AssertParamIsCopy], ); } else { - match substr { - StaticStruct(vdata, ..) => { + match &item.kind { + ast::ItemKind::Struct(.., vdata) => { process_variant(vdata); } - StaticEnum(enum_def, ..) => { + ast::ItemKind::Enum(.., enum_def) => { for variant in &enum_def.variants { process_variant(&variant.data); } } - _ => cx.dcx().span_bug(trait_span, "unexpected substructure in simple `derive(Clone)`"), + _ => unreachable!(), } } BlockOrExpr::new_mixed(stmts, Some(cx.expr_deref(trait_span, cx.expr_self(trait_span)))) @@ -169,7 +172,7 @@ fn clone_body( substr: Substructure<'_>, type_ident: Ident, ) -> BlockOrExpr { - let subcall = |field: FieldInfo| { + let subcall = |field: FieldInfo<'_>| { let args = thin_vec![field.self_expr]; cx.expr_call_global( field.span, @@ -201,7 +204,7 @@ fn clone_body( VariantData::Struct { .. } => { let fields = all_fields .into_iter() - .map(|field| cx.field_imm(field.span, field.name.unwrap(), subcall(field))) + .map(|field| cx.field_imm(field.span, field.def.ident.unwrap(), subcall(field))) .collect::>(); cx.expr_struct(trait_span, ctor_path, fields) diff --git a/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs b/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs index 6a7ecba0d1bf9..53d37503dca29 100644 --- a/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs +++ b/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs @@ -15,6 +15,7 @@ use thin_vec::{ThinVec, thin_vec}; use crate::deriving::generic::*; use crate::deriving::path_std; use crate::diagnostics; +use crate::util::generic_param_to_arg; pub(crate) fn expand_derive_coerce_pointee( cx: &ExtCtxt<'_>, diff --git a/compiler/rustc_builtin_macros/src/deriving/debug.rs b/compiler/rustc_builtin_macros/src/deriving/debug.rs index b372874fc5814..6ea38b38782fd 100644 --- a/compiler/rustc_builtin_macros/src/deriving/debug.rs +++ b/compiler/rustc_builtin_macros/src/deriving/debug.rs @@ -22,12 +22,7 @@ pub(crate) fn expand_derive_debug( ast::Mutability::Mut, ); - let all_fieldless = match &item.kind { - ast::ItemKind::Enum(_, _, def) => { - def.variants.len() > 1 && def.variants.iter().all(|v| v.data.fields().is_empty()) - } - _ => false, - }; + let ident = item.kind.ident().unwrap(); let trait_def = TraitDef { span, @@ -38,26 +33,35 @@ pub(crate) fn expand_derive_debug( methods: smallvec![MethodDef { name: sym::fmt, generics: cx.empty_generics(span), - explicit_self: true, - nonself_args: smallvec![(sym::f, fmtr)], - has_other_selflike_arg: false, + args: thin_vec![cx.param_self_ref(span), cx.param(span, sym::f, fmtr)], ret_ty: cx.ty_path(path_std!(cx, span, fmt::Result)), attributes: thin_vec![ cx.generated_attr(span, ast::GeneratedAttr::Inline), cx.generated_attr(span, ast::GeneratedAttr::RustcTrivialFieldReads) ], - fieldless_variants_strategy: FieldlessVariantsStrategy::Default, - body: Box::new(|cx, span, substr| debug_body( - cx, - span, - substr, - item.kind.ident().unwrap() - )), + body: match &item.kind { + _ if cx.sess.opts.unstable_opts.fmt_debug == FmtDebug::None => { + MethodBody::Directly(BlockOrExpr::new_expr( + cx.expr_ok(span, cx.expr_tuple(span, ThinVec::new())), + )) + } + ast::ItemKind::Enum(_, _, def) + if def.variants.len() > 1 + && def.variants.iter().all(|v| v.data.fields().is_empty()) => + { + MethodBody::Directly(debug_fieldless_enum(cx, span, def, ident)) + } + _ => MethodBody::SubstructureFunc { + body_func: Box::new(|cx, span, substr| debug_body(cx, span, substr, ident)), + strategy: FieldlessVariantsStrategy::Default, + has_other_selflike_arg: false, + }, + }, }], is_const, .. }; - trait_def.expand_ext(cx, item, push, all_fieldless); + trait_def.expand(cx, item, push); } fn debug_body( @@ -67,14 +71,10 @@ fn debug_body( type_ident: Ident, ) -> BlockOrExpr { let fmt_detail = cx.sess.opts.unstable_opts.fmt_debug; - if fmt_detail == FmtDebug::None { - return BlockOrExpr::new_expr(cx.expr_ok(span, cx.expr_tuple(span, ThinVec::new()))); - } let (ident, vdata, fields) = match substr { Struct(vdata, fields) => (type_ident, vdata, fields), EnumMatching(v, fields) => (v.ident, &v.data, fields), - StaticEnum(enum_def) => return debug_fieldless_enum(cx, span, enum_def, type_ident), _ => cx.dcx().span_bug(span, "unexpected substructure in `derive(Debug)`"), }; @@ -104,7 +104,7 @@ fn debug_body( const CUTOFF: usize = 5; let len = fields.len(); - let expr_for_field = |field: FieldInfo, index: usize| -> Box { + let expr_for_field = |field: FieldInfo<'_>, index: usize| -> Box { if index < len - 1 { field.self_expr } else { @@ -125,15 +125,15 @@ fn debug_body( let fn_path_debug = cx.std_path(span, &[sym::fmt, sym::Formatter, Symbol::intern(&debug)]); let mut args = ThinVec::with_capacity(2 + fields.len()); - args.extend([fmt]); + args.push(fmt); if is_struct { let mut names = String::new(); - names.push_str(ident.name.as_str()); + names.push_str(ident.as_str()); for field in fields.iter() { names.push(' '); - names.push_str(field.name.unwrap().name.as_str()); + names.push_str(field.def.ident.unwrap().as_str()); } let name_expr = cx.expr_str(span, Symbol::intern(&names)); @@ -152,68 +152,34 @@ fn debug_body( // Enough fields that we must use the any-length method. let mut names = String::new(); if is_struct { - names.push_str(ident.name.as_str()); + names.push_str(ident.as_str()); } let mut value_exprs = ThinVec::with_capacity(fields.len()); for (i, field) in fields.into_iter().enumerate() { if is_struct { names.push(' '); - names.push_str(field.name.unwrap().name.as_str()); + names.push_str(field.def.ident.unwrap().name.as_str()); } let field = expr_for_field(field, i); value_exprs.push(field); } - // `let names: &'static _ = "StructName field1 field2"` - let names_let = is_struct.then(|| { - let lt_static = Some(cx.lifetime_static(span)); - let ty_static_ref = cx.ty_ref(span, cx.ty_infer(span), lt_static, ast::Mutability::Not); - let names_expr = cx.expr_str(span, Symbol::intern(&names)); - cx.stmt_let_ty(span, false, sym::names, Some(ty_static_ref), names_expr) - }); - - // `let values: &[&dyn Debug] = &[&&self.field1, &&self.field2];` - let path_debug = cx.std_path(span, &[sym::fmt, sym::Debug]); - let ty_dyn_debug = cx.ty( - span, - ast::TyKind::TraitObject( - thin_vec![cx.trait_bound(path_debug, false)], - ast::TraitObjectSyntax::Dyn, - ), - ); - let ty_slice = cx.ty( - span, - ast::TyKind::Slice(cx.ty_ref(span, ty_dyn_debug, None, ast::Mutability::Not)), - ); - let values_let = cx.stmt_let_ty( - span, - false, - sym::values, - Some(cx.ty_ref(span, ty_slice, None, ast::Mutability::Not)), - cx.expr_array_ref(span, value_exprs), - ); - - // `fmt::Formatter::debug_struct_fields_finish(fmt, names, values)` + // `fmt::Formatter::debug_struct_fields_finish(fmt, "StructName field1 field2", &[&&self.field1, &&self.field2])` or + // `fmt::Formatter::debug_struct_fields_finish(fmt, "StructName", &[&&self.field1, &&self.field2])` let sym_debug = sym::debug_struct_fields_finish; let fn_path_debug_internal = cx.std_path(span, &[sym::fmt, sym::Formatter, sym_debug]); let args = thin_vec![ fmt, - if is_struct { cx.expr_name(span, sym::names) } else { expr_name() }, - cx.expr_name(span, sym::values) + if is_struct { cx.expr_str(span, Symbol::intern(&names)) } else { expr_name() }, + cx.expr_array_ref(span, value_exprs), ]; let expr = cx.expr_call_global(span, fn_path_debug_internal, args); - let stmts = if is_struct { - thin_vec![names_let.unwrap(), values_let] - } else { - thin_vec![values_let] - }; - - BlockOrExpr::new_mixed(stmts, Some(expr)) + BlockOrExpr::new_expr(expr) } } @@ -319,8 +285,7 @@ fn debug_fieldless_enum_concat_str( .map(|(i, v)| { let name_offset = concatenated_names.len(); - let name = v.ident.name.as_str(); - concatenated_names.push_str(name); + concatenated_names.push_str(v.ident.as_str()); let is_last = i == def.variants.len() - 1; if !is_last { diff --git a/compiler/rustc_builtin_macros/src/deriving/default.rs b/compiler/rustc_builtin_macros/src/deriving/default.rs index 6aa45b9d41126..6c6e01abc6a75 100644 --- a/compiler/rustc_builtin_macros/src/deriving/default.rs +++ b/compiler/rustc_builtin_macros/src/deriving/default.rs @@ -1,7 +1,7 @@ use core::ops::ControlFlow; use rustc_ast::visit::{Visitor, WalkItemKind, visit_opt}; -use rustc_ast::{self as ast, EnumDef, VariantData, attr}; +use rustc_ast::{self as ast, EnumDef, ItemKind, VariantData, attr}; use rustc_expand::base::{DummyResult, ExtCtxt}; use rustc_span::{ErrorGuaranteed, Ident, Span, kw, sym}; use smallvec::SmallVec; @@ -29,26 +29,20 @@ pub(crate) fn expand_derive_default( methods: smallvec![MethodDef { name: kw::Default, generics: cx.empty_generics(span), - explicit_self: false, - nonself_args: SmallVec::new(), - has_other_selflike_arg: false, + args: ThinVec::new(), ret_ty: cx.ty_self(span), attributes: thin_vec![cx.generated_attr(span, ast::GeneratedAttr::Inline)], - fieldless_variants_strategy: FieldlessVariantsStrategy::Default, - body: Box::new(|cx, trait_span, substr| { - match substr { - StaticStruct(variant_data) => default_struct_body( - cx, - trait_span, - variant_data, - // We cannot use `Self` here, see https://github.com/rust-lang/rust/issues/163800 - item.kind.ident().unwrap(), - ), - StaticEnum(enum_def) => default_enum_body(cx, trait_span, enum_def, item.span), - _ => cx - .dcx() - .span_bug(trait_span, "unexpected substructure in `derive(Default)`"), - } + body: MethodBody::Directly(match &item.kind { + ItemKind::Struct(ident, _, variant_data) + | ItemKind::Union(ident, _, variant_data) => default_struct_body( + cx, + span, + variant_data, + // We cannot use `Self` here, see https://github.com/rust-lang/rust/issues/163800 + *ident, + ), + ItemKind::Enum(_, _, enum_def) => default_enum_body(cx, span, enum_def, item.span), + _ => unreachable!(), }), }], is_const, diff --git a/compiler/rustc_builtin_macros/src/deriving/eq.rs b/compiler/rustc_builtin_macros/src/deriving/eq.rs index ff11d3e3110f4..6bb0bfb590bbb 100644 --- a/compiler/rustc_builtin_macros/src/deriving/eq.rs +++ b/compiler/rustc_builtin_macros/src/deriving/eq.rs @@ -25,9 +25,7 @@ pub(crate) fn expand_derive_eq( methods: smallvec![MethodDef { name: sym::assert_fields_are_eq, generics: cx.empty_generics(span), - explicit_self: true, - nonself_args: smallvec![], - has_other_selflike_arg: false, + args: thin_vec![cx.param_self_ref(span)], ret_ty: cx.ty_unit(span), attributes: thin_vec![ // This method will never be called, so doing codegen etc. for it is unnecessary. @@ -36,20 +34,15 @@ pub(crate) fn expand_derive_eq( cx.generated_attr(span, ast::GeneratedAttr::DocHidden), cx.generated_attr(span, ast::GeneratedAttr::CoverageOff), ], - fieldless_variants_strategy: FieldlessVariantsStrategy::Unify, - body: Box::new(assert_fields_eq_body), + body: MethodBody::Directly(assert_fields_eq_body(cx, item)), }], is_const, .. }; - trait_def.expand_ext(cx, item, push, true) + trait_def.expand(cx, item, push); } -fn assert_fields_eq_body( - cx: &ExtCtxt<'_>, - trait_span: Span, - substr: Substructure<'_>, -) -> BlockOrExpr { +fn assert_fields_eq_body(cx: &ExtCtxt<'_>, item: &ast::Item) -> BlockOrExpr { let mut stmts = ThinVec::new(); let mut seen_type_names = FxHashSet::default(); let mut process_variant = |variant: &ast::VariantData| { @@ -74,16 +67,16 @@ fn assert_fields_eq_body( } }; - match substr { - StaticStruct(vdata, ..) => { + match &item.kind { + ast::ItemKind::Struct(.., vdata) | ast::ItemKind::Union(.., vdata) => { process_variant(vdata); } - StaticEnum(enum_def, ..) => { + ast::ItemKind::Enum(.., enum_def) => { for variant in &enum_def.variants { process_variant(&variant.data); } } - _ => cx.dcx().span_bug(trait_span, "unexpected substructure in `derive(Eq)`"), + _ => unreachable!(), } BlockOrExpr::new_stmts(stmts) } diff --git a/compiler/rustc_builtin_macros/src/deriving/from.rs b/compiler/rustc_builtin_macros/src/deriving/from.rs index 52455971fb7af..84bc3a19b954f 100644 --- a/compiler/rustc_builtin_macros/src/deriving/from.rs +++ b/compiler/rustc_builtin_macros/src/deriving/from.rs @@ -27,7 +27,7 @@ pub(crate) fn expand_derive_from( let field = match &item.kind { ItemKind::Struct(_, _, data) => { if let [field] = data.fields() { - Ok(field.clone()) + Ok((field.clone(), data)) } else { let guar = cx.dcx().emit_err(diagnostics::DeriveFromWrongFieldCount { span: err_span(), @@ -47,7 +47,7 @@ pub(crate) fn expand_derive_from( }; let from_type = match field { - Ok(ref field) => field.ty.clone(), + Ok((ref field, _)) => field.ty.clone(), Err(guar) => cx.ty(span, ast::TyKind::Err(guar)), }; @@ -77,23 +77,13 @@ pub(crate) fn expand_derive_from( methods: smallvec![MethodDef { name: sym::from, generics: cx.empty_generics(span), - explicit_self: false, - nonself_args: smallvec![(sym::value, from_type)], - has_other_selflike_arg: false, + args: thin_vec![cx.param(span, sym::value, from_type)], ret_ty: cx.ty_self(span), attributes: thin_vec![cx.generated_attr(span, ast::GeneratedAttr::Inline)], - fieldless_variants_strategy: FieldlessVariantsStrategy::Default, - body: Box::new(|cx, span, substructure| { - let field = match field { - Ok(ref field) => field, - Err(guar) => { - return BlockOrExpr::new_expr(DummyResult::raw_expr(span, Some(guar))); - } - }; - - let self_kw = Ident::new(kw::SelfUpper, span); - let expr: Box = match substructure { - StaticStruct(variant) => match variant { + body: MethodBody::Directly(BlockOrExpr::new_expr(match field { + Ok((field, variant)) => { + let self_kw = Ident::new(kw::SelfUpper, span); + match variant { // Self { field: value } VariantData::Struct { .. } => cx.expr_struct_ident( span, @@ -113,11 +103,10 @@ pub(crate) fn expand_derive_from( variant => { cx.dcx().bug(format!("Invalid derive(From) ADT variant: {variant:?}")); } - }, - _ => cx.dcx().bug("Invalid derive(From) ADT input"), - }; - BlockOrExpr::new_expr(expr) - }), + } + } + Err(guar) => DummyResult::raw_expr(span, Some(guar)), + })), }], is_const, .. diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index 216abecf194cb..df90000337a71 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -1,159 +1,8 @@ -//! Some code that abstracts away much of the boilerplate of writing -//! `derive` instances for traits. Among other things it manages getting -//! access to the fields of the 4 different sorts of structs and enum -//! variants, as well as creating the method and impl ast instances. -//! -//! Supported features (fairly exhaustive): -//! -//! - Methods taking any number of parameters of any type and returning -//! any type. -//! - Generating `impl`s for types with type parameters and lifetimes -//! (e.g., `Option`), the parameters are automatically given the -//! current trait as a bound. (This includes separate type parameters -//! and lifetimes for methods.) -//! - Additional bounds on the type parameters (`TraitDef.additional_bounds`) -//! -//! The most important thing for implementors is the `Substructure` objects. -//! The latter groups 5 possibilities of the arguments: -//! -//! - `Struct`, when `Self` is a struct (including tuple structs, e.g -//! `struct T(i32, char)`). -//! - `EnumMatching`, when `Self` is an enum and all the arguments are the -//! same variant of the enum (e.g., `Some(1)`, `Some(3)` and `Some(4)`) -//! - `EnumDiscr` when `Self` is an enum, for comparing the enum discriminants. -//! - `StaticEnum` and `StaticStruct` for static methods, where the type -//! being derived upon is either an enum or struct respectively. (Any -//! argument with type Self is just grouped among the non-self -//! arguments.) -//! -//! In the first two cases, the values from the corresponding fields in -//! all the arguments are grouped together. -//! -//! The non-static cases have `Option` in several places associated -//! with field `expr`s. This represents the name of the field it is -//! associated with. It is only not `None` when the associated field has -//! an identifier in the source code. For example, the `x`s in the -//! following snippet -//! -//! ```rust -//! struct A { -//! x: i32, -//! } -//! -//! struct B(i32); -//! -//! enum C { -//! C0(i32), -//! C1 { x: i32 } -//! } -//! ``` -//! -//! The `i32`s in `B` and `C0` don't have an identifier, so the -//! `Option`s would be `None` for them. -//! -//! # Examples -//! -//! The following simplified `PartialEq` is used for in-code examples: -//! -//! ```rust -//! trait PartialEq { -//! fn eq(&self, other: &Self) -> bool; -//! } -//! -//! impl PartialEq for i32 { -//! fn eq(&self, other: &i32) -> bool { -//! *self == *other -//! } -//! } -//! ``` -//! -//! Some examples of the values of `Substructure` follow, using the -//! above `PartialEq`, `A`, `B` and `C`. -//! -//! ## Structs -//! -//! When generating the `expr` for the `A` impl, the `Substructure` is -//! -//! ```text -//! Struct(vec![FieldInfo { -//! span: , -//! name: Some(), -//! self_expr: , -//! other_selflike_expr: Some(), -//! }]) -//! ``` -//! -//! For the `B` impl, called with `B(a)` and `B(b)`, -//! -//! ```text -//! Struct(vec![FieldInfo { -//! span: , -//! name: None, -//! self_expr: , -//! other_selflike_expr: Some(), -//! }]) -//! ``` -//! -//! ## Enums -//! -//! When generating the `expr` for a call with `self == C0(a)` and `other -//! == C0(b)`, the Substructure is -//! -//! ```text -//! EnumMatching( -//! , -//! vec![FieldInfo { -//! span: , -//! name: None, -//! self_expr: , -//! other_selflike_expr: Some(), -//! }], -//! ) -//! ``` -//! -//! For `C1 {x}` and `C1 {x}`, -//! -//! ```text -//! EnumMatching( -//! , -//! vec![FieldInfo { -//! span: , -//! name: Some(), -//! self_expr: , -//! other_selflike_expr: Some(), -//! }], -//! ) -//! ``` -//! -//! For the discriminants, -//! -//! ```text -//! EnumDiscr() -//! ``` -//! -//! Note that this setup doesn't allow for the brute-force "match every variant -//! against every other variant" approach, which is bad because it produces a -//! quadratic amount of code (see #15375). -//! -//! ## Static -//! -//! A static method on the types above would result in, -//! -//! ```text -//! StaticStruct() -//! -//! StaticStruct() -//! -//! StaticEnum() -//! ``` - use std::ops::Not; pub(crate) use Substructure::*; pub(crate) use rustc_ast as ast; -use rustc_ast::{ - EnumDef, Expr, GenericArg, GenericParam, GenericParamKind, Generics, Safety, VariantData, -}; +use rustc_ast::{EnumDef, Expr, GenericParamKind, Generics, Param, Safety, VariantData}; use rustc_attr_ir::{Attribute, AttributeKind, ReprPacked}; use rustc_attr_parsing::AttributeParser; use rustc_expand::base::ExtCtxt; @@ -161,6 +10,7 @@ use rustc_span::{Ident, Span, Symbol, kw, sym}; pub(crate) use smallvec::{SmallVec, smallvec}; use thin_vec::{ThinVec, thin_vec}; +use crate::util::generic_param_to_arg; use crate::{deriving, diagnostics}; pub(crate) struct TraitDef<'a> { @@ -200,23 +50,14 @@ pub(crate) struct MethodDef<'a> { /// List of generics, e.g., `R: rand::Rng` pub generics: Generics, - /// Is there is a `&self` argument? If not, it is a static function. - pub explicit_self: bool, - - /// Arguments other than the self argument. - pub nonself_args: SmallVec<[(Symbol, Box); 1]>, - - /// Whether this method has another arg of type `&self`. - pub has_other_selflike_arg: bool, + pub args: ThinVec, /// Returns type pub ret_ty: Box, pub attributes: ast::AttrVec, - pub fieldless_variants_strategy: FieldlessVariantsStrategy, - - pub body: MethodBodyFunc<'a>, + pub body: MethodBody<'a>, } /// How to handle fieldless enum variants. @@ -232,46 +73,44 @@ pub(crate) enum FieldlessVariantsStrategy { } /// Summary of the relevant parts of a struct/enum field. -pub(crate) struct FieldInfo { +pub(crate) struct FieldInfo<'a> { pub span: Span, - /// None for tuple structs/normal enum variants, Some for normal - /// structs/struct enum variants. - pub name: Option, /// The expression corresponding to this field of `self` /// (specifically, a reference to it). pub self_expr: Box, /// The expression corresponding to a reference to this field in /// the other selflike argument. pub other_selflike_expr: Option>, - pub maybe_scalar: bool, + pub def: &'a ast::FieldDef, } -/// A summary of the possible sets of fields. -/// If the trait supports unions, they are treated like structs here. +/// A helper that makes the code for several derive macros easier to write +/// as they all have a similar base structure. pub(crate) enum Substructure<'a> { - /// A non-static method where `Self` is a struct. - Struct(&'a ast::VariantData, Vec), + /// A non-static method where `Self` is a struct, including tuple structs. + Struct(&'a ast::VariantData, Vec>), - /// Matching variants of the enum: ast::Variant, - /// fields: the field name is only non-`None` in the case of a struct - /// variant. - EnumMatching(&'a ast::Variant, Vec), + /// Matching variants of the enum: ast::Variant, fields. + /// Created when `Self` is an enum and all the arguments are the + /// same variant of the enum. + EnumMatching(&'a ast::Variant, Vec>), /// The discriminant of an enum. The field is the expression to combine the /// discriminant expression with; it will be `None` if no match is necessary. EnumDiscr(Option>), - - /// A static method where `Self` is a struct. - StaticStruct(&'a ast::VariantData), - - /// A static method where `Self` is an enum. - StaticEnum(&'a ast::EnumDef), } -/// Combine the values of all the fields together. The last argument is -/// all the fields of all the structures. -pub(crate) type MethodBodyFunc<'a> = - Box, Span, Substructure<'_>) -> BlockOrExpr + 'a>; +pub(crate) enum MethodBody<'a> { + /// See the documentation on [`Substructure`] for when this is used. + SubstructureFunc { + body_func: Box, Span, Substructure<'_>) -> BlockOrExpr + 'a>, + strategy: FieldlessVariantsStrategy, + has_other_selflike_arg: bool, + }, + /// The common case. + /// If you are adding a new macro, you most likely want to use this. + Directly(BlockOrExpr), +} struct TypeParameter { bound_generic_params: ThinVec, @@ -325,6 +164,10 @@ impl BlockOrExpr { cx.expr_block(self.into_block(cx, span)) } } + + fn take(&mut self) -> BlockOrExpr { + std::mem::replace(self, BlockOrExpr::new_stmts(ThinVec::new())) + } } /// This method helps to extract all the type parameters referenced from a @@ -402,16 +245,6 @@ impl<'a> TraitDef<'a> { cx: &ExtCtxt<'_>, item: &'a ast::Item, push: &mut dyn FnMut(Box), - ) { - self.expand_ext(cx, item, push, false); - } - - pub(crate) fn expand_ext( - self, - cx: &ExtCtxt<'_>, - item: &'a ast::Item, - push: &mut dyn FnMut(Box), - from_scratch: bool, ) { let span = self.span; let is_packed = matches!( @@ -432,9 +265,9 @@ impl<'a> TraitDef<'a> { methods = self .methods .into_iter() - .filter_map(|method_def| { - let body = if from_scratch || method_def.is_static() { - method_def.call_substructure_method(cx, span, StaticStruct(struct_def)) + .filter_map(|mut method_def| { + let body = if let MethodBody::Directly(body) = &mut method_def.body { + body.take() } else { method_def.expand_struct_method_body(cx, span, struct_def, is_packed) }; @@ -457,9 +290,9 @@ impl<'a> TraitDef<'a> { methods = self .methods .into_iter() - .filter_map(|method_def| { - let body = if from_scratch || method_def.is_static() { - method_def.call_substructure_method(cx, span, StaticEnum(enum_def)) + .filter_map(|mut method_def| { + let body = if let MethodBody::Directly(body) = &mut method_def.body { + body.take() } else { method_def.expand_enum_method_body(cx, span, enum_def) }; @@ -659,19 +492,6 @@ impl<'a> TraitDef<'a> { } impl<'a> MethodDef<'a> { - fn call_substructure_method( - &self, - cx: &ExtCtxt<'_>, - span: Span, - fields: Substructure<'_>, - ) -> BlockOrExpr { - (self.body)(cx, span, fields) - } - - fn is_static(&self) -> bool { - !self.explicit_self - } - fn create_method( self, cx: &ExtCtxt<'_>, @@ -683,17 +503,6 @@ impl<'a> MethodDef<'a> { return None; } - let self_arg = self.explicit_self.then(|| { - let infer_ty = cx.ty(span, ast::TyKind::ImplicitSelf); - let ty = cx.ty_ref(span, infer_ty, None, ast::Mutability::Not); - (kw::SelfLower, ty) - }); - let args = self_arg - .into_iter() - .chain(self.nonself_args) - .map(|(name, ty)| cx.param(span, name, ty)) - .collect(); - let ret_type = if self.ret_ty.kind.is_unit() { ast::FnRetTy::Default(span) } else { @@ -701,7 +510,7 @@ impl<'a> MethodDef<'a> { }; let method_ident = Ident::new(self.name, span); - let fn_decl = cx.fn_decl(args, ret_type); + let fn_decl = cx.fn_decl(self.args, ret_type); let body_block = body.into_block(cx, span); let trait_lo_sp = span.shrink_to_lo(); @@ -766,6 +575,10 @@ impl<'a> MethodDef<'a> { struct_def: &'b VariantData, is_packed: bool, ) -> BlockOrExpr { + let MethodBody::SubstructureFunc { body_func, has_other_selflike_arg, .. } = &self.body + else { + unreachable!() + }; let selflike_fields = struct_def .fields() .iter() @@ -799,19 +612,13 @@ impl<'a> MethodDef<'a> { }; let self_expr = expr_for_selflike_arg(cx.expr_self(span)); - let other_selflike_expr = self - .has_other_selflike_arg - .then(|| expr_for_selflike_arg(cx.expr_name(span, self.nonself_args[0].0))); - FieldInfo { - span: field_span, - name: struct_field.ident, - self_expr, - other_selflike_expr, - maybe_scalar: struct_field.ty.peel_refs().kind.maybe_scalar(), - } + let other_selflike_expr = has_other_selflike_arg + .then(|| expr_for_selflike_arg(cx.expr_name(span, sym::other))); + FieldInfo { span: field_span, self_expr, other_selflike_expr, def: struct_field } }) .collect(); - self.call_substructure_method(cx, span, Struct(struct_def, selflike_fields)) + + body_func(cx, span, Struct(struct_def, selflike_fields)) } /// ``` @@ -855,45 +662,45 @@ impl<'a> MethodDef<'a> { ) -> BlockOrExpr { let variants = &enum_def.variants; - // For zero-variant enum, this function body is unreachable. Generate - // `match *self {}`. This produces machine code identical to `unsafe { - // core::intrinsics::unreachable() }` while being safe and stable. - if variants.is_empty() { - let match_arg = cx.expr_deref(span, cx.expr_self(span)); - let expr = cx.expr_match(span, match_arg, ThinVec::new()); - return BlockOrExpr::new_expr(expr); - } - // There are some special cases involving fieldless enums where no // match is necessary. let all_fieldless = variants.iter().all(|v| v.data.fields().is_empty()); - if all_fieldless { - if variants.len() > 1 { - match self.fieldless_variants_strategy { - FieldlessVariantsStrategy::Unify => { - // If the type is fieldless and the trait uses the discriminant and - // there are multiple variants, we need just an operation on - // the discriminant(s). - return self.call_substructure_method(cx, span, EnumDiscr(None)); - } - FieldlessVariantsStrategy::Default => (), - } - } else if let [variant] = variants.as_slice() { + let MethodBody::SubstructureFunc { body_func, strategy, has_other_selflike_arg } = + &self.body + else { + unreachable!() + }; + // Traits that unify fieldless variants always use the discriminant(s). + let unify_fieldless_variants = *strategy == FieldlessVariantsStrategy::Unify; + + match variants.as_slice() { + [] => { + // For zero-variant enum, this function body is unreachable. Generate + // `match *self {}`. This produces machine code identical to `unsafe { + // core::intrinsics::unreachable() }` while being safe and stable. + let match_arg = cx.expr_deref(span, cx.expr_self(span)); + let expr = cx.expr_match(span, match_arg, ThinVec::new()); + return BlockOrExpr::new_expr(expr); + } + [variant] if all_fieldless => { // If there is a single variant, we don't need an operation on // the discriminant(s). Just use the most degenerate result. - return self.call_substructure_method(cx, span, EnumMatching(variant, Vec::new())); + return body_func(cx, span, EnumMatching(variant, Vec::new())); } + _ if all_fieldless && unify_fieldless_variants => { + // If the type is fieldless and the trait uses the discriminant and + // there are multiple variants, we need just an operation on + // the discriminant(s). + return body_func(cx, span, EnumDiscr(None)); + } + _ => (), } - // Traits that unify fieldless variants always use the discriminant(s). - let unify_fieldless_variants = - self.fieldless_variants_strategy == FieldlessVariantsStrategy::Unify; - // These arms are of the form: // (Variant1, Variant1) => Body1 // (Variant2, Variant2) => Body2 // ... - // where each tuple has length 2 if `self.has_other_selflike_arg` and 1 otherwise + // where each tuple has length 2 if `has_other_selflike_arg` and 1 otherwise let mut match_arms: ThinVec = variants .iter() .filter(|&v| !(unify_fieldless_variants && v.data.fields().is_empty())) @@ -939,7 +746,7 @@ impl<'a> MethodDef<'a> { }; // `(VariantK, VariantK)` or just `VariantK`. - let single_pat = if self.has_other_selflike_arg { + let single_pat = if *has_other_selflike_arg { cx.pat_tuple(span, thin_vec![pat_for_field("__self"), pat_for_field("__arg1"),]) } else { pat_for_field("__self") @@ -959,14 +766,8 @@ impl<'a> MethodDef<'a> { let self_expr = expr_for_field("__self"); let other_selflike_expr = - self.has_other_selflike_arg.then(|| expr_for_field("__arg1")); - FieldInfo { - span, - name: struct_field.ident, - self_expr, - other_selflike_expr, - maybe_scalar: struct_field.ty.peel_refs().kind.maybe_scalar(), - } + has_other_selflike_arg.then(|| expr_for_field("__arg1")); + FieldInfo { span, self_expr, other_selflike_expr, def: struct_field } }) .collect(); // For the BodyK, we need to delegate to our caller, @@ -977,9 +778,8 @@ impl<'a> MethodDef<'a> { // expressions for referencing every field of every // Self arg, assuming all are instances of VariantK. // Build up code associated with such a case. - let arm_expr = self - .call_substructure_method(cx, span, EnumMatching(variant, fields)) - .into_expr(cx, span); + let arm_expr = + body_func(cx, span, EnumMatching(variant, fields)).into_expr(cx, span); cx.arm(span, single_pat, arm_expr) }) @@ -990,12 +790,9 @@ impl<'a> MethodDef<'a> { let default = match first_fieldless { Some(v) if unify_fieldless_variants => { // We need a default case that handles all the fieldless variants. - Some( - self.call_substructure_method(cx, span, EnumMatching(v, Vec::new())) - .into_expr(cx, span), - ) + Some(body_func(cx, span, EnumMatching(v, Vec::new())).into_expr(cx, span)) } - _ if variants.len() > 1 && self.has_other_selflike_arg => { + _ if variants.len() > 1 && *has_other_selflike_arg => { // Because we know that all the arguments will match if we reach // the match expression we add the unreachable intrinsic as the // result of the default which should help llvm in optimizing it. @@ -1017,8 +814,8 @@ impl<'a> MethodDef<'a> { // } let self_expr = cx.expr_self(span); - let match_arg = if self.has_other_selflike_arg { - cx.expr_tuple(span, thin_vec![self_expr, cx.expr_name(span, self.nonself_args[0].0)]) + let match_arg = if *has_other_selflike_arg { + cx.expr_tuple(span, thin_vec![self_expr, cx.expr_name(span, sym::other)]) } else { self_expr }; @@ -1029,21 +826,13 @@ impl<'a> MethodDef<'a> { // is enough. if unify_fieldless_variants && variants.len() > 1 { // Combine a discriminant check with the match. - self.call_substructure_method(cx, span, EnumDiscr(Some(match_expr))) + body_func(cx, span, EnumDiscr(Some(match_expr))) } else { BlockOrExpr::new_expr(match_expr) } } } -pub(crate) fn generic_param_to_arg(cx: &ExtCtxt<'_>, p: &GenericParam, span: Span) -> GenericArg { - match p.kind { - GenericParamKind::Lifetime => GenericArg::Lifetime(cx.lifetime(span, p.ident)), - GenericParamKind::Type { .. } => GenericArg::Type(cx.ty_ident(span, p.ident)), - GenericParamKind::Const { .. } => GenericArg::Const(cx.const_ident(span, p.ident)), - } -} - pub(crate) fn generics_without_defaults(g: &Generics) -> Generics { Generics { params: g diff --git a/compiler/rustc_builtin_macros/src/deriving/hash.rs b/compiler/rustc_builtin_macros/src/deriving/hash.rs index b88176edd785a..18315b0015ed7 100644 --- a/compiler/rustc_builtin_macros/src/deriving/hash.rs +++ b/compiler/rustc_builtin_macros/src/deriving/hash.rs @@ -37,13 +37,17 @@ pub(crate) fn expand_derive_hash( methods: smallvec![MethodDef { name: sym::hash, generics, - explicit_self: true, - nonself_args: smallvec![(sym::state, cx.ty_ref(span, arg, None, Mutability::Mut))], - has_other_selflike_arg: false, + args: thin_vec![ + cx.param_self_ref(span), + cx.param(span, sym::state, cx.ty_ref(span, arg, None, Mutability::Mut)) + ], ret_ty: cx.ty_unit(span), attributes: thin_vec![cx.generated_attr(span, ast::GeneratedAttr::Inline)], - fieldless_variants_strategy: FieldlessVariantsStrategy::Unify, - body: Box::new(hash_body), + body: MethodBody::SubstructureFunc { + body_func: Box::new(hash_body), + strategy: FieldlessVariantsStrategy::Unify, + has_other_selflike_arg: false, + }, }], is_const, .. @@ -72,6 +76,5 @@ fn hash_body(cx: &ExtCtxt<'_>, span: Span, substr: Substructure<'_>) -> BlockOrE )]; BlockOrExpr::new_mixed(stmts, match_expr) } - _ => cx.dcx().span_bug(span, "unexpected substructure in `derive(Hash)`"), } } diff --git a/compiler/rustc_builtin_macros/src/deriving/mod.rs b/compiler/rustc_builtin_macros/src/deriving/mod.rs index 31875f702818c..4e862f7fb528e 100644 --- a/compiler/rustc_builtin_macros/src/deriving/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/mod.rs @@ -55,7 +55,7 @@ impl MultiItemModifier for BuiltinDerive { ecx, span, &item, - &mut |a| items.push(Annotatable::Stmt(Box::new(ecx.stmt_item(span, a)))), + &mut |a| items.push(Annotatable::Stmt(ecx.stmt_item(span, a))), is_derive_const, ); } else { diff --git a/compiler/rustc_builtin_macros/src/deriving/ord.rs b/compiler/rustc_builtin_macros/src/deriving/ord.rs index 7d3248c92c32b..e9efec79abe56 100644 --- a/compiler/rustc_builtin_macros/src/deriving/ord.rs +++ b/compiler/rustc_builtin_macros/src/deriving/ord.rs @@ -24,23 +24,27 @@ pub(crate) fn expand_derive_ord( methods: smallvec![MethodDef { name: sym::cmp, generics: cx.empty_generics(span), - explicit_self: true, - nonself_args: smallvec![(sym::other, cx.ty_self_ref(span))], - has_other_selflike_arg: true, + args: thin_vec![ + cx.param_self_ref(span), + cx.param(span, sym::other, cx.ty_self_ref(span)) + ], ret_ty: cx.ty_path(path_std!(cx, span, cmp::Ordering)), attributes: thin_vec![cx.generated_attr(span, ast::GeneratedAttr::Inline)], - fieldless_variants_strategy: FieldlessVariantsStrategy::Unify, - body: Box::new(|cx, span, substr| { - // Builds: - // - // match ::core::cmp::Ord::cmp(&self.x, &other.x) { - // ::std::cmp::Ordering::Equal => - // ::core::cmp::Ord::cmp(&self.y, &other.y), - // cmp => cmp, - // } - let expr = cmp_body(cx, span, substr, discr_then_data, OrdlikeDerive::Ord); - BlockOrExpr::new_expr(expr) - }), + body: MethodBody::SubstructureFunc { + body_func: Box::new(|cx, span, substr| { + // Builds: + // + // match ::core::cmp::Ord::cmp(&self.x, &other.x) { + // ::std::cmp::Ordering::Equal => + // ::core::cmp::Ord::cmp(&self.y, &other.y), + // cmp => cmp, + // } + let expr = cmp_body(cx, span, substr, discr_then_data, OrdlikeDerive::Ord); + BlockOrExpr::new_expr(expr) + }), + strategy: FieldlessVariantsStrategy::Unify, + has_other_selflike_arg: true, + }, }], is_const, .. diff --git a/compiler/rustc_builtin_macros/src/deriving/partial_eq.rs b/compiler/rustc_builtin_macros/src/deriving/partial_eq.rs index ea6bb72b2ea79..b81c44a36a312 100644 --- a/compiler/rustc_builtin_macros/src/deriving/partial_eq.rs +++ b/compiler/rustc_builtin_macros/src/deriving/partial_eq.rs @@ -38,13 +38,14 @@ pub(crate) fn expand_derive_partial_eq( let methods = smallvec![MethodDef { name: sym::eq, generics: cx.empty_generics(span), - explicit_self: true, - nonself_args: smallvec![(sym::other, cx.ty_self_ref(span))], - has_other_selflike_arg: true, + args: thin_vec![cx.param_self_ref(span), cx.param(span, sym::other, cx.ty_self_ref(span))], ret_ty: cx.ty_name(span, sym::bool), attributes: thin_vec![cx.generated_attr(span, ast::GeneratedAttr::Inline)], - fieldless_variants_strategy: FieldlessVariantsStrategy::Unify, - body: Box::new(partial_eq_body), + body: MethodBody::SubstructureFunc { + body_func: Box::new(partial_eq_body), + strategy: FieldlessVariantsStrategy::Unify, + has_other_selflike_arg: true, + }, }]; let trait_def = TraitDef { @@ -109,7 +110,7 @@ pub(crate) fn expand_derive_partial_eq( fn partial_eq_body(cx: &ExtCtxt<'_>, span: Span, substructure: Substructure<'_>) -> BlockOrExpr { BlockOrExpr::new_expr(match substructure { EnumMatching(.., fields) | Struct(.., fields) => { - let combine = move |acc, field: &FieldInfo| { + let combine = move |acc, field: &FieldInfo<'_>| { let rhs = field .other_selflike_expr .as_ref() @@ -130,12 +131,13 @@ fn partial_eq_body(cx: &ExtCtxt<'_>, span: Span, substructure: Substructure<'_>) } }; + let maybe_scalar = |field: &FieldInfo<'_>| field.def.ty.peel_refs().kind.maybe_scalar(); // First compare scalar fields, then compound fields, combining all // with logical AND. fields .iter() - .filter(|field| field.maybe_scalar) - .chain(fields.iter().filter(|field| !field.maybe_scalar)) + .filter(|field| maybe_scalar(field)) + .chain(fields.iter().filter(|field| !maybe_scalar(field))) .fold(None, combine) // If there are no fields, treat as always equal. .unwrap_or_else(|| cx.expr_bool(span, true)) @@ -151,7 +153,6 @@ fn partial_eq_body(cx: &ExtCtxt<'_>, span: Span, substructure: Substructure<'_>) // fields. cx.expr_binary(span, BinOpKind::And, lhs, match_expr) } - _ => cx.dcx().span_bug(span, "unexpected substructure in `derive(PartialEq)`"), }) } diff --git a/compiler/rustc_builtin_macros/src/deriving/partial_ord.rs b/compiler/rustc_builtin_macros/src/deriving/partial_ord.rs index 3bfc7bc05153f..46c0625072d88 100644 --- a/compiler/rustc_builtin_macros/src/deriving/partial_ord.rs +++ b/compiler/rustc_builtin_macros/src/deriving/partial_ord.rs @@ -25,10 +25,6 @@ pub(crate) fn expand_derive_partial_ord( let container_id = cx.current_expansion.id.expn_data().parent.expect_local(); let has_derive_ord = cx.resolver.has_derive_ord(container_id); - let default_body: MethodBodyFunc<'_> = - Box::new(|cx, span, substr| partial_cmp_body(cx, span, substr, discr_then_data)); - let simple_body: MethodBodyFunc<'_> = - Box::new(|cx, span, _| partial_cmp_simple_body(cx, span, cx.expr_name(span, sym::other))); let is_simple = match &item.kind { // For unit structs/zero-variant enums, the default generated code is better. ItemKind::Struct(.., ast::VariantData::Unit(..)) => false, @@ -55,13 +51,20 @@ pub(crate) fn expand_derive_partial_ord( let partial_cmp_def = MethodDef { name: sym::partial_cmp, generics: cx.empty_generics(span), - explicit_self: true, - nonself_args: smallvec![(sym::other, cx.ty_self_ref(span))], - has_other_selflike_arg: true, + args: thin_vec![cx.param_self_ref(span), cx.param(span, sym::other, cx.ty_self_ref(span))], ret_ty, attributes: thin_vec![cx.generated_attr(span, ast::GeneratedAttr::Inline)], - fieldless_variants_strategy: FieldlessVariantsStrategy::Unify, - body: if is_simple { simple_body } else { default_body }, + body: if is_simple { + MethodBody::Directly(partial_cmp_simple_body(cx, span, cx.expr_name(span, sym::other))) + } else { + MethodBody::SubstructureFunc { + body_func: Box::new(|cx, span, substr| { + partial_cmp_body(cx, span, substr, discr_then_data) + }), + strategy: FieldlessVariantsStrategy::Unify, + has_other_selflike_arg: true, + } + }, }; let trait_def = TraitDef { @@ -74,7 +77,7 @@ pub(crate) fn expand_derive_partial_ord( is_const, .. }; - trait_def.expand_ext(cx, item, push, is_simple) + trait_def.expand(cx, item, push); } pub(crate) fn discr_data_order(item: &ast::Item) -> bool { @@ -208,7 +211,7 @@ pub(crate) fn cmp_body( match substructure { EnumMatching(.., all_fields) | Struct(_, all_fields) => { - let op = |old, field: FieldInfo| { + let op = |old, field: FieldInfo<'_>| { // The basic case: a field expression for one or more selflike args. E.g. // for `Ord::cmp` this is something like `Ord::cmp(&self.x, &other.x)`. let other_expr = @@ -242,6 +245,5 @@ pub(crate) fn cmp_body( discr_check_expr } } - _ => cx.dcx().span_bug(span, "unexpected substructure in `derive`"), } } diff --git a/compiler/rustc_builtin_macros/src/deriving/reborrow.rs b/compiler/rustc_builtin_macros/src/deriving/reborrow.rs index 4ae79420f26c6..af091db2163da 100644 --- a/compiler/rustc_builtin_macros/src/deriving/reborrow.rs +++ b/compiler/rustc_builtin_macros/src/deriving/reborrow.rs @@ -9,6 +9,7 @@ use rustc_span::{Ident, Span, Symbol, sym}; use thin_vec::ThinVec; use crate::deriving::generic::*; +use crate::util::generic_param_to_arg; pub(crate) fn expand_derive_reborrow( cx: &ExtCtxt<'_>, diff --git a/compiler/rustc_builtin_macros/src/global_allocator.rs b/compiler/rustc_builtin_macros/src/global_allocator.rs index 960cf3e2caddf..8cbd4df5b0f18 100644 --- a/compiler/rustc_builtin_macros/src/global_allocator.rs +++ b/compiler/rustc_builtin_macros/src/global_allocator.rs @@ -2,8 +2,8 @@ use rustc_ast::expand::allocator::{ ALLOCATOR_METHODS, AllocatorMethod, AllocatorMethodInput, AllocatorTy, global_fn_name, }; use rustc_ast::{ - self as ast, AttrVec, Expr, FnHeader, FnSig, Generics, ItemKind, Mutability, Param, Safety, - Stmt, StmtKind, Ty, + self as ast, Expr, FnHeader, FnSig, Generics, ItemKind, Mutability, Param, Safety, Stmt, + StmtKind, Ty, }; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::{Ident, Span, Symbol, sym}; @@ -45,17 +45,18 @@ pub(crate) fn expand( return vec![orig_item]; } - // Generate a bunch of new items using the AllocFnFactory let span = ecx.with_def_site_ctxt(item.span); - let f = AllocFnFactory { span, ty_span, global: ident, cx: ecx }; // Generate item statements for the allocator methods. - let stmts = ALLOCATOR_METHODS.iter().map(|method| f.allocator_fn(method)).collect(); + let stmts = ALLOCATOR_METHODS + .iter() + .map(|method| allocator_fn(ecx, span, ty_span, ident, method)) + .collect(); // Generate anonymous constant serving as container for the allocator methods. let const_item = ecx.item_const_underscore(span, ecx.block(span, stmts)); let const_item = if is_stmt { - Annotatable::Stmt(Box::new(ecx.stmt_item(span, const_item))) + Annotatable::Stmt(ecx.stmt_item(span, const_item)) } else { Annotatable::Item(const_item) }; @@ -64,124 +65,108 @@ pub(crate) fn expand( vec![orig_item, const_item] } -struct AllocFnFactory<'a, 'b> { +fn allocator_fn( + cx: &ExtCtxt<'_>, span: Span, ty_span: Span, global: Ident, - cx: &'a ExtCtxt<'b>, + method: &AllocatorMethod, +) -> Stmt { + let mut abi_args = ThinVec::new(); + let args = method.inputs.iter().map(|input| arg_ty(cx, span, input, &mut abi_args)).collect(); + let result = call_allocator(cx, ty_span, global, method.name, args); + let output_ty = match method.output { + AllocatorTy::ResultPtr => ptr_u8(cx, span), + AllocatorTy::Unit => cx.ty_unit(span), + AllocatorTy::Layout | AllocatorTy::Never | AllocatorTy::Usize | AllocatorTy::Ptr => { + panic!("can't convert `AllocatorTy` to an output") + } + }; + let decl = cx.fn_decl(abi_args, ast::FnRetTy::Ty(output_ty)); + let header = FnHeader { safety: Safety::Unsafe(span), ..FnHeader::default() }; + let sig = FnSig { decl, header, span }; + let body = Some(cx.block_expr(result)); + let kind = ItemKind::Fn(cx.item_fn( + sig, + Ident::from_str_and_span(&global_fn_name(method.name), span), + Generics::default(), + body, + )); + let alloc_attr = match method.name { + sym::alloc => sym::rustc_allocator, + sym::dealloc => sym::rustc_deallocator, + sym::realloc => sym::rustc_reallocator, + sym::alloc_zeroed => sym::rustc_allocator_zeroed, + _ => unreachable!("Unknown allocator method!"), + }; + let attrs = thin_vec![ + cx.attr_word(sym::rustc_std_internal_symbol, span), + cx.attr_word(alloc_attr, span) + ]; + let item = cx.item(span, attrs, kind); + cx.stmt_item(ty_span, item) } -impl AllocFnFactory<'_, '_> { - fn allocator_fn(&self, method: &AllocatorMethod) -> Stmt { - let mut abi_args = ThinVec::new(); - let args = method.inputs.iter().map(|input| self.arg_ty(input, &mut abi_args)).collect(); - let result = self.call_allocator(method.name, args); - let output_ty = self.ret_ty(&method.output); - let decl = self.cx.fn_decl(abi_args, ast::FnRetTy::Ty(output_ty)); - let header = FnHeader { safety: Safety::Unsafe(self.span), ..FnHeader::default() }; - let sig = FnSig { decl, header, span: self.span }; - let body = Some(self.cx.block_expr(result)); - let kind = ItemKind::Fn(self.cx.item_fn( - sig, - Ident::from_str_and_span(&global_fn_name(method.name), self.span), - Generics::default(), - body, - )); - let item = self.cx.item(self.span, self.attrs(method), kind); - self.cx.stmt_item(self.ty_span, item) - } - - fn call_allocator(&self, method: Symbol, mut args: ThinVec>) -> Box { - let method = self.cx.std_path(self.ty_span, &[sym::alloc, sym::GlobalAlloc, method]); - let method = self.cx.expr_path(method); - let allocator = self.cx.path_ident(self.ty_span, self.global); - let allocator = self.cx.expr_path(allocator); - let allocator = self.cx.expr_ref(self.ty_span, allocator); - args.insert(0, allocator); - - self.cx.expr_call(self.ty_span, method, args) - } - - fn attrs(&self, method: &AllocatorMethod) -> AttrVec { - let alloc_attr = match method.name { - sym::alloc => sym::rustc_allocator, - sym::dealloc => sym::rustc_deallocator, - sym::realloc => sym::rustc_reallocator, - sym::alloc_zeroed => sym::rustc_allocator_zeroed, - _ => unreachable!("Unknown allocator method!"), - }; - thin_vec![ - self.cx.attr_word(sym::rustc_std_internal_symbol, self.span), - self.cx.attr_word(alloc_attr, self.span) - ] - } +fn call_allocator( + cx: &ExtCtxt<'_>, + ty_span: Span, + global: Ident, + method: Symbol, + mut args: ThinVec>, +) -> Box { + let method = cx.std_path(ty_span, &[sym::alloc, sym::GlobalAlloc, method]); + let method = cx.expr_path(method); + let allocator = cx.path_ident(ty_span, global); + let allocator = cx.expr_path(allocator); + let allocator = cx.expr_ref(ty_span, allocator); + args.insert(0, allocator); + + cx.expr_call(ty_span, method, args) +} - fn arg_ty(&self, input: &AllocatorMethodInput, args: &mut ThinVec) -> Box { - match input.ty { - AllocatorTy::Layout => { - // If an allocator method is ever introduced having multiple - // Layout arguments, these argument names need to be - // disambiguated somehow. Currently the generated code would - // fail to compile with "identifier is bound more than once in - // this parameter list". - - let ty_usize = self.usize(); - args.push(self.cx.param(self.span, sym::size, ty_usize)); - let ty_align = self.ptr_alignment(); - args.push(self.cx.param(self.span, sym::align, ty_align)); - - let layout_new = self.cx.std_path( - self.span, - &[sym::alloc, sym::Layout, sym::from_size_alignment_unchecked], - ); - let layout_new = self.cx.expr_path(layout_new); - let size = self.cx.expr_name(self.span, sym::size); - let align = self.cx.expr_name(self.span, sym::align); - let layout = self.cx.expr_call(self.span, layout_new, thin_vec![size, align]); - layout - } - - AllocatorTy::Ptr => { - let name = Symbol::intern(input.name); - args.push(self.cx.param(self.span, name, self.ptr_u8())); - self.cx.expr_name(self.span, name) - } - - AllocatorTy::Usize => { - let name = Symbol::intern(input.name); - args.push(self.cx.param(self.span, name, self.usize())); - self.cx.expr_name(self.span, name) - } - - AllocatorTy::Never | AllocatorTy::ResultPtr | AllocatorTy::Unit => { - panic!("can't convert AllocatorTy to an argument") - } +fn arg_ty( + cx: &ExtCtxt<'_>, + span: Span, + input: &AllocatorMethodInput, + args: &mut ThinVec, +) -> Box { + match input.ty { + AllocatorTy::Layout => { + // If an allocator method is ever introduced having multiple + // Layout arguments, these argument names need to be + // disambiguated somehow. Currently the generated code would + // fail to compile with "identifier is bound more than once in + // this parameter list". + + let ty_usize = cx.ty_name(span, sym::usize); + args.push(cx.param(span, sym::size, ty_usize)); + let ty_align = cx.ty_path(cx.std_path(span, &[sym::mem, sym::Alignment])); + args.push(cx.param(span, sym::align, ty_align)); + + let layout_new = + cx.std_path(span, &[sym::alloc, sym::Layout, sym::from_size_alignment_unchecked]); + let layout_new = cx.expr_path(layout_new); + let size = cx.expr_name(span, sym::size); + let align = cx.expr_name(span, sym::align); + cx.expr_call(span, layout_new, thin_vec![size, align]) } - } - - fn ret_ty(&self, ty: &AllocatorTy) -> Box { - match *ty { - AllocatorTy::ResultPtr => self.ptr_u8(), - - AllocatorTy::Unit => self.cx.ty_unit(self.span), - - AllocatorTy::Layout | AllocatorTy::Never | AllocatorTy::Usize | AllocatorTy::Ptr => { - panic!("can't convert `AllocatorTy` to an output") - } + AllocatorTy::Ptr => { + let name = Symbol::intern(input.name); + args.push(cx.param(span, name, ptr_u8(cx, span))); + cx.expr_name(span, name) + } + AllocatorTy::Usize => { + let name = Symbol::intern(input.name); + args.push(cx.param(span, name, cx.ty_name(span, sym::usize))); + cx.expr_name(span, name) + } + AllocatorTy::Never | AllocatorTy::ResultPtr | AllocatorTy::Unit => { + panic!("can't convert AllocatorTy to an argument") } } +} - fn usize(&self) -> Box { - self.cx.ty_name(self.span, sym::usize) - } - - fn ptr_alignment(&self) -> Box { - let path = self.cx.std_path(self.span, &[sym::mem, sym::Alignment]); - self.cx.ty_path(path) - } - - fn ptr_u8(&self) -> Box { - let ty_u8 = self.cx.ty_name(self.span, sym::u8); - self.cx.ty_ptr(self.span, ty_u8, Mutability::Mut) - } +fn ptr_u8(cx: &ExtCtxt<'_>, span: Span) -> Box { + let ty_u8 = cx.ty_name(span, sym::u8); + cx.ty_ptr(span, ty_u8, Mutability::Mut) } diff --git a/compiler/rustc_builtin_macros/src/offload.rs b/compiler/rustc_builtin_macros/src/offload.rs index e5076978f7cd1..73e407093fb80 100644 --- a/compiler/rustc_builtin_macros/src/offload.rs +++ b/compiler/rustc_builtin_macros/src/offload.rs @@ -118,9 +118,7 @@ pub(crate) fn expand_kernel( match &item { Annotatable::Item(_) => Annotatable::Item(device_item_ecx), - Annotatable::Stmt(_) => { - Annotatable::Stmt(Box::new(ecx.stmt_item(span, device_item_ecx))) - } + Annotatable::Stmt(_) => Annotatable::Stmt(ecx.stmt_item(span, device_item_ecx)), _ => { unreachable!("item kind checked previously") } @@ -180,7 +178,7 @@ pub(crate) fn expand_kernel( match &item { Annotatable::Item(_) => Annotatable::Item(host_item_ecx), - Annotatable::Stmt(_) => Annotatable::Stmt(Box::new(ecx.stmt_item(span, host_item_ecx))), + Annotatable::Stmt(_) => Annotatable::Stmt(ecx.stmt_item(span, host_item_ecx)), _ => { unreachable!("item kind checked previously") } diff --git a/compiler/rustc_builtin_macros/src/test.rs b/compiler/rustc_builtin_macros/src/test.rs index d8608b8418a27..ed90d669371bb 100644 --- a/compiler/rustc_builtin_macros/src/test.rs +++ b/compiler/rustc_builtin_macros/src/test.rs @@ -73,7 +73,7 @@ pub(crate) fn expand_test_case( } let ret = if is_stmt { - Annotatable::Stmt(Box::new(ecx.stmt_item(item.span, item))) + Annotatable::Stmt(ecx.stmt_item(item.span, item)) } else { Annotatable::Item(item) }; @@ -121,7 +121,7 @@ pub(crate) fn expand_test_or_bench( let ast::ItemKind::Fn(fn_) = &item.kind else { not_testable_error(cx, is_bench, attr_sp, Some(&item)); return if is_stmt { - vec![Annotatable::Stmt(Box::new(cx.stmt_item(item.span, item)))] + vec![Annotatable::Stmt(cx.stmt_item(item.span, item))] } else { vec![Annotatable::Item(item)] }; @@ -155,7 +155,7 @@ pub(crate) fn expand_test_or_bench( }; if check_result.is_err() { return if is_stmt { - vec![Annotatable::Stmt(Box::new(cx.stmt_item(item.span, item)))] + vec![Annotatable::Stmt(cx.stmt_item(item.span, item))] } else { vec![Annotatable::Item(item)] }; @@ -385,11 +385,11 @@ pub(crate) fn expand_test_or_bench( if is_stmt { vec![ // Access to libtest under a hygienic name - Annotatable::Stmt(Box::new(cx.stmt_item(sp, test_extern))), + Annotatable::Stmt(cx.stmt_item(sp, test_extern)), // The generated test case - Annotatable::Stmt(Box::new(cx.stmt_item(sp, test_const))), + Annotatable::Stmt(cx.stmt_item(sp, test_const)), // The original item - Annotatable::Stmt(Box::new(cx.stmt_item(sp, item))), + Annotatable::Stmt(cx.stmt_item(sp, item)), ] } else { vec![ diff --git a/compiler/rustc_builtin_macros/src/util.rs b/compiler/rustc_builtin_macros/src/util.rs index c4c90d2cb5378..27eb63b4a07d4 100644 --- a/compiler/rustc_builtin_macros/src/util.rs +++ b/compiler/rustc_builtin_macros/src/util.rs @@ -1,5 +1,8 @@ use rustc_ast::tokenstream::TokenStream; -use rustc_ast::{self as ast, AttrStyle, Attribute, MetaItem, attr, token}; +use rustc_ast::{ + self as ast, AttrStyle, Attribute, GenericArg, GenericParam, GenericParamKind, MetaItem, attr, + token, +}; use rustc_attr_parsing::{AttributeTemplate, DuplicateAttribute, validate_attr}; use rustc_errors::{Applicability, Diag, ErrorGuaranteed}; use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt}; @@ -261,3 +264,11 @@ pub(crate) fn get_exprs_from_tts( } ExpandResult::Ready(Ok(es)) } + +pub(crate) fn generic_param_to_arg(cx: &ExtCtxt<'_>, p: &GenericParam, span: Span) -> GenericArg { + match p.kind { + GenericParamKind::Lifetime => GenericArg::Lifetime(cx.lifetime(span, p.ident)), + GenericParamKind::Type { .. } => GenericArg::Type(cx.ty_ident(span, p.ident)), + GenericParamKind::Const { .. } => GenericArg::Const(cx.const_ident(span, p.ident)), + } +} diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs index 350fb01df53c8..32ed80437ed95 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs @@ -22,7 +22,7 @@ use rustc_codegen_ssa::{MemFlags, RetagInfo}; use rustc_data_structures::fx::FxHashSet; #[cfg(feature = "master")] use rustc_middle::ty::layout::FnAbiOf; -use rustc_middle::ty::layout::LayoutOf; +use rustc_middle::ty::layout::{HasTypingEnv, LayoutOf}; use rustc_middle::ty::{self, Instance, Intrinsic, Ty}; use rustc_session::config::OptLevel; use rustc_span::{Span, Symbol, bug, span_bug, sym}; @@ -511,6 +511,7 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc &mut self, instance: ty::Instance<'tcx>, args: &[OperandRef<'tcx, Self::Value>], + memory_return_place: Option>, is_cleanup: bool, ) -> Self::Value { let func = if let Some(&func) = self.intrinsic_instances.borrow().get(&instance) { @@ -557,7 +558,48 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc self.apply_attrs_to_cleanup_callsite(llret); } - llret + let fn_sig = match *instance.ty(self.tcx, self.typing_env()).kind() { + ty::FnDef(def_id, args) => self.tcx.instantiate_bound_regions_with_erased( + self.tcx + .fn_sig(def_id) + .instantiate(self.tcx, args.no_bound_vars().unwrap()) + .skip_norm_wip(), + ), + _ => unreachable!(), + }; + let ret_layout = self.layout_of(fn_sig.output()); + + if !ret_layout.is_zst() && ret_layout.is_aggregate() { + let fields = + rustc_codegen_ssa::mir::intrinsic_return_struct_fields(self.cx, ret_layout) + .into_iter() + .enumerate() + .map(|(i, (_, offset))| (offset, self.extract_value(llret, i as u64))) + .collect(); + let is_memory = matches!(ret_layout.backend_repr, BackendRepr::Memory { .. }); + match rustc_codegen_ssa::mir::store_intrinsic_return_struct( + self, + ret_layout, + memory_return_place, + fields, + ) { + IntrinsicResult::Operand(val) => { + assert!(!is_memory); + assert!(memory_return_place.is_none()); + OperandRef { val, layout: ret_layout, move_annotation: None } + .immediate_or_packed_pair(self) + } + IntrinsicResult::WroteIntoPlace => { + assert!(is_memory); + assert!(memory_return_place.is_some()); + // Return value won't be used. + self.const_u8(0) + } + res => bug!("Unexpected LLVM intrinsic result {res:?}"), + } + } else { + llret + } } fn abort_immediate(&mut self) { diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 2f00202146f15..ddefd07efe56b 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -20,7 +20,7 @@ use rustc_hir::def_id::LOCAL_CRATE; use rustc_lint_defs::builtin::DEPRECATED_LLVM_INTRINSIC; use rustc_middle::mir::interpret::{AllocId, Allocation, ErrorHandled, GlobalAlloc, alloc_range}; use rustc_middle::mir::{self, BinOp}; -use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, HasTypingEnv, LayoutOf}; +use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout}; use rustc_middle::ty::offload_meta::OffloadMetadata; use rustc_middle::ty::{self, GenericArgs, Instance, Intrinsic, SimdAlign, Ty, TyCtxt}; use rustc_session::diagnostics::feature_err; @@ -799,6 +799,17 @@ impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> { _ => unreachable!(), }; self.type_vector(elem_ll_ty, size) + } else if let ty::Array(elem, _) = result_layout.ty.kind() + && let ty::Uint(ty::UintTy::U8) = elem.kind() + { + // Byte arrays are used to represent iN. + assert_matches!( + result_layout.backend_repr, + BackendRepr::Memory { sized: true } + ); + self.type_ix(result_layout.size.bits()) + } else if result_layout.is_zst() { + self.type_void() } else { result_layout.llvm_type(self) }; @@ -880,7 +891,8 @@ impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> { instance: ty::Instance<'tcx>, intrinsic_name: &str, args: &[OperandRef<'tcx, Value<'ll>>], - ) -> Value<'ll> { + memory_return_place: Option>>, + ) -> (IntrinsicResult<'tcx, Value<'ll>>, TyAndLayout<'tcx>) { let tcx = self.tcx(); let fn_ty = instance.ty(tcx, self.typing_env()); @@ -893,10 +905,15 @@ impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> { assert!(!fn_sig.c_variadic()); let ret_layout = self.layout_of(fn_sig.output()); - let llreturn_ty = if ret_layout.is_zst() { - self.type_void() + let (llreturn_ty, return_struct_fields) = if ret_layout.is_zst() { + (self.type_void(), vec![]) + } else if ret_layout.is_aggregate() { + let fields = + rustc_codegen_ssa::mir::intrinsic_return_struct_fields(self.cx, ret_layout); + let llvm_fields = fields.iter().copied().map(|(t, _)| t).collect::>(); + (self.type_struct(&llvm_fields), fields) } else { - ret_layout.immediate_llvm_type(self) + (ret_layout.immediate_llvm_type(self), vec![]) }; let mut llargument_tys = Vec::with_capacity(fn_sig.inputs().len()); @@ -950,14 +967,44 @@ impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> { ) }; - let src_ty = self.val_ty(llret); - let dest_ty = llreturn_ty; - assert!( - can_autocast(self, dest_ty, src_ty), - "Cannot match `{src_ty:?}` (expected) with `{dest_ty:?}` (found) in `{fn_ptr:?}`" - ); + if ret_layout.is_zst() { + // Match `llvm_value_to_intrinsicresult` + (IntrinsicResult::WroteIntoPlace, ret_layout) + } else if return_struct_fields.is_empty() { + let src_ty = self.val_ty(llret); + let dest_ty = llreturn_ty; + assert!( + can_autocast(self, dest_ty, src_ty), + "Cannot match `{src_ty:?}` (expected) with `{dest_ty:?}` (found) in `{fn_ptr:?}`" + ); - autocast(self, llret, src_ty, dest_ty) + ( + IntrinsicResult::Operand(OperandValue::Immediate(autocast( + self, llret, src_ty, dest_ty, + ))), + ret_layout, + ) + } else { + let fields = return_struct_fields.into_iter().enumerate().map(|(i, (dest_ty, offset))| { + let value = self.extract_value(llret, i as u64); + let src_ty = self.val_ty(value); + assert!( + can_autocast(self, dest_ty, src_ty), + "Cannot match `{src_ty:?}` (expected) with `{dest_ty:?}` (found) in `{fn_ptr:?}`" + ); + let value = autocast(self, value, src_ty, dest_ty); + (offset, value) + }).collect(); + ( + rustc_codegen_ssa::mir::store_intrinsic_return_struct( + self, + ret_layout, + memory_return_place, + fields, + ), + ret_layout, + ) + } } } @@ -983,8 +1030,7 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { name, ), Intrinsic::Backend { llvm } => { - let value = self.codegen_llvm_intrinsic_call_impl(instance, llvm.as_str(), args); - self.llvm_value_to_intrinsicresult(value, result_layout, result_place) + self.codegen_llvm_intrinsic_call_impl(instance, llvm.as_str(), args, result_place).0 } } } @@ -993,9 +1039,31 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { &mut self, instance: ty::Instance<'tcx>, args: &[OperandRef<'tcx, Self::Value>], + memory_return_place: Option>, _is_cleanup: bool, ) -> Self::Value { - self.codegen_llvm_intrinsic_call_impl(instance, self.tcx().symbol_name(instance).name, args) + let (result, ret_layout) = self.codegen_llvm_intrinsic_call_impl( + instance, + self.tcx().symbol_name(instance).name, + args, + memory_return_place, + ); + let is_memory = matches!(ret_layout.backend_repr, BackendRepr::Memory { .. }); + match result { + IntrinsicResult::Operand(val) => { + assert!(!is_memory); + assert!(memory_return_place.is_none()); + OperandRef { val, layout: ret_layout, move_annotation: None } + .immediate_or_packed_pair(self) + } + IntrinsicResult::WroteIntoPlace => { + assert!(is_memory); + assert!(memory_return_place.is_some() || ret_layout.is_zst()); + // Return value won't be used. + self.const_u8(0) + } + res => bug!("Unexpected LLVM intrinsic result {res:?}"), + } } fn abort_immediate(&mut self) { @@ -1081,23 +1149,6 @@ fn can_autocast<'ll>(cx: &CodegenCx<'ll, '_>, rust_ty: Type<'ll>, llvm_ty: Type< } match cx.type_kind(llvm_ty) { - // Some LLVM intrinsics return **non-packed** structs, but they can't be mimicked from Rust - // due to auto field-alignment in non-packed structs (packed structs are represented in LLVM - // as, well, packed structs, so they won't match with those either) - TypeKind::Struct if cx.type_kind(rust_ty) == TypeKind::Struct => { - let rust_element_tys = cx.struct_element_types(rust_ty); - let llvm_element_tys = cx.struct_element_types(llvm_ty); - - if rust_element_tys.len() != llvm_element_tys.len() { - return false; - } - - iter::zip(rust_element_tys, llvm_element_tys).all( - |(rust_element_ty, llvm_element_ty)| { - can_autocast(cx, rust_element_ty, llvm_element_ty) - }, - ) - } _ if let Some((llvm_element_ty, element_count)) = cx.vector_element_type_and_length(llvm_ty) => { @@ -1141,19 +1192,6 @@ fn autocast<'ll>( return val; } match (bx.type_kind(src_ty), bx.type_kind(dest_ty)) { - // re-pack structs - (TypeKind::Struct, TypeKind::Struct) => { - let mut ret = bx.const_poison(dest_ty); - for (idx, (src_element_ty, dest_element_ty)) in - iter::zip(bx.struct_element_types(src_ty), bx.struct_element_types(dest_ty)) - .enumerate() - { - let elt = bx.extract_value(val, idx as u64); - let casted_elt = autocast(bx, elt, src_element_ty, dest_element_ty); - ret = bx.insert_value(ret, casted_elt, idx as u64); - } - ret - } // cast from the i1xN vector type to the primitive type (TypeKind::Vector, TypeKind::Integer) if let Some((elem, vector_length)) = bx.vector_element_type_and_length(src_ty) @@ -1251,9 +1289,17 @@ fn intrinsic_fn<'ll, 'tcx>( let llvm_argument_tys = bx.func_params_types(llvm_fn_ty); let llvm_is_variadic = bx.func_is_variadic(llvm_fn_ty); + let (rust_return_tys, llvm_return_tys) = if bx.type_kind(rust_return_ty) == TypeKind::Struct + && bx.type_kind(llvm_return_ty) == TypeKind::Struct + { + (bx.struct_element_types(rust_return_ty), bx.struct_element_types(llvm_return_ty)) + } else { + (vec![rust_return_ty], vec![llvm_return_ty]) + }; let is_correct_signature = !llvm_is_variadic && rust_argument_tys.len() == llvm_argument_tys.len() - && iter::once((rust_return_ty, llvm_return_ty)) + && rust_return_tys.len() == llvm_return_tys.len() + && iter::zip(rust_return_tys, llvm_return_tys) .chain(iter::zip(rust_argument_tys, llvm_argument_tys)) .all(|(rust_ty, llvm_ty)| can_autocast(bx, rust_ty, llvm_ty)); @@ -2420,12 +2466,9 @@ fn generic_simd_intrinsic<'ll, 'tcx>( { // Zero-extend iN to the array length: let ze = bx.zext(i_, bx.type_ix(expected_bytes * 8)); - - // Convert the integer to a byte array - let ptr = bx.alloca(Size::from_bytes(expected_bytes), Align::ONE); - bx.store(ze, ptr, Align::ONE); - let array_ty = bx.type_byte_array(Size::from_bytes(expected_bytes)); - return Ok(bx.load(array_ty, ptr, Align::ONE)); + // `codegen_intrinsic_call` will store the result to the return place for + // `BackendRepr::Memory` types. + return Ok(ze); } _ => return_error!(InvalidMonomorphization::CannotReturn { span, diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index 678d8c00c68dc..71889fa9c417d 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -2,7 +2,8 @@ use std::cmp; use std::ops::Range; use rustc_abi::{ - Align, ArmCall, CanonAbi, ExternAbi, FieldsShape, HasDataLayout, Size, VariantIdx, Variants, + Align, ArmCall, BackendRepr, CanonAbi, ExternAbi, FieldsShape, HasDataLayout, Size, VariantIdx, + Variants, }; use rustc_ast as ast; use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; @@ -1166,38 +1167,42 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let result_layout = self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref())); - let return_dest = if result_layout.is_zst() { - ReturnDest::Nothing - } else if let Some(index) = destination.as_local() { - match self.locals[index] { - LocalRef::Place(dest) => ReturnDest::Store(dest), - LocalRef::UnsizedPlace(_) => bug!("return type must be sized"), - LocalRef::PendingOperand => { - // Handle temporary places, specifically `Operand` ones, as - // they don't have `alloca`s. - ReturnDest::DirectOperand(index) - } - LocalRef::Operand(_) => bug!("place local already assigned to"), + let return_mode = if result_layout.is_zst() { + PassMode::Ignore + } else if let BackendRepr::ScalarPair { .. } = result_layout.backend_repr { + PassMode::Pair(ArgAttributes::new(), ArgAttributes::new()) + } else if result_layout.is_aggregate() { + PassMode::Indirect { + attrs: ArgAttributes::new(), + address_space: None, + mode: IndirectMode::Pointer, } } else { - ReturnDest::Store(self.codegen_place(bx, destination.as_ref())) + PassMode::Direct(ArgAttributes::new()) }; + let return_abi = ArgAbi { layout: result_layout, mode: return_mode }; + let (return_dest, memory_return_place) = + self.make_return_place(bx, destination, &return_abi); + assert_eq!( + memory_return_place.is_some(), + !result_layout.is_zst() + && matches!(result_layout.backend_repr, BackendRepr::Memory { sized: true }) + ); let args = args.into_iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect::>(); self.set_debug_loc(bx, source_info); - let llret = - bx.codegen_llvm_intrinsic_call(instance, &args, self.mir[helper.bb].is_cleanup); + let llret = bx.codegen_llvm_intrinsic_call( + instance, + &args, + memory_return_place, + self.mir[helper.bb].is_cleanup, + ); if let Some(target) = target { - self.store_return( - bx, - return_dest, - &ArgAbi { layout: result_layout, mode: PassMode::Direct(ArgAttributes::new()) }, - llret, - ); + self.store_return(bx, return_dest, &return_abi, llret); return helper.funclet_br(self, bx, target, mergeable_succ, &[]); } else { bx.unreachable(); @@ -2435,15 +2440,33 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } } + // This function is separate from `make_return_place` as `ReturnSlot` should only be constructed + // when it will be used for an indirect return (sret) from an actual backend function call. fn make_return_dest( &mut self, bx: &mut Bx, dest: mir::Place<'tcx>, fn_ret: &ArgAbi<'tcx, Ty<'tcx>>, ) -> (ReturnDest<'tcx, Bx::Value>, ReturnSlot) { + let (dest, place) = self.make_return_place(bx, dest, fn_ret); + ( + dest, + match place { + None => ReturnSlot::Direct, + Some(place) => ReturnSlot::Indirect(place.llval), + }, + ) + } + + fn make_return_place( + &mut self, + bx: &mut Bx, + dest: mir::Place<'tcx>, + fn_ret: &ArgAbi<'tcx, Ty<'tcx>>, + ) -> (ReturnDest<'tcx, Bx::Value>, Option>) { // If the return is ignored, we can just return a do-nothing `ReturnDest`. if fn_ret.is_ignore() { - return (ReturnDest::Nothing, ReturnSlot::Direct); + return (ReturnDest::Nothing, None); } let dest = if let Some(index) = dest.as_local() { match self.locals[index] { @@ -2457,12 +2480,9 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // but the calling convention has an indirect return. let tmp = PlaceRef::alloca(bx, fn_ret.layout); tmp.storage_live(bx); - ( - ReturnDest::IndirectOperand(tmp, index), - ReturnSlot::Indirect(tmp.val.llval), - ) + (ReturnDest::IndirectOperand(tmp, index), Some(tmp.val)) } else { - (ReturnDest::DirectOperand(index), ReturnSlot::Direct) + (ReturnDest::DirectOperand(index), None) }; } LocalRef::Operand(_) => { @@ -2482,13 +2502,13 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // to create a temporary. span_bug!(self.mir.span, "can't directly store to unaligned value"); } - (ReturnDest::Nothing, ReturnSlot::Indirect(dest.val.llval)) + (ReturnDest::Nothing, Some(dest.val)) } else { - (ReturnDest::Store(dest), ReturnSlot::Direct) + (ReturnDest::Store(dest), None) } } - // Stores the return value of a function call into it's final location. + /// Stores the return value of a function call into it's final location. fn store_return( &mut self, bx: &mut Bx, @@ -2618,3 +2638,64 @@ pub fn store_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( bx.store(value, ptr, align); }; } + +/// This function returns the fields of a Rust struct or tuple for use with +/// [`store_intrinsic_return_struct`] below. All fields must be scalar or SIMD types. This returns +/// a [`Vec`] of `(field_type, field_offset)` pairs. +pub fn intrinsic_return_struct_fields<'tcx, Cx: CodegenMethods<'tcx>>( + cx: &Cx, + ret_layout: TyAndLayout<'tcx>, +) -> Vec<(Cx::Type, Size)> { + let ret_layout = ret_layout.peel_transparent_wrappers_from_non_1zst(cx); + match ret_layout.ty.kind() { + ty::Adt(adt_def, _) if adt_def.is_struct() => {} + ty::Tuple(_) => {} + _ => bug!("invalid intrinsic return type: {ret_layout:?}"), + } + let fields = (0..ret_layout.fields.count()) + .map(|i| { + let field = ret_layout.field(cx, i); + assert!(!field.is_aggregate(), "invalid intrinsic return field: {field:?}"); + (cx.immediate_backend_type(field), ret_layout.fields.offset(i)) + }) + .collect::>(); + assert!(fields.len() >= 2, "invalid intrinsic return type: {ret_layout:?}"); + fields +} + +/// Some LLVM intrinsics return LLVM structs that don't have an equivalent in the Rust type system. +/// This function allows the fields of a LLVM struct to be stored in the fields of a Rust struct. +/// The Rust struct's fields can be obtained using [`intrinsic_return_struct_fields`]. `fields` must +/// be a [`Vec`] of (field_offset, field_value) pairs. +pub fn store_intrinsic_return_struct<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( + bx: &mut Bx, + ret_layout: TyAndLayout<'tcx>, + memory_return_place: Option>, + fields: Vec<(Size, Bx::Value)>, +) -> IntrinsicResult<'tcx, Bx::Value> { + match ret_layout.backend_repr { + BackendRepr::ScalarPair { a: _, b: _, b_offset } => { + let &[(offset0, value0), (offset1, value1)] = fields.as_slice() else { + bug!("Invalid fields for ScalarPair: {fields:?}") + }; + assert_ne!(offset0, offset1); + assert!(offset0 == Size::ZERO || offset1 == Size::ZERO); + assert!(offset0 == b_offset || offset1 == b_offset); + let (a, b) = if offset0 < offset1 { (value0, value1) } else { (value1, value0) }; + IntrinsicResult::Operand(OperandValue::Pair(a, b)) + } + BackendRepr::Memory { sized: true } => { + let dest = + memory_return_place.expect("BackendRepr::Memory return with no return place"); + for (offset, value) in fields.into_iter() { + let pointer = match offset.bytes() { + 0 => dest.llval, + bytes => bx.inbounds_ptradd(dest.llval, bx.const_usize(bytes)), + }; + bx.store(value, pointer, dest.align.restrict_for_offset(offset)); + } + IntrinsicResult::WroteIntoPlace + } + _ => bug!("unexpected aggregate return layout: {ret_layout:?}"), + } +} diff --git a/compiler/rustc_codegen_ssa/src/mir/mod.rs b/compiler/rustc_codegen_ssa/src/mir/mod.rs index 2826952a3bec3..3a74677577eb2 100644 --- a/compiler/rustc_codegen_ssa/src/mir/mod.rs +++ b/compiler/rustc_codegen_ssa/src/mir/mod.rs @@ -28,7 +28,7 @@ mod retag; mod rvalue; mod statement; -pub use self::block::store_cast; +pub use self::block::{intrinsic_return_struct_fields, store_cast, store_intrinsic_return_struct}; use self::debuginfo::{FunctionDebugContext, PerLocalVarDebugInfo}; use self::operand::{OperandRef, OperandValue}; use self::place::PlaceRef; @@ -160,6 +160,7 @@ enum LocalRef<'tcx, V> { PendingOperand, } +#[derive(Debug)] pub enum IntrinsicResult<'tcx, V> { /// This intrinsic created an operand without using the `result_place` argument. /// diff --git a/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs b/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs index 530597c616ff9..49a8eedc8898b 100644 --- a/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs +++ b/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs @@ -35,6 +35,7 @@ pub trait IntrinsicCallBuilderMethods<'tcx>: BackendTypes { &mut self, instance: ty::Instance<'tcx>, args: &[OperandRef<'tcx, Self::Value>], + memory_return_place: Option>, is_cleanup: bool, ) -> Self::Value; diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 501bb21c1eea9..8695e7dd71672 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -44,7 +44,7 @@ pub enum Annotatable { Item(Box), AssocItem(Box, AssocCtxt), ForeignItem(Box), - Stmt(Box), + Stmt(ast::Stmt), Expr(Box), Arm(ast::Arm), ExprField(ast::ExprField), @@ -168,7 +168,7 @@ impl Annotatable { pub fn expect_stmt(self) -> ast::Stmt { match self { - Annotatable::Stmt(stmt) => *stmt, + Annotatable::Stmt(stmt) => stmt, _ => panic!("expected statement"), } } @@ -272,12 +272,12 @@ impl<'cx> MacroExpanderResult<'cx> { site_span: Span, arm_span: Span, macro_ident: Ident, - ) -> Self { + ) -> Box { // Emit SEMICOLON_IN_EXPRESSIONS_FROM_MACROS here, rather than the NON_LOCAL version. let is_local = true; let parser = ParserAnyMacro::from_tts(cx, tts, site_span, arm_span, is_local, macro_ident, &[], &[]); - ExpandResult::Ready(Box::new(parser)) + Box::new(parser) } } diff --git a/compiler/rustc_expand/src/build.rs b/compiler/rustc_expand/src/build.rs index 44f4799ab1abc..54e92ac5a4378 100644 --- a/compiler/rustc_expand/src/build.rs +++ b/compiler/rustc_expand/src/build.rs @@ -634,6 +634,21 @@ impl<'a> ExtCtxt<'a> { } } + pub fn param_self_ref(&self, span: Span) -> ast::Param { + let infer_ty = self.ty(span, ast::TyKind::ImplicitSelf); + let ty = self.ty_ref(span, infer_ty, None, ast::Mutability::Not); + let pat = Box::new(self.pat_name(span, kw::SelfLower)); + ast::Param { + attrs: AttrVec::default(), + id: ast::DUMMY_NODE_ID, + pat, + span, + ty, + is_placeholder: false, + has_const_keyword: false, + } + } + // `self` is unused but keep it as method for the convenience use. pub fn fn_decl(&self, inputs: ThinVec, output: ast::FnRetTy) -> Box { Box::new(ast::FnDecl { inputs, output }) diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index d3dea34aff80e..e60b1829e56de 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -1769,7 +1769,7 @@ impl InvocationCollectorNode for ast::Arm { impl InvocationCollectorNode for ast::Stmt { const KIND: AstFragmentKind = AstFragmentKind::Stmts; fn to_annotatable(self) -> Annotatable { - Annotatable::Stmt(Box::new(self)) + Annotatable::Stmt(self) } fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { fragment.make_stmts() diff --git a/compiler/rustc_expand/src/proc_macro.rs b/compiler/rustc_expand/src/proc_macro.rs index 5e01b851b75c7..aa4e1aafcda41 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -135,7 +135,7 @@ impl MultiItemModifier for DeriveProcMacro { Ok(None) => break, Ok(Some(item)) => { if is_stmt { - items.push(Annotatable::Stmt(Box::new(ecx.stmt_item(span, item)))); + items.push(Annotatable::Stmt(ecx.stmt_item(span, item))); } else { items.push(Annotatable::Item(item)); } diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index b2823e3ab9c06..7538ec2660322 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -386,6 +386,8 @@ declare_features! ( (unstable, asm_experimental_reg, "1.85.0", Some(133416)), /// Allows using `label` operands in inline assembly together with output operands. (unstable, asm_goto_with_outputs, "1.85.0", Some(119364)), + /// Allows using thin `NonNull` pointer input operands in inline assembly. + (unstable, asm_nonnull_inputs, "CURRENT_RUSTC_VERSION", Some(166132)), /// Allows the `may_unwind` option in inline assembly. (unstable, asm_unwind, "1.58.0", Some(93334)), /// Allows `_` for the name of associated constants. diff --git a/compiler/rustc_graphviz/src/lib.rs b/compiler/rustc_graphviz/src/lib.rs index 2aaf9cea97e44..237d1ecfdeb83 100644 --- a/compiler/rustc_graphviz/src/lib.rs +++ b/compiler/rustc_graphviz/src/lib.rs @@ -319,22 +319,30 @@ pub enum Style { Bold, Rounded, Diagonals, - Filled, + Filled(FillColor), Striped, Wedged, } +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub enum FillColor { + Red, + Green, + Unspecified, +} + impl Style { pub fn as_slice(self) -> &'static str { match self { - Style::None => "", + Style::None + // Filling is handled later in `render_opts` + | Style::Filled(_) => "", Style::Solid => "solid", Style::Dashed => "dashed", Style::Dotted => "dotted", Style::Bold => "bold", Style::Rounded => "rounded", Style::Diagonals => "diagonals", - Style::Filled => "filled", Style::Striped => "striped", Style::Wedged => "wedged", } @@ -624,7 +632,17 @@ where let style = g.node_style(n); if !options.contains(&RenderOption::NoNodeStyles) && style != Style::None { - write!(text, "[style=\"{}\"]", style.as_slice()).unwrap(); + if let Style::Filled(fillcolor) = style { + // Filling needs separate handling + let fillcolor_str = match fillcolor { + FillColor::Green => "green", + FillColor::Red => "red", + FillColor::Unspecified => "lightgrey", + }; + write!(text, "[style=\"filled\" fillcolor=\"{fillcolor_str}\"]").unwrap(); + } else { + write!(text, "[style=\"{}\"]", style.as_slice()).unwrap(); + } } if let Some(s) = g.node_shape(n) { diff --git a/compiler/rustc_hir_typeck/src/inline_asm.rs b/compiler/rustc_hir_typeck/src/inline_asm.rs index 384d5302e39e7..32873c1d0d3e9 100644 --- a/compiler/rustc_hir_typeck/src/inline_asm.rs +++ b/compiler/rustc_hir_typeck/src/inline_asm.rs @@ -52,6 +52,19 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { } } + fn maybe_to_pointee_ty(&self, ty: Ty<'tcx>) -> Option> { + Some(match *ty.kind() { + ty::RawPtr(pointee, _) => pointee, + ty::Adt(adt, args) + if self.tcx().is_lang_item(adt.did(), LangItem::NonNull) + && self.tcx().features().asm_nonnull_inputs() => + { + args.type_at(0) + } + _ => return None, + }) + } + // FIXME(compiler-errors): This could use `<$ty as Pointee>::Metadata == ()` fn is_thin_ptr_ty(&self, ty: Ty<'tcx>) -> bool { // Type still may have region variables, but `Sized` does not depend @@ -91,7 +104,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { ty::Float(FloatTy::F64) => Ok(InlineAsmType::F64), ty::Float(FloatTy::F128) => Ok(InlineAsmType::F128), ty::FnPtr(..) => Ok(asm_ty_isize), - ty::RawPtr(elem_ty, _) => { + _ if let Some(elem_ty) = self.maybe_to_pointee_ty(ty) => { if self.is_thin_ptr_ty(elem_ty) { Ok(asm_ty_isize) } else { @@ -245,15 +258,24 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { bug!("inference variable in asm operand ty: {:?} {:?}", expr, ty); } - let asm_ty = match *ty.kind() { + let eff_ty = match *ty.kind() { // `!` is allowed for input but not for output (issue #87802) ty::Never if is_input => return None, _ if ty.references_error() => return None, ty::Adt(adt, args) if self.tcx().is_lang_item(adt.did(), LangItem::MaybeUninit) => { - let ty = args.type_at(0); - self.get_asm_ty(expr.span, ty) + args.type_at(0) + } + _ => ty, + }; + + let asm_ty = match *eff_ty.kind() { + // `NonNull` is allowed as input but not as output. + ty::Adt(adt, _) + if !is_input && self.tcx().is_lang_item(adt.did(), LangItem::NonNull) => + { + Err(NonAsmTypeReason::Invalid(ty)) } - _ => self.get_asm_ty(expr.span, ty), + _ => self.get_asm_ty(expr.span, eff_ty), }; let asm_ty = match asm_ty { Ok(asm_ty) => asm_ty, diff --git a/compiler/rustc_incremental/src/assert_dep_graph.rs b/compiler/rustc_incremental/src/assert_dep_graph.rs index 8147e3c3ae550..74d35753a1461 100644 --- a/compiler/rustc_incremental/src/assert_dep_graph.rs +++ b/compiler/rustc_incremental/src/assert_dep_graph.rs @@ -40,13 +40,15 @@ use std::io::Write; use rustc_attr_ir::{Attribute, AttributeKind}; use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::graph::linked_graph::{Direction, INCOMING, NodeIndex, OUTGOING}; -use rustc_graphviz as dot; +use rustc_graphviz::{self as dot, FillColor, Style}; use rustc_hir as hir; use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId}; use rustc_hir::intravisit::{self, Visitor}; -use rustc_middle::dep_graph::{DepKind, DepNode, DepNodeFilter, EdgeFilter, RetainedDepGraph}; +use rustc_middle::dep_graph::{ + DepGraph, DepKind, DepNode, DepNodeColor, DepNodeFilter, EdgeFilter, RetainedDepGraph, +}; use rustc_middle::hir::nested_filter; -use rustc_middle::ty::TyCtxt; +use rustc_middle::ty::{TyCtxt, tls}; use rustc_span::{Span, Symbol, bug, sym}; use tracing::debug; @@ -60,9 +62,7 @@ pub(crate) fn assert_dep_graph(tcx: TyCtxt<'_>) { let retained_dep_graph = tcx.dep_graph.retained_dep_graph(); if tcx.sess.opts.unstable_opts.dump_dep_graph { - if let Some(graph) = &retained_dep_graph { - dump_graph(graph); - } + dump_graph(&tcx.dep_graph); } if !tcx.sess.opts.unstable_opts.query_dep_graph { @@ -206,7 +206,11 @@ fn check_paths<'tcx>( } } -fn dump_graph(graph: &RetainedDepGraph) { +fn dump_graph(graph: &DepGraph) { + let Some(retained) = &graph.retained_dep_graph() else { + return; + }; + let path: String = env::var("RUST_DEP_GRAPH").unwrap_or_else(|_| "dep_graph".to_string()); let nodes = match env::var("RUST_DEP_GRAPH_FILTER") { @@ -214,13 +218,13 @@ fn dump_graph(graph: &RetainedDepGraph) { // Expect one of: "-> target", "source -> target", or "source ->". let edge_filter = EdgeFilter::new(&string).unwrap_or_else(|e| bug!("invalid filter: {}", e)); - let sources = node_set(graph, &edge_filter.source); - let targets = node_set(graph, &edge_filter.target); - filter_nodes(graph, &sources, &targets) + let sources = node_set(retained, &edge_filter.source); + let targets = node_set(retained, &edge_filter.target); + filter_nodes(retained, &sources, &targets) } - Err(_) => graph.nodes().into_iter().map(|n| n.kind).collect(), + Err(_) => retained.nodes().into_iter().collect(), }; - let edges = filter_edges(graph, &nodes); + let edges = filter_edges(retained, &nodes); { // dump a .txt file with just the edges: @@ -235,39 +239,51 @@ fn dump_graph(graph: &RetainedDepGraph) { // dump a .dot file in graphviz format: let dot_path = format!("{path}.dot"); let mut v = Vec::new(); - dot::render(&GraphvizDepGraph(nodes, edges), &mut v).unwrap(); + dot::render( + &GraphvizDepGraph { + dep_graph: graph.clone(), + nodes: nodes.clone(), + edges: edges.into_iter().map(|(&a, &b)| (a, b)).clone().collect(), + }, + &mut v, + ) + .unwrap(); fs::write(dot_path, v).unwrap(); } } #[allow(missing_docs)] -struct GraphvizDepGraph(FxIndexSet, Vec<(DepKind, DepKind)>); +struct GraphvizDepGraph<'g> { + dep_graph: DepGraph, + nodes: FxIndexSet<&'g DepNode>, + edges: Vec<(DepNode, DepNode)>, +} -impl<'a> dot::GraphWalk<'a> for GraphvizDepGraph { - type Node = DepKind; - type Edge = (DepKind, DepKind); - fn nodes(&self) -> dot::Nodes<'_, DepKind> { - let nodes: Vec<_> = self.0.iter().cloned().collect(); +impl<'a> dot::GraphWalk<'a> for GraphvizDepGraph<'a> { + type Node = DepNode; + type Edge = (DepNode, DepNode); + fn nodes(&self) -> dot::Nodes<'_, DepNode> { + let nodes: Vec<_> = self.nodes.iter().cloned().map(|&a| a).collect(); nodes.into() } - fn edges(&self) -> dot::Edges<'_, (DepKind, DepKind)> { - self.1[..].into() + fn edges(&self) -> dot::Edges<'_, (DepNode, DepNode)> { + self.edges[..].into() } - fn source(&self, edge: &(DepKind, DepKind)) -> DepKind { + fn source(&self, edge: &(DepNode, DepNode)) -> DepNode { edge.0 } - fn target(&self, edge: &(DepKind, DepKind)) -> DepKind { + fn target(&self, edge: &(DepNode, DepNode)) -> DepNode { edge.1 } } -impl<'a> dot::Labeller<'a> for GraphvizDepGraph { - type Node = DepKind; - type Edge = (DepKind, DepKind); +impl<'a> dot::Labeller<'a> for GraphvizDepGraph<'a> { + type Node = DepNode; + type Edge = (DepNode, DepNode); fn graph_id(&self) -> dot::Id<'_> { dot::Id::new("DependencyGraph").unwrap() } - fn node_id(&self, n: &DepKind) -> dot::Id<'_> { + fn node_id(&self, n: &DepNode) -> dot::Id<'_> { let s: String = format!("{n:?}") .chars() .map(|c| if c == '_' || c.is_alphanumeric() { c } else { '_' }) @@ -275,8 +291,25 @@ impl<'a> dot::Labeller<'a> for GraphvizDepGraph { debug!("n={:?} s={:?}", n, s); dot::Id::new(s).unwrap() } - fn node_label(&self, n: &DepKind) -> dot::LabelText<'_> { - dot::LabelText::label(format!("{n:?}")) + fn node_label(&self, n: &DepNode) -> dot::LabelText<'_> { + tls::with_opt(|opt_tcx| { + if let Some(tcx) = opt_tcx + && let Some(def_id) = n.extract_def_id(tcx) + { + dot::LabelText::label(format!("{:?} ({})", n.kind, tcx.def_path_debug_str(def_id))) + } else { + dot::LabelText::label(format!("{:?}", n.kind)) + } + }) + } + + /// Maps `n` to a style that will be used in the rendered output. + fn node_style(&'a self, n: &DepNode) -> Style { + Style::Filled(match self.dep_graph.node_color(n) { + DepNodeColor::Green(_) => FillColor::Green, + DepNodeColor::Red => FillColor::Red, + DepNodeColor::Unknown => FillColor::Unspecified, + }) } } @@ -300,7 +333,7 @@ fn filter_nodes<'g>( graph: &'g RetainedDepGraph, sources: &Option>, targets: &Option>, -) -> FxIndexSet { +) -> FxIndexSet<&'g DepNode> { if let Some(sources) = sources { if let Some(targets) = targets { walk_between(graph, sources, targets) @@ -310,7 +343,7 @@ fn filter_nodes<'g>( } else if let Some(targets) = targets { walk_nodes(graph, targets, INCOMING) } else { - graph.nodes().into_iter().map(|n| n.kind).collect() + graph.nodes().into_iter().collect() } } @@ -318,17 +351,17 @@ fn walk_nodes<'g>( graph: &'g RetainedDepGraph, starts: &FxIndexSet<&'g DepNode>, direction: Direction, -) -> FxIndexSet { +) -> FxIndexSet<&'g DepNode> { let mut set = FxIndexSet::default(); for &start in starts { debug!("walk_nodes: start={:?} outgoing?={:?}", start, direction == OUTGOING); - if set.insert(start.kind) { + if set.insert(start) { let mut stack = vec![graph.indices[start]]; while let Some(index) = stack.pop() { for (_, edge) in graph.inner.adjacent_edges(index, direction) { let neighbor_index = edge.source_or_target(direction); let neighbor = graph.inner.node_data(neighbor_index); - if set.insert(neighbor.kind) { + if set.insert(neighbor) { stack.push(neighbor_index); } } @@ -342,7 +375,7 @@ fn walk_between<'g>( graph: &'g RetainedDepGraph, sources: &FxIndexSet<&'g DepNode>, targets: &FxIndexSet<&'g DepNode>, -) -> FxIndexSet { +) -> FxIndexSet<&'g DepNode> { // This is a bit tricky. We want to include a node only if it is: // (a) reachable from a source and (b) will reach a target. And we // have to be careful about cycles etc. Luckily efficiency is not @@ -373,7 +406,6 @@ fn walk_between<'g>( let index = graph.indices[n]; node_states[index.0] == State::Included }) - .map(|n| n.kind) .collect(); fn recurse(graph: &RetainedDepGraph, node_states: &mut [State], node: NodeIndex) -> bool { @@ -409,12 +441,14 @@ fn walk_between<'g>( } } -fn filter_edges(graph: &RetainedDepGraph, nodes: &FxIndexSet) -> Vec<(DepKind, DepKind)> { +fn filter_edges<'g>( + graph: &'g RetainedDepGraph, + nodes: &'g FxIndexSet<&'g DepNode>, +) -> Vec<(&'g DepNode, &'g DepNode)> { let uniq: FxIndexSet<_> = graph .edges() .into_iter() - .map(|(s, t)| (s.kind, t.kind)) - .filter(|(source, target)| nodes.contains(source) && nodes.contains(target)) + .filter(|&(&source, &target)| nodes.contains(&source) && nodes.contains(&target)) .collect(); uniq.into_iter().collect() } diff --git a/compiler/rustc_middle/src/dep_graph/graph.rs b/compiler/rustc_middle/src/dep_graph/graph.rs index 040e33b16bb17..d2d2a49d13c17 100644 --- a/compiler/rustc_middle/src/dep_graph/graph.rs +++ b/compiler/rustc_middle/src/dep_graph/graph.rs @@ -124,7 +124,7 @@ impl Drop for EdgeFrame<'_> { } #[derive(Debug)] -pub(super) enum DepNodeColor { +pub enum DepNodeColor { Green(DepNodeIndex), Red, Unknown, @@ -877,7 +877,7 @@ impl DepGraph { .any(|node| node.kind == dep_kind) } - fn node_color(&self, dep_node: &DepNode) -> DepNodeColor { + pub fn node_color(&self, dep_node: &DepNode) -> DepNodeColor { if let Some(ref data) = self.data { return data.node_color(dep_node); } diff --git a/compiler/rustc_middle/src/dep_graph/mod.rs b/compiler/rustc_middle/src/dep_graph/mod.rs index e63a281002f0d..b28c5f8a53f15 100644 --- a/compiler/rustc_middle/src/dep_graph/mod.rs +++ b/compiler/rustc_middle/src/dep_graph/mod.rs @@ -5,7 +5,7 @@ use tracing::instrument; pub use self::dep_node::{DepKind, DepKindVTable, DepNode, WorkProductId, dep_kind_from_label}; pub use self::dep_node_key::DepNodeKey; pub use self::graph::{ - DepGraph, DepGraphData, DepNodeIndex, QuerySideEffect, TaskDepsRef, WorkProduct, + DepGraph, DepGraphData, DepNodeColor, DepNodeIndex, QuerySideEffect, TaskDepsRef, WorkProduct, WorkProductMap, hash_result, }; use self::graph::{MarkFrame, print_markframe_trace}; diff --git a/compiler/rustc_public/src/compiler_interface.rs b/compiler/rustc_public/src/compiler_interface.rs index 0c77abee2dab6..d8021447be79d 100644 --- a/compiler/rustc_public/src/compiler_interface.rs +++ b/compiler/rustc_public/src/compiler_interface.rs @@ -389,6 +389,19 @@ impl<'tcx> CompilerInterface<'tcx> { self.with_cx(|tables, cx| cx.adt_repr(def.internal(tables, cx.tcx)).stable(tables, cx)) } + /// Returns whether this ADT is a phantom data + pub(crate) fn adt_is_phantom_data(&self, def: AdtDef) -> bool { + self.with_cx(|tables, cx| cx.adt_is_phantom_data(def.internal(tables, cx.tcx))) + } + /// Returns whether this ADT is manually drop + pub(crate) fn adt_is_manually_drop(&self, def: AdtDef) -> bool { + self.with_cx(|tables, cx| cx.adt_is_manually_drop(def.internal(tables, cx.tcx))) + } + /// Returns whether this ADT is unsafe cell + pub(crate) fn adt_is_unsafe_cell(&self, def: AdtDef) -> bool { + self.with_cx(|tables, cx| cx.adt_is_unsafe_cell(def.internal(tables, cx.tcx))) + } + /// Retrieve the function signature for the given generic arguments. pub(crate) fn fn_sig(&self, def: FnDef, args: &GenericArgs) -> PolyFnSig { self.with_cx(|tables, cx| { diff --git a/compiler/rustc_public/src/ty/def.rs b/compiler/rustc_public/src/ty/def.rs index 4e34e3bbb2e33..2ce9c1d572c53 100644 --- a/compiler/rustc_public/src/ty/def.rs +++ b/compiler/rustc_public/src/ty/def.rs @@ -204,6 +204,18 @@ impl AdtDef { with(|cx| cx.adt_is_simd(*self)) } + pub fn is_phantom_data(&self) -> bool { + with(|cx| cx.adt_is_phantom_data(*self)) + } + + pub fn is_manually_drop(&self) -> bool { + with(|cx| cx.adt_is_manually_drop(*self)) + } + + pub fn is_unsafe_cell(&self) -> bool { + with(|cx| cx.adt_is_unsafe_cell(*self)) + } + /// The number of variants in this ADT. pub fn num_variants(&self) -> usize { with(|cx| cx.adt_variants_len(*self)) diff --git a/compiler/rustc_public_bridge/src/context/impls.rs b/compiler/rustc_public_bridge/src/context/impls.rs index 1ae42f619c4ba..1290273f2c408 100644 --- a/compiler/rustc_public_bridge/src/context/impls.rs +++ b/compiler/rustc_public_bridge/src/context/impls.rs @@ -376,6 +376,20 @@ impl<'tcx, B: Bridge> CompilerCtxt<'tcx, B> { def.repr() } + /// Returns if the ADT is a PhantomData + pub fn adt_is_phantom_data(&self, def: AdtDef<'tcx>) -> bool { + def.is_phantom_data() + } + + /// Returns if the ADT is ManuallyDrop + pub fn adt_is_manually_drop(&self, def: AdtDef<'tcx>) -> bool { + def.is_manually_drop() + } + + /// Returns if the ADT is an UnsafeCell + pub fn adt_is_unsafe_cell(&self, def: AdtDef<'tcx>) -> bool { + def.is_unsafe_cell() + } /// Retrieve the function signature for the given generic arguments. pub fn fn_sig(&self, def_id: DefId, args_ref: GenericArgs<'tcx>) -> Binder<'tcx, FnSig<'tcx>> { let sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, args_ref).skip_norm_wip(); diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index a128abd07b460..a21cecf04448f 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -468,6 +468,7 @@ symbols! { asm_experimental_reg, asm_goto, asm_goto_with_outputs, + asm_nonnull_inputs, asm_sym, asm_unwind, assert, diff --git a/library/Cargo.lock b/library/Cargo.lock index bd63144008d6c..27cb038fb8023 100644 --- a/library/Cargo.lock +++ b/library/Cargo.lock @@ -234,6 +234,8 @@ name = "profiler_builtins" version = "0.0.0" dependencies = [ "cc", + "compiler_builtins", + "core", ] [[package]] diff --git a/library/alloc/src/alloc.rs b/library/alloc/src/alloc.rs index 06bc8a589e1fc..1bb17abbe661e 100644 --- a/library/alloc/src/alloc.rs +++ b/library/alloc/src/alloc.rs @@ -119,8 +119,7 @@ unsafe impl core::alloc::StaticAllocator for Global {} /// /// Users of this function have to consider that in the future, allocators may be allowed to unwind. /// -/// This function is expected to be deprecated in favor of the `allocate` method -/// of the [`Global`] type when it and the [`Allocator`] trait become stable. +/// Calling [`Allocator::allocate`] on `Global` is preferred. /// /// # Safety /// diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs index eb122c3a4294d..19621a5b1cb64 100644 --- a/library/core/src/fmt/mod.rs +++ b/library/core/src/fmt/mod.rs @@ -284,7 +284,7 @@ pub enum DebugAsHex { /// /// `FormattingOptions` is a [`Formatter`] without an attached [`Write`] trait. /// It is mainly used to construct `Formatter` instances. -#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[derive(Copy, Clone, PartialEq, Eq)] #[unstable(feature = "formatting_options", issue = "118117")] pub struct FormattingOptions { /// Flags, with the following bit fields: @@ -535,6 +535,49 @@ impl FormattingOptions { pub const fn create_formatter<'a>(self, write: &'a mut (dyn Write + 'a)) -> Formatter<'a> { Formatter { options: self, buf: write } } + + /// Recreate a format specifier like `-<04x` matching these options. Public only for testing. + #[doc(hidden)] + #[unstable(feature = "fmt_internals", issue = "none")] + pub fn write_fmt_specifier(&self, f: &mut Formatter<'_>, str_escape: bool) -> Result { + let fill = self.get_fill(); + if fill != ' ' { + if str_escape { + write!(f, "{}", fill.escape_debug())?; + } else { + write!(f, "{fill}")?; + } + } + match self.get_align() { + Some(Alignment::Left) => write!(f, "<")?, + Some(Alignment::Right) => write!(f, ">")?, + Some(Alignment::Center) => write!(f, "^")?, + None => (), + } + match self.get_sign() { + Some(Sign::Plus) => write!(f, "+")?, + Some(Sign::Minus) => write!(f, "-")?, + None => (), + } + if self.get_alternate() { + write!(f, "#")?; + } + if self.get_sign_aware_zero_pad() { + write!(f, "0")?; + } + if let Some(width) = self.get_width() { + write!(f, "{width}")?; + } + if let Some(precision) = self.get_precision() { + write!(f, ".{precision}")?; + } + match self.get_debug_as_hex() { + Some(DebugAsHex::Lower) => write!(f, "x")?, + Some(DebugAsHex::Upper) => write!(f, "X")?, + None => (), + } + Ok(()) + } } #[unstable(feature = "formatting_options", issue = "118117")] @@ -546,6 +589,30 @@ impl Default for FormattingOptions { } } +#[unstable(feature = "formatting_options", issue = "118117")] +impl Debug for FormattingOptions { + fn fmt(&self, f: &mut Formatter<'_>) -> Result { + // `field_with` for optional values so we don't propagate `#` and turn a simple + // `Some(1)` into three lines. + f.debug_struct("FormattingOptions") + .field_with("align", |f| write!(f, "{:?}", self.get_align())) + .field("alternate", &self.get_alternate()) + .field_with("debug_as_hex", |f| write!(f, "{:?}", self.get_debug_as_hex())) + .field("fill", &self.get_fill()) + .field_with("precision", |f| write!(f, "{:?}", self.get_precision())) + .field_with("sign", |f| write!(f, "{:?}", self.get_sign())) + .field("sign_aware_zero_pad", &self.get_sign_aware_zero_pad()) + .field_with("width", |f| write!(f, "{:?}", self.get_width())) + .field_with("specifier", |f| { + f.write_char('"')?; + self.write_fmt_specifier(f, true)?; + f.write_char('"')?; + Ok(()) + }) + .finish() + } +} + /// Configuration for formatting. /// /// A `Formatter` represents various options related to formatting. Users do not diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index 5c20f4a93fb2e..a1153e61bb873 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -2701,7 +2701,7 @@ pub const fn ub_checks() -> bool { #[inline(always)] #[rustc_intrinsic] pub const fn overflow_checks() -> bool { - cfg!(debug_assertions) + cfg!(overflow_checks) } /// Allocates a block of memory at compile time. diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 7f0f250a96486..d1d15c974c0d4 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -110,6 +110,7 @@ #![feature(allow_internal_unstable)] #![feature(arbitrary_self_types_pointers)] #![feature(auto_traits)] +#![feature(cfg_overflow_checks)] #![feature(cfg_sanitize)] #![feature(cfg_target_has_atomic)] #![feature(cfg_ub_checks)] diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index 6aded7cfec682..2f53435f3c3c9 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -1340,8 +1340,6 @@ macro_rules! nonzero_integer { /// # Examples /// /// ``` - /// #![feature(nonzero_ops)] - /// /// # use std::num::NonZero; /// # /// # fn main() { test().unwrap(); } @@ -1355,12 +1353,17 @@ macro_rules! nonzero_integer { /// ``` /// /// [`checked_mul`]: Self::checked_mul - #[unstable(feature = "nonzero_ops", issue = "84186")] + #[stable(feature = "nonzero_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "nonzero_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] pub const unsafe fn unchecked_mul(self, other: Self) -> Self { - // SAFETY: The caller ensures there is no overflow. + // SAFETY: + // - the caller promises that the multiplication does not overflow; + // - `self` and `other` are non-zero; + // - the only way to get zero from a multiplication without overflow + // is for either factor to be zero. unsafe { Self::new_unchecked(self.get().unchecked_mul(other.get())) } } @@ -2042,8 +2045,6 @@ macro_rules! nonzero_integer_signedness_dependent_methods { /// # Examples /// /// ``` - /// #![feature(nonzero_ops)] - /// /// # use std::num::NonZero; /// # /// # fn main() { test().unwrap(); } @@ -2057,12 +2058,17 @@ macro_rules! nonzero_integer_signedness_dependent_methods { /// ``` /// /// [`checked_add`]: Self::checked_add - #[unstable(feature = "nonzero_ops", issue = "84186")] + #[stable(feature = "nonzero_ops", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "nonzero_ops", since = "CURRENT_RUSTC_VERSION")] #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] pub const unsafe fn unchecked_add(self, other: $Int) -> Self { - // SAFETY: The caller ensures there is no overflow. + // SAFETY: + // - the caller promises that the addition does not overflow; + // - `self` is non-zero; + // - the only way to get zero from an addition of unsigned integers + // without overflow is for both addends to be zero. unsafe { Self::new_unchecked(self.get().unchecked_add(other)) } } diff --git a/library/core/src/ops/range.rs b/library/core/src/ops/range.rs index d81279cb56be3..1395630396b89 100644 --- a/library/core/src/ops/range.rs +++ b/library/core/src/ops/range.rs @@ -1,6 +1,5 @@ use crate::fmt; use crate::hash::Hash; -use crate::marker::Destruct; /// An unbounded range (`..`). /// /// `RangeFull` is primarily used as a [slicing index], its shorthand is `..`. @@ -987,76 +986,6 @@ pub const trait IntoBounds: [const] RangeBounds { /// assert_eq!((..=7).into_bounds(), (Unbounded, Included(7))); /// ``` fn into_bounds(self) -> (Bound, Bound); - - /// Compute the intersection of `self` and `other`. - /// - /// # Examples - /// - /// ``` - /// #![feature(range_into_bounds)] - /// use std::ops::Bound::*; - /// use std::ops::IntoBounds; - /// - /// assert_eq!((3..).intersect(..5), (Included(3), Excluded(5))); - /// assert_eq!((-12..387).intersect(0..256), (Included(0), Excluded(256))); - /// assert_eq!((1..5).intersect(..), (Included(1), Excluded(5))); - /// assert_eq!((1..=9).intersect(0..10), (Included(1), Included(9))); - /// assert_eq!((7..=13).intersect(8..13), (Included(8), Excluded(13))); - /// ``` - /// - /// Combine with `is_empty` to determine if two ranges overlap. - /// - /// ``` - /// #![feature(range_into_bounds)] - /// #![feature(range_bounds_is_empty)] - /// use std::ops::{RangeBounds, IntoBounds}; - /// - /// assert!(!(3..).intersect(..5).is_empty()); - /// assert!(!(-12..387).intersect(0..256).is_empty()); - /// assert!((1..5).intersect(6..).is_empty()); - /// ``` - fn intersect(self, other: R) -> (Bound, Bound) - where - Self: Sized, - T: [const] Ord + [const] Destruct, - R: Sized + [const] IntoBounds, - { - let (self_start, self_end) = IntoBounds::into_bounds(self); - let (other_start, other_end) = IntoBounds::into_bounds(other); - - let start = match (self_start, other_start) { - (Included(a), Included(b)) => Included(Ord::max(a, b)), - (Excluded(a), Excluded(b)) => Excluded(Ord::max(a, b)), - (Unbounded, Unbounded) => Unbounded, - - (x, Unbounded) | (Unbounded, x) => x, - - (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => { - if i > e { - Included(i) - } else { - Excluded(e) - } - } - }; - let end = match (self_end, other_end) { - (Included(a), Included(b)) => Included(Ord::min(a, b)), - (Excluded(a), Excluded(b)) => Excluded(Ord::min(a, b)), - (Unbounded, Unbounded) => Unbounded, - - (x, Unbounded) | (Unbounded, x) => x, - - (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => { - if i < e { - Included(i) - } else { - Excluded(e) - } - } - }; - - (start, end) - } } use self::Bound::{Excluded, Included, Unbounded}; diff --git a/library/core/src/range.rs b/library/core/src/range.rs index ea4ac96179981..a96abbee34de4 100644 --- a/library/core/src/range.rs +++ b/library/core/src/range.rs @@ -17,6 +17,7 @@ use crate::fmt; use crate::hash::Hash; +use crate::marker::Destruct; mod iter; @@ -759,3 +760,452 @@ where (OneSidedRangeBound::EndInclusive, self.last) } } + +/// Computes the intersection of two ranges, returning the most specific range type possible. +/// +/// This trait is not implemented for all combinations, only the ones with a good +/// `Self::Intersection` type available. +/// +/// However, because `(Bound, Bound): RangeIntersect`, you can always use +/// `a.into_bounds().intersect(b.into_bounds())` for any two [`IntoBounds`] types if needed. +/// +/// # Examples +/// +/// ``` +/// #![feature(range_intersect)] +/// use core::range::{Range, RangeFrom, RangeInclusive, RangeIntersect}; +/// +/// assert_eq!( +/// Range::from(-12..387).intersect(Range::from(0..256)), +/// Range::from(0..256), +/// ); +/// assert_eq!( +/// RangeFrom::from(3..).intersect(..5), +/// Range::from(3..5), +/// ); +/// assert_eq!( +/// RangeInclusive::from(1..=9).intersect(RangeFrom::from(5..)), +/// RangeInclusive::from(5..=9), +/// ); +/// ``` +/// +/// Combine with `is_empty` to determine if two ranges overlap: +/// +/// ``` +/// #![feature(range_intersect)] +/// use core::range::{Range, RangeFrom, RangeIntersect}; +/// +/// assert!(!RangeFrom::from(3..).intersect(..5).is_empty()); +/// assert!(!Range::from(-12..387).intersect(Range::from(0..256)).is_empty()); +/// assert!(Range::from(1..5).intersect(RangeFrom::from(6..)).is_empty()); +/// ``` +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +pub const trait RangeIntersect: Sized { + /// The resulting range type of the intersection. + #[unstable(feature = "range_intersect", issue = "165428")] + type Intersection; + + /// Computes the intersection of `self` and `rhs`. + #[unstable(feature = "range_intersect", issue = "165428")] + #[must_use] + fn intersect(self, rhs: Rhs) -> Self::Intersection; +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for (Bound, Bound) +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = Self; + + #[inline] + fn intersect(self, rhs: Self) -> Self::Intersection { + let (self_start, self_end) = self; + let (other_start, other_end) = rhs; + + let start = match (self_start, other_start) { + (Included(a), Included(b)) => Included(Ord::max(a, b)), + (Excluded(a), Excluded(b)) => Excluded(Ord::max(a, b)), + (Unbounded, Unbounded) => Unbounded, + + (x, Unbounded) | (Unbounded, x) => x, + + (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => { + if i > e { + Included(i) + } else { + Excluded(e) + } + } + }; + let end = match (self_end, other_end) { + (Included(a), Included(b)) => Included(Ord::min(a, b)), + (Excluded(a), Excluded(b)) => Excluded(Ord::min(a, b)), + (Unbounded, Unbounded) => Unbounded, + + (x, Unbounded) | (Unbounded, x) => x, + + (Included(i), Excluded(e)) | (Excluded(e), Included(i)) => { + if i < e { + Included(i) + } else { + Excluded(e) + } + } + }; + + (start, end) + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for Range +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = Range; + + #[inline] + fn intersect(self, rhs: Self) -> Self::Intersection { + Range { start: Ord::max(self.start, rhs.start), end: Ord::min(self.end, rhs.end) } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for Range +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = Range; + + #[inline] + fn intersect(self, rhs: RangeFrom) -> Self::Intersection { + Range { start: Ord::max(self.start, rhs.start), end: self.end } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for Range +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = Range; + + #[inline] + fn intersect(self, rhs: RangeTo) -> Self::Intersection { + Range { start: self.start, end: Ord::min(self.end, rhs.end) } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for Range { + type Intersection = Range; + + #[inline] + fn intersect(self, _rhs: RangeFull) -> Self::Intersection { + self + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFrom +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = Range; + + #[inline] + fn intersect(self, rhs: Range) -> Self::Intersection { + Range { start: Ord::max(self.start, rhs.start), end: rhs.end } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeFrom +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = RangeFrom; + + #[inline] + fn intersect(self, rhs: Self) -> Self::Intersection { + RangeFrom { start: Ord::max(self.start, rhs.start) } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFrom { + type Intersection = Range; + + #[inline] + fn intersect(self, rhs: RangeTo) -> Self::Intersection { + Range { start: self.start, end: rhs.end } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeFrom { + type Intersection = RangeFrom; + + #[inline] + fn intersect(self, _rhs: RangeFull) -> Self::Intersection { + self + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFrom +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, rhs: RangeInclusive) -> Self::Intersection { + RangeInclusive { start: Ord::max(self.start, rhs.start), last: rhs.last } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFrom { + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, rhs: RangeToInclusive) -> Self::Intersection { + RangeInclusive { start: self.start, last: rhs.last } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeTo +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = Range; + + #[inline] + fn intersect(self, rhs: Range) -> Self::Intersection { + Range { start: rhs.start, end: Ord::min(self.end, rhs.end) } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeTo { + type Intersection = Range; + + #[inline] + fn intersect(self, rhs: RangeFrom) -> Self::Intersection { + Range { start: rhs.start, end: self.end } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeTo +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = RangeTo; + + #[inline] + fn intersect(self, rhs: Self) -> Self::Intersection { + RangeTo { end: Ord::min(self.end, rhs.end) } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeTo { + type Intersection = RangeTo; + + #[inline] + fn intersect(self, _rhs: RangeFull) -> Self::Intersection { + self + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFull { + type Intersection = Range; + + #[inline] + fn intersect(self, rhs: Range) -> Self::Intersection { + rhs + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFull { + type Intersection = RangeFrom; + + #[inline] + fn intersect(self, rhs: RangeFrom) -> Self::Intersection { + rhs + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFull { + type Intersection = RangeTo; + + #[inline] + fn intersect(self, rhs: RangeTo) -> Self::Intersection { + rhs + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeFull { + type Intersection = RangeFull; + + #[inline] + fn intersect(self, _rhs: RangeFull) -> Self::Intersection { + RangeFull + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFull { + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, rhs: RangeInclusive) -> Self::Intersection { + rhs + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeFull { + type Intersection = RangeToInclusive; + + #[inline] + fn intersect(self, rhs: RangeToInclusive) -> Self::Intersection { + rhs + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeInclusive +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, rhs: RangeFrom) -> Self::Intersection { + RangeInclusive { start: Ord::max(self.start, rhs.start), last: self.last } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeInclusive { + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, _rhs: RangeFull) -> Self::Intersection { + self + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeInclusive +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, rhs: Self) -> Self::Intersection { + RangeInclusive { + start: Ord::max(self.start, rhs.start), + last: Ord::min(self.last, rhs.last), + } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeInclusive +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, rhs: RangeToInclusive) -> Self::Intersection { + RangeInclusive { start: self.start, last: Ord::min(self.last, rhs.last) } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeToInclusive { + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, rhs: RangeFrom) -> Self::Intersection { + RangeInclusive { start: rhs.start, last: self.last } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeToInclusive { + type Intersection = RangeToInclusive; + + #[inline] + fn intersect(self, _rhs: RangeFull) -> Self::Intersection { + self + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect> for RangeToInclusive +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = RangeInclusive; + + #[inline] + fn intersect(self, rhs: RangeInclusive) -> Self::Intersection { + RangeInclusive { start: rhs.start, last: Ord::min(self.last, rhs.last) } + } +} + +#[unstable(feature = "range_intersect", issue = "165428")] +#[rustc_const_unstable(feature = "const_range", issue = "none")] +const impl RangeIntersect for RangeToInclusive +where + T: [const] Ord + [const] Destruct, +{ + type Intersection = RangeToInclusive; + + #[inline] + fn intersect(self, rhs: Self) -> Self::Intersection { + RangeToInclusive { last: Ord::min(self.last, rhs.last) } + } +} diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index be0162e9ccc5e..ca90bdb60efac 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -186,12 +186,14 @@ impl [T] { /// # Examples /// /// ``` - /// let x = &[0, 1, 2]; + /// let many = &[0, 1, 2]; + /// assert_eq!(many.split_first(), Some((&0, &[1, 2][..]))); /// - /// if let Some((first, elements)) = x.split_first() { - /// assert_eq!(first, &0); - /// assert_eq!(elements, &[1, 2]); - /// } + /// let one = &[42]; + /// assert_eq!(one.split_first(), Some((&42, &[][..]))); + /// + /// let none: &[i32] = &[]; + /// assert_eq!(none.split_first(), None); /// ``` #[stable(feature = "slice_splits", since = "1.5.0")] #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] @@ -206,14 +208,22 @@ impl [T] { /// # Examples /// /// ``` - /// let x = &mut [0, 1, 2]; + /// let many = &mut [0, 1, 2]; /// - /// if let Some((first, elements)) = x.split_first_mut() { + /// if let Some((first, rest)) = many.split_first_mut() { /// *first = 3; - /// elements[0] = 4; - /// elements[1] = 5; + /// rest[0] = 4; + /// rest[1] = 5; /// } - /// assert_eq!(x, &[3, 4, 5]); + /// assert_eq!(many, &[3, 4, 5]); + /// + /// let mut one = [42]; + /// let (first, rest) = one.split_first_mut().unwrap(); + /// assert_eq!(*first, 42); + /// assert!(rest.is_empty()); + /// + /// let none: &mut [i32] = &mut []; + /// assert!(none.split_first_mut().is_none()); /// ``` #[stable(feature = "slice_splits", since = "1.5.0")] #[rustc_const_stable(feature = "const_slice_first_last", since = "1.83.0")] @@ -228,12 +238,14 @@ impl [T] { /// # Examples /// /// ``` - /// let x = &[0, 1, 2]; + /// let many = &[0, 1, 2]; + /// assert_eq!(many.split_last(), Some((&2, &[0, 1][..]))); /// - /// if let Some((last, elements)) = x.split_last() { - /// assert_eq!(last, &2); - /// assert_eq!(elements, &[0, 1]); - /// } + /// let one = &[42]; + /// assert_eq!(one.split_last(), Some((&42, &[][..]))); + /// + /// let none: &[i32] = &[]; + /// assert_eq!(none.split_last(), None); /// ``` #[stable(feature = "slice_splits", since = "1.5.0")] #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] @@ -248,14 +260,22 @@ impl [T] { /// # Examples /// /// ``` - /// let x = &mut [0, 1, 2]; + /// let many = &mut [0, 1, 2]; /// - /// if let Some((last, elements)) = x.split_last_mut() { + /// if let Some((last, rest)) = many.split_last_mut() { /// *last = 3; - /// elements[0] = 4; - /// elements[1] = 5; + /// rest[0] = 4; + /// rest[1] = 5; /// } - /// assert_eq!(x, &[4, 5, 3]); + /// assert_eq!(many, &[4, 5, 3]); + /// + /// let mut one = [42]; + /// let (last, rest) = one.split_last_mut().unwrap(); + /// assert_eq!(*last, 42); + /// assert!(rest.is_empty()); + /// + /// let none: &mut [i32] = &mut []; + /// assert!(none.split_last_mut().is_none()); /// ``` #[stable(feature = "slice_splits", since = "1.5.0")] #[rustc_const_stable(feature = "const_slice_first_last", since = "1.83.0")] diff --git a/library/coretests/tests/fmt/mod.rs b/library/coretests/tests/fmt/mod.rs index 67ba49db4d919..016c57e69944d 100644 --- a/library/coretests/tests/fmt/mod.rs +++ b/library/coretests/tests/fmt/mod.rs @@ -2,6 +2,9 @@ mod builders; mod float; mod num; +use core::fmt; +use core::fmt::Write; + #[test] fn test_lifetime() { // Trigger all different forms of expansion, @@ -199,3 +202,74 @@ fn formatting_options_flags() { } } } + +#[test] +fn test_options_as_specifier() { + struct F; + impl fmt::Display for F { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.options().write_fmt_specifier(f, false) + } + } + impl fmt::Debug for F { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self, f) + } + } + + // LowerExp (arbitrary choice) prints in string format + impl fmt::LowerExp for F { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_char('"')?; + f.options().write_fmt_specifier(f, true)?; + f.write_char('"')?; + Ok(()) + } + } + + let f = F; + + // Default + assert_eq!(format!("{f}"), ""); + + // Width + assert_eq!(format!("{f:1}"), "1"); + + // Fill and align + assert_eq!(format!("{f:<}"), "<"); + assert_eq!(format!("{f:^}"), "^"); + assert_eq!(format!("{f:>}"), ">"); + assert_eq!(format!("{f:<5}"), "<5"); + assert_eq!(format!("{f:^5}"), "^5"); + assert_eq!(format!("{f:>5}"), ">5"); + assert_eq!(format!("{f:x>5}"), "x>5"); + + // Sign and alternates + assert_eq!(format!("{f:+}"), "+"); + assert_eq!(format!("{f:-}"), "-"); + assert_eq!(format!("{f:#}"), "#"); + assert_eq!(format!("{f:0}"), "0"); + + // Precision + assert_eq!(format!("{f:.1}"), ".1"); + + // Hex within other format types + assert_eq!(format!("{f:x?}"), "x"); + assert_eq!(format!("{f:X?}"), "X"); + + // Hodgepodge + assert_eq!(format!("{f:#018}"), "#018"); + assert_eq!(format!("{f:0123}"), "0123"); + assert_eq!(format!("{f:-<5}"), "-<5"); + assert_eq!(format!("{f:+<05.2}"), "+<05.2"); + assert_eq!(format!("{f:x<+#065535.123X?}"), "x<+#065535.123X"); + + // String quoting is done by the lowerexp impl in our tests + assert_eq!(format!("{f:\"<5e}"), r#""\"<5""#); + assert_eq!(format!("{f:'<5e}"), r#""\'<5""#); + assert_eq!(format!("{f:\\<5e}"), r#""\\<5""#); + // Same thing, unescaped + assert_eq!(format!("{f:\"<5}"), r#""<5"#); + assert_eq!(format!("{f:'<5}"), r#"'<5"#); + assert_eq!(format!("{f:\\<5}"), r#"\<5"#); +} diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs index 3e79c88a116e3..224f316fcbc8f 100644 --- a/library/coretests/tests/lib.rs +++ b/library/coretests/tests/lib.rs @@ -105,6 +105,8 @@ #![feature(pointer_is_aligned_to)] #![feature(portable_simd)] #![feature(ptr_metadata)] +#![feature(range_intersect)] +#![feature(range_into_bounds)] #![feature(raw_os_error_ty)] #![feature(register_tool)] #![feature(rustc_attrs)] diff --git a/library/coretests/tests/ops.rs b/library/coretests/tests/ops.rs index 1cbc625959886..6c644d4d221a6 100644 --- a/library/coretests/tests/ops.rs +++ b/library/coretests/tests/ops.rs @@ -318,3 +318,86 @@ fn test_fmt() { assert_eq!(format!("{:?}", ..=1), "..=1"); assert_eq!(format!("{:?}", ..), ".."); } + +#[test] +fn test_range_intersect() { + use core::ops::Bound::{Excluded, Included, Unbounded}; + use core::ops::IntoBounds; + use core::range::{ + Range as NewRange, RangeFrom as NewRangeFrom, RangeInclusive as NewRangeInclusive, + RangeIntersect, RangeToInclusive as NewRangeToInclusive, + }; + + assert_eq!(NewRange::from(-12..387).intersect(NewRange::from(0..256)), NewRange::from(0..256)); + assert_eq!(NewRange::from(1..5).intersect(NewRangeFrom::from(3..)), NewRange::from(3..5)); + assert_eq!(NewRange::from(1..5).intersect(..3), NewRange::from(1..3)); + assert_eq!(NewRange::from(1..5).intersect(..), NewRange::from(1..5)); + + assert_eq!(NewRangeFrom::from(3..).intersect(NewRange::from(1..5)), NewRange::from(3..5)); + assert_eq!(NewRangeFrom::from(3..).intersect(NewRangeFrom::from(5..)), NewRangeFrom::from(5..)); + assert_eq!(NewRangeFrom::from(3..).intersect(..5), NewRange::from(3..5)); + assert_eq!(NewRangeFrom::from(3..).intersect(..), NewRangeFrom::from(3..)); + assert_eq!( + NewRangeFrom::from(3..).intersect(NewRangeInclusive::from(1..=5)), + NewRangeInclusive::from(3..=5), + ); + assert_eq!( + NewRangeFrom::from(3..).intersect(NewRangeToInclusive::from(..=5)), + NewRangeInclusive::from(3..=5), + ); + + assert_eq!((..5).intersect(NewRange::from(1..8)), NewRange::from(1..5)); + assert_eq!((..5).intersect(NewRangeFrom::from(3..)), NewRange::from(3..5)); + assert_eq!((..5).intersect(..3), ..3); + assert_eq!((..5).intersect(..), ..5); + + assert_eq!((..).intersect(NewRange::from(1..5)), NewRange::from(1..5)); + assert_eq!((..).intersect(NewRangeFrom::from(3..)), NewRangeFrom::from(3..)); + assert_eq!((..).intersect(..5), ..5); + assert_eq!((..).intersect(..), ..); + assert_eq!((..).intersect(NewRangeInclusive::from(1..=5)), NewRangeInclusive::from(1..=5)); + assert_eq!((..).intersect(NewRangeToInclusive::from(..=5)), NewRangeToInclusive::from(..=5)); + + assert_eq!( + NewRangeInclusive::from(1..=9).intersect(NewRangeFrom::from(3..)), + NewRangeInclusive::from(3..=9), + ); + assert_eq!(NewRangeInclusive::from(1..=9).intersect(..), NewRangeInclusive::from(1..=9)); + assert_eq!( + NewRangeInclusive::from(1..=9).intersect(NewRangeInclusive::from(3..=5)), + NewRangeInclusive::from(3..=5), + ); + assert_eq!( + NewRangeInclusive::from(1..=9).intersect(NewRangeToInclusive::from(..=5)), + NewRangeInclusive::from(1..=5), + ); + + assert_eq!( + NewRangeToInclusive::from(..=9).intersect(NewRangeFrom::from(3..)), + NewRangeInclusive::from(3..=9), + ); + assert_eq!(NewRangeToInclusive::from(..=9).intersect(..), NewRangeToInclusive::from(..=9)); + assert_eq!( + NewRangeToInclusive::from(..=9).intersect(NewRangeInclusive::from(3..=12)), + NewRangeInclusive::from(3..=9), + ); + assert_eq!( + NewRangeToInclusive::from(..=9).intersect(NewRangeToInclusive::from(..=5)), + NewRangeToInclusive::from(..=5), + ); + + // Fallback via into_bounds() for combinations without a concrete range type + assert_eq!((1..=9).into_bounds().intersect((0..10).into_bounds()), (Included(1), Included(9))); + assert_eq!( + (7..=13).into_bounds().intersect((8..13).into_bounds()), + (Included(8), Excluded(13)), + ); + assert_eq!( + (Excluded(1), Included(9)).intersect((Included(2), Excluded(9))), + (Included(2), Excluded(9)), + ); + assert_eq!( + (Unbounded::, Unbounded).intersect((Included(1), Excluded(5))), + (Included(1), Excluded(5)), + ); +} diff --git a/library/profiler_builtins/Cargo.toml b/library/profiler_builtins/Cargo.toml index 00a535544bf47..f9c34bf56ff4d 100644 --- a/library/profiler_builtins/Cargo.toml +++ b/library/profiler_builtins/Cargo.toml @@ -9,6 +9,8 @@ bench = false doc = false [dependencies] +core = { path = "../core" } +compiler_builtins = { path = "../compiler-builtins/compiler-builtins", features = ["compiler-builtins"] } [build-dependencies] # Pinned so `cargo update` bumps don't cause breakage diff --git a/library/profiler_builtins/src/lib.rs b/library/profiler_builtins/src/lib.rs index a258f7d31a191..68b6058db978c 100644 --- a/library/profiler_builtins/src/lib.rs +++ b/library/profiler_builtins/src/lib.rs @@ -1,12 +1,11 @@ // tidy-alphabetical-start #![allow(internal_features)] -#![feature(no_core)] #![feature(profiler_runtime)] #![feature(staged_api)] // tidy-alphabetical-end // Other attributes: -#![no_core] +#![no_std] #![profiler_runtime] #![unstable( feature = "profiler_runtime_lib", diff --git a/library/std/src/fs.rs b/library/std/src/fs.rs index d75107616a283..6f05f6246ad86 100644 --- a/library/std/src/fs.rs +++ b/library/std/src/fs.rs @@ -2035,16 +2035,14 @@ impl OpenOptions { /// Sets the option for the append mode. /// - /// This option, when true, means that writes will append to a file instead - /// of overwriting previous contents. - /// Note that setting `.write(true).append(true)` has the same effect as - /// setting only `.append(true)`. + /// This option, when true, means that writes will append to a file instead of overwriting + /// previous contents. The `write` setting is ignored when `append` is true, i.e., + /// `.write(true).append(true).open(...)` has the same effect as `.append(true).open(...)`. /// /// Append mode guarantees that writes will be positioned at the current end of file, /// even when there are other processes or threads appending to the same file. This is - /// unlike [seek]\([SeekFrom]::[End]\(0)) followed by `write()`, which - /// has a race between seeking and writing during which another writer can write, with - /// our `write()` overwriting their data. + /// a race-free version of [seek]\([SeekFrom]::[End]\(0)) followed by `write()`, + /// working correctly even if there are concurrent writers. /// /// Keep in mind that this does not necessarily guarantee that data appended by /// different processes or threads does not interleave. The amount of data accepted a @@ -2872,6 +2870,7 @@ impl DirEntry { /// # Examples /// /// ``` + /// # if cfg!(all(windows, skip_unsupported_miri_tests)) { return; } /// use std::fs; /// /// if let Ok(entries) = fs::read_dir(".") { @@ -2909,6 +2908,7 @@ impl DirEntry { /// # Examples /// /// ``` + /// # if cfg!(all(windows, skip_unsupported_miri_tests)) { return; } /// use std::fs; /// /// if let Ok(entries) = fs::read_dir(".") { @@ -2942,6 +2942,7 @@ impl DirEntry { /// # Examples /// /// ``` + /// # if cfg!(all(windows, skip_unsupported_miri_tests)) { return; } /// use std::fs; /// /// if let Ok(entries) = fs::read_dir(".") { 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/os/unix/net/addr.rs b/library/std/src/os/unix/net/addr.rs index e5fcb93b88308..f4567959f0931 100644 --- a/library/std/src/os/unix/net/addr.rs +++ b/library/std/src/os/unix/net/addr.rs @@ -80,6 +80,7 @@ enum AddressKind<'a> { /// #[cfg_attr(target_family = "unix", doc = "```")] #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")] +/// # if cfg!(skip_unsupported_miri_tests) { return; } /// use std::os::unix::net::UnixListener; /// /// let socket = match UnixListener::bind("/tmp/sock") { @@ -204,6 +205,7 @@ impl SocketAddr { /// use std::os::unix::net::UnixDatagram; /// /// fn main() -> std::io::Result<()> { + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// let socket = UnixDatagram::unbound()?; /// let addr = socket.local_addr().expect("`UnixListener::local_addr` should not fail"); /// assert_eq!(addr.is_unnamed(), true); @@ -242,6 +244,7 @@ impl SocketAddr { /// use std::os::unix::net::UnixDatagram; /// /// fn main() -> std::io::Result<()> { + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// let socket = UnixDatagram::unbound()?; /// let addr = socket.local_addr().expect("`UnixListener::local_addr` should not fail"); /// assert_eq!(addr.as_pathname(), None); diff --git a/library/std/src/os/unix/net/datagram.rs b/library/std/src/os/unix/net/datagram.rs index ce5654b5576c7..0aea5115f042f 100644 --- a/library/std/src/os/unix/net/datagram.rs +++ b/library/std/src/os/unix/net/datagram.rs @@ -722,6 +722,7 @@ impl UnixDatagram { /// use std::time::Duration; /// /// fn main() -> std::io::Result<()> { + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// let sock = UnixDatagram::unbound()?; /// sock.set_read_timeout(Some(Duration::new(1, 0))) /// .expect("`UnixDatagram::set_read_timeout` should not fail"); @@ -769,6 +770,7 @@ impl UnixDatagram { /// use std::time::Duration; /// /// fn main() -> std::io::Result<()> { + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// let sock = UnixDatagram::unbound()?; /// sock.set_write_timeout(Some(Duration::new(1, 0))) /// .expect("`UnixDatagram::set_write_timeout` should not fail"); @@ -809,6 +811,7 @@ impl UnixDatagram { /// use std::time::Duration; /// /// fn main() -> std::io::Result<()> { + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// let sock = UnixDatagram::unbound()?; /// sock.set_read_timeout(Some(Duration::new(1, 0))) /// .expect("`UnixDatagram::set_read_timeout` should not fail"); @@ -832,6 +835,7 @@ impl UnixDatagram { /// use std::time::Duration; /// /// fn main() -> std::io::Result<()> { + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// let sock = UnixDatagram::unbound()?; /// sock.set_write_timeout(Some(Duration::new(1, 0))) /// .expect("`UnixDatagram::set_write_timeout` should not fail"); @@ -854,6 +858,7 @@ impl UnixDatagram { /// use std::os::unix::net::UnixDatagram; /// /// fn main() -> std::io::Result<()> { + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// let sock = UnixDatagram::unbound()?; /// sock.set_nonblocking(true).expect("`UnixDatagram::set_nonblocking` should not fail"); /// Ok(()) diff --git a/library/std/src/os/unix/process.rs b/library/std/src/os/unix/process.rs index 1aa6076f3a7ed..f555e5e686ae2 100644 --- a/library/std/src/os/unix/process.rs +++ b/library/std/src/os/unix/process.rs @@ -818,6 +818,7 @@ impl From for process::ChildStderr { /// #[cfg_attr(target_family = "unix", doc = "```")] #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")] +/// # if cfg!(skip_unsupported_miri_tests) { return; } /// use std::os::unix::process; /// let parent = process::parent_id(); /// println!("The parent process has ID {}", parent); diff --git a/library/std/src/os/windows/process.rs b/library/std/src/os/windows/process.rs index 422e5f172229d..6be974443ff68 100644 --- a/library/std/src/os/windows/process.rs +++ b/library/std/src/os/windows/process.rs @@ -334,6 +334,7 @@ pub impl(self) trait CommandExt { #[cfg_attr(windows, doc = "```")] #[cfg_attr(not(windows), doc = "```ignore (needs windows)")] /// #![feature(windows_process_extensions_raw_attribute)] + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// use std::os::windows::io::AsRawHandle; /// use std::os::windows::process::{CommandExt, ProcThreadAttributeList}; /// use std::process::Command; @@ -614,6 +615,7 @@ impl<'a> ProcThreadAttributeListBuilder<'a> { #[cfg_attr(all(windows, target_vendor = "win7"), doc = "```no_run")] #[cfg_attr(all(windows, not(target_vendor = "win7")), doc = "```")] /// #![feature(windows_process_extensions_raw_attribute)] + /// # if cfg!(skip_unsupported_miri_tests) { return Ok(()); } /// use std::ffi::c_void; /// use std::os::windows::process::{CommandExt, ProcThreadAttributeList}; /// use std::os::windows::raw::HANDLE; diff --git a/library/std/src/process.rs b/library/std/src/process.rs index fb3b72607e4d8..5bb8e3c73ec4c 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -550,7 +550,7 @@ impl fmt::Debug for ChildStderr { /// to be changed (for example, by adding arguments) prior to spawning: /// /// ``` -/// # if cfg!(not(all(target_vendor = "apple", not(target_os = "macos")))) { +/// # if cfg!(all(not(all(target_vendor = "apple", not(target_os = "macos"))), not(skip_unsupported_miri_tests))) { /// use std::process::Command; /// /// let output = if cfg!(target_os = "windows") { @@ -1249,6 +1249,7 @@ impl Command { /// # Examples /// /// ``` + /// # if cfg!(all(windows, skip_unsupported_miri_tests)) { return; } /// use std::ffi::OsStr; /// use std::process::Command; /// @@ -1283,6 +1284,7 @@ impl Command { /// /// ``` /// #![feature(command_resolved_envs)] + /// # if cfg!(all(windows, skip_unsupported_miri_tests)) { return; } /// use std::process::Command; /// use std::ffi::{OsString, OsStr}; /// use std::env; @@ -1509,7 +1511,7 @@ impl Output { /// ``` /// # #![allow(unused_features)] /// #![feature(exit_status_error)] - /// # #[cfg(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos")))))] { + /// # #[cfg(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(skip_unsupported_miri_tests)))] { /// use std::process::Command; /// assert!(Command::new("false").output().unwrap().exit_ok().is_err()); /// # } @@ -1856,7 +1858,7 @@ impl From for Stdio { /// # Ok(()) /// # } /// # - /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))))) { + /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(skip_unsupported_miri_tests))) { /// # test().unwrap(); /// # } /// ``` @@ -1885,7 +1887,7 @@ impl From for Stdio { /// # Ok(()) /// # } /// # - /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))))) { + /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(skip_unsupported_miri_tests))) { /// # test().unwrap(); /// # } /// ``` @@ -1957,7 +1959,7 @@ impl ExitStatus { /// /// ``` /// #![feature(exit_status_error)] - /// # if cfg!(all(unix, not(all(target_vendor = "apple", not(target_os = "macos"))))) { + /// # if cfg!(all(unix, not(all(target_vendor = "apple", not(target_os = "macos"))), not(skip_unsupported_miri_tests))) { /// use std::process::Command; /// /// let status = Command::new("ls") @@ -2060,7 +2062,7 @@ impl fmt::Display for ExitStatus { /// /// ``` /// #![feature(exit_status_error)] -/// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))))) { +/// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(skip_unsupported_miri_tests))) { /// use std::process::{Command, ExitStatusError}; /// /// fn run(cmd: &str) -> Result<(), ExitStatusError> { @@ -2104,7 +2106,7 @@ impl ExitStatusError { /// /// ``` /// #![feature(exit_status_error)] - /// # #[cfg(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos")))))] { + /// # #[cfg(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(skip_unsupported_miri_tests)))] { /// use std::process::Command; /// /// let bad = Command::new("false").status().unwrap().exit_ok().unwrap_err(); @@ -2129,7 +2131,7 @@ impl ExitStatusError { /// ``` /// #![feature(exit_status_error)] /// - /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))))) { + /// # if cfg!(all(unix, not(target_os = "android"), not(all(target_vendor = "apple", not(target_os = "macos"))), not(skip_unsupported_miri_tests))) { /// use std::num::NonZero; /// use std::process::Command; /// diff --git a/library/std/src/sys/alloc/windows.rs b/library/std/src/sys/alloc/windows.rs index a62a634857d1e..b80728956b6f3 100644 --- a/library/std/src/sys/alloc/windows.rs +++ b/library/std/src/sys/alloc/windows.rs @@ -192,7 +192,11 @@ pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) { // SAFETY: Because of the contract of `System`, `ptr` is guaranteed to be non-null // and have a header readable directly before it. - unsafe { ptr::read((ptr as *mut Header).sub(1)).0 } + let block_ptr = unsafe { ptr::read((ptr as *mut Header).sub(1)).0 }; + // Always deallocate using the provenance that was passed to us, not what we stored in + // the header. The passed-in provenance may be protected, for example because it is from + // a Box argument to mem::drop. + ptr.with_addr(block_ptr.addr()) } }; 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/src/bootstrap/mk/Makefile.in b/src/bootstrap/mk/Makefile.in index 07412657f8687..a4e38ce894a9f 100644 --- a/src/bootstrap/mk/Makefile.in +++ b/src/bootstrap/mk/Makefile.in @@ -80,8 +80,7 @@ check-aux: $(BOOTSTRAP) miri --stage 2 \ library/std \ $(BOOTSTRAP_ARGS) \ - --target x86_64-unknown-linux-gnu,aarch64-apple-darwin,i686-pc-windows-msvc \ - --tests # skip all doctests, they are not using skip_unsupported_miri_tests + --target x86_64-unknown-linux-gnu,aarch64-apple-darwin,i686-pc-windows-msvc dist: $(Q)$(BOOTSTRAP) dist $(BOOTSTRAP_ARGS) distcheck: diff --git a/src/doc/unstable-book/src/language-features/asm-nonnull-inputs.md b/src/doc/unstable-book/src/language-features/asm-nonnull-inputs.md new file mode 100644 index 0000000000000..ebe60cdf17baa --- /dev/null +++ b/src/doc/unstable-book/src/language-features/asm-nonnull-inputs.md @@ -0,0 +1,25 @@ +# `asm_nonnull_inputs` + +The tracking issue for this feature is: [#166132] + +[#166132]: https://github.com/rust-lang/rust/issues/166132 + +------------------------ + +This feature allows thin `NonNull` pointers to be used as input +operands in inline assembly. + +Example: +```rust,ignore (partial-example, x86-only) +let mut x = 1; +let p = core::ptr::NonNull::from_mut(&mut x); + +unsafe { + core::arch::asm!( + "mov dword ptr [{}], 2", + in(reg) p, + ) +}; + +assert_eq!(x, 2); +``` 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..a3d001eec03d6 100644 --- a/src/tools/miri/src/concurrency/thread.rs +++ b/src/tools/miri/src/concurrency/thread.rs @@ -668,6 +668,25 @@ 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( 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/intrinsics/mod.rs b/src/tools/miri/src/intrinsics/mod.rs index d6e0e24e8ab15..bbd05b64f7f3e 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 { diff --git a/src/tools/miri/src/intrinsics/x86/avx2.rs b/src/tools/miri/src/intrinsics/x86/avx2.rs index fe83e95f4c155..46f4865ca310c 100644 --- a/src/tools/miri/src/intrinsics/x86/avx2.rs +++ b/src/tools/miri/src/intrinsics/x86/avx2.rs @@ -75,7 +75,9 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { 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); + // 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, 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..40d666424c07f 100644 --- a/src/tools/miri/src/intrinsics/x86/mod.rs +++ b/src/tools/miri/src/intrinsics/x86/mod.rs @@ -740,7 +740,7 @@ 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)?; @@ -750,20 +750,29 @@ fn conditional_dot_product<'tcx>( 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)?; 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..17a9d25130352 100644 --- a/src/tools/miri/src/shims/foreign_items.rs +++ b/src/tools/miri/src/shims/foreign_items.rs @@ -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/time.rs b/src/tools/miri/src/shims/time.rs index 97127d8e34a97..9099356f74e97 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,23 @@ 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(); + ecx.read_scalar(&timep)?.to_int(timep.layout.size)?.try_into().unwrap(); 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 +159,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 +177,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 +200,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 +214,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 +236,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 +257,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 +292,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 +307,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 +348,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 +381,28 @@ 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 clockid_t_size = ecx.libc_ty_layout("clockid_t").size; - 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_int(clockid_t_size)?; + 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("CLOCK_MONOTONIC").to_int(clockid_t_size)? { 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 +413,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 +431,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 +458,11 @@ 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_scalar(&sec_field)?.to_int(sec_field.layout.size)?; + let nsec_field = ecx.project_field_named(tp, "tv_nsec")?; + let nsec = ecx.read_scalar(&nsec_field)?.to_int(nsec_field.layout.size)?; // 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,12 +485,12 @@ 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 sec_field = ecx.project_field_named(tp, "tv_sec")?; + let sec = ecx.read_scalar(&sec_field)?.to_int(sec_field.layout.size)?; - let usec_field = this.project_field_named(tp, "tv_usec")?; - let usec = this.read_scalar(&usec_field)?.to_int(usec_field.layout.size)?; + let usec_field = ecx.project_field_named(tp, "tv_usec")?; + let usec = ecx.read_scalar(&usec_field)?.to_int(usec_field.layout.size)?; interp_ok(try { // tv_sec must be non-negative. diff --git a/src/tools/miri/src/shims/unix/foreign_items.rs b/src/tools/miri/src/shims/unix/foreign_items.rs index c6169fb7fdfe8..38c94bd3bc9df 100644 --- a/src/tools/miri/src/shims/unix/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/foreign_items.rs @@ -89,21 +89,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 +114,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_scalar(offset)?.to_int(offset.layout.size)?; + 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_scalar(offset)?.to_int(offset.layout.size)?; 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 +341,988 @@ 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)?; + let result = ecx.mkdir(path, mode)?; + ecx.write_scalar(result, 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_scalar(offset)?.to_int(offset.layout.size)?; + 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_scalar(length)?.to_int(length.layout.size)?; + 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_scalar(offset)?.to_int(offset.layout.size)?; + ecx.read_scalar(len)?.to_int(len.layout.size)?; + 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(); + 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 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( + let [socket, level, option_name, option_value, option_len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, i32, i32, *_, *_) -> 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( + let [node, service, hints, res] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, *_, *_, **_) -> 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 + let [res] = &ecx .check_shim_sig(shim_sig!(extern "C" fn(*_) -> ()), (link_name, abi, args))?; - this.freeaddrinfo(res)?; + 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_scalar(offset)?.to_int(ecx.libc_ty_layout("off_t").size)?; + 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_scalar(Scalar::from_uint(key, key_place.layout.size), &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_scalar(key)?.to_bits(key.layout.size)?; + 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_scalar(key)?.to_bits(key.layout.size)?; + 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_scalar(key)?.to_bits(key.layout.size)?; + 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)?; + let res = ecx.pthread_self()?; + ecx.write_scalar(res, 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 +1330,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 +1382,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 +1422,80 @@ 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), + let guard_size = ecx.deref_pointer(guard_size)?; + ecx.write_scalar( + Scalar::from_uint(ecx.machine.page_size, guard_size.layout.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)?; - } - - "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)?; + ecx.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()), + ecx.write_scalar( + Scalar::from_uint(ecx.machine.stack_addr, ecx.pointer_size()), &addr_place, )?; - this.write_scalar( - Scalar::from_uint(this.machine.stack_size, this.pointer_size()), + ecx.write_scalar( + Scalar::from_uint(ecx.machine.stack_size, ecx.pointer_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 +1504,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..9207f44f62a4b 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( + ecx.read_scalar(thread)?, + ecx.read_scalar(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( + ecx.read_scalar(thread)?, + ecx.read_scalar(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..4699c064bed0e 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(); @@ -621,7 +679,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 +716,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 { @@ -808,32 +872,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}") }; - interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result.map(|()| 0))?)) + + 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(ecx.try_unwrap_io_result(result.map(|()| 0))?)) } fn symlink( @@ -1369,22 +1466,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))?)) } 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..c3c5204ba3dd6 100644 --- a/src/tools/miri/src/shims/unix/linux/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/linux/foreign_items.rs @@ -359,11 +359,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/macos/foreign_items.rs b/src/tools/miri/src/shims/unix/macos/foreign_items.rs index 875abab202c6b..0f8a3a5a3e3f9 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,208 @@ 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)?; + let stack_addr = Scalar::from_uint(ecx.machine.stack_addr, ecx.pointer_size()); + ecx.write_scalar(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)?; + let stack_size = Scalar::from_uint(ecx.machine.stack_size, ecx.pointer_size()); + ecx.write_scalar(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 +240,25 @@ 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( + let thread = ecx.pthread_self()?; + let res = match ecx.pthread_setname_np( thread, - this.read_scalar(name)?, - this.eval_libc("MAXTHREADNAMESIZE").to_target_usize(this)?, + ecx.read_scalar(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 +271,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( + ecx.read_scalar(thread)?, + ecx.read_scalar(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 +308,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 +323,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 +338,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 +436,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/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..21b11e8ea8178 100644 --- a/src/tools/miri/src/shims/unix/poll.rs +++ b/src/tools/miri/src/shims/unix/poll.rs @@ -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..a67bd868620da 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, @@ -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,32 @@ 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_ptr = ecx.read_pointer(dest_addr)?; + let socklen_layout = ecx.libc_ty_layout("socklen_t"); let dest_addr_len_int = - this.read_scalar(dest_addr_len)?.to_uint(socklen_layout.size)?; + ecx.read_scalar(dest_addr_len)?.to_uint(socklen_layout.size)?; // 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 +532,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 +545,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 +573,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 +603,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 +630,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 +647,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 +669,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 +713,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 Some(option_len) = ecx.read_socklen(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), } } @@ -755,42 +754,42 @@ 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 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_ptr = ecx.read_pointer(option_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")); }; - 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_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 socklen_layout = ecx.libc_ty_layout("socklen_t"); + let option_len_ptr_mplace = ecx.ptr_to_mplace(option_len_ptr, socklen_layout); + let Some(option_len) = ecx.read_socklen(&option_len_ptr_mplace)? 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 +797,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,11 +816,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( + ecx.write_scalar( Scalar::from_uint(output_value_len.bytes(), socklen_layout.size), &option_len_ptr_mplace, )?; @@ -835,27 +834,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 +866,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 +909,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 +1292,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..2652f7887af97 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_ptr = ecx.read_pointer(hints)?; + let res_mplace = 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_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,34 @@ 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 hints_layout = ecx.libc_ty_layout("addrinfo"); + let hints_mplace = ecx.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_mplace, "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_mplace, "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_mplace, "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_mplace, "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,24 +102,24 @@ 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_mplace)?; interp_ok(Scalar::from_i32(0)) } fn freeaddrinfo(&mut self, res: &OpTy<'tcx>) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let res_ptr = this.read_pointer(res)?; + let res_ptr = ecx.read_pointer(res)?; - this.free_address_infos(res_ptr) + ecx.free_address_infos(res_ptr) } /// Read a `socklen_t` value. Returns `None` if it does not fit into a `u64`, e.g. if it @@ -149,17 +149,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 Some(address_len) = ecx.read_socklen(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 +171,32 @@ 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_layout = ecx.libc_ty_layout("sa_family_t"); + let family = ecx.read_scalar(&family_field)?.to_int(family_layout.size)?; // 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 +206,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 +282,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 +297,14 @@ 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 + let address_buffer_len: u64 = ecx .read_scalar(address_len_place)? .to_int(address_len_place.layout.size)? .try_into() .unwrap(); // 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 +313,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 +323,44 @@ 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 af_inet = ecx.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)?; + ecx.write_scalar(address_family, &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 +375,49 @@ 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 af_inet6 = ecx.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)?; + ecx.write_scalar(address_family, &sin6_family_field)?; - let sin6_port_field = this.project_field_named(&address_buffer, "sin6_port")?; + 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 +425,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 +436,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,63 +453,63 @@ 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()) } @@ -517,25 +517,25 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// 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(); + let ecx = self.eval_context_mut(); - if this.ptr_is_null(address_ptr)? { + if ecx.ptr_is_null(address_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 addrinfo_layout = ecx.libc_ty_layout("addrinfo"); + let addrinfo_mplace = ecx.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_mplace, "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_mplace, "ai_next")?; + let next_ptr = ecx.read_pointer(&next_field)?; + ecx.free_address_infos(next_ptr)?; - this.deallocate_ptr(address_ptr, None, MiriMemoryKind::SocketAddress.into())?; + ecx.deallocate_ptr(address_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..543fbf9655097 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( + ecx.read_scalar(thread)?, + ecx.read_scalar(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( + ecx.read_scalar(thread)?, + ecx.read_scalar(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( + let [node, service, hints, res] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(*_, *_, *_, **_) -> 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( + let [socket, level, option_name, option_value, option_len] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, i32, i32, *_, *_) -> 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..d91b73bc98f97 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,123 @@ 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>, + 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_info_place = this.deref_pointer(thread)?; + let thread_info_place = ecx.deref_pointer(thread)?; - let start_routine = this.read_pointer(start_routine)?; + let start_routine = ecx.read_pointer(start_routine)?; - let func_arg = this.read_immediate(arg)?; + let func_arg = ecx.read_immediate(arg)?; - this.start_regular_thread( + // 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); + } + + ecx.start_regular_thread( Some(thread_info_place), start_routine, ExternAbi::C { unwind: false }, func_arg, - this.machine.layouts.unit_ptr_mut, + ecx.machine.layouts.unit_ptr_mut, )?; - interp_ok(()) + ecx.write_scalar(Scalar::from_i32(0), dest) } fn pthread_join( @@ -43,22 +135,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_scalar(thread)?.to_int(ecx.libc_ty_layout("pthread_t").size)?; // 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,25 +158,25 @@ 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_scalar(thread)?.to_int(ecx.libc_ty_layout("pthread_t").size)?; // 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(); + let ecx = self.eval_context_ref(); - 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(); + interp_ok(Scalar::from_uint(thread_id.to_u32(), ecx.libc_ty_layout("pthread_t").size)) } /// Set the name of the specified thread. If the name including the null terminator @@ -98,16 +190,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { 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 { + let thread = thread.to_int(ecx.libc_ty_layout("pthread_t").size)?; + 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"); }; - let name = name.to_pointer(this); - let mut name = this.read_c_str(name)?.to_owned(); + let name = name.to_pointer(ecx); + 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 +210,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } } - this.set_thread_name(thread, name); + ecx.set_thread_name(thread, name); interp_ok(ThreadNameResult::Ok) } @@ -134,34 +226,34 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { 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 { + let thread = thread.to_int(ecx.libc_ty_layout("pthread_t").size)?; + 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"); }; - let name_out = name_out.to_pointer(this); - let len = len.to_target_usize(this)?; + let name_out = name_out.to_pointer(ecx); + 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..7ccab41a29a27 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,18 @@ 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_scalar(sv0, &sv)?; + ecx.write_scalar(sv1, &ecx.project_c_array_field(&sv, 1)?)?; interp_ok(Scalar::from_i32(0)) } @@ -643,16 +643,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 +671,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 +680,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 +691,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 +701,18 @@ 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_scalar(pipefd0, &pipefd)?; + ecx.write_scalar(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..5fbfa6adc4783 100644 --- a/src/tools/miri/src/shims/windows/foreign_items.rs +++ b/src/tools/miri/src/shims/windows/foreign_items.rs @@ -212,7 +212,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), 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/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..2a1eada1cf675 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,12 @@ 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 `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..b449669f8e87a 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,8 @@ warning: `readlink` was made to return an error due to isolation +warning: `unlinkat` 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: 3 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..aba1e5b6783af 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,7 @@ fn main() { test_openat(libc::openat); #[cfg(target_os = "linux")] test_openat(libc::openat64); + test_unlinkat(); #[cfg(target_os = "linux")] test_o_tmpfile_flag(); test_posix_mkstemp(); @@ -116,6 +120,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 +641,86 @@ 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_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 +736,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 +915,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, ) { 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..e8532e9bb9cd8 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 @@ -67,7 +67,7 @@ fn main() { /// 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(); + 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() }; @@ -105,7 +105,7 @@ 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(); + 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() }; @@ -138,7 +138,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 +193,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 +310,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 +417,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 +505,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 +542,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 +638,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 +820,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..e616db42f1d13 100644 --- a/src/tools/miri/tests/pass/float.rs +++ b/src/tools/miri/tests/pass/float.rs @@ -1245,14 +1245,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 +1303,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 +1336,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); 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..6ae5bfdb510eb 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()?; @@ -846,7 +872,16 @@ fn test_directory_handle() { assert_eq!(err.kind(), ErrorKind::AlreadyExists); fs::create_dir(dirname.join("subdir")).unwrap(); - let _subdir = dir.open_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/src/tools/tidy/src/walk.rs b/src/tools/tidy/src/walk.rs index 701450db5fb50..a1bccb3797c8f 100644 --- a/src/tools/tidy/src/walk.rs +++ b/src/tools/tidy/src/walk.rs @@ -64,6 +64,8 @@ pub fn walk_many( contents.clear(); let mut file = t!(File::open(entry.path()), entry.path()); t!(file.read_to_end(&mut contents), entry.path()); + drop(file); // Drop it early so that tempfiles can persist to this file on Windows + let contents_str = match std::str::from_utf8(&contents) { Ok(s) => s, Err(_) => return, // skip this file diff --git a/tests/assembly-llvm/asm/aarch64-types.rs b/tests/assembly-llvm/asm/aarch64-types.rs index da625b1211602..1c516a6541777 100644 --- a/tests/assembly-llvm/asm/aarch64-types.rs +++ b/tests/assembly-llvm/asm/aarch64-types.rs @@ -9,7 +9,7 @@ //@ [arm64ec] needs-llvm-components: aarch64 //@ compile-flags: -Zmerge-functions=disabled -#![feature(asm_experimental_reg, no_core, f16, f128, rustc_attrs)] +#![feature(asm_experimental_reg, asm_nonnull_inputs, no_core, f16, f128, rustc_attrs)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types)] @@ -19,6 +19,7 @@ use minicore::simd::*; use minicore::*; type ptr = *mut u8; +type nonnull = NonNull; #[cfg(target_feature = "sve")] #[rustc_scalable_vector(16)] @@ -113,11 +114,14 @@ pub unsafe fn issue_75761() { macro_rules! check { ($func:ident $ty:ident $class:ident $mov:literal $modifier:literal) => { - // FIXME(f128): Change back to `$func(x: $ty) -> $ty` once arm64ec can pass and return - // `f128` without LLVM erroring. + check!($func $ty:$ty $class $mov $modifier); + }; + ($func:ident $in_ty:ident:$out_ty:ident $class:ident $mov:literal $modifier:literal) => { + // FIXME(f128): Change back to `$func(x: $in_ty) -> $out_ty` once arm64ec + // can pass and return `f128` without LLVM erroring. // LLVM issue: #[no_mangle] - pub unsafe fn $func(inp: &$ty, out: &mut $ty) { + pub unsafe fn $func(inp: &$in_ty, out: &mut $out_ty) { let x = *inp; let y; asm!( @@ -151,9 +155,12 @@ macro_rules! check_sve { macro_rules! check_reg { ($func:ident $ty:ident $reg:tt $mov:literal) => { + check_reg!($func $ty:$ty $reg $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $reg:tt $mov:literal) => { // FIXME(f128): See FIXME in `check!` #[no_mangle] - pub unsafe fn $func(inp: &$ty, out: &mut $ty) { + pub unsafe fn $func(inp: &$in_ty, out: &mut $out_ty) { let x = *inp; let y; asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); @@ -229,6 +236,12 @@ check!(reg_f64 f64 reg "mov" ""); // CHECK: //NO_APP check!(reg_ptr ptr reg "mov" ""); +// CHECK-LABEL: {{("#)?}}reg_nonnull{{"?}} +// CHECK: //APP +// CHECK: mov x{{[0-9]+}}, x{{[0-9]+}} +// CHECK: //NO_APP +check!(reg_nonnull nonnull:ptr reg "mov" ""); + // CHECK-LABEL: {{("#)?}}vreg_i8{{"?}} // CHECK: //APP // CHECK: fmov s{{[0-9]+}}, s{{[0-9]+}} @@ -283,6 +296,12 @@ check!(vreg_f128 f128 vreg "fmov" "s"); // CHECK: //NO_APP check!(vreg_ptr ptr vreg "fmov" "s"); +// CHECK-LABEL: {{("#)?}}vreg_nonnull{{"?}} +// CHECK: //APP +// CHECK: fmov s{{[0-9]+}}, s{{[0-9]+}} +// CHECK: //NO_APP +check!(vreg_nonnull nonnull:ptr vreg "fmov" "s"); + // CHECK-LABEL: {{("#)?}}vreg_i8x8{{"?}} // CHECK: //APP // CHECK: fmov s{{[0-9]+}}, s{{[0-9]+}} @@ -415,6 +434,12 @@ check!(vreg_low16_f128 f128 vreg_low16 "fmov" "s"); // CHECK: //NO_APP check!(vreg_low16_ptr ptr vreg_low16 "fmov" "s"); +// CHECK-LABEL: {{("#)?}}vreg_low16_nonnull{{"?}} +// CHECK: //APP +// CHECK: fmov s{{[0-9]+}}, s{{[0-9]+}} +// CHECK: //NO_APP +check!(vreg_low16_nonnull nonnull:ptr vreg_low16 "fmov" "s"); + // CHECK-LABEL: {{("#)?}}vreg_low16_i8x8{{"?}} // CHECK: //APP // CHECK: fmov s{{[0-9]+}}, s{{[0-9]+}} @@ -637,6 +662,12 @@ check_reg!(x0_f64 f64 "x0" "mov"); // CHECK: //NO_APP check_reg!(x0_ptr ptr "x0" "mov"); +// CHECK-LABEL: {{("#)?}}x0_nonnull{{"?}} +// CHECK: //APP +// CHECK: mov x{{[0-9]+}}, x{{[0-9]+}} +// CHECK: //NO_APP +check_reg!(x0_nonnull nonnull:ptr "x0" "mov"); + // CHECK-LABEL: {{("#)?}}v0_i8{{"?}} // CHECK: //APP // CHECK: fmov s0, s0 @@ -747,6 +778,12 @@ pub unsafe fn p0_bool(inp: &svbool_t, pred: &svbool_t) -> svbool_t { // CHECK: //NO_APP check_reg!(v0_ptr ptr "s0" "fmov"); +// CHECK-LABEL: {{("#)?}}v0_nonnull{{"?}} +// CHECK: //APP +// CHECK: fmov s0, s0 +// CHECK: //NO_APP +check_reg!(v0_nonnull nonnull:ptr "s0" "fmov"); + // CHECK-LABEL: {{("#)?}}v0_i8x8{{"?}} // CHECK: //APP // CHECK: fmov s0, s0 diff --git a/tests/assembly-llvm/asm/arm-types.rs b/tests/assembly-llvm/asm/arm-types.rs index 4cf945c5959b6..16e27049ac6b9 100644 --- a/tests/assembly-llvm/asm/arm-types.rs +++ b/tests/assembly-llvm/asm/arm-types.rs @@ -9,7 +9,7 @@ //@[neon] filecheck-flags: --check-prefix d32 //@ needs-llvm-components: arm -#![feature(no_core, f16)] +#![feature(asm_nonnull_inputs, no_core, f16)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types)] @@ -19,6 +19,7 @@ use minicore::simd::*; use minicore::*; type ptr = *mut u8; +type nonnull = NonNull; extern "C" { fn extern_func(); @@ -54,8 +55,11 @@ pub unsafe fn issue_82052() { macro_rules! check { ($func:ident $ty:ident $class:ident $mov:literal) => { + check!($func $ty:$ty $class $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $class:ident $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " {}, {}"), out($class) y, in($class) x); y @@ -65,8 +69,11 @@ macro_rules! check { macro_rules! check_reg { ($func:ident $ty:ident $reg:tt $mov:literal) => { + check_reg!($func $ty:$ty $reg $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $reg:tt $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); y @@ -110,6 +117,12 @@ check!(reg_f32 f32 reg "mov"); // CHECK: @NO_APP check!(reg_ptr ptr reg "mov"); +// CHECK-LABEL: reg_nonnull: +// CHECK: @APP +// CHECK: mov {{[a-z0-9]+}}, {{[a-z0-9]+}} +// CHECK: @NO_APP +check!(reg_nonnull nonnull:ptr reg "mov"); + // CHECK-LABEL: sreg_i32: // CHECK: @APP // CHECK: vmov.f32 s{{[0-9]+}}, s{{[0-9]+}} @@ -134,6 +147,12 @@ check!(sreg_f32 f32 sreg "vmov.f32"); // CHECK: @NO_APP check!(sreg_ptr ptr sreg "vmov.f32"); +// CHECK-LABEL: sreg_nonnull: +// CHECK: @APP +// CHECK: vmov.f32 s{{[0-9]+}}, s{{[0-9]+}} +// CHECK: @NO_APP +check!(sreg_nonnull nonnull:ptr sreg "vmov.f32"); + // CHECK-LABEL: sreg_low16_i32: // CHECK: @APP // CHECK: vmov.f32 s{{[0-9]+}}, s{{[0-9]+}} @@ -478,6 +497,12 @@ check_reg!(r0_f32 f32 "r0" "mov"); // CHECK: @NO_APP check_reg!(r0_ptr ptr "r0" "mov"); +// CHECK-LABEL: r0_nonnull: +// CHECK: @APP +// CHECK: mov r0, r0 +// CHECK: @NO_APP +check_reg!(r0_nonnull nonnull:ptr "r0" "mov"); + // CHECK-LABEL: s0_i32: // CHECK: @APP // CHECK: vmov.f32 s0, s0 @@ -502,6 +527,12 @@ check_reg!(s0_f32 f32 "s0" "vmov.f32"); // CHECK: @NO_APP check_reg!(s0_ptr ptr "s0" "vmov.f32"); +// CHECK-LABEL: s0_nonnull: +// CHECK: @APP +// CHECK: vmov.f32 s0, s0 +// CHECK: @NO_APP +check_reg!(s0_nonnull nonnull:ptr "s0" "vmov.f32"); + // FIXME(#126797): "d0" should work with `i64` and `f64` even when `d32` is disabled. // d32-LABEL: d0_i64: // d32: @APP diff --git a/tests/assembly-llvm/asm/hexagon-types.rs b/tests/assembly-llvm/asm/hexagon-types.rs index 829696153293c..2a083758f9673 100644 --- a/tests/assembly-llvm/asm/hexagon-types.rs +++ b/tests/assembly-llvm/asm/hexagon-types.rs @@ -5,7 +5,7 @@ //@ compile-flags: -Zmerge-functions=disabled //@ needs-llvm-components: hexagon -#![feature(no_core, asm_experimental_arch)] +#![feature(asm_nonnull_inputs, no_core, asm_experimental_arch)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types)] @@ -15,6 +15,7 @@ use minicore::simd::*; use minicore::*; type ptr = *const i32; +type nonnull = NonNull; type i32x32 = Simd; // 1024-bit HVX vector (128B mode) type i32x64 = Simd; // 2048-bit HVX vector pair (128B mode) @@ -26,8 +27,11 @@ extern "C" { macro_rules! check { ($func:ident $ty:ident $class:ident) => { + check!($func $ty:$ty $class); + }; + ($func:ident $in_ty:ident:$out_ty:ident $class:ident) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!("{} = {}", out($class) y, in($class) x); y @@ -37,8 +41,11 @@ macro_rules! check { macro_rules! check_reg { ($func:ident $ty:ident $reg:tt) => { + check_reg!($func $ty:$ty $reg); + }; + ($func:ident $in_ty:ident:$out_ty:ident $reg:tt) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($reg, " = ", $reg), lateout($reg) y, in($reg) x); y @@ -89,6 +96,12 @@ pub unsafe fn packet() { // CHECK: InlineAsm End check!(reg_ptr ptr reg); +// CHECK-LABEL: reg_nonnull: +// CHECK: InlineAsm Start +// CHECK: r{{[0-9]+}} = r{{[0-9]+}} +// CHECK: InlineAsm End +check!(reg_nonnull nonnull:ptr reg); + // CHECK-LABEL: reg_f32: // CHECK: InlineAsm Start // CHECK: r{{[0-9]+}} = r{{[0-9]+}} @@ -119,6 +132,12 @@ check!(reg_i16 i16 reg); // CHECK: InlineAsm End check_reg!(r0_ptr ptr "r0"); +// CHECK-LABEL: r0_nonnull: +// CHECK: InlineAsm Start +// CHECK: r0 = r0 +// CHECK: InlineAsm End +check_reg!(r0_nonnull nonnull:ptr "r0"); + // CHECK-LABEL: r0_f32: // CHECK: InlineAsm Start // CHECK: r0 = r0 diff --git a/tests/assembly-llvm/asm/loongarch-type.rs b/tests/assembly-llvm/asm/loongarch-type.rs index 124d82c5d5d6c..27c663403e011 100644 --- a/tests/assembly-llvm/asm/loongarch-type.rs +++ b/tests/assembly-llvm/asm/loongarch-type.rs @@ -14,7 +14,7 @@ //@ compile-flags: -Zmerge-functions=disabled -#![feature(no_core, f16)] +#![feature(asm_nonnull_inputs, no_core, f16)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types)] @@ -23,6 +23,7 @@ extern crate minicore; use minicore::*; type ptr = *const i32; +type nonnull = NonNull; extern "C" { fn extern_func(); @@ -58,23 +59,33 @@ pub unsafe fn sym_static() { asm!("la.got $r12, {}", sym extern_static); } -macro_rules! check { ($func:ident, $ty:ty, $class:ident, $mov:literal) => { - #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { - let y; - asm!(concat!($mov," {}, {}"), out($class) y, in($class) x); - y - } -};} - -macro_rules! check_reg { ($func:ident, $ty:ty, $reg:tt, $mov:literal) => { - #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { - let y; - asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); - y - } -};} +macro_rules! check { + ($func:ident, $ty:ty, $class:ident, $mov:literal) => { + check!($func, $ty:$ty, $class, $mov); + }; + ($func:ident, $in_ty:ty:$out_ty:ty, $class:ident, $mov:literal) => { + #[no_mangle] + pub unsafe fn $func(x: $in_ty) -> $out_ty { + let y; + asm!(concat!($mov," {}, {}"), out($class) y, in($class) x); + y + } + }; +} + +macro_rules! check_reg { + ($func:ident, $ty:ty, $reg:tt, $mov:literal) => { + check_reg!($func, $ty:$ty, $reg, $mov); + }; + ($func:ident, $in_ty:ty:$out_ty:ty, $reg:tt, $mov:literal) => { + #[no_mangle] + pub unsafe fn $func(x: $in_ty) -> $out_ty { + let y; + asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); + y + } + }; +} // CHECK-LABEL: reg_i8: // CHECK: #APP @@ -126,6 +137,12 @@ check!(reg_f64, f64, reg, "move"); // CHECK: #NO_APP check!(reg_ptr, ptr, reg, "move"); +// CHECK-LABEL: reg_nonnull: +// CHECK: #APP +// CHECK: move ${{[a-z0-9]+}}, ${{[a-z0-9]+}} +// CHECK: #NO_APP +check!(reg_nonnull, nonnull:ptr, reg, "move"); + // CHECK-LABEL: freg_f16: // CHECK: #APP // CHECK: fmov.s $f{{[a-z0-9]+}}, $f{{[a-z0-9]+}} @@ -194,6 +211,12 @@ check_reg!(r4_f64, f64, "$r4", "move"); // CHECK: #NO_APP check_reg!(r4_ptr, ptr, "$r4", "move"); +// CHECK-LABEL: r4_nonnull: +// CHECK: #APP +// CHECK: move $a0, $a0 +// CHECK: #NO_APP +check_reg!(r4_nonnull, nonnull:ptr, "$r4", "move"); + // CHECK-LABEL: f0_f16: // CHECK: #APP // CHECK: fmov.s $f{{[a-z0-9]+}}, $f{{[a-z0-9]+}} diff --git a/tests/assembly-llvm/asm/mips-types.rs b/tests/assembly-llvm/asm/mips-types.rs index ea46386df133d..fc879354a6b77 100644 --- a/tests/assembly-llvm/asm/mips-types.rs +++ b/tests/assembly-llvm/asm/mips-types.rs @@ -66,7 +66,7 @@ //@ min-llvm-version: 23 #![deny(unexpected_cfgs)] -#![feature(no_core, asm_experimental_arch, f16)] +#![feature(asm_nonnull_inputs, no_core, asm_experimental_arch, f16)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types, unused)] @@ -96,29 +96,40 @@ compile_error!("mips64r6 cfg mismatch"); compile_error!("msa cfg mismatch"); type ptr = *const i32; +type nonnull = NonNull; extern "C" { fn extern_func(); static extern_static: u8; } -macro_rules! check { ($func:ident, $ty:ty, $class:ident, $mov:literal) => { - #[unsafe(no_mangle)] - pub unsafe fn $func(x: $ty) -> $ty { - let y; - asm!(concat!($mov," {}, {}"), out($class) y, in($class) x); - y - } -};} - -macro_rules! check_reg { ($func:ident, $ty:ty, $reg:tt, $mov:literal) => { - #[unsafe(no_mangle)] - pub unsafe fn $func(x: $ty) -> $ty { - let y; - asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); - y - } -};} +macro_rules! check { + ($func:ident, $ty:ty, $class:ident, $mov:literal) => { + check!($func, $ty:$ty, $class, $mov); + }; + ($func:ident, $in_ty:ty:$out_ty:ty, $class:ident, $mov:literal) => { + #[unsafe(no_mangle)] + pub unsafe fn $func(x: $in_ty) -> $out_ty { + let y; + asm!(concat!($mov," {}, {}"), out($class) y, in($class) x); + y + } + }; +} + +macro_rules! check_reg { + ($func:ident, $ty:ty, $reg:tt, $mov:literal) => { + check_reg!($func, $ty:$ty, $reg, $mov); + }; + ($func:ident, $in_ty:ty:$out_ty:ty, $reg:tt, $mov:literal) => { + #[unsafe(no_mangle)] + pub unsafe fn $func(x: $in_ty) -> $out_ty { + let y; + asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); + y + } + }; +} // mips32-LABEL: sym_static_32: // mips32: #APP @@ -232,6 +243,12 @@ check_reg!(f0_f64, f64, "$f0", "mov.d"); // CHECK: #NO_APP check!(reg_ptr, ptr, reg, "move"); +// CHECK-LABEL: reg_nonnull: +// CHECK: #APP +// CHECK: move ${{[0-9]+}}, ${{[0-9]+}} +// CHECK: #NO_APP +check!(reg_nonnull, nonnull:ptr, reg, "move"); + // CHECK-LABEL: reg_i32: // CHECK: #APP // CHECK: move ${{[0-9]+}}, ${{[0-9]+}} @@ -288,6 +305,12 @@ check!(reg_i64, i64, reg, "move"); // CHECK: #NO_APP check_reg!(r8_ptr, ptr, "$8", "move"); +// CHECK-LABEL: r8_nonnull: +// CHECK: #APP +// CHECK: move $8, $8 +// CHECK: #NO_APP +check_reg!(r8_nonnull, nonnull:ptr, "$8", "move"); + // CHECK-LABEL: r8_i32: // CHECK: #APP // CHECK: move $8, $8 diff --git a/tests/assembly-llvm/asm/nvptx-types.rs b/tests/assembly-llvm/asm/nvptx-types.rs index 15c4dabbfecee..d615beb351d96 100644 --- a/tests/assembly-llvm/asm/nvptx-types.rs +++ b/tests/assembly-llvm/asm/nvptx-types.rs @@ -3,7 +3,7 @@ //@ compile-flags: --target nvptx64-nvidia-cuda //@ needs-llvm-components: nvptx -#![feature(no_core, asm_experimental_arch, f16)] +#![feature(asm_nonnull_inputs, no_core, asm_experimental_arch, f16)] #![crate_type = "rlib"] #![no_core] @@ -11,6 +11,7 @@ extern crate minicore; use minicore::*; type ptr = *mut u8; +type nonnull = NonNull; // NVPTX does not support static variables #[no_mangle] @@ -27,8 +28,11 @@ pub unsafe fn sym_fn() { macro_rules! check { ($func:ident $ty:ident $class:ident $mov:literal) => { + check!($func $ty:$ty $class $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $class:ident $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " {}, {};"), out($class) y, in($class) x); y @@ -131,3 +135,9 @@ check!(reg64_f64 f64 reg64 "mov.b64"); // CHECK: mov.b64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}}; // CHECK: // end inline asm check!(reg64_ptr ptr reg64 "mov.b64"); + +// CHECK-LABEL: .visible .func (.param .b64 func_retval0) reg64_nonnull +// CHECK: // begin inline asm +// CHECK: mov.b64 %{{[a-z0-9]+}}, %{{[a-z0-9]+}}; +// CHECK: // end inline asm +check!(reg64_nonnull nonnull:ptr reg64 "mov.b64"); diff --git a/tests/assembly-llvm/asm/riscv-types.rs b/tests/assembly-llvm/asm/riscv-types.rs index 3ebfbaee43198..ff3620997d0fb 100644 --- a/tests/assembly-llvm/asm/riscv-types.rs +++ b/tests/assembly-llvm/asm/riscv-types.rs @@ -30,7 +30,7 @@ //@ compile-flags: -C target-feature=+d //@ compile-flags: -Zmerge-functions=disabled -#![feature(no_core, f16)] +#![feature(asm_nonnull_inputs, no_core, f16)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register)] @@ -39,6 +39,7 @@ extern crate minicore; use minicore::*; type ptr = *mut u8; +type nonnull = NonNull; extern "C" { fn extern_func(); @@ -66,8 +67,11 @@ pub unsafe fn sym_static() { macro_rules! check { ($func:ident $ty:ident $class:ident $mov:literal) => { + check!($func $ty:$ty $class $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $class:ident $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " {}, {}"), out($class) y, in($class) x); y @@ -77,8 +81,11 @@ macro_rules! check { macro_rules! check_reg { ($func:ident $ty:ident $reg:tt $mov:literal) => { + check_reg!($func $ty:$ty $reg $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $reg:tt $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); y @@ -136,6 +143,12 @@ check!(reg_f64 f64 reg "mv"); // CHECK: #NO_APP check!(reg_ptr ptr reg "mv"); +// CHECK-LABEL: reg_nonnull: +// CHECK: #APP +// CHECK: mv {{[a-z0-9]+}}, {{[a-z0-9]+}} +// CHECK: #NO_APP +check!(reg_nonnull nonnull:ptr reg "mv"); + // CHECK-LABEL: freg_f16: // zfhmin-NOT: or // CHECK: #APP @@ -206,6 +219,12 @@ check_reg!(a0_f64 f64 "a0" "mv"); // CHECK: #NO_APP check_reg!(a0_ptr ptr "a0" "mv"); +// CHECK-LABEL: a0_nonnull: +// CHECK: #APP +// CHECK: mv a0, a0 +// CHECK: #NO_APP +check_reg!(a0_nonnull nonnull:ptr "a0" "mv"); + // CHECK-LABEL: fa0_f16: // zfhmin-NOT: or // CHECK: #APP diff --git a/tests/assembly-llvm/asm/s390x-types.rs b/tests/assembly-llvm/asm/s390x-types.rs index f649a6babdc27..f2f3e539fb2e7 100644 --- a/tests/assembly-llvm/asm/s390x-types.rs +++ b/tests/assembly-llvm/asm/s390x-types.rs @@ -7,7 +7,7 @@ //@[s390x_vector] needs-llvm-components: systemz //@ compile-flags: -Zmerge-functions=disabled -#![feature(no_core, f16, f128)] +#![feature(asm_nonnull_inputs, no_core, f16, f128)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types)] @@ -17,20 +17,26 @@ use minicore::simd::*; use minicore::*; type ptr = *const i32; +type nonnull = NonNull; extern "C" { fn extern_func(); static extern_static: u8; } -macro_rules! check { ($func:ident, $ty:ty, $class:ident, $mov:literal) => { - #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { - let y; - asm!(concat!($mov," {}, {}"), out($class) y, in($class) x); - y - } -};} +macro_rules! check { + ($func:ident, $ty:ty, $class:ident, $mov:literal) => { + check!($func, $ty:$ty, $class, $mov); + }; + ($func:ident, $in_ty:ty:$out_ty:ty, $class:ident, $mov:literal) => { + #[no_mangle] + pub unsafe fn $func(x: $in_ty) -> $out_ty { + let y; + asm!(concat!($mov," {}, {}"), out($class) y, in($class) x); + y + } + }; +} macro_rules! check_reg { ($func:ident, $ty:ty, $reg:tt, $mov:literal) => { #[no_mangle] @@ -131,6 +137,12 @@ check!(reg_f64, f64, freg, "ldr"); // CHECK: #NO_APP check!(reg_ptr, ptr, reg, "lgr"); +// CHECK-LABEL: reg_nonnull: +// CHECK: #APP +// CHECK: lgr %r{{[0-9]+}}, %r{{[0-9]+}} +// CHECK: #NO_APP +check!(reg_nonnull, nonnull:ptr, reg, "lgr"); + // s390x_vector-LABEL: vreg_i8x16: // s390x_vector: #APP // s390x_vector: vlr %v{{[0-9]+}}, %v{{[0-9]+}} diff --git a/tests/assembly-llvm/asm/sparc-types.rs b/tests/assembly-llvm/asm/sparc-types.rs index 9fabd8dcdd09e..9763d543ab675 100644 --- a/tests/assembly-llvm/asm/sparc-types.rs +++ b/tests/assembly-llvm/asm/sparc-types.rs @@ -13,7 +13,7 @@ //@ compile-flags: --check-cfg=cfg(v9) #![deny(unexpected_cfgs)] -#![feature(no_core, asm_experimental_arch, f128)] +#![feature(no_core, asm_experimental_arch, asm_nonnull_inputs, f128)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types)] @@ -26,20 +26,26 @@ extern crate minicore; use minicore::*; type ptr = *const i32; +type nonnull = NonNull; extern "C" { fn extern_func(); static extern_static: u8; } -macro_rules! check { ($func:ident, $ty:ty, $class:ident, $mov:literal) => { - #[unsafe(no_mangle)] - pub unsafe fn $func(x: $ty) -> $ty { - let y; - asm!(concat!($mov," {}, {}"), in($class) x, out($class) y); - y - } -};} +macro_rules! check { + ($func:ident, $ty:ty, $class:ident, $mov:literal) => { + check!($func, $ty:$ty, $class, $mov); + }; + ($func:ident, $in_ty:ty:$out_ty:ty, $class:ident, $mov:literal) => { + #[unsafe(no_mangle)] + pub unsafe fn $func(x: $in_ty) -> $out_ty { + let y; + asm!(concat!($mov," {}, {}"), in($class) x, out($class) y); + y + } + }; +} macro_rules! check_reg { ($func:ident, $ty:ty, $reg:tt, $mov:literal) => { @@ -110,6 +116,12 @@ check!(reg_i64, i64, reg, "mov"); // CHECK-NEXT: !NO_APP check!(reg_ptr, ptr, reg, "mov"); +// CHECK-LABEL: reg_nonnull: +// CHECK: !APP +// CHECK-NEXT: mov %{{[goli]}}{{[0-9]+}}, %{{[goli]}}{{[0-9]+}} +// CHECK-NEXT: !NO_APP +check!(reg_nonnull, nonnull:ptr, reg, "mov"); + // CHECK-LABEL: o0_i8: // CHECK: !APP // CHECK-NEXT: mov %o0, %o0 diff --git a/tests/assembly-llvm/asm/wasm-types.rs b/tests/assembly-llvm/asm/wasm-types.rs index b00a84acf50c5..2e452534fa37a 100644 --- a/tests/assembly-llvm/asm/wasm-types.rs +++ b/tests/assembly-llvm/asm/wasm-types.rs @@ -3,7 +3,7 @@ //@ compile-flags: --target wasm32-unknown-unknown //@ needs-llvm-components: webassembly -#![feature(no_core, asm_experimental_arch)] +#![feature(no_core, asm_experimental_arch, asm_nonnull_inputs)] #![crate_type = "rlib"] #![no_core] @@ -11,6 +11,7 @@ extern crate minicore; use minicore::*; type ptr = *mut u8; +type nonnull = NonNull; extern "C" { fn extern_func(); @@ -41,8 +42,11 @@ pub unsafe fn sym_static() { macro_rules! check { ($func:ident $ty:ident $instr:literal) => { + check!($func $ty:$ty $instr); + }; + ($func:ident $in_ty:ident:$out_ty:ident $instr:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!("local.get {}\n", $instr, "\nlocal.set {}"), in(local) x, out(local) y); y @@ -129,3 +133,11 @@ check!(f64_f64 f64 "f64.abs"); // CHECK: local.set {{[0-9]}} // CHECK: #NO_APP check!(i32_ptr ptr "i32.eqz"); + +// CHECK-LABEL: i32_nonnull +// CHECK: #APP +// CHECK: local.get {{[0-9]}} +// CHECK: i32.eqz +// CHECK: local.set {{[0-9]}} +// CHECK: #NO_APP +check!(i32_nonnull nonnull:ptr "i32.eqz"); diff --git a/tests/assembly-llvm/asm/x86-types.rs b/tests/assembly-llvm/asm/x86-types.rs index e9511f230d0ea..fb8961e35edea 100644 --- a/tests/assembly-llvm/asm/x86-types.rs +++ b/tests/assembly-llvm/asm/x86-types.rs @@ -9,7 +9,7 @@ //@ compile-flags: -C target-feature=+avx512bw //@ compile-flags: -Zmerge-functions=disabled -#![feature(no_core, f16, f128, asm_const_ptr)] +#![feature(no_core, f16, f128, asm_const_ptr, asm_nonnull_inputs)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types)] @@ -19,6 +19,7 @@ use minicore::simd::*; use minicore::*; type ptr = *mut u8; +type nonnull = NonNull; extern "C" { fn extern_func(); @@ -54,8 +55,11 @@ pub unsafe fn const_ptr() { macro_rules! check { ($func:ident $ty:ident $class:ident $mov:literal) => { + check!($func $ty:$ty $class $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $class:ident $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " {}, {}"), lateout($class) y, in($class) x); y @@ -65,8 +69,11 @@ macro_rules! check { macro_rules! check_reg { ($func:ident $ty:ident $reg:tt $mov:literal) => { + check_reg!($func $ty:$ty $reg $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $reg:tt $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); y @@ -123,6 +130,13 @@ check!(reg_f64 f64 reg "mov"); // CHECK: #NO_APP check!(reg_ptr ptr reg "mov"); +// CHECK-LABEL: reg_nonnull: +// CHECK: #APP +// x86_64: mov r{{[a-z0-9]+}}, r{{[a-z0-9]+}} +// i686: mov e{{[a-z0-9]+}}, e{{[a-z0-9]+}} +// CHECK: #NO_APP +check!(reg_nonnull nonnull:ptr reg "mov"); + // CHECK-LABEL: reg_abcd_i16: // CHECK: #APP // x86_64: mov r{{[a-z0-9]+}}, r{{[a-z0-9]+}} @@ -172,6 +186,13 @@ check!(reg_abcd_f64 f64 reg_abcd "mov"); // CHECK: #NO_APP check!(reg_abcd_ptr ptr reg_abcd "mov"); +// CHECK-LABEL: reg_abcd_nonnull: +// CHECK: #APP +// x86_64: mov r{{[a-z0-9]+}}, r{{[a-z0-9]+}} +// i686: mov e{{[a-z0-9]+}}, e{{[a-z0-9]+}} +// CHECK: #NO_APP +check!(reg_abcd_nonnull nonnull:ptr reg_abcd "mov"); + // CHECK-LABEL: reg_byte: // CHECK: #APP // CHECK: mov {{[a-z0-9]+}}, {{[a-z0-9]+}} @@ -220,6 +241,12 @@ check!(xmm_reg_f128 f128 xmm_reg "movaps"); // CHECK: #NO_APP check!(xmm_reg_ptr ptr xmm_reg "movaps"); +// CHECK-LABEL: xmm_reg_nonnull: +// CHECK: #APP +// CHECK: movaps xmm{{[0-9]+}}, xmm{{[0-9]+}} +// CHECK: #NO_APP +check!(xmm_reg_nonnull nonnull:ptr xmm_reg "movaps"); + // CHECK-LABEL: xmm_reg_i8x16: // CHECK: #APP // CHECK: movaps xmm{{[0-9]+}}, xmm{{[0-9]+}} @@ -304,6 +331,12 @@ check!(ymm_reg_f128 f128 ymm_reg "vmovaps"); // CHECK: #NO_APP check!(ymm_reg_ptr ptr ymm_reg "vmovaps"); +// CHECK-LABEL: ymm_reg_nonnull: +// CHECK: #APP +// CHECK: vmovaps ymm{{[0-9]+}}, ymm{{[0-9]+}} +// CHECK: #NO_APP +check!(ymm_reg_nonnull nonnull:ptr ymm_reg "vmovaps"); + // CHECK-LABEL: ymm_reg_i8x16: // CHECK: #APP // CHECK: vmovaps ymm{{[0-9]+}}, ymm{{[0-9]+}} @@ -430,6 +463,12 @@ check!(zmm_reg_f128 f128 zmm_reg "vmovaps"); // CHECK: #NO_APP check!(zmm_reg_ptr ptr zmm_reg "vmovaps"); +// CHECK-LABEL: zmm_reg_nonnull: +// CHECK: #APP +// CHECK: vmovaps zmm{{[0-9]+}}, zmm{{[0-9]+}} +// CHECK: #NO_APP +check!(zmm_reg_nonnull nonnull:ptr zmm_reg "vmovaps"); + // CHECK-LABEL: zmm_reg_i8x16: // CHECK: #APP // CHECK: vmovaps zmm{{[0-9]+}}, zmm{{[0-9]+}} @@ -586,6 +625,12 @@ check!(kreg_i64 i64 kreg "kmovq"); // CHECK: #NO_APP check!(kreg_ptr ptr kreg "kmovq"); +// CHECK-LABEL: kreg_nonnull: +// CHECK: #APP +// CHECK: kmovq k{{[0-9]+}}, k{{[0-9]+}} +// CHECK: #NO_APP +check!(kreg_nonnull nonnull:ptr kreg "kmovq"); + // CHECK-LABEL: eax_i16: // CHECK: #APP // CHECK: mov eax, eax @@ -630,6 +675,12 @@ check_reg!(eax_f64 f64 "eax" "mov"); // CHECK: #NO_APP check_reg!(eax_ptr ptr "eax" "mov"); +// CHECK-LABEL: eax_nonnull: +// CHECK: #APP +// CHECK: mov eax, eax +// CHECK: #NO_APP +check_reg!(eax_nonnull nonnull:ptr "eax" "mov"); + // i686-LABEL: ah_byte: // i686: #APP // i686: mov ah, ah @@ -679,6 +730,12 @@ check_reg!(xmm0_f128 f128 "xmm0" "movaps"); // CHECK: #NO_APP check_reg!(xmm0_ptr ptr "xmm0" "movaps"); +// CHECK-LABEL: xmm0_nonnull: +// CHECK: #APP +// CHECK: movaps xmm0, xmm0 +// CHECK: #NO_APP +check_reg!(xmm0_nonnull nonnull:ptr "xmm0" "movaps"); + // CHECK-LABEL: xmm0_i8x16: // CHECK: #APP // CHECK: movaps xmm0, xmm0 @@ -763,6 +820,12 @@ check_reg!(ymm0_f128 f128 "ymm0" "vmovaps"); // CHECK: #NO_APP check_reg!(ymm0_ptr ptr "ymm0" "vmovaps"); +// CHECK-LABEL: ymm0_nonnull: +// CHECK: #APP +// CHECK: vmovaps ymm0, ymm0 +// CHECK: #NO_APP +check_reg!(ymm0_nonnull nonnull:ptr "ymm0" "vmovaps"); + // CHECK-LABEL: ymm0_i8x16: // CHECK: #APP // CHECK: vmovaps ymm0, ymm0 @@ -889,6 +952,12 @@ check_reg!(zmm0_f128 f128 "zmm0" "vmovaps"); // CHECK: #NO_APP check_reg!(zmm0_ptr ptr "zmm0" "vmovaps"); +// CHECK-LABEL: zmm0_nonnull: +// CHECK: #APP +// CHECK: vmovaps zmm0, zmm0 +// CHECK: #NO_APP +check_reg!(zmm0_nonnull nonnull:ptr "zmm0" "vmovaps"); + // CHECK-LABEL: zmm0_i8x16: // CHECK: #APP // CHECK: vmovaps zmm0, zmm0 @@ -1044,3 +1113,9 @@ check_reg!(k1_i64 i64 "k1" "kmovq"); // CHECK: kmovq k1, k1 // CHECK: #NO_APP check_reg!(k1_ptr ptr "k1" "kmovq"); + +// CHECK-LABEL: k1_nonnull: +// CHECK: #APP +// CHECK: kmovq k1, k1 +// CHECK: #NO_APP +check_reg!(k1_nonnull nonnull:ptr "k1" "kmovq"); diff --git a/tests/assembly-llvm/asm/xtensa-types.rs b/tests/assembly-llvm/asm/xtensa-types.rs index 9419a78f9e07c..a7d679c22767e 100644 --- a/tests/assembly-llvm/asm/xtensa-types.rs +++ b/tests/assembly-llvm/asm/xtensa-types.rs @@ -3,7 +3,7 @@ //@ compile-flags: --target xtensa-esp32-none-elf -Zmerge-functions=disabled //@ needs-llvm-components: xtensa -#![feature(no_core, lang_items, rustc_attrs, asm_experimental_arch)] +#![feature(no_core, lang_items, rustc_attrs, asm_experimental_arch, asm_nonnull_inputs)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register, non_camel_case_types)] @@ -13,6 +13,7 @@ use minicore::simd::*; use minicore::*; type ptr = *mut u8; +type nonnull = NonNull; extern "C" { fn extern_func(); @@ -29,8 +30,11 @@ pub unsafe fn sym_fn() { macro_rules! check_general_reg { ($func:ident $ty:ident $class:ident $mov:literal) => { + check_general_reg!($func $ty:$ty $class $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $class:ident $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " {}, {}"), out($class) y, in($class) x); y @@ -62,10 +66,19 @@ check_general_reg!(reg_i32 i32 reg "mov"); // CHECK: #NO_APP check_general_reg!(reg_ptr ptr reg "mov"); +// CHECK-LABEL: reg_nonnull: +// CHECK: #APP +// CHECK: or a{{[0-9]+}}, a{{[0-9]+}}, a{{[0-9]+}} +// CHECK: #NO_APP +check_general_reg!(reg_nonnull nonnull:ptr reg "mov"); + macro_rules! check_explicit_reg { ($func:ident $ty:ident $reg:tt $mov:literal) => { + check_explicit_reg!($func $ty:$ty $reg $mov); + }; + ($func:ident $in_ty:ident:$out_ty:ident $reg:tt $mov:literal) => { #[no_mangle] - pub unsafe fn $func(x: $ty) -> $ty { + pub unsafe fn $func(x: $in_ty) -> $out_ty { let y; asm!(concat!($mov, " ", $reg, ", ", $reg), lateout($reg) y, in($reg) x); y @@ -103,6 +116,12 @@ check_explicit_reg!(a5_i32 i32 "a5" "mov"); // CHECK: #NO_APP check_explicit_reg!(a5_ptr ptr "a5" "mov"); +// CHECK-LABEL: a5_nonnull: +// CHECK: #APP +// CHECK: or a5, a5, a5 +// CHECK: #NO_APP +check_explicit_reg!(a5_nonnull nonnull:ptr "a5" "mov"); + // CHECK-LABEL: a14_i32: // CHECK: #APP // CHECK: or a14, a14, a14 diff --git a/tests/auxiliary/minicore.rs b/tests/auxiliary/minicore.rs index aca69642057ab..6e99ef96a7ef6 100644 --- a/tests/auxiliary/minicore.rs +++ b/tests/auxiliary/minicore.rs @@ -203,6 +203,7 @@ impl MaybeUninit { } } +#[lang = "non_null"] #[repr(transparent)] #[rustc_nonnull_optimization_guaranteed] pub struct NonNull { diff --git a/tests/codegen-llvm/inject-autocast.rs b/tests/codegen-llvm/inject-autocast.rs index f07153c17daf7..b2c0ab0e7b809 100644 --- a/tests/codegen-llvm/inject-autocast.rs +++ b/tests/codegen-llvm/inject-autocast.rs @@ -6,9 +6,7 @@ use std::simd::{f32x4, i16x8, i64x2}; -#[repr(C, packed)] pub struct Bar(u32, i64x2, i64x2, i64x2, i64x2, i64x2, i64x2); -// CHECK: %Bar = type <{ i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> }> #[repr(simd)] pub struct Tile([i8; 1024]); @@ -21,21 +19,27 @@ pub unsafe fn struct_autocast(key_metadata: u32, key: i64x2) -> Bar { fn foo(key_metadata: u32, key: i64x2) -> Bar; } - // CHECK: [[A:%[0-9]+]] = call { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } @llvm.x86.encodekey128(i32 {{.*}}, <2 x i64> {{.*}}) - // CHECK: [[B:%[0-9]+]] = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } [[A]], 0 - // CHECK: [[C:%[0-9]+]] = insertvalue %Bar poison, i32 [[B]], 0 - // CHECK: [[D:%[0-9]+]] = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } [[A]], 1 - // CHECK: [[E:%[0-9]+]] = insertvalue %Bar [[C]], <2 x i64> [[D]], 1 - // CHECK: [[F:%[0-9]+]] = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } [[A]], 2 - // CHECK: [[G:%[0-9]+]] = insertvalue %Bar [[E]], <2 x i64> [[F]], 2 - // CHECK: [[H:%[0-9]+]] = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } [[A]], 3 - // CHECK: [[I:%[0-9]+]] = insertvalue %Bar [[G]], <2 x i64> [[H]], 3 - // CHECK: [[J:%[0-9]+]] = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } [[A]], 4 - // CHECK: [[K:%[0-9]+]] = insertvalue %Bar [[I]], <2 x i64> [[J]], 4 - // CHECK: [[L:%[0-9]+]] = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } [[A]], 5 - // CHECK: [[M:%[0-9]+]] = insertvalue %Bar [[K]], <2 x i64> [[L]], 5 - // CHECK: [[N:%[0-9]+]] = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } [[A]], 6 - // CHECK: insertvalue %Bar [[M]], <2 x i64> [[N]], 6 + // CHECK: %0 = call { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } @llvm.x86.encodekey128(i32 %key_metadata, <2 x i64> %key) + // CHECK-NEXT: %1 = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } %0, 0 + // CHECK-NEXT: %2 = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } %0, 1 + // CHECK-NEXT: %3 = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } %0, 2 + // CHECK-NEXT: %4 = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } %0, 3 + // CHECK-NEXT: %5 = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } %0, 4 + // CHECK-NEXT: %6 = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } %0, 5 + // CHECK-NEXT: %7 = extractvalue { i32, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64>, <2 x i64> } %0, 6 + // CHECK-NEXT: %8 = getelementptr inbounds i8, ptr %_0, i64 96 + // CHECK-NEXT: store i32 %1, ptr %8, align 16 + // CHECK-NEXT: store <2 x i64> %2, ptr %_0, align 16 + // CHECK-NEXT: %9 = getelementptr inbounds i8, ptr %_0, i64 16 + // CHECK-NEXT: store <2 x i64> %3, ptr %9, align 16 + // CHECK-NEXT: %10 = getelementptr inbounds i8, ptr %_0, i64 32 + // CHECK-NEXT: store <2 x i64> %4, ptr %10, align 16 + // CHECK-NEXT: %11 = getelementptr inbounds i8, ptr %_0, i64 48 + // CHECK-NEXT: store <2 x i64> %5, ptr %11, align 16 + // CHECK-NEXT: %12 = getelementptr inbounds i8, ptr %_0, i64 64 + // CHECK-NEXT: store <2 x i64> %6, ptr %12, align 16 + // CHECK-NEXT: %13 = getelementptr inbounds i8, ptr %_0, i64 80 + // CHECK-NEXT: store <2 x i64> %7, ptr %13, align 16 foo(key_metadata, key) } @@ -47,15 +51,17 @@ pub unsafe fn struct_with_i1_vector_autocast(a: i64x2, b: i64x2) -> (u8, u8) { fn foo(a: i64x2, b: i64x2) -> (u8, u8); } - // CHECK: [[A:%[0-9]+]] = call { <2 x i1>, <2 x i1> } @llvm.x86.avx512.vp2intersect.q.128(<2 x i64> {{.*}}, <2 x i64> {{.*}}) - // CHECK: [[B:%[0-9]+]] = extractvalue { <2 x i1>, <2 x i1> } [[A]], 0 - // CHECK: [[C:%[0-9]+]] = shufflevector <2 x i1> [[B]], <2 x i1> zeroinitializer, <8 x i32> - // CHECK: [[D:%[0-9]+]] = bitcast <8 x i1> [[C]] to i8 - // CHECK: [[E:%[0-9]+]] = insertvalue { i8, i8 } poison, i8 [[D]], 0 - // CHECK: [[F:%[0-9]+]] = extractvalue { <2 x i1>, <2 x i1> } [[A]], 1 - // CHECK: [[G:%[0-9]+]] = shufflevector <2 x i1> [[F]], <2 x i1> zeroinitializer, <8 x i32> - // CHECK: [[H:%[0-9]+]] = bitcast <8 x i1> [[G]] to i8 - // CHECK: insertvalue { i8, i8 } [[E]], i8 [[H]], 1 + // CHECK: %0 = call { <2 x i1>, <2 x i1> } @llvm.x86.avx512.vp2intersect.q.128(<2 x i64> %a, <2 x i64> %b) + // CHECK-NEXT: %1 = extractvalue { <2 x i1>, <2 x i1> } %0, 0 + // CHECK-NEXT: %2 = shufflevector <2 x i1> %1, <2 x i1> zeroinitializer, <8 x i32> + // CHECK-NEXT: %3 = bitcast <8 x i1> %2 to i8 + // CHECK-NEXT: %4 = extractvalue { <2 x i1>, <2 x i1> } %0, 1 + // CHECK-NEXT: %5 = shufflevector <2 x i1> %4, <2 x i1> zeroinitializer, <8 x i32> + // CHECK-NEXT: %6 = bitcast <8 x i1> %5 to i8 + // CHECK-NEXT: %7 = insertvalue { i8, i8 } poison, i8 %3, 0 + // CHECK-NEXT: %8 = insertvalue { i8, i8 } %7, i8 %6, 1 + // CHECK-NEXT: %_0.0 = extractvalue { i8, i8 } %8, 0 + // CHECK-NEXT: %_0.1 = extractvalue { i8, i8 } %8, 1 foo(a, b) } diff --git a/tests/ui-fulldeps/rustc_public/check_adt_queries.rs b/tests/ui-fulldeps/rustc_public/check_adt_queries.rs new file mode 100644 index 0000000000000..ebad1b56903e3 --- /dev/null +++ b/tests/ui-fulldeps/rustc_public/check_adt_queries.rs @@ -0,0 +1,158 @@ +//@ run-pass +//! Test that users are able to retrieve information about ADTs + +//@ ignore-stage1 +//@ ignore-cross-compile +//@ ignore-remote +//@ edition: 2024 + +#![feature(rustc_private)] + +extern crate rustc_middle; + +extern crate rustc_driver; +extern crate rustc_interface; +#[macro_use] +extern crate rustc_public; + +use std::{collections::HashSet, io::Write, ops::ControlFlow}; +use rustc_public::{ + mir::{mono::Instance, MirVisitor}, + ty::{AdtDef, RigidTy, Ty, TyKind} +}; + +const CRATE_NAME: &str = "adt_test"; + +#[derive(Default)] +struct AdtDefVisitor { + adt_defs: HashSet, +} + +impl MirVisitor for AdtDefVisitor { + fn visit_ty(&mut self, ty: &Ty, _location: rustc_public::mir::visit::Location) { + if let TyKind::RigidTy(RigidTy::Adt(adt, _)) = ty.kind() { + self.adt_defs.insert(adt); + } + self.super_ty(ty) + } +} + +/// This function uses the Stable MIR APIs to get information about the test crate. +fn test_adts() -> ControlFlow<()> { + let entry = rustc_public::entry_fn().expect("Expected main function"); + let main_fn = Instance::try_from(entry).expect("Expected main instance"); + let mut visitor = AdtDefVisitor::default(); + visitor.visit_body(&main_fn.body().expect("Expected main body")); + let AdtDefVisitor { adt_defs } = visitor; + + assert_eq!( + adt_defs.len(), + 5, + "Expected 5 ADTs, but found {:?}", adt_defs, + ); + + let has_box = adt_defs + .iter() + .any(|item| item.is_box()); + + let has_simd = adt_defs + .iter() + .any(|item| item.is_simd()); + + let has_phantom_data = adt_defs + .iter() + .any(|item| item.is_phantom_data()); + + let has_manually_drop = adt_defs + .iter() + .any(|item| item.is_manually_drop()); + + let has_unsafe_cell = adt_defs + .iter() + .any(|item| item.is_unsafe_cell()); + + assert!(has_box); + assert!(has_simd); + assert!(has_phantom_data); + assert!(has_manually_drop); + assert!(has_unsafe_cell); + + let adt_names = adt_defs.iter().map(|def| def.0.trimmed_name()).collect::>(); + + assert_name(&adt_names, "Box"); + assert_name(&adt_names, "PhantomData"); + assert_name(&adt_names, "Simd"); + assert_name(&adt_names, "ManuallyDrop"); + assert_name(&adt_names, "UnsafeCell"); + + // Verify all AdtDef::ty() returns the self type (Adt) + adt_defs.iter().for_each(|adt|{ + let ty = adt.ty(); + assert!( + matches!( + ty.kind(), + rustc_public::ty::TyKind::RigidTy(RigidTy::Adt(..)) + ), + ); + }); + + ControlFlow::Continue(()) +} + +fn assert_name(adt_names: &HashSet, target: &str) { + assert!( + adt_names.contains(target), + "Failed to find `{target}`. Implementations available: {adt_names:?}", + ); +} + +/// This test will generate and analyze a dummy crate using the stable mir. +/// For that, it will first write the dummy crate into a file. +/// Then it will create a `RustcPublic` using custom arguments and then +/// it will run the compiler. +fn main() { + let path = "adt_queries.rs"; + generate_input(&path).unwrap(); + let args = &[ + "rustc".to_string(), + "-Cpanic=abort".to_string(), + "--edition".to_string(), + "2024".to_string(), + "--crate-name".to_string(), + CRATE_NAME.to_string(), + path.to_string(), + ]; + run!(args, test_adts).unwrap(); +} + +fn generate_input(path: &str) -> std::io::Result<()> { + let mut file = std::fs::File::create(path)?; + write!( + file, + r#" + #![feature(portable_simd)] + + use std::boxed::Box; + use std::cell::UnsafeCell; + use std::ffi::CStr; + use std::mem::ManuallyDrop; + use std::marker::PhantomData; + use std::simd::f32x4; + + fn main() {{ + let _box = Box::new(42); + + let _phantom = PhantomData::; + + let _unsafe_cell = UnsafeCell::new(42); + + let mut _manually_drop = ManuallyDrop::new(42); + + let _cs: &CStr = c"hello"; + + let _simd = f32x4::splat(10.0); + }} + "# + )?; + Ok(()) +} diff --git a/tests/ui/asm/nonnull-output-fail.rs b/tests/ui/asm/nonnull-output-fail.rs new file mode 100644 index 0000000000000..457d1e7f6cee8 --- /dev/null +++ b/tests/ui/asm/nonnull-output-fail.rs @@ -0,0 +1,23 @@ +//@ needs-asm-support + +#![feature(asm_nonnull_inputs)] + +use std::arch::asm; +use std::ptr::NonNull; + +fn _f() { + let p: NonNull; + unsafe { + asm!("/* {} */", out(reg) p); + //~^ ERROR cannot use value of type `NonNull` for inline assembly + } +} + +fn _g(mut p: NonNull) { + unsafe { + asm!("/* {} */", inout(reg) p); + //~^ ERROR cannot use value of type `NonNull` for inline assembly + } +} + +fn main() {} diff --git a/tests/ui/asm/nonnull-output-fail.stderr b/tests/ui/asm/nonnull-output-fail.stderr new file mode 100644 index 0000000000000..16156a924199b --- /dev/null +++ b/tests/ui/asm/nonnull-output-fail.stderr @@ -0,0 +1,18 @@ +error: cannot use value of type `NonNull` for inline assembly + --> $DIR/nonnull-output-fail.rs:11:35 + | +LL | asm!("/* {} */", out(reg) p); + | ^ + | + = note: only integers, floats, SIMD vectors, scalable vectors, pointers and function pointers can be used as arguments for inline assembly + +error: cannot use value of type `NonNull` for inline assembly + --> $DIR/nonnull-output-fail.rs:18:37 + | +LL | asm!("/* {} */", inout(reg) p); + | ^ + | + = note: only integers, floats, SIMD vectors, scalable vectors, pointers and function pointers can be used as arguments for inline assembly + +error: aborting due to 2 previous errors + diff --git a/tests/ui/asm/x86_64/type-check-5.rs b/tests/ui/asm/x86_64/type-check-5.rs index aa7d3b2d2308b..b373a5aab5cf2 100644 --- a/tests/ui/asm/x86_64/type-check-5.rs +++ b/tests/ui/asm/x86_64/type-check-5.rs @@ -1,5 +1,7 @@ //@ only-x86_64 +#![feature(asm_nonnull_inputs)] + use std::arch::asm; fn main() { @@ -31,8 +33,8 @@ fn main() { // Register operands must be Copy - // Register operands must be integers, floats, SIMD vectors, pointers or - // function pointers. + // Register operands must be integers, floats, SIMD vectors, pointers, + // function pointers, or `NonNull` pointers. asm!("{}", in(reg) 0i64); asm!("{}", in(reg) 0f64); @@ -40,14 +42,18 @@ fn main() { asm!("{}", in(reg) 0 as *const u8); asm!("{}", in(reg) 0 as *mut u8); asm!("{}", in(reg) main as fn()); + asm!("{}", in(reg) std::ptr::NonNull::::dangling()); - // Register inputs (but not outputs) allow references and function types + // Register inputs (but not outputs) allow references, function types, + // and `NonNull` pointers. let mut f = main; let mut r = &mut 0; + let mut p = std::ptr::NonNull::::dangling(); asm!("{}", in(reg) f); asm!("{}", in(reg) r); - let _ = (f, r); + asm!("{}", in(reg) p); + let _ = (f, r, p); // Type checks ignore never type diff --git a/tests/ui/asm/x86_64/type-check-5.stderr b/tests/ui/asm/x86_64/type-check-5.stderr index 0c471ee28d261..377e1d19f6c5c 100644 --- a/tests/ui/asm/x86_64/type-check-5.stderr +++ b/tests/ui/asm/x86_64/type-check-5.stderr @@ -1,5 +1,5 @@ error[E0381]: used binding `x` isn't initialized - --> $DIR/type-check-5.rs:10:28 + --> $DIR/type-check-5.rs:12:28 | LL | let x: u64; | - binding declared here but left uninitialized @@ -12,7 +12,7 @@ LL | let x: u64 = 42; | ++++ error[E0381]: used binding `y` isn't initialized - --> $DIR/type-check-5.rs:13:9 + --> $DIR/type-check-5.rs:15:9 | LL | let mut y: u64; | ----- binding declared here but left uninitialized @@ -25,7 +25,7 @@ LL | let mut y: u64 = 42; | ++++ error[E0596]: cannot borrow `v` as mutable, as it is not declared as mutable - --> $DIR/type-check-5.rs:19:13 + --> $DIR/type-check-5.rs:21:13 | LL | let v: Vec = vec![0, 1, 2]; | ^ not mutable diff --git a/tests/ui/derives/deriving-all-codegen.stdout b/tests/ui/derives/deriving-all-codegen.stdout index 356e81b9a483e..6a385dde1353e 100644 --- a/tests/ui/derives/deriving-all-codegen.stdout +++ b/tests/ui/derives/deriving-all-codegen.stdout @@ -434,11 +434,10 @@ impl ::core::fmt::Debug for Big { #[inline] #[rustc_trivial_field_reads] fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { - let names: &'static _ = "Big b1 b2 b3 b4 b5 b6 b7 b8"; - let values: &[&dyn ::core::fmt::Debug] = + ::core::fmt::Formatter::debug_struct_fields_finish(f, + "Big b1 b2 b3 b4 b5 b6 b7 b8", &[&self.b1, &self.b2, &self.b3, &self.b4, &self.b5, &self.b6, - &self.b7, &&self.b8]; - ::core::fmt::Formatter::debug_struct_fields_finish(f, names, values) + &self.b7, &&self.b8]) } } #[automatically_derived] diff --git a/tests/ui/diagnostic_namespace/unsafe_attr.rs b/tests/ui/diagnostic_namespace/unsafe_attr.rs index 7a945dad0b66e..7db50a9ca4103 100644 --- a/tests/ui/diagnostic_namespace/unsafe_attr.rs +++ b/tests/ui/diagnostic_namespace/unsafe_attr.rs @@ -1,7 +1,9 @@ #[unsafe(diagnostic::on_unimplemented(message = "xyz"))] //~ ERROR `diagnostic::on_unimplemented` is not an unsafe attribute trait Test1 {} -#[unsafe(diagnostic::invalid)] //~ WARN unknown diagnostic attribute +#[unsafe(diagnostic::invalid)] +//~^ ERROR `diagnostic::invalid` is not an unsafe attribute +//~| WARN unknown diagnostic attribute trait Test2 {} fn main() { } diff --git a/tests/ui/diagnostic_namespace/unsafe_attr.stderr b/tests/ui/diagnostic_namespace/unsafe_attr.stderr index 732b466f22faa..a231ff5cfe3ec 100644 --- a/tests/ui/diagnostic_namespace/unsafe_attr.stderr +++ b/tests/ui/diagnostic_namespace/unsafe_attr.stderr @@ -6,6 +6,14 @@ LL | #[unsafe(diagnostic::on_unimplemented(message = "xyz"))] | = note: extraneous unsafe is not allowed in attributes +error: `diagnostic::invalid` is not an unsafe attribute + --> $DIR/unsafe_attr.rs:4:3 + | +LL | #[unsafe(diagnostic::invalid)] + | ^^^^^^ this is not an unsafe attribute + | + = note: extraneous unsafe is not allowed in attributes + warning: unknown diagnostic attribute --> $DIR/unsafe_attr.rs:4:22 | @@ -14,5 +22,5 @@ LL | #[unsafe(diagnostic::invalid)] | = note: `#[warn(unknown_diagnostic_attributes)]` (part of `#[warn(unknown_or_malformed_diagnostic_attributes)]`) on by default -error: aborting due to 1 previous error; 1 warning emitted +error: aborting due to 2 previous errors; 1 warning emitted diff --git a/tests/ui/feature-gates/feature-gate-asm_nonnull_inputs.rs b/tests/ui/feature-gates/feature-gate-asm_nonnull_inputs.rs new file mode 100644 index 0000000000000..9d70bb4051219 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-asm_nonnull_inputs.rs @@ -0,0 +1,11 @@ +//@ only-x86_64 + +use std::arch::asm; + +fn main() { + let mut p = core::ptr::NonNull::::dangling(); + unsafe { + asm!("/* {} */", in(reg) p); + //~^ ERROR cannot use value of type `NonNull` for inline assembly + } +} diff --git a/tests/ui/feature-gates/feature-gate-asm_nonnull_inputs.stderr b/tests/ui/feature-gates/feature-gate-asm_nonnull_inputs.stderr new file mode 100644 index 0000000000000..feee0d0bf92b6 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-asm_nonnull_inputs.stderr @@ -0,0 +1,10 @@ +error: cannot use value of type `NonNull` for inline assembly + --> $DIR/feature-gate-asm_nonnull_inputs.rs:8:34 + | +LL | asm!("/* {} */", in(reg) p); + | ^ + | + = note: only integers, floats, SIMD vectors, scalable vectors, pointers and function pointers can be used as arguments for inline assembly + +error: aborting due to 1 previous error +