diff --git a/compiler/rustc_attr_ir/src/lang_items.rs b/compiler/rustc_attr_ir/src/lang_items.rs index 844daa32a04ac..b576c5038404d 100644 --- a/compiler/rustc_attr_ir/src/lang_items.rs +++ b/compiler/rustc_attr_ir/src/lang_items.rs @@ -169,6 +169,7 @@ language_item_table! { Copy, sym::copy, copy_trait, Target::Trait, GenericRequirement::Exact(0); Clone, sym::clone, clone_trait, Target::Trait, GenericRequirement::None; CloneFn, sym::clone_fn, clone_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None; + CloneFromFn, sym::clone_from_fn, clone_from_fn, Target::Method(MethodKind::Trait { body: true }), GenericRequirement::None; UseCloned, sym::use_cloned, use_cloned_trait, Target::Trait, GenericRequirement::None; TrivialClone, sym::trivial_clone, trivial_clone_trait, Target::Trait, GenericRequirement::None; Sync, sym::sync, sync_trait, Target::Trait, GenericRequirement::Exact(0); diff --git a/compiler/rustc_builtin_macros/src/cmdline_attrs.rs b/compiler/rustc_builtin_macros/src/cmdline_attrs.rs index b294328b0bb17..b0045c359160d 100644 --- a/compiler/rustc_builtin_macros/src/cmdline_attrs.rs +++ b/compiler/rustc_builtin_macros/src/cmdline_attrs.rs @@ -8,7 +8,7 @@ use rustc_session::parse::ParseSess; use rustc_span::FileName; pub fn inject(krate: &mut ast::Crate, psess: &ParseSess, attrs: &[String]) { - for raw_attr in attrs { + let injected = attrs.iter().filter_map(|raw_attr| { let source = format!("#![{raw_attr}]"); let parse = || -> Result>> { let tokens = source_str_to_stream( @@ -22,16 +22,15 @@ pub fn inject(krate: &mut ast::Crate, psess: &ParseSess, attrs: &[String]) { }) .map_err(|e| vec![e]) }; - let meta = match parse() { - Ok(meta) => meta, + match parse() { + Ok(meta) => Some(meta), Err(errs) => { for err in errs { err.emit(); } - continue; + None } - }; - - krate.attrs.push(meta); - } + } + }); + krate.attrs.splice(0..0, injected); } diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index bdbd43de07a53..d74c6dd68564b 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -478,6 +478,8 @@ pub(crate) fn default_optimisation_attrs<'ll>( sess: &Session, ) -> SmallVec<[&'ll Attribute; 2]> { let mut attrs = SmallVec::new(); + // Either attribute satisfies LLVM's combined size predicate, but the software pipeliner reads + // `optsize` alone, so a `z` build needs both. match sess.opts.optimize { OptLevel::Size => { attrs.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx)); diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index 693d8e6adb1c3..e43b9ba6359ed 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -119,15 +119,15 @@ pub(crate) fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> OwnedTar target_machine_factory(tcx.sess, tcx.backend_optimization_level(()))(tcx.dcx(), config) } -fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) { +// `s` and `z` are the same codegen level; what tells LLVM that they are size builds is the +// per-function attribute, not this setting. +fn to_llvm_opt_level(cfg: config::OptLevel) -> llvm::CodeGenOptLevel { use self::config::OptLevel::*; match cfg { - No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone), - Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone), - More => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone), - Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone), - Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault), - SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive), + No => llvm::CodeGenOptLevel::None, + Less => llvm::CodeGenOptLevel::Less, + More | Size | SizeMin => llvm::CodeGenOptLevel::Default, + Aggressive => llvm::CodeGenOptLevel::Aggressive, } } @@ -184,7 +184,7 @@ pub(crate) fn target_machine_factory( let reloc_model = to_llvm_relocation_model(sess.relocation_model()); - let (opt_level, _) = to_llvm_opt_settings(optlvl); + let opt_level = to_llvm_opt_level(optlvl); let float_abi = to_llvm_float_abi(sess.target.llvm_floatabi); let ffunction_sections = @@ -594,8 +594,7 @@ pub(crate) unsafe fn llvm_optimize<'ll>( vectorize_slp = false; vectorize_loop = false; } else { - unroll_loops = - opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin; + unroll_loops = opt_level.objective() != config::OptimizationObjective::Size; merge_functions = config.merge_functions; vectorize_slp = config.vectorize_slp; vectorize_loop = config.vectorize_loop; diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 40d5e08578faf..6ba3a82de659f 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -1071,6 +1071,11 @@ impl<'ll, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> { attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &attrs); } + fn apply_default_optimisation_attrs(&self, llfn: &'ll Value) { + let attrs = attributes::default_optimisation_attrs(self, self.sess()); + attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &attrs); + } + fn declare_c_main(&self, fn_type: Self::Type) -> Option { let entry_name = self.sess().target.entry_name.as_ref(); if self.get_declared_value(entry_name).is_none() { diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 594f4cbcf759d..38af3011b47e7 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -1707,6 +1707,7 @@ fn gen_fn<'a, 'll, 'tcx>( let llfn = cx.declare_fn(name, fn_abi, None); cx.set_frame_pointer_type(llfn); cx.apply_target_cpu_attr(llfn); + cx.apply_default_optimisation_attrs(llfn); // FIXME(eddyb) find a nicer way to do this. llvm::set_linkage(llfn, llvm::Linkage::InternalLinkage); let llbb = Builder::append_block(cx, llfn, "entry-block"); diff --git a/compiler/rustc_codegen_llvm/src/llvm/mod.rs b/compiler/rustc_codegen_llvm/src/llvm/mod.rs index f9863da230dfb..e77fed0913ec2 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/mod.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/mod.rs @@ -10,7 +10,6 @@ use rustc_abi::{AddressSpace, Align, Size, WrappingRange}; use rustc_llvm::RustString; pub(crate) use self::CallConv::*; -pub(crate) use self::CodeGenOptSize::*; pub(crate) use self::conversions::*; pub(crate) use self::ffi::*; pub(crate) use self::metadata_kind::*; @@ -195,14 +194,6 @@ impl AttributePlace { } } -#[derive(Copy, Clone, PartialEq)] -#[repr(C)] -pub(crate) enum CodeGenOptSize { - CodeGenOptSizeNone = 0, - CodeGenOptSizeDefault = 1, - CodeGenOptSizeAggressive = 2, -} - pub(crate) fn SetInstructionCallConv(instr: &Value, cc: CallConv) { unsafe { LLVMSetInstructionCallConv(instr, cc as c_uint); diff --git a/compiler/rustc_codegen_ssa/src/back/linker.rs b/compiler/rustc_codegen_ssa/src/back/linker.rs index ffb9130ed1a08..b92e79c8f43ec 100644 --- a/compiler/rustc_codegen_ssa/src/back/linker.rs +++ b/compiler/rustc_codegen_ssa/src/back/linker.rs @@ -407,6 +407,7 @@ impl<'a> GccLinker<'a> { self.link_arg(&arg); } + // The plugin has no distinct size setting: `s` and `z` both map to `O2`, as `More` does. let opt_level = match self.sess.opts.optimize { config::OptLevel::No => "O0", config::OptLevel::Less => "O1", @@ -698,9 +699,7 @@ impl<'a> Linker for GccLinker<'a> { // GNU-style linkers support optimization with -O. GNU ld doesn't // need a numeric argument, but other linkers do. - if self.sess.opts.optimize == config::OptLevel::More - || self.sess.opts.optimize == config::OptLevel::Aggressive - { + if self.sess.optimization_objective() == config::OptimizationObjective::Speed { self.link_arg("-O1"); } } @@ -1021,7 +1020,7 @@ impl<'a> Linker for MsvcLinker<'a> { // MSVC's ICF (Identical COMDAT Folding) link optimization is // slow for Rust and thus we disable it by default when not in // optimization build. - if self.sess.opts.optimize != config::OptLevel::No { + if self.sess.optimization_objective() != config::OptimizationObjective::None { self.link_arg("/OPT:REF,ICF"); } else { // It is necessary to specify NOICF here, because /OPT:REF diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index 44958c376a46a..406e5a5b04c61 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -23,8 +23,8 @@ use rustc_metadata::fs::copy_to_stdout; use rustc_middle::dep_graph::{WorkProduct, WorkProductMap}; use rustc_middle::ty::TyCtxt; use rustc_session::config::{ - self, JobsMode, Lto, OptLevel, OutFileName, OutputFilenames, OutputType, Passes, - SwitchWithOptPath, + self, JobsMode, Lto, OptLevel, OptimizationObjective, OutFileName, OutputFilenames, OutputType, + Passes, SwitchWithOptPath, }; use rustc_session::{BorrowedIncrCompSession, IncrCompSession, Session}; use rustc_span::source_map::SourceMap; @@ -231,8 +231,7 @@ impl ModuleConfig { // Copy what clang does by turning on loop vectorization at O2 and // slp vectorization at O3. vectorize_loop: !sess.opts.cg.no_vectorize_loops - && (sess.opts.optimize == config::OptLevel::More - || sess.opts.optimize == config::OptLevel::Aggressive), + && sess.optimization_objective() == OptimizationObjective::Speed, vectorize_slp: !sess.opts.cg.no_vectorize_slp && sess.opts.optimize == config::OptLevel::Aggressive, @@ -247,13 +246,10 @@ impl ModuleConfig { // O2 and O3) since it can be useful for reducing code size. merge_functions: match sess.merge_functions() { MergeFunctions::Disabled => false, - MergeFunctions::Trampolines | MergeFunctions::Aliases => { - use config::OptLevel::*; - match sess.opts.optimize { - Aggressive | More | SizeMin | Size => true, - Less | No => false, - } - } + MergeFunctions::Trampolines | MergeFunctions::Aliases => matches!( + sess.optimization_objective(), + OptimizationObjective::Speed | OptimizationObjective::Size + ), }, emit_lifetime_markers: sess.emit_lifetime_markers(), diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index 1f820a17195bb..ae35dcfe42e60 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -555,6 +555,8 @@ pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( // `main` should respect same config for frame pointer elimination as rest of code cx.set_frame_pointer_type(llfn); cx.apply_target_cpu_attr(llfn); + // The shim has no item behind it, so it does not go through the per-item attribute path. + cx.apply_default_optimisation_attrs(llfn); let llbb = Bx::append_block(cx, llfn, "top"); let mut bx = Bx::build(cx, llbb); @@ -1217,23 +1219,16 @@ impl CrateInfo { pub(crate) fn provide(providers: &mut Providers) { providers.backend_optimization_level = |tcx, cratenum| { - let for_speed = match tcx.sess.opts.optimize { - // If globally no optimisation is done, #[optimize] has no effect. - // - // This is done because if we ended up "upgrading" to `-O2` here, we’d populate the - // pass manager and it is likely that some module-wide passes (such as inliner or - // cross-function constant propagation) would ignore the `optnone` annotation we put - // on the functions, thus necessarily involving these functions into optimisations. - config::OptLevel::No => return config::OptLevel::No, - // If globally optimise-speed is already specified, just use that level. - config::OptLevel::Less => return config::OptLevel::Less, - config::OptLevel::More => return config::OptLevel::More, - config::OptLevel::Aggressive => return config::OptLevel::Aggressive, - // If globally optimize-for-size has been requested, use -O2 instead (if optimize(size) - // are present). - config::OptLevel::Size => config::OptLevel::More, - config::OptLevel::SizeMin => config::OptLevel::More, - }; + let global = tcx.sess.opts.optimize; + + // Nothing to promote outside a size build. At `-Copt-level=0` the upgrade would populate + // the pass manager, and its module-wide passes ignore the `optnone` annotation. + if global.objective() != config::OptimizationObjective::Size { + return global; + } + + // A speed-marked body in a size build needs a speed level, and `-O2` is the lowest one. + let for_speed = config::OptLevel::More; let defids = tcx.collect_and_partition_mono_items(cratenum).all_mono_items; @@ -1242,11 +1237,7 @@ pub(crate) fn provide(providers: &mut Providers) { matches!(optimize, OptimizeAttr::Speed) }); - if any_for_speed { - return for_speed; - } - - tcx.sess.opts.optimize + if any_for_speed { for_speed } else { global } }; } diff --git a/compiler/rustc_codegen_ssa/src/traits/misc.rs b/compiler/rustc_codegen_ssa/src/traits/misc.rs index add7128a2974b..7e48e86290ee8 100644 --- a/compiler/rustc_codegen_ssa/src/traits/misc.rs +++ b/compiler/rustc_codegen_ssa/src/traits/misc.rs @@ -28,6 +28,9 @@ pub trait MiscCodegenMethods<'tcx>: BackendTypes { fn sess(&self) -> &Session; fn set_frame_pointer_type(&self, llfn: Self::Function); fn apply_target_cpu_attr(&self, llfn: Self::Function); + /// Applies the compilation's optimization attributes to a function that no item produced, + /// such as the C entry shim. + fn apply_default_optimisation_attrs(&self, _llfn: Self::Function) {} /// Declares the extern "C" main function for the entry point. Returns None if the symbol /// already exists. fn declare_c_main(&self, fn_type: Self::FunctionSignature) -> Option; diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 52b584f12213a..20576ce4dd034 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -1346,11 +1346,33 @@ pub struct BasicBlockData<'tcx> { } impl<'tcx> BasicBlockData<'tcx> { - pub fn new(terminator: Option>, is_cleanup: bool) -> BasicBlockData<'tcx> { + pub fn new(terminator: Terminator<'tcx>, is_cleanup: bool) -> BasicBlockData<'tcx> { BasicBlockData::new_stmts(Vec::new(), terminator, is_cleanup) } pub fn new_stmts( + statements: Vec>, + terminator: Terminator<'tcx>, + is_cleanup: bool, + ) -> BasicBlockData<'tcx> { + BasicBlockData { + statements, + after_last_stmt_debuginfos: StmtDebugInfos::default(), + terminator: Some(terminator), + is_cleanup, + } + } + + /// This is being phased out. Use [`BasicBlockData::new`] instead. + pub fn maybe_unterminated( + terminator: Option>, + is_cleanup: bool, + ) -> BasicBlockData<'tcx> { + BasicBlockData::maybe_unterminated_stmts(Vec::new(), terminator, is_cleanup) + } + + /// This is being phased out. Use [`BasicBlockData::new_stmts`] instead. + pub fn maybe_unterminated_stmts( statements: Vec>, terminator: Option>, is_cleanup: bool, diff --git a/compiler/rustc_mir_build/src/builder/cfg.rs b/compiler/rustc_mir_build/src/builder/cfg.rs index 75377f761f401..76bb5009a6ec1 100644 --- a/compiler/rustc_mir_build/src/builder/cfg.rs +++ b/compiler/rustc_mir_build/src/builder/cfg.rs @@ -21,7 +21,7 @@ impl<'tcx> CFG<'tcx> { // it as #[inline(never)] to keep rustc's stack use in check. #[inline(never)] pub(crate) fn start_new_block(&mut self) -> BasicBlock { - self.basic_blocks.push(BasicBlockData::new(None, false)) + self.basic_blocks.push(BasicBlockData::maybe_unterminated(None, false)) } pub(crate) fn start_new_cleanup_block(&mut self) -> BasicBlock { diff --git a/compiler/rustc_mir_build/src/builder/custom/mod.rs b/compiler/rustc_mir_build/src/builder/custom/mod.rs index f6c8658544b43..6d0c415b7358a 100644 --- a/compiler/rustc_mir_build/src/builder/custom/mod.rs +++ b/compiler/rustc_mir_build/src/builder/custom/mod.rs @@ -64,7 +64,7 @@ pub(super) fn build_custom_mir<'tcx>( }; body.local_decls.push(LocalDecl::new(return_ty, return_ty_span)); - body.basic_blocks_mut().push(BasicBlockData::new(None, false)); + body.basic_blocks_mut().push(BasicBlockData::maybe_unterminated(None, false)); body.source_scopes.push(SourceScopeData { span, parent_scope: None, diff --git a/compiler/rustc_mir_build/src/builder/custom/parse.rs b/compiler/rustc_mir_build/src/builder/custom/parse.rs index b227923292779..0cc73e381ea2b 100644 --- a/compiler/rustc_mir_build/src/builder/custom/parse.rs +++ b/compiler/rustc_mir_build/src/builder/custom/parse.rs @@ -199,7 +199,7 @@ impl<'a, 'tcx> ParseCtxt<'a, 'tcx> { match &self.thir[stmt].kind { StmtKind::Let { pattern, initializer: Some(initializer), .. } => { let (var, ..) = self.parse_var(pattern)?; - let data = BasicBlockData::new( + let data = BasicBlockData::maybe_unterminated( None, parse_by_kind!(self, *initializer, _, "basic block declaration", @variant(mir_basic_block, Normal) => false, @@ -303,7 +303,7 @@ impl<'a, 'tcx> ParseCtxt<'a, 'tcx> { ExprKind::Block { block } => &self.thir[*block], ); - let mut data = BasicBlockData::new(None, is_cleanup); + let mut data = BasicBlockData::maybe_unterminated(None, is_cleanup); for stmt_id in &*block.stmts { let stmt = self.statement_as_expr(*stmt_id)?; let span = self.thir[stmt].span; diff --git a/compiler/rustc_mir_build/src/builder/mod.rs b/compiler/rustc_mir_build/src/builder/mod.rs index 4e97ddd991e2d..6e8df5e0809ba 100644 --- a/compiler/rustc_mir_build/src/builder/mod.rs +++ b/compiler/rustc_mir_build/src/builder/mod.rs @@ -833,7 +833,7 @@ fn mir_for_direct_const<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Body<'tc let rvalue = Rvalue::Use(Operand::Constant(Box::new(value)), WithRetag::Yes); let statement_kind = StatementKind::Assign(Box::new((Place::return_place(), rvalue))); let statement = Statement::new(source_info, statement_kind); - let terminator = Some(Terminator { source_info, kind: TerminatorKind::Return }); + let terminator = Terminator { source_info, kind: TerminatorKind::Return }; let block = BasicBlockData::new_stmts(vec![statement], terminator, false); let basic_blocks = IndexVec::from_elem_n(block, 1); diff --git a/compiler/rustc_mir_dataflow/src/framework/tests.rs b/compiler/rustc_mir_dataflow/src/framework/tests.rs index bfdf96a48f401..5f9545860b6bb 100644 --- a/compiler/rustc_mir_dataflow/src/framework/tests.rs +++ b/compiler/rustc_mir_dataflow/src/framework/tests.rs @@ -21,7 +21,7 @@ fn mock_body<'tcx>() -> mir::Body<'tcx> { blocks.push(mir::BasicBlockData::new_stmts( std::iter::repeat(&nop).cloned().take(n).collect(), - Some(mir::Terminator { source_info, kind }), + mir::Terminator { source_info, kind }, false, )) }; diff --git a/compiler/rustc_mir_transform/src/add_call_guards.rs b/compiler/rustc_mir_transform/src/add_call_guards.rs index 17e99f506e0f2..5bf932a42e43a 100644 --- a/compiler/rustc_mir_transform/src/add_call_guards.rs +++ b/compiler/rustc_mir_transform/src/add_call_guards.rs @@ -88,7 +88,7 @@ impl<'tcx> crate::MirPass<'tcx> for AddCallGuards { let cur_len = body.basic_blocks.len(); let mut new_block = |source_info: SourceInfo, is_cleanup: bool, target: BasicBlock| { let block = BasicBlockData::new( - Some(Terminator { source_info, kind: TerminatorKind::goto(target) }), + Terminator { source_info, kind: TerminatorKind::goto(target) }, is_cleanup, ); let idx = cur_len + new_blocks.len(); diff --git a/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs b/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs index 41c63d4857df8..1be185bd5b6bd 100644 --- a/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs +++ b/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs @@ -94,7 +94,7 @@ fn add_move_for_packed_drop<'tcx>( let storage_dead_block = patch.new_block(BasicBlockData::new_stmts( vec![Statement::new(source_info, StatementKind::StorageDead(temp))], - Some(Terminator { source_info, kind: TerminatorKind::goto(target) }), + Terminator { source_info, kind: TerminatorKind::goto(target) }, is_cleanup, )); diff --git a/compiler/rustc_mir_transform/src/check_enums.rs b/compiler/rustc_mir_transform/src/check_enums.rs index 260028c570461..6cc12f48debb8 100644 --- a/compiler/rustc_mir_transform/src/check_enums.rs +++ b/compiler/rustc_mir_transform/src/check_enums.rs @@ -244,7 +244,7 @@ fn split_block( let block_data = &mut basic_blocks[location.block]; // Drain every statement after this one and move the current terminator to a new basic block. - let new_block = BasicBlockData::new_stmts( + let new_block = BasicBlockData::maybe_unterminated_stmts( block_data.statements.split_off(location.statement_index), block_data.terminator.take(), block_data.is_cleanup, @@ -348,7 +348,7 @@ fn insert_direct_enum_check<'tcx>( new_block: BasicBlock, ) { // Insert a new target block that is branched to in case of an invalid discriminant. - let invalid_discr_block_data = BasicBlockData::new(None, false); + let invalid_discr_block_data = BasicBlockData::maybe_unterminated(None, false); let invalid_discr_block = basic_blocks.push(invalid_discr_block_data); let block_data = &mut basic_blocks[current_block]; let discr_place = insert_discr_cast_to_u128( diff --git a/compiler/rustc_mir_transform/src/check_pointers.rs b/compiler/rustc_mir_transform/src/check_pointers.rs index 25336280926fe..0c73e3af0eb00 100644 --- a/compiler/rustc_mir_transform/src/check_pointers.rs +++ b/compiler/rustc_mir_transform/src/check_pointers.rs @@ -235,7 +235,7 @@ fn split_block( let block_data = &mut basic_blocks[location.block]; // Drain every statement after this one and move the current terminator to a new basic block. - let new_block = BasicBlockData::new_stmts( + let new_block = BasicBlockData::maybe_unterminated_stmts( block_data.statements.split_off(location.statement_index), block_data.terminator.take(), block_data.is_cleanup, diff --git a/compiler/rustc_mir_transform/src/coroutine/drop.rs b/compiler/rustc_mir_transform/src/coroutine/drop.rs index c6bd539eb6eee..69f950c6396e0 100644 --- a/compiler/rustc_mir_transform/src/coroutine/drop.rs +++ b/compiler/rustc_mir_transform/src/coroutine/drop.rs @@ -377,7 +377,7 @@ pub(super) fn create_coroutine_drop_shim_proxy_async<'tcx>( body.local_decls[RETURN_PLACE] = LocalDecl::with_source_info(poll_enum, source_info); // call coroutine_drop() - let call_bb = body.basic_blocks_mut().push(BasicBlockData::new(None, false)); + let call_bb = body.basic_blocks_mut().push(BasicBlockData::maybe_unterminated(None, false)); // return Poll::Ready() let ret_bb = insert_poll_ready_block(tcx, &mut body); diff --git a/compiler/rustc_mir_transform/src/coroutine/mod.rs b/compiler/rustc_mir_transform/src/coroutine/mod.rs index 9bf85b56a4c66..c62982764f937 100644 --- a/compiler/rustc_mir_transform/src/coroutine/mod.rs +++ b/compiler/rustc_mir_transform/src/coroutine/mod.rs @@ -252,7 +252,7 @@ impl<'tcx> TransformVisitor<'tcx> { body.basic_blocks_mut().push(BasicBlockData::new_stmts( statements, - Some(Terminator { source_info, kind: TerminatorKind::Return }), + Terminator { source_info, kind: TerminatorKind::Return }, false, )); @@ -722,7 +722,7 @@ fn insert_switch<'tcx>( // Add the switch as entry block, and put the former entry block at the end. let former_entry = std::mem::replace( &mut body.basic_blocks_mut()[START_BLOCK], - BasicBlockData::new_stmts(vec![assign], None, false), + BasicBlockData::maybe_unterminated_stmts(vec![assign], None, false), ); let former_entry = body.basic_blocks_mut().push(former_entry); @@ -742,7 +742,7 @@ fn insert_switch<'tcx>( fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock { let source_info = SourceInfo::outermost(body.span); - body.basic_blocks_mut().push(BasicBlockData::new(Some(Terminator { source_info, kind }), false)) + body.basic_blocks_mut().push(BasicBlockData::new(Terminator { source_info, kind }, false)) } fn return_poll_ready_assign<'tcx>(tcx: TyCtxt<'tcx>, source_info: SourceInfo) -> Statement<'tcx> { @@ -761,7 +761,7 @@ fn insert_poll_ready_block<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> Ba let source_info = SourceInfo::outermost(body.span); body.basic_blocks_mut().push(BasicBlockData::new_stmts( [return_poll_ready_assign(tcx, source_info)].to_vec(), - Some(Terminator { source_info, kind: TerminatorKind::Return }), + Terminator { source_info, kind: TerminatorKind::Return }, false, )) } @@ -813,7 +813,7 @@ fn insert_poll_pending_block<'tcx>( let source_info = SourceInfo::outermost(body.span); body.basic_blocks_mut().push(BasicBlockData::new_stmts( [return_poll_pending(tcx, source_info, return_type)].to_vec(), - Some(Terminator { source_info, kind: TerminatorKind::Return }), + Terminator { source_info, kind: TerminatorKind::Return }, false, )) } @@ -847,7 +847,7 @@ fn generate_poison_block_and_redirect_unwinds_there<'tcx>( let source_info = SourceInfo::outermost(body.span); let poison_block = body.basic_blocks_mut().push(BasicBlockData::new_stmts( vec![transform.set_discr(VariantIdx::new(CoroutineArgs::POISONED), source_info)], - Some(Terminator { source_info, kind: TerminatorKind::UnwindResume }), + Terminator { source_info, kind: TerminatorKind::UnwindResume }, true, )); @@ -1049,7 +1049,7 @@ fn create_cases<'tcx>( // Then jump to the real target let block = body.basic_blocks_mut().push(BasicBlockData::new_stmts( statements, - Some(Terminator { source_info, kind: TerminatorKind::goto(target) }), + Terminator { source_info, kind: TerminatorKind::goto(target) }, false, )); diff --git a/compiler/rustc_mir_transform/src/coverage/tests.rs b/compiler/rustc_mir_transform/src/coverage/tests.rs index 9fcd2a3028f84..cef8d42fb1539 100644 --- a/compiler/rustc_mir_transform/src/coverage/tests.rs +++ b/compiler/rustc_mir_transform/src/coverage/tests.rs @@ -69,10 +69,10 @@ impl<'tcx> MockBlocks<'tcx> { }; let next_hi = next_lo + BytePos(1); self.blocks.push(BasicBlockData::new( - Some(Terminator { + Terminator { source_info: SourceInfo::outermost(Span::with_root_ctxt(next_lo, next_hi)), kind, - }), + }, false, )) } diff --git a/compiler/rustc_mir_transform/src/early_otherwise_branch.rs b/compiler/rustc_mir_transform/src/early_otherwise_branch.rs index 6a34f0167354b..cc4f3e2b3911b 100644 --- a/compiler/rustc_mir_transform/src/early_otherwise_branch.rs +++ b/compiler/rustc_mir_transform/src/early_otherwise_branch.rs @@ -167,14 +167,14 @@ impl<'tcx> crate::MirPass<'tcx> for EarlyOtherwiseBranch { // Create `bbEq` in example above let eq_switch = BasicBlockData::new( - Some(Terminator { + Terminator { source_info: bbs[parent].terminator().source_info, kind: TerminatorKind::SwitchInt { // switch on the first discriminant, so we can mark the second one as dead discr: parent_op, targets: eq_targets, }, - }), + }, bbs[parent].is_cleanup, ); diff --git a/compiler/rustc_mir_transform/src/elaborate_drop.rs b/compiler/rustc_mir_transform/src/elaborate_drop.rs index dd58a72512007..0fc322e8d768b 100644 --- a/compiler/rustc_mir_transform/src/elaborate_drop.rs +++ b/compiler/rustc_mir_transform/src/elaborate_drop.rs @@ -1618,7 +1618,7 @@ where #[instrument(level = "trace", skip(self), ret)] fn new_block(&mut self, unwind: Unwind, k: TerminatorKind<'tcx>) -> BasicBlock { self.elaborator.patch().new_block(BasicBlockData::new( - Some(Terminator { source_info: self.source_info, kind: k }), + Terminator { source_info: self.source_info, kind: k }, unwind.is_cleanup(), )) } @@ -1632,7 +1632,7 @@ where ) -> BasicBlock { self.elaborator.patch().new_block(BasicBlockData::new_stmts( statements, - Some(Terminator { source_info: self.source_info, kind: k }), + Terminator { source_info: self.source_info, kind: k }, unwind.is_cleanup(), )) } diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index 501d2c38df170..bae72f0198a03 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -868,10 +868,7 @@ fn inline_call<'tcx, I: Inliner<'tcx>>( // Prepare a new block for code that should execute when call returns. We don't use // target block directly since it might have other predecessors. let data = BasicBlockData::new( - Some(Terminator { - source_info: terminator.source_info, - kind: TerminatorKind::goto(block), - }), + Terminator { source_info: terminator.source_info, kind: TerminatorKind::goto(block) }, caller_body[block].is_cleanup, ); Some(caller_body.basic_blocks_mut().push(data)) diff --git a/compiler/rustc_mir_transform/src/move_elimination.rs b/compiler/rustc_mir_transform/src/move_elimination.rs index 95a7f8cf237b5..3717dcc864c5b 100644 --- a/compiler/rustc_mir_transform/src/move_elimination.rs +++ b/compiler/rustc_mir_transform/src/move_elimination.rs @@ -742,7 +742,7 @@ fn get_or_split_edge<'tcx>( } let source_info = body.basic_blocks[pred].terminator().source_info; let split_bb = patcher.new_block(BasicBlockData::new( - Some(Terminator { source_info, kind: TerminatorKind::goto(succ) }), + Terminator { source_info, kind: TerminatorKind::goto(succ) }, body.basic_blocks[succ].is_cleanup, )); patcher.mutate_terminator(body, pred, |kind| { diff --git a/compiler/rustc_mir_transform/src/patch.rs b/compiler/rustc_mir_transform/src/patch.rs index 739fa5e37ab13..f1476108557a8 100644 --- a/compiler/rustc_mir_transform/src/patch.rs +++ b/compiler/rustc_mir_transform/src/patch.rs @@ -89,10 +89,10 @@ impl<'tcx> MirPatch<'tcx> { } let bb = self.new_block(BasicBlockData::new( - Some(Terminator { + Terminator { source_info: SourceInfo::outermost(self.body_span), kind: TerminatorKind::UnwindResume, - }), + }, true, )); self.resume_block = Some(bb); @@ -105,10 +105,10 @@ impl<'tcx> MirPatch<'tcx> { } let bb = self.new_block(BasicBlockData::new( - Some(Terminator { + Terminator { source_info: SourceInfo::outermost(self.body_span), kind: TerminatorKind::Unreachable, - }), + }, true, )); self.unreachable_cleanup_block = Some(bb); @@ -121,10 +121,10 @@ impl<'tcx> MirPatch<'tcx> { } let bb = self.new_block(BasicBlockData::new( - Some(Terminator { + Terminator { source_info: SourceInfo::outermost(self.body_span), kind: TerminatorKind::Unreachable, - }), + }, false, )); self.unreachable_no_cleanup_block = Some(bb); @@ -139,10 +139,10 @@ impl<'tcx> MirPatch<'tcx> { } let bb = self.new_block(BasicBlockData::new( - Some(Terminator { + Terminator { source_info: SourceInfo::outermost(self.body_span), kind: TerminatorKind::UnwindTerminate(reason), - }), + }, true, )); self.terminate_block = Some((bb, reason)); diff --git a/compiler/rustc_mir_transform/src/promote_consts.rs b/compiler/rustc_mir_transform/src/promote_consts.rs index 7ad164956cbfd..5be8a1b8523c8 100644 --- a/compiler/rustc_mir_transform/src/promote_consts.rs +++ b/compiler/rustc_mir_transform/src/promote_consts.rs @@ -752,10 +752,7 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> { fn new_block(&mut self) -> BasicBlock { let span = self.promoted.span; self.promoted.basic_blocks_mut().push(BasicBlockData::new( - Some(Terminator { - source_info: SourceInfo::outermost(span), - kind: TerminatorKind::Return, - }), + Terminator { source_info: SourceInfo::outermost(span), kind: TerminatorKind::Return }, false, )) } diff --git a/compiler/rustc_mir_transform/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs index 170a13ac173ea..abe3490fb7886 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -279,7 +279,7 @@ pub fn build_drop_shim<'tcx>( let return_block = BasicBlock::new(1); let mut blocks = IndexVec::with_capacity(2); let block = |blocks: &mut IndexVec<_, _>, kind| -> BasicBlock { - blocks.push(BasicBlockData::new(Some(Terminator { source_info, kind }), false)) + blocks.push(BasicBlockData::new(Terminator { source_info, kind }, false)) }; if ty.is_some() { block(&mut blocks, TerminatorKind::goto(return_block)); @@ -493,7 +493,7 @@ fn build_thread_local_shim<'tcx>(tcx: TyCtxt<'tcx>, shim: ty::ShimKind<'tcx>) -> Rvalue::ThreadLocalRef(def_id), ))), )], - Some(Terminator { source_info, kind: TerminatorKind::Return }), + Terminator { source_info, kind: TerminatorKind::Return }, false, )]); @@ -579,7 +579,7 @@ impl<'tcx> CloneShimBuilder<'tcx> { let source_info = self.source_info(); self.blocks.push(BasicBlockData::new_stmts( statements, - Some(Terminator { source_info, kind }), + Terminator { source_info, kind }, is_cleanup, )) } @@ -933,7 +933,7 @@ fn build_call_shim<'tcx>( let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| { blocks.push(BasicBlockData::new_stmts( statements, - Some(Terminator { source_info, kind }), + Terminator { source_info, kind }, is_cleanup, )) }; @@ -1060,7 +1060,7 @@ pub(super) fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> { let start_block = BasicBlockData::new_stmts( vec![statement], - Some(Terminator { source_info, kind: TerminatorKind::Return }), + Terminator { source_info, kind: TerminatorKind::Return }, false, ); @@ -1143,7 +1143,7 @@ fn build_fn_ptr_as_ptr_shim<'tcx>( let start_block = BasicBlockData::new_stmts( statements, - Some(Terminator { source_info, kind: TerminatorKind::Return }), + Terminator { source_info, kind: TerminatorKind::Return }, false, ); let source = MirSource::from_shim(ty::ShimKind::FnPtrAsPtr(def_id, self_ty)); @@ -1178,7 +1178,7 @@ fn build_fn_ptr_from_ptr_shim<'tcx>( let start_block = BasicBlockData::new_stmts( statements, - Some(Terminator { source_info, kind: TerminatorKind::Return }), + Terminator { source_info, kind: TerminatorKind::Return }, false, ); let source = MirSource::from_shim(ty::ShimKind::FnPtrFromPtr(def_id, self_ty)); @@ -1276,7 +1276,7 @@ fn build_construct_coroutine_by_move_shim<'tcx>( let statements = vec![stmt]; let start_block = BasicBlockData::new_stmts( statements, - Some(Terminator { source_info, kind: TerminatorKind::Return }), + Terminator { source_info, kind: TerminatorKind::Return }, false, ); diff --git a/compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs b/compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs index 510da5cbce89b..70de1cc6a2d63 100644 --- a/compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs +++ b/compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs @@ -85,7 +85,7 @@ pub(super) fn build_async_drop_shim<'tcx>( let return_block = BasicBlock::new(1); let mut blocks = IndexVec::with_capacity(2); let block = |blocks: &mut IndexVec<_, _>, kind| -> BasicBlock { - blocks.push(BasicBlockData::new(Some(Terminator { source_info, kind }), false)) + blocks.push(BasicBlockData::new(Terminator { source_info, kind }, false)) }; block( &mut blocks, @@ -386,7 +386,7 @@ fn build_adrop_for_adrop_shim<'tcx>( // call Pin::new_unchecked(&mut impl_cor) blocks.push(BasicBlockData::new_stmts( statements, - Some(Terminator { + Terminator { source_info, kind: TerminatorKind::Call { func: Operand::function_handle(tcx, pin_fn, &[cor_ref.into()], span), @@ -397,7 +397,7 @@ fn build_adrop_for_adrop_shim<'tcx>( call_source: CallSource::Misc, fn_span: span, }, - }), + }, false, )); // When dropping async drop coroutine, we continue its execution: @@ -405,7 +405,7 @@ fn build_adrop_for_adrop_shim<'tcx>( let poll_fn = tcx.require_lang_item(LangItem::FuturePoll, span); let resume_ctx = Place::from(Local::new(2)); blocks.push(BasicBlockData::new( - Some(Terminator { + Terminator { source_info, kind: TerminatorKind::Call { func: Operand::function_handle(tcx, poll_fn, &[impl_ty.into()], span), @@ -420,13 +420,11 @@ fn build_adrop_for_adrop_shim<'tcx>( call_source: CallSource::Misc, fn_span: span, }, - }), - false, - )); - blocks.push(BasicBlockData::new( - Some(Terminator { source_info, kind: TerminatorKind::Return }), + }, false, )); + blocks + .push(BasicBlockData::new(Terminator { source_info, kind: TerminatorKind::Return }, false)); let source = MirSource::from_shim(shim); let mut body = new_body(source, blocks, locals, sig.inputs().len(), span); diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index b3d30997aca2a..2665cb92fc8d0 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -126,6 +126,33 @@ impl OptLevel { _ => 2, } } + + /// Maps a general opt-level onto the objective it is trying to achieve. + pub fn objective(&self) -> OptimizationObjective { + match self { + OptLevel::No => OptimizationObjective::None, + OptLevel::Less => OptimizationObjective::Balanced, + OptLevel::More | OptLevel::Aggressive => OptimizationObjective::Speed, + OptLevel::Size | OptLevel::SizeMin => OptimizationObjective::Size, + } + } +} + +/// What a compilation, or a single item, is being asked to optimize *for*. +/// +/// Unlike [`OptLevel`], speed and size are alternatives here rather than degrees of the same +/// thing. Sites that map a level onto an LLVM or linker flag, where `s` and `z` produce different +/// flags, still match on [`OptLevel`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OptimizationObjective { + /// Nothing is optimized, so there is no objective (`-Copt-level=0`). + None, + /// Optimize, without a strong preference for speed over size (`-Copt-level=1`). + Balanced, + /// Favor runtime speed over binary size (`-Copt-level=2`/`3`, `#[optimize(speed)]`). + Speed, + /// Favor binary size over runtime speed (`-Copt-level=s`/`z`, `#[optimize(size)]`). + Size, } /// This is what the `LtoCli` values get mapped to after resolving defaults and @@ -1572,10 +1599,9 @@ impl Options { pub fn share_generics(&self) -> bool { match self.unstable_opts.share_generics { Some(setting) => setting, - None => match self.optimize { - OptLevel::No | OptLevel::Less | OptLevel::Size | OptLevel::SizeMin => true, - OptLevel::More | OptLevel::Aggressive => false, - }, + // Sharing instantiations means fewer copies, at the cost of leaving them opaque to + // speed optimizations. That is a good trade unless speed is what is asked for. + None => self.optimize.objective() != OptimizationObjective::Speed, } } diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index b69c26639e7e8..9bf2de0466233 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -988,6 +988,11 @@ impl Session { self.opts.unstable_opts.mir_opt_level.unwrap_or_else(|| self.opts.optimize.mir_opt_level()) } + /// What this compilation optimizes for; see [`config::OptimizationObjective`]. + pub fn optimization_objective(&self) -> config::OptimizationObjective { + self.opts.optimize.objective() + } + /// Calculates the flavor of LTO to use for this compilation. pub fn lto(&self) -> config::Lto { // If our target has codegen requirements ignore the command line diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index a7f8e37687b18..2170f610f0939 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -648,6 +648,7 @@ symbols! { clone_closures, clone_fn, clone_from, + clone_from_fn, close_fn, closure, closure_lifetime_binder, diff --git a/compiler/rustc_ty_utils/src/instance.rs b/compiler/rustc_ty_utils/src/instance.rs index 9640f9add604c..2bdffe20f5bcd 100644 --- a/compiler/rustc_ty_utils/src/instance.rs +++ b/compiler/rustc_ty_utils/src/instance.rs @@ -271,30 +271,29 @@ fn resolve_associated_item<'tcx>( } traits::ImplSource::Builtin(BuiltinImplSource::Misc | BuiltinImplSource::Trivial, _) => { if tcx.is_lang_item(trait_ref.def_id, LangItem::Clone) { - // FIXME(eddyb) use lang items for methods instead of names. - let name = tcx.item_name(trait_item_id); - if name == sym::clone { - let self_ty = trait_ref.self_ty(); - match self_ty.kind() { - ty::FnDef(..) | ty::FnPtr(..) => (), - ty::Coroutine(..) - | ty::CoroutineWitness(..) - | ty::Closure(..) - | ty::CoroutineClosure(..) - | ty::Tuple(..) => {} - _ => return Ok(None), - }; + let self_ty = trait_ref.self_ty(); + match self_ty.kind() { + ty::FnDef(..) + | ty::FnPtr(..) + | ty::Coroutine(..) + | ty::CoroutineWitness(..) + | ty::Closure(..) + | ty::CoroutineClosure(..) + | ty::Tuple(..) => {} + _ => return Ok(None), + }; - Some(Instance { + match tcx.as_lang_item(trait_item_id) { + Some(LangItem::CloneFn) => Some(Instance { def: ty::InstanceKind::Shim(ty::ShimKind::Clone(trait_item_id, self_ty)), args: rcvr_args, - }) - } else { - assert_eq!(name, sym::clone_from); - - // Use the default `fn clone_from` from `trait Clone`. - let args = tcx.erase_and_anonymize_regions(rcvr_args); - Some(ty::Instance::new_raw(trait_item_id, args)) + }), + Some(LangItem::CloneFromFn) => { + // Use the default `fn clone_from` from `trait Clone`. + let args = tcx.erase_and_anonymize_regions(rcvr_args); + Some(ty::Instance::new_raw(trait_item_id, args)) + } + _ => bug!("unknown `Clone` item"), } } else if tcx.is_lang_item(trait_ref.def_id, LangItem::FnPtrTrait) { let self_ty = trait_ref.self_ty(); diff --git a/library/core/src/clone.rs b/library/core/src/clone.rs index 61528873a38c7..a549e12c33995 100644 --- a/library/core/src/clone.rs +++ b/library/core/src/clone.rs @@ -242,6 +242,7 @@ pub const trait Clone: Sized { /// allocations. #[inline] #[stable(feature = "rust1", since = "1.0.0")] + #[lang = "clone_from_fn"] fn clone_from(&mut self, source: &Self) where Self: [const] Destruct, diff --git a/library/core/src/num/int_macros.rs b/library/core/src/num/int_macros.rs index 96981a75d98f2..fb86481c42443 100644 --- a/library/core/src/num/int_macros.rs +++ b/library/core/src/num/int_macros.rs @@ -56,6 +56,78 @@ macro_rules! int_impl { #[stable(feature = "int_bits_const", since = "1.53.0")] pub const BITS: u32 = <$UnsignedT>::BITS; + /// Tests the value of a specific bit. + /// + /// # Panics + /// + /// If overflow checks are enabled, this method will panic if the provided index is + /// greater than or equal to [`BITS`]. + /// + /// [`BITS`]: Self::BITS + /// + /// # Examples + /// + /// ``` + /// #![feature(get_set_bit)] + /// + #[doc = concat!("let n = 0b111_1001", stringify!($SelfT), ";")] + /// + /// assert!(n.bit(0)); + /// assert!(!n.bit(1)); + /// assert!(!n.bit(2)); + /// assert!(n.bit(3)); + /// assert!(n.bit(4)); + /// assert!(n.bit(5)); + /// assert!(n.bit(6)); + /// ``` + #[unstable(feature = "get_set_bit", issue = "147702")] + #[rustc_const_unstable(feature = "get_set_bit", issue = "147702")] + #[rustc_inherit_overflow_checks] + #[inline] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[track_caller] + pub const fn bit(self, index: u32) -> bool { + self.cast_unsigned().bit(index) + } + + /// Sets the value of a specific bit. + /// + /// # Panics + /// + /// If overflow checks are enabled, this method will panic if the provided index is + /// greater than or equal to [`BITS`]. + /// + /// [`BITS`]: Self::BITS + /// + /// # Examples + /// + /// ``` + /// #![feature(get_set_bit)] + /// + #[doc = concat!("let mut n = 0b101_0101", stringify!($SelfT), ";")] + /// + /// n = n.set_bit(0, false); + /// n = n.set_bit(1, true); + /// n = n.set_bit(2, false); + /// n = n.set_bit(3, true); + /// n = n.set_bit(4, false); + /// n = n.set_bit(5, true); + /// n = n.set_bit(6, false); + /// + /// assert_eq!(n, 0b010_1010); + /// ``` + #[unstable(feature = "get_set_bit", issue = "147702")] + #[rustc_const_unstable(feature = "get_set_bit", issue = "147702")] + #[rustc_inherit_overflow_checks] + #[inline] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[track_caller] + pub const fn set_bit(self, index: u32, value: bool) -> Self { + self.cast_unsigned().set_bit(index, value).cast_signed() + } + /// Returns the number of ones in the binary representation of `self`. /// /// # Examples diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs index 84107ec3f1883..e202621673604 100644 --- a/library/core/src/num/uint_macros.rs +++ b/library/core/src/num/uint_macros.rs @@ -60,6 +60,83 @@ macro_rules! uint_impl { #[stable(feature = "int_bits_const", since = "1.53.0")] pub const BITS: u32 = Self::MAX.count_ones(); + /// Tests the value of a specific bit. + /// + /// # Panics + /// + /// If overflow checks are enabled, this method will panic if the provided index is + /// greater than or equal to [`BITS`]. + /// + /// [`BITS`]: Self::BITS + /// + /// # Examples + /// + /// ``` + /// #![feature(get_set_bit)] + /// + #[doc = concat!("let n = 0b0111_1001", stringify!($SelfT), ";")] + /// + /// assert!(n.bit(0)); + /// assert!(!n.bit(1)); + /// assert!(!n.bit(2)); + /// assert!(n.bit(3)); + /// assert!(n.bit(4)); + /// assert!(n.bit(5)); + /// assert!(n.bit(6)); + /// assert!(!n.bit(7)); + /// ``` + #[unstable(feature = "get_set_bit", issue = "147702")] + #[rustc_const_unstable(feature = "get_set_bit", issue = "147702")] + #[rustc_inherit_overflow_checks] + #[inline] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[track_caller] + pub const fn bit(self, index: u32) -> bool { + (self & (1 << index)) != 0 + } + + /// Sets the value of a specific bit. + /// + /// # Panics + /// + /// If overflow checks are enabled, this method will panic if the provided index is + /// greater than or equal [`BITS`]. + /// + /// [`BITS`]: Self::BITS + /// + /// # Examples + /// + /// ``` + /// #![feature(get_set_bit)] + /// + #[doc = concat!("let mut n = 0b0101_0101", stringify!($SelfT), ";")] + /// + /// n = n.set_bit(0, false); + /// n = n.set_bit(1, true); + /// n = n.set_bit(2, false); + /// n = n.set_bit(3, true); + /// n = n.set_bit(4, false); + /// n = n.set_bit(5, true); + /// n = n.set_bit(6, false); + /// n = n.set_bit(7, true); + /// + /// assert_eq!(n, 0b1010_1010); + /// ``` + #[unstable(feature = "get_set_bit", issue = "147702")] + #[rustc_const_unstable(feature = "get_set_bit", issue = "147702")] + #[rustc_inherit_overflow_checks] + #[inline] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[track_caller] + pub const fn set_bit(mut self, index: u32, value: bool) -> Self { + self &= !(1 << index); + self |= (value as $SelfT) << index; + + self + } + /// Returns the number of ones in the binary representation of `self`. /// /// # Examples diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs index 4e1b1a1aa6f6e..c9c07fe817cac 100644 --- a/library/coretests/tests/lib.rs +++ b/library/coretests/tests/lib.rs @@ -71,6 +71,7 @@ #![feature(freeze)] #![feature(future_join)] #![feature(generic_assert_internals)] +#![feature(get_set_bit)] #![feature(hasher_prefixfree_extras)] #![feature(hashmap_internals)] #![feature(int_from_ascii)] diff --git a/library/coretests/tests/num/int_macros.rs b/library/coretests/tests/num/int_macros.rs index f391fe23cd1f5..6165edc6dda1e 100644 --- a/library/coretests/tests/num/int_macros.rs +++ b/library/coretests/tests/num/int_macros.rs @@ -32,7 +32,6 @@ macro_rules! int_module { } test_runtime_and_compiletime! { - fn test_rem_euclid() { assert_eq_const_safe!($T: (-1 as $T).rem_euclid(MIN), MAX); } @@ -73,6 +72,58 @@ macro_rules! int_module { const _1: $T = !0; test_runtime_and_compiletime! { + fn test_bit() { + assert!(!A.bit(0)); + assert!(!A.bit(1)); + assert!(A.bit(2)); + assert!(A.bit(3)); + assert!(!A.bit(4)); + assert!(A.bit(5)); + assert!(!A.bit(6)); + + assert!(B.bit(0)); + assert!(!B.bit(1)); + assert!(!B.bit(2)); + assert!(!B.bit(3)); + assert!(!B.bit(4)); + assert!(B.bit(5)); + assert!(!B.bit(6)); + + assert!(C.bit(0)); + assert!(!C.bit(1)); + assert!(!C.bit(2)); + assert!(C.bit(3)); + assert!(C.bit(4)); + assert!(C.bit(5)); + assert!(C.bit(6)); + } + + fn test_set_bit() { + assert_eq_const_safe!($T: A.set_bit(0, true), 0b0101101); + assert_eq_const_safe!($T: A.set_bit(1, true), 0b0101110); + assert_eq_const_safe!($T: A.set_bit(2, false), 0b0101000); + assert_eq_const_safe!($T: A.set_bit(3, false), 0b0100100); + assert_eq_const_safe!($T: A.set_bit(4, true), 0b0111100); + assert_eq_const_safe!($T: A.set_bit(5, false), 0b0001100); + assert_eq_const_safe!($T: A.set_bit(6, true), 0b1101100); + + assert_eq_const_safe!($T: B.set_bit(0, false), 0b0100000); + assert_eq_const_safe!($T: B.set_bit(1, true), 0b0100011); + assert_eq_const_safe!($T: B.set_bit(2, true), 0b0100101); + assert_eq_const_safe!($T: B.set_bit(3, true), 0b0101001); + assert_eq_const_safe!($T: B.set_bit(4, true), 0b0110001); + assert_eq_const_safe!($T: B.set_bit(5, false), 0b0000001); + assert_eq_const_safe!($T: B.set_bit(6, true), 0b1100001); + + assert_eq_const_safe!($T: C.set_bit(0, false), 0b1111000); + assert_eq_const_safe!($T: C.set_bit(1, true), 0b1111011); + assert_eq_const_safe!($T: C.set_bit(2, true), 0b1111101); + assert_eq_const_safe!($T: C.set_bit(3, false), 0b1110001); + assert_eq_const_safe!($T: C.set_bit(4, false), 0b1101001); + assert_eq_const_safe!($T: C.set_bit(5, false), 0b1011001); + assert_eq_const_safe!($T: C.set_bit(6, false), 0b0111001); + } + fn test_count_ones() { assert_eq_const_safe!(u32: A.count_ones(), 3); assert_eq_const_safe!(u32: B.count_ones(), 2); diff --git a/library/coretests/tests/num/uint_macros.rs b/library/coretests/tests/num/uint_macros.rs index 4dfcb1b8b4688..9d500d1578b64 100644 --- a/library/coretests/tests/num/uint_macros.rs +++ b/library/coretests/tests/num/uint_macros.rs @@ -35,6 +35,58 @@ macro_rules! uint_module { const _1: $T = !0; test_runtime_and_compiletime! { + fn test_bit() { + assert!(!A.bit(0)); + assert!(!A.bit(1)); + assert!(A.bit(2)); + assert!(A.bit(3)); + assert!(!A.bit(4)); + assert!(A.bit(5)); + assert!(!A.bit(6)); + + assert!(B.bit(0)); + assert!(!B.bit(1)); + assert!(!B.bit(2)); + assert!(!B.bit(3)); + assert!(!B.bit(4)); + assert!(B.bit(5)); + assert!(!B.bit(6)); + + assert!(C.bit(0)); + assert!(!C.bit(1)); + assert!(!C.bit(2)); + assert!(C.bit(3)); + assert!(C.bit(4)); + assert!(C.bit(5)); + assert!(C.bit(6)); + } + + fn test_set_bit() { + assert_eq_const_safe!($T: A.set_bit(0, true), 0b0101101); + assert_eq_const_safe!($T: A.set_bit(1, true), 0b0101110); + assert_eq_const_safe!($T: A.set_bit(2, false), 0b0101000); + assert_eq_const_safe!($T: A.set_bit(3, false), 0b0100100); + assert_eq_const_safe!($T: A.set_bit(4, true), 0b0111100); + assert_eq_const_safe!($T: A.set_bit(5, false), 0b0001100); + assert_eq_const_safe!($T: A.set_bit(6, true), 0b1101100); + + assert_eq_const_safe!($T: B.set_bit(0, false), 0b0100000); + assert_eq_const_safe!($T: B.set_bit(1, true), 0b0100011); + assert_eq_const_safe!($T: B.set_bit(2, true), 0b0100101); + assert_eq_const_safe!($T: B.set_bit(3, true), 0b0101001); + assert_eq_const_safe!($T: B.set_bit(4, true), 0b0110001); + assert_eq_const_safe!($T: B.set_bit(5, false), 0b0000001); + assert_eq_const_safe!($T: B.set_bit(6, true), 0b1100001); + + assert_eq_const_safe!($T: C.set_bit(0, false), 0b1111000); + assert_eq_const_safe!($T: C.set_bit(1, true), 0b1111011); + assert_eq_const_safe!($T: C.set_bit(2, true), 0b1111101); + assert_eq_const_safe!($T: C.set_bit(3, false), 0b1110001); + assert_eq_const_safe!($T: C.set_bit(4, false), 0b1101001); + assert_eq_const_safe!($T: C.set_bit(5, false), 0b1011001); + assert_eq_const_safe!($T: C.set_bit(6, false), 0b0111001); + } + fn test_count_ones() { assert!(A.count_ones() == 3); assert!(B.count_ones() == 2); diff --git a/library/std/src/sys/net/connection/socket/unix.rs b/library/std/src/sys/net/connection/socket/unix.rs index 0f80646449e1f..9c8b9e6f3a2e6 100644 --- a/library/std/src/sys/net/connection/socket/unix.rs +++ b/library/std/src/sys/net/connection/socket/unix.rs @@ -172,7 +172,9 @@ impl Socket { } pub fn poll_connected(&self, timeout: Duration) -> io::Result<()> { - let mut pollfd = libc::pollfd { fd: self.as_raw_fd(), events: libc::POLLOUT, revents: 0 }; + let mut pollfd: libc::pollfd = unsafe { mem::zeroed() }; + pollfd.fd = self.as_raw_fd(); + pollfd.events = libc::POLLOUT; if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 { return Err(io::Error::ZERO_TIMEOUT); diff --git a/library/std/src/sys/pal/unix/mod.rs b/library/std/src/sys/pal/unix/mod.rs index 53bbdfc988a8f..4b0bbdaf073ca 100644 --- a/library/std/src/sys/pal/unix/mod.rs +++ b/library/std/src/sys/pal/unix/mod.rs @@ -88,13 +88,16 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { )))] 'poll: { use crate::sys::io::errno; - let pfds: &mut [_] = &mut [ - libc::pollfd { fd: 0, events: 0, revents: 0 }, - libc::pollfd { fd: 1, events: 0, revents: 0 }, - libc::pollfd { fd: 2, events: 0, revents: 0 }, - ]; - while libc::poll(pfds.as_mut_ptr(), 3, 0) == -1 { + let mut pfds: [libc::pollfd; 3] = crate::mem::zeroed(); + pfds[0].fd = 0; + pfds[0].events = 0; + pfds[1].fd = 1; + pfds[1].events = 0; + pfds[2].fd = 2; + pfds[2].events = 0; + + while libc::poll(pfds.as_mut_ptr(), pfds.len() as libc::nfds_t, 0) == -1 { match errno() { libc::EINTR => continue, #[cfg(target_vendor = "unikraft")] diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 3bf73c67bc0c1..d3d3cef8d7860 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -608,8 +608,9 @@ pub(crate) fn build_impl( }; let trait_ = associated_trait .map(|t| clean_trait_ref_with_constraints(cx, ty::Binder::dummy(t), ThinVec::new())); - if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() - && polarity != ty::ImplPolarity::Negative + if trait_ + .as_ref() + .is_some_and(|t| polarity != ty::ImplPolarity::Negative && t.is_deref_trait(tcx)) { super::build_deref_target_impls(cx, &trait_items, ret); } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index b8e9d8a3f4633..79840366fc74c 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -3064,7 +3064,7 @@ fn clean_impl<'tcx>( // If this impl block is a positive implementation of the Deref trait, then we // need to try inlining the target's inherent impl blocks as well. - if trait_.as_ref().is_some_and(|t| tcx.lang_items().deref_trait() == Some(t.def_id())) + if trait_.as_ref().is_some_and(|t| t.is_deref_trait(tcx)) && tcx.impl_polarity(def_id) != ty::ImplPolarity::Negative { build_deref_target_impls(cx, &items, &mut ret); diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 2dcf3d51fc509..a200b6c3c14dc 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -21,7 +21,7 @@ use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId}; use rustc_hir::{BodyId, Mutability}; use rustc_index::IndexVec; use rustc_metadata::rendered_const; -use rustc_middle::ty::fast_reject::SimplifiedType; +use rustc_middle::ty::fast_reject::{DeepRejectCtxt, SimplifiedType}; use rustc_middle::ty::{self, Ty, TyCtxt, Visibility}; use rustc_resolve::rustdoc::{ DocFragment, add_doc_fragment, attrs_to_doc_fragments, span_of_fragments, @@ -1348,6 +1348,22 @@ pub(crate) struct PolyTrait { pub(crate) generic_params: Vec, } +// Also used in `write_shared.rs` when generating the JS `impl` file for aliased types. +// +// FIXME(checked_type_alias): Once the feature is complete or stable, rewrite this +// to use type unification. +// Be aware of `tests/rustdoc-html/type-alias/deeply-nested-112515.rs` which might +// regress. +pub(crate) fn impl_may_apply_to_type_alias( + tcx: TyCtxt<'_>, + alias_def_id: DefId, + impl_def_id: DefId, +) -> bool { + let alias_ty = tcx.type_of(alias_def_id).skip_binder(); + let for_ty = tcx.type_of(impl_def_id).skip_binder(); + DeepRejectCtxt::relate_infer_infer(tcx).types_may_unify(alias_ty, for_ty) +} + /// Rustdoc's representation of types, mostly based on the [`hir::Ty`]. #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub(crate) enum Type { @@ -1437,7 +1453,7 @@ impl Type { /// /// An owned type is also the same as its borrowed variants (this is commutative), /// but `&T` is not the same as `&mut T`. - pub(crate) fn is_doc_subtype_of(&self, other: &Self, cache: &Cache) -> bool { + pub(crate) fn is_doc_subtype_of(&self, other: &Self, cx: &Context<'_>) -> bool { // Strip the references so that it can compare the actual types, unless both are references. // If both are references, leave them alone and compare the mutabilities later. let (self_cleared, other_cleared) = if !self.is_borrowed_ref() || !other.is_borrowed_ref() { @@ -1446,29 +1462,33 @@ impl Type { (self, other) }; - // FIXME: `Cache` does not have the data required to unwrap type aliases, - // so we just assume they are equal. - // This is only remotely acceptable because we were previously - // assuming all types were equal when used - // as a generic parameter of a type in `Deref::Target`. + // FIXME(checked_type_alias): Once the feature is complete or stable, rewrite this + // to use type unification. + // Be aware of `tests/rustdoc-html/type-alias/deeply-nested-112515.rs` which might + // regress. if self_cleared.is_type_alias() || other_cleared.is_type_alias() { - return true; + let cache = cx.cache(); + if let Some(self_def_id) = self_cleared.def_id(&cache) + && let Some(other_def_id) = other_cleared.def_id(&cache) + { + return impl_may_apply_to_type_alias(cx.tcx(), self_def_id, other_def_id); + } } match (self_cleared, other_cleared) { // Recursive cases. (Type::Tuple(a), Type::Tuple(b)) => { - a.iter().eq_by(b, |a, b| a.is_doc_subtype_of(b, cache)) + a.iter().eq_by(b, |a, b| a.is_doc_subtype_of(b, cx)) } - (Type::Slice(a), Type::Slice(b)) => a.is_doc_subtype_of(b, cache), - (Type::Array(a, al), Type::Array(b, bl)) => al == bl && a.is_doc_subtype_of(b, cache), + (Type::Slice(a), Type::Slice(b)) => a.is_doc_subtype_of(b, cx), + (Type::Array(a, al), Type::Array(b, bl)) => al == bl && a.is_doc_subtype_of(b, cx), (Type::RawPointer(mutability, type_), Type::RawPointer(b_mutability, b_type_)) => { - mutability == b_mutability && type_.is_doc_subtype_of(b_type_, cache) + mutability == b_mutability && type_.is_doc_subtype_of(b_type_, cx) } ( Type::BorrowedRef { mutability, type_, .. }, Type::BorrowedRef { mutability: b_mutability, type_: b_type_, .. }, - ) => mutability == b_mutability && type_.is_doc_subtype_of(b_type_, cache), + ) => mutability == b_mutability && type_.is_doc_subtype_of(b_type_, cx), // Placeholders are equal to all other types. (Type::Infer, _) | (_, Type::Infer) => true, // Generics match everything on the right, but not on the left. @@ -1482,13 +1502,13 @@ impl Type { a.def_id() == b.def_id() && a.generics() .zip(b.generics()) - .map(|(ag, bg)| ag.zip(bg).all(|(at, bt)| at.is_doc_subtype_of(bt, cache))) + .map(|(ag, bg)| ag.zip(bg).all(|(at, bt)| at.is_doc_subtype_of(bt, cx))) .unwrap_or(true) } // Other cases, such as primitives, just use recursion. (a, b) => a - .def_id(cache) - .and_then(|a| Some((a, b.def_id(cache)?))) + .def_id(cx.cache()) + .and_then(|a| Some((a, b.def_id(cx.cache())?))) .map(|(a, b)| a == b) .unwrap_or(false), } @@ -2117,6 +2137,10 @@ impl Path { } }) } + + pub(crate) fn is_deref_trait(&self, tcx: TyCtxt<'_>) -> bool { + tcx.lang_items().deref_trait() == Some(self.def_id()) + } } #[derive(Clone, PartialEq, Eq, Debug, Hash)] diff --git a/src/librustdoc/clean/types/tests.rs b/src/librustdoc/clean/types/tests.rs index 29a8fd5e2678e..13437e5a008c6 100644 --- a/src/librustdoc/clean/types/tests.rs +++ b/src/librustdoc/clean/types/tests.rs @@ -69,16 +69,3 @@ fn should_not_trim() { run_test("\t line1 \n\t line2", "line1 \nline2"); run_test(" \tline1 \n \tline2", "line1 \nline2"); } - -#[test] -fn is_same_generic() { - use crate::clean::types::{PrimitiveType, Type}; - use crate::formats::cache::Cache; - create_default_session_globals_then(|| { - let cache = Cache::new(false, false); - let generic = Type::Generic(sym::character('T')); - let unit = Type::Primitive(PrimitiveType::Unit); - assert!(!generic.is_doc_subtype_of(&unit, &cache)); - assert!(unit.is_doc_subtype_of(&generic, &cache)); - }) -} diff --git a/src/librustdoc/formats/mod.rs b/src/librustdoc/formats/mod.rs index e9cbefea4a982..6135c0d7b3160 100644 --- a/src/librustdoc/formats/mod.rs +++ b/src/librustdoc/formats/mod.rs @@ -4,6 +4,7 @@ pub(crate) mod renderer; pub(crate) use renderer::{FormatRenderer, run_format}; use rustc_hir::def_id::DefId; +use rustc_middle::ty::TyCtxt; use crate::clean::{self, ItemId}; use crate::html::render::Context; @@ -26,6 +27,14 @@ impl Impl { self.inner_impl().trait_.as_ref().map(|t| t.def_id()) } + pub(crate) fn is_deref_trait(&self, tcx: TyCtxt<'_>) -> bool { + self.trait_did().is_some_and(|did| Some(did) == tcx.lang_items().deref_trait()) + } + + pub(crate) fn is_deref_mut_trait(&self, tcx: TyCtxt<'_>) -> bool { + self.trait_did().is_some_and(|did| Some(did) == tcx.lang_items().deref_mut_trait()) + } + /// This function is used to extract a `DefId` to be used as a key for the `Cache::impls` field. /// /// It allows to prevent having duplicated implementations showing up (the biggest issue was diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 7b2cad75050c7..0a771497860e6 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -39,7 +39,7 @@ mod sorted_template; mod type_layout; mod write_shared; -use std::borrow::Cow; +use std::borrow::{Borrow, Cow}; use std::cmp::Ordering; use std::collections::{BTreeMap, VecDeque}; use std::fmt::{self, Display as _, Write}; @@ -1402,16 +1402,77 @@ fn render_all_impls( Ok(()) } +fn aliased_type_deref_impl<'a>( + cx: &'a Context<'_>, + alias_def_id: DefId, + aliased_def_id: DefId, +) -> Option<(&'a Impl, bool)> { + let tcx = cx.tcx(); + let applies = |impl_: &Impl| { + impl_.impl_item.item_id.as_def_id().is_some_and(|impl_def_id| { + clean::types::impl_may_apply_to_type_alias(tcx, alias_def_id, impl_def_id) + }) + }; + let impls = cx.cache().impls.get(&aliased_def_id)?; + let mut deref_impl = None; + let mut has_deref_mut = false; + + for impl_ in impls { + if impl_.is_deref_trait(tcx) { + if !impl_.is_negative_trait_impl() && applies(impl_) { + deref_impl = Some(impl_); + } + } else if impl_.is_deref_mut_trait(tcx) && applies(impl_) { + has_deref_mut = true; + } + } + Some((deref_impl?, has_deref_mut)) +} + +/// Try to get the `Deref` trait `Impl` for `item`. If it cannot be found, it will try to do the +/// same with `aliased_type`. Returns a tuple containing the `Deref` `Impl`, and a bool set to +/// `true` if `DerefMut` is also implemented. +fn get_deref_impls<'a, I: Borrow>( + cx: &'a Context<'_>, + trait_impls: &'a [I], + item: DefId, + aliased_type: Option, +) -> Option<(&'a Impl, bool)> { + let tcx = cx.tcx(); + let mut impls = trait_impls.iter().map(|t| t.borrow()); + if let Some(impl_) = + impls.clone().find(|t| t.is_deref_trait(tcx) && !t.is_negative_trait_impl()) + { + let has_deref_mut = impls.any(|t| t.is_deref_mut_trait(tcx)); + Some((impl_, has_deref_mut)) + } else { + aliased_type.and_then(|aliased_did| aliased_type_deref_impl(cx, item, aliased_did)) + } +} + fn render_assoc_items( cx: &Context<'_>, containing_item: &clean::Item, it: DefId, what: AssocItemRender<'_>, +) -> impl fmt::Display { + render_assoc_items_with_aliased_type(cx, containing_item, it, what, None) +} + +fn render_assoc_items_with_aliased_type( + cx: &Context<'_>, + containing_item: &clean::Item, + it: DefId, + what: AssocItemRender<'_>, + aliased_type: Option, ) -> impl fmt::Display { fmt::from_fn(move |f| { let mut derefs = DefIdSet::default(); derefs.insert(it); - render_assoc_items_inner(f, cx, containing_item, it, what, &mut derefs) + if let Some(aliased_type) = aliased_type { + derefs.insert(aliased_type); + } + render_assoc_items_inner(f, cx, containing_item, it, what, &mut derefs, aliased_type) }) } @@ -1422,10 +1483,15 @@ fn render_assoc_items_inner( it: DefId, what: AssocItemRender<'_>, derefs: &mut DefIdSet, + aliased_type: Option, ) -> fmt::Result { info!("Documenting associated items of {:?}", containing_item.name); let cache = &cx.shared.cache; - let Some(impls) = cache.impls.get(&it) else { return Ok(()) }; + let impls = match cache.impls.get(&it) { + Some(impls) => impls.as_slice(), + None if aliased_type.is_some() => &[], + None => return Ok(()), + }; let (mut inherent_impls, trait_impls): (Vec<_>, _) = impls.iter().partition(|i| i.inner_impl().trait_.is_none()); if !inherent_impls.is_empty() { @@ -1451,9 +1517,8 @@ fn render_assoc_items_inner( // we should not show methods from `[MaybeUninit]`. // this `retain` filters out any instances where // the types do not line up perfectly. - inherent_impls.retain(|impl_| { - type_.is_doc_subtype_of(&impl_.inner_impl().for_, &cx.shared.cache) - }); + inherent_impls + .retain(|impl_| type_.is_doc_subtype_of(&impl_.inner_impl().for_, &cx)); let derived_id = cx.derive_id(&id); if let Some(def_id) = type_.def_id(cx.cache()) { cx.deref_id_map.borrow_mut().insert(def_id, id.clone()); @@ -1513,17 +1578,11 @@ fn render_assoc_items_inner( } } - if !trait_impls.is_empty() { - let deref_impl = trait_impls.iter().find(|t| { - t.trait_did() == cx.tcx().lang_items().deref_trait() && !t.is_negative_trait_impl() - }); - if let Some(impl_) = deref_impl { - let has_deref_mut = trait_impls - .iter() - .any(|t| t.trait_did() == cx.tcx().lang_items().deref_mut_trait()); - render_deref_methods(&mut w, cx, impl_, containing_item, has_deref_mut, derefs)?; - } + if let Some((impl_, has_deref_mut)) = get_deref_impls(cx, &trait_impls, it, aliased_type) { + render_deref_methods(&mut w, cx, impl_, containing_item, has_deref_mut, derefs)?; + } + if !trait_impls.is_empty() { // If we were already one level into rendering deref methods, we don't want to render // anything after recursing into any further deref methods above. if let AssocItemRender::DerefFor { .. } = what { @@ -1580,11 +1639,11 @@ fn render_deref_methods( return Ok(()); } } - render_assoc_items_inner(&mut w, cx, container_item, did, what, derefs)?; + render_assoc_items_inner(&mut w, cx, container_item, did, what, derefs, None)?; } else if let Some(prim) = target.primitive_type() && let Some(&did) = cache.primitive_locations.get(&prim) { - render_assoc_items_inner(&mut w, cx, container_item, did, what, derefs)?; + render_assoc_items_inner(&mut w, cx, container_item, did, what, derefs, None)?; } Ok(()) } @@ -1641,7 +1700,7 @@ fn notable_traits_button(ty: &clean::Type, cx: &Context<'_>) -> Option) -> (String, .filter(|impl_| impl_.polarity == ty::ImplPolarity::Positive) .filter(|impl_| { // Two different types might have the same did, without actually being the same. - ty.is_doc_subtype_of(&impl_.for_, cx.cache()) + ty.is_doc_subtype_of(&impl_.for_, cx) }) .filter_map(|impl_| { if let Some(trait_) = &impl_.trait_ diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index fe495f8558f77..8de8bd23cadbd 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -22,9 +22,9 @@ use super::{ AssocItemLink, AssocItemRender, Context, ImplRenderingParameters, RenderMode, collect_paths_for_type, document, ensure_trailing_slash, get_filtered_impls_for_reference, item_ty_to_section, notable_traits_button, notable_traits_json, render_all_impls, - render_assoc_item, render_assoc_items, render_attributes_in_code, render_impl, - render_repr_attribute_in_code, render_rightside, render_stability_since_raw, - render_stability_since_raw_with_extra, write_section_heading, + render_assoc_item, render_assoc_items, render_assoc_items_with_aliased_type, + render_attributes_in_code, render_impl, render_repr_attribute_in_code, render_rightside, + render_stability_since_raw, render_stability_since_raw_with_extra, write_section_heading, }; use crate::clean::{self, ItemKind}; use crate::config::ModuleSorting; @@ -1488,7 +1488,13 @@ impl<'a, 'cx: 'a> ItemUnion<'a, 'cx> { fn render_assoc_items(&self) -> impl fmt::Display { let def_id = self.it.item_id.expect_def_id(); - render_assoc_items(self.cx, self.it, def_id, AssocItemRender::All) + render_assoc_items_with_aliased_type( + self.cx, + self.it, + def_id, + AssocItemRender::All, + if self.is_type_alias { Some(self.def_id) } else { None }, + ) } fn render_union(&self) -> impl Display { @@ -1631,7 +1637,13 @@ impl<'clean> DisplayEnum<'clean> { write!( w, "{}{}", - render_assoc_items(cx, it, def_id, AssocItemRender::All), + render_assoc_items_with_aliased_type( + cx, + it, + def_id, + AssocItemRender::All, + if is_type_alias { Some(self.def_id) } else { None }, + ), document_type_layout(cx, layout_def_id) ) } @@ -2084,7 +2096,13 @@ impl<'a> DisplayStruct<'a> { w, "{}{}{}", item_fields(cx, it, self.fields, self.ctor_kind), - render_assoc_items(cx, it, def_id, AssocItemRender::All), + render_assoc_items_with_aliased_type( + cx, + it, + def_id, + AssocItemRender::All, + if is_type_alias { Some(self.def_id) } else { None }, + ), document_type_layout(cx, def_id), ) } diff --git a/src/librustdoc/html/render/sidebar.rs b/src/librustdoc/html/render/sidebar.rs index 90077b1aa5f9e..e754854d13bd6 100644 --- a/src/librustdoc/html/render/sidebar.rs +++ b/src/librustdoc/html/render/sidebar.rs @@ -5,7 +5,7 @@ use std::fmt; use askama::Template; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir::def::CtorKind; -use rustc_hir::def_id::{DefIdMap, DefIdSet}; +use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet}; use tracing::debug; use super::{Context, ItemSection, impl_trait_key, item_ty_to_section}; @@ -284,7 +284,7 @@ fn sidebar_struct<'a>( if let Some(name) = field_name { items.push(LinkBlock::new(Link::new("fields", name), "structfield", fields)); } - sidebar_assoc_items(cx, it, items, deref_id_map); + sidebar_assoc_items(cx, it.item_id.expect_def_id(), items, deref_id_map); } fn sidebar_trait<'a>( @@ -357,7 +357,7 @@ fn sidebar_trait<'a>( prov_assoc_fns, )); - sidebar_assoc_items(cx, it, blocks, deref_id_map); + sidebar_assoc_items(cx, it.item_id.expect_def_id(), blocks, deref_id_map); blocks.push(LinkBlock::forced( Link::new("dyn-compatibility", "Dyn Compatibility"), @@ -386,7 +386,7 @@ fn sidebar_primitive<'a>( deref_id_map: &'a DefIdMap, ) { if it.name.map(|n| n.as_str() != "reference").unwrap_or(false) { - sidebar_assoc_items(cx, it, items, deref_id_map); + sidebar_assoc_items(cx, it.item_id.expect_def_id(), items, deref_id_map); } else { let (concrete, synthetic, blanket_impl) = super::get_filtered_impls_for_reference(&cx.shared, it); @@ -423,7 +423,17 @@ fn sidebar_type_alias<'a>( } } } - sidebar_assoc_items(cx, it, items, deref_id_map); + let alias_def_id = it.item_id.expect_def_id(); + let aliased_type = t.inner_type.as_ref().and_then(|_| { + cx.tcx().type_of(alias_def_id).instantiate_identity().skip_norm_wip().ty_adt_def() + }); + sidebar_assoc_items_with_aliased_type( + cx, + alias_def_id, + items, + deref_id_map, + aliased_type.map(|adt| adt.did()), + ); } fn sidebar_union<'a>( @@ -435,106 +445,106 @@ fn sidebar_union<'a>( ) { let fields = get_struct_fields_name(&u.fields); items.push(LinkBlock::new(Link::new("fields", "Fields"), "structfield", fields)); - sidebar_assoc_items(cx, it, items, deref_id_map); + sidebar_assoc_items(cx, it.item_id.expect_def_id(), items, deref_id_map); } /// Adds trait implementations into the blocks of links fn sidebar_assoc_items<'a>( cx: &'a Context<'_>, - it: &'a clean::Item, + item_def_id: DefId, + links: &mut Vec>, + deref_id_map: &'a DefIdMap, +) { + sidebar_assoc_items_with_aliased_type(cx, item_def_id, links, deref_id_map, None) +} + +fn sidebar_assoc_items_with_aliased_type<'a>( + cx: &'a Context<'_>, + item_def_id: DefId, links: &mut Vec>, deref_id_map: &'a DefIdMap, + aliased_type: Option, ) { - let did = it.item_id.expect_def_id(); let cache = cx.cache(); + let v = match cache.impls.get(&item_def_id) { + Some(impls) => impls.as_slice(), + None if aliased_type.is_some() => &[], + None => return, + }; let mut assoc_consts = Vec::new(); let mut assoc_types = Vec::new(); let mut assoc_fns = Vec::new(); let mut methods = Vec::new(); - if let Some(v) = cache.impls.get(&did) { - let mut used_links = UsedLinks::default(); - let mut id_map = IdMap::new(); + let mut used_links = UsedLinks::default(); + let mut id_map = IdMap::new(); - { - let used_links_bor = &mut used_links; - for impl_ in v.iter().map(|i| i.inner_impl()).filter(|i| i.trait_.is_none()) { - assoc_consts.extend(get_associated_constants(impl_, used_links_bor)); - assoc_types.extend(get_associated_types(impl_, used_links_bor)); - methods.extend(get_methods( - impl_, - GetMethodsMode::AlsoCollectAssocFns { assoc_fns: &mut assoc_fns }, - used_links_bor, - cx, - )); - } - // We want links' order to be reproducible so we don't use unstable sort. - assoc_consts.sort(); - assoc_types.sort(); - postprocess_method_list(&mut assoc_fns); - postprocess_method_list(&mut methods); + { + let used_links_bor = &mut used_links; + for impl_ in v.iter().map(|i| i.inner_impl()).filter(|i| i.trait_.is_none()) { + assoc_consts.extend(get_associated_constants(impl_, used_links_bor)); + assoc_types.extend(get_associated_types(impl_, used_links_bor)); + methods.extend(get_methods( + impl_, + GetMethodsMode::AlsoCollectAssocFns { assoc_fns: &mut assoc_fns }, + used_links_bor, + cx, + )); } + // We want links' order to be reproducible so we don't use unstable sort. + assoc_consts.sort(); + assoc_types.sort(); + postprocess_method_list(&mut assoc_fns); + postprocess_method_list(&mut methods); + } - let mut blocks = vec![ - LinkBlock::new( - Link::new("implementations", "Associated Constants"), - "associatedconstant", - assoc_consts, - ), - LinkBlock::new( - Link::new("implementations", "Associated Types"), - "associatedtype", - assoc_types, - ), - LinkBlock::new( - Link::new("implementations", "Associated Functions"), - "method", - assoc_fns, - ), - LinkBlock::new(Link::new("implementations", "Methods"), "method", methods), - ]; - - if v.iter().any(|i| i.inner_impl().trait_.is_some()) { - if let Some(impl_) = v.iter().find(|i| { - i.trait_did() == cx.tcx().lang_items().deref_trait() && !i.is_negative_trait_impl() - }) { - let mut derefs = DefIdSet::default(); - derefs.insert(did); - sidebar_deref_methods( - cx, - &mut blocks, - impl_, - v, - &mut derefs, - &mut used_links, - deref_id_map, - ); - } - - let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = - v.iter().partition::, _>(|i| i.inner_impl().kind.is_auto()); - let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = - concrete.into_iter().partition::, _>(|i| i.inner_impl().kind.is_blanket()); + let mut blocks = vec![ + LinkBlock::new( + Link::new("implementations", "Associated Constants"), + "associatedconstant", + assoc_consts, + ), + LinkBlock::new( + Link::new("implementations", "Associated Types"), + "associatedtype", + assoc_types, + ), + LinkBlock::new(Link::new("implementations", "Associated Functions"), "method", assoc_fns), + LinkBlock::new(Link::new("implementations", "Methods"), "method", methods), + ]; + + if let Some((impl_, deref_mut)) = super::get_deref_impls(cx, v, item_def_id, aliased_type) { + let mut derefs = DefIdSet::default(); + derefs.insert(item_def_id); + derefs.extend(aliased_type); + sidebar_deref_methods( + cx, + &mut blocks, + impl_, + deref_mut, + &mut derefs, + &mut used_links, + deref_id_map, + ); + } - sidebar_render_assoc_items( - cx, - &mut id_map, - concrete, - synthetic, - blanket_impl, - &mut blocks, - ); - } + if v.iter().any(|i| i.inner_impl().trait_.is_some()) { + let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = + v.iter().partition::, _>(|i| i.inner_impl().kind.is_auto()); + let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = + concrete.into_iter().partition::, _>(|i| i.inner_impl().kind.is_blanket()); - links.append(&mut blocks); + sidebar_render_assoc_items(cx, &mut id_map, concrete, synthetic, blanket_impl, &mut blocks); } + + links.append(&mut blocks); } fn sidebar_deref_methods<'a>( cx: &'a Context<'_>, out: &mut Vec>, impl_: &Impl, - v: &[Impl], + deref_mut: bool, derefs: &mut DefIdSet, used_links: &mut UsedLinks, deref_id_map: &'a DefIdMap, @@ -551,6 +561,7 @@ fn sidebar_deref_methods<'a>( }) { debug!("found target, real_target: {target:?} {real_target:?}"); + if let Some(did) = target.def_id(c) && let Some(type_did) = impl_.inner_impl().for_.def_id(c) && // `impl Deref for S` @@ -560,7 +571,6 @@ fn sidebar_deref_methods<'a>( return; } let tcx = cx.tcx(); - let deref_mut = v.iter().any(|i| i.trait_did() == tcx.lang_items().deref_mut_trait()); let inner_impl = target .def_id(c) .or_else(|| { @@ -575,7 +585,7 @@ fn sidebar_deref_methods<'a>( .iter() .filter(|i| { i.inner_impl().trait_.is_none() - && real_target.is_doc_subtype_of(&i.inner_impl().for_, c) + && real_target.is_doc_subtype_of(&i.inner_impl().for_, cx) }) .flat_map(|i| { get_methods( @@ -613,11 +623,7 @@ fn sidebar_deref_methods<'a>( if let Some(target_did) = target.def_id(c) && let Some(target_impls) = c.impls.get(&target_did) && let Some(target_deref_impl) = target_impls.iter().find(|i| { - i.inner_impl() - .trait_ - .as_ref() - .map(|t| Some(t.def_id()) == tcx.lang_items().deref_trait()) - .unwrap_or(false) + i.inner_impl().trait_.as_ref().map(|t| t.is_deref_trait(tcx)).unwrap_or(false) && !i.is_negative_trait_impl() }) { @@ -625,7 +631,7 @@ fn sidebar_deref_methods<'a>( cx, out, target_deref_impl, - target_impls, + deref_mut, derefs, used_links, deref_id_map, @@ -649,7 +655,7 @@ fn sidebar_enum<'a>( variants.sort_unstable(); items.push(LinkBlock::new(Link::new("variants", "Variants"), "variant", variants)); - sidebar_assoc_items(cx, it, items, deref_id_map); + sidebar_assoc_items(cx, it.item_id.expect_def_id(), items, deref_id_map); } pub(crate) fn sidebar_module_like( @@ -710,7 +716,7 @@ fn sidebar_foreign_type<'a>( items: &mut Vec>, deref_id_map: &'a DefIdMap, ) { - sidebar_assoc_items(cx, it, items, deref_id_map); + sidebar_assoc_items(cx, it.item_id.expect_def_id(), items, deref_id_map); } /// Renders the trait implementations for this type diff --git a/src/librustdoc/html/render/write_shared.rs b/src/librustdoc/html/render/write_shared.rs index 17c636b351943..b9ddb227a8204 100644 --- a/src/librustdoc/html/render/write_shared.rs +++ b/src/librustdoc/html/render/write_shared.rs @@ -29,7 +29,6 @@ use indexmap::IndexMap; use rustc_ast::join_path_syms; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_middle::ty::TyCtxt; -use rustc_middle::ty::fast_reject::DeepRejectCtxt; use rustc_session::Session; use rustc_span::Symbol; use rustc_span::def_id::DefId; @@ -38,6 +37,7 @@ use serde::ser::SerializeSeq; use serde::{Deserialize, Serialize, Serializer}; use super::{Context, RenderMode, collect_paths_for_type, ensure_trailing_slash}; +use crate::clean::types::impl_may_apply_to_type_alias; use crate::clean::{Crate, Item, ItemId, ItemKind}; use crate::config::{EmitType, PathToParts, RenderOptions, ShouldMerge}; use crate::docfs::PathError; @@ -1031,7 +1031,6 @@ impl<'item> DocVisitor<'item> for TypeImplCollector<'_, '_, 'item> { let Some(self_fqp) = cache.exact_paths.get(&self_did).or_else(get_local) else { return; }; - let aliased_ty = self.cx.tcx().type_of(self_did).skip_binder(); // Exclude impls that are directly on this type. They're already in the HTML. // Some inlining scenarios can cause there to be two versions of the same // impl: one on the type alias and one on the underlying target type. @@ -1040,15 +1039,8 @@ impl<'item> DocVisitor<'item> for TypeImplCollector<'_, '_, 'item> { for (impl_item_id, aliased_type_impl) in &mut aliased_type.impl_ { // Only include this impl if it actually unifies with this alias. // Synthetic impls are not included; those are also included in the HTML. - // - // FIXME(checked_type_alias): Once the feature is complete or stable, rewrite this - // to use type unification. - // Be aware of `tests/rustdoc-html/type-alias/deeply-nested-112515.rs` which might - // regress. let Some(impl_did) = impl_item_id.as_def_id() else { continue }; - let for_ty = self.cx.tcx().type_of(impl_did).skip_binder(); - let reject_cx = DeepRejectCtxt::relate_infer_infer(self.cx.tcx()); - if !reject_cx.types_may_unify(aliased_ty, for_ty) { + if !impl_may_apply_to_type_alias(self.cx.tcx(), self_did, impl_did) { continue; } // Avoid duplicates diff --git a/src/tools/miri/.github/workflows/ci.yml b/src/tools/miri/.github/workflows/ci.yml index 4728eb5d786b4..51bfb25136f08 100644 --- a/src/tools/miri/.github/workflows/ci.yml +++ b/src/tools/miri/.github/workflows/ci.yml @@ -254,29 +254,43 @@ jobs: persist-credentials: false - name: install josh-sync run: cargo +stable install --locked --git https://github.com/rust-lang/josh-sync - - name: setup bot git name and email - run: | - git config --global user.name 'The Miri Cronjob Bot' - git config --global user.email 'miri@cron.bot' - name: Install nightly toolchain run: rustup toolchain install nightly --profile minimal - name: Install rustup-toolchain-install-master run: cargo install --locked -f rustup-toolchain-install-master # Create a token for the next step so it can create a PR that actually runs CI. - - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + - name: Create GitHub App Token + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 id: app-token with: permission-contents: write # The cronjob needs to be able to push to the repo... permission-pull-requests: write # ... and create a PR. app-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} + # This configures `git` to use `gh` as a credential helper, which will + # look for the `GH_TOKEN` environment variable. It also sets up the git user + # so that the new commits will be attributed to the app. + - name: Setup `git` as ${{ steps.app-token.outputs.app-slug }} bot + run: | + user_id=$(gh api "/users/${BOT_SLUG}[bot]" --jq .id) + git config --global user.name "${BOT_SLUG}[bot]" + git config --global user.email "${user_id}+${BOT_SLUG}[bot]@users.noreply.github.com" + gh auth setup-git + env: + BOT_SLUG: ${{ steps.app-token.outputs.app-slug }} + GH_TOKEN: ${{ steps.app-token.outputs.token }} - name: pull changes from rustc and create PR run: | # Make it easier to see what happens. set -x + + if [[ "${GH_EVENT_NAME}" == "workflow_dispatch" ]]; then + PULL_FLAGS="--allow-noop" + fi + # Temporarily disable early exit to examine the status code of rustc-josh-sync set +e - rustc-josh-sync pull + rustc-josh-sync pull $PULL_FLAGS exitcode=$? set -e @@ -297,9 +311,6 @@ jobs: # Format changes ./miri toolchain ./miri fmt --check || (./miri fmt && git commit -am "fmt") - - # Configure remote URL to use the GitHub App token - git config remote.origin.url "https://git:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" # Create a PR BRANCH="rustup-$(date -u +%Y-%m-%d)" @@ -307,7 +318,8 @@ jobs: git push -u origin $BRANCH gh pr create -B master --title 'Automatic Rustup' --body-file message.txt env: - GITHUB_TOKEN: ${{ steps.app-token.outputs.token }} + GH_TOKEN: ${{ steps.app-token.outputs.token }} + GH_EVENT_NAME: ${{ github.event_name }} cron-fail-notify: name: cronjob failure notification diff --git a/src/tools/miri/cargo-miri/Cargo.toml b/src/tools/miri/cargo-miri/Cargo.toml index d240a5d665f13..5a1d3e9b68bbb 100644 --- a/src/tools/miri/cargo-miri/Cargo.toml +++ b/src/tools/miri/cargo-miri/Cargo.toml @@ -9,7 +9,7 @@ edition = "2024" [[bin]] name = "cargo-miri" path = "src/main.rs" -test = false # we have no unit tests +test = true doctest = false # and no doc tests [dependencies] diff --git a/src/tools/miri/cargo-miri/src/arg.rs b/src/tools/miri/cargo-miri/src/arg.rs index d7216060358cb..c7c55fc6aae18 100644 --- a/src/tools/miri/cargo-miri/src/arg.rs +++ b/src/tools/miri/cargo-miri/src/arg.rs @@ -3,14 +3,70 @@ use std::borrow::Cow; use std::env; -/// Determines whether a `--flag` is present. -pub fn has_arg_flag(name: &str) -> bool { - num_arg_flag(name) > 0 +/// Owned command-line arguments providing flag inspection queries. +#[derive(Debug)] +pub struct Args { + args: Vec, } -/// Determines how many times a `--flag` is present. -pub fn num_arg_flag(name: &str) -> usize { - env::args().take_while(|val| val != "--").filter(|val| val == name).count() +impl Args { + /// Reads arguments from `std::env::args()`, skipping the binary name. + pub fn from_env() -> Self { + let mut args = env::args(); + args.next(); + Self { args: args.collect() } + } + + pub fn as_slice(&self) -> &[String] { + &self.args + } + + pub fn iter(&self) -> impl Iterator { + self.args.iter().map(String::as_str) + } + + pub fn first(&self) -> Option<&str> { + self.args.first().map(String::as_str) + } + + pub fn consume_first(&mut self) -> Option { + if self.args.is_empty() { None } else { Some(self.args.remove(0)) } + } + + /// Determines whether a `--flag` is present before `--`. + pub fn has_arg_flag(&self, name: &str) -> bool { + self.num_arg_flag(name) > 0 + } + + /// Determines how many times a `--flag` is present before `--`. + pub fn num_arg_flag(&self, name: &str) -> usize { + self.args.iter().take_while(|val| *val != "--").filter(|val| *val == name).count() + } + + /// Yields all values of command line flag `name` before `--`. + pub fn get_arg_flag_values<'x, 'a>( + &'x self, + name: &'a str, + ) -> impl Iterator + 'a + where + 'x: 'a, + { + ArgFlagValueIter::from_str_iter(self.iter(), name) + } + + /// Gets the first value of a `--flag` before `--`. + pub fn get_arg_flag_value<'x>(&'x self, name: &str) -> Option<&'x str> { + self.get_arg_flag_values(name).next() + } +} + +impl IntoIterator for Args { + type Item = String; + type IntoIter = std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.args.into_iter() + } } /// Yields all values of command line flag `name` as `Ok(arg)`, and all other arguments except @@ -105,15 +161,6 @@ impl<'x: 'a, 'a, I: Iterator + 'a> ArgSplitFlagValue<'a, I> { /// Yields all values of command line flag `name`. pub struct ArgFlagValueIter; -impl ArgFlagValueIter { - pub fn from_string_iter<'a, I: Iterator + 'a>( - args: I, - name: &'a str, - ) -> impl Iterator + 'a { - ArgSplitFlagValue::from_string_iter(args, name).filter_map(Result::ok) - } -} - impl ArgFlagValueIter { pub fn from_str_iter<'x: 'a, 'a, I: Iterator + 'a>( args: I, @@ -123,12 +170,88 @@ impl ArgFlagValueIter { } } -/// Gets the values of a `--flag`. -pub fn get_arg_flag_values(name: &str) -> impl Iterator + '_ { - ArgFlagValueIter::from_string_iter(env::args(), name) -} +#[cfg(test)] +mod tests { + use super::*; + + impl<'a> FromIterator<&'a str> for Args { + fn from_iter>(iter: T) -> Self { + Self { args: iter.into_iter().map(String::from).collect() } + } + } + + #[test] + fn test_flag_queries() { + let args = Args::from_iter([ + "run", + "-v", + "--verbose", + "-v", + "--target=x86_64", + "--target", + "i686", + "--", + "-v", + "--target", + "arm", + "-q", + ]); + + assert!(args.has_arg_flag("-v")); + assert!(args.has_arg_flag("--verbose")); + assert!(!args.has_arg_flag("-q")); + assert_eq!(args.num_arg_flag("-v"), 2); + assert_eq!(args.num_arg_flag("--verbose"), 1); + assert_eq!(args.num_arg_flag("-q"), 0); + + let targets: Vec<_> = args.get_arg_flag_values("--target").collect(); + assert_eq!(targets, vec!["x86_64", "i686"]); + assert_eq!(args.get_arg_flag_value("--target"), Some("x86_64")); + assert_eq!(args.get_arg_flag_value("--missing"), None); + // `iter()` yields all arguments including those after `--`. + assert!(args.iter().any(|arg| arg == "-q")); + } -/// Gets the value of a `--flag`. -pub fn get_arg_flag_value(name: &str) -> Option { - get_arg_flag_values(name).next() + #[test] + fn test_extra_filename_prefix() { + let args = Args::from_iter(["-C", "extra-filename=-suffix", "-o", "output"]); + assert_eq!(args.get_arg_flag_value("extra-filename"), Some("-suffix")); + assert_eq!(args.get_arg_flag_value("-o"), Some("output")); + } + + #[test] + fn test_consume_first() { + let mut args = Args::from_iter(["miri", "run", "--flag"]); + assert_eq!(args.as_slice(), &["miri", "run", "--flag"]); + assert_eq!(args.first(), Some("miri")); + assert_eq!(args.consume_first(), Some("miri".into())); + assert_eq!(args.first(), Some("run")); + assert_eq!(args.consume_first(), Some("run".into())); + assert_eq!(args.first(), Some("--flag")); + assert!(args.has_arg_flag("--flag")); + assert_eq!(args.consume_first(), Some("--flag".into())); + assert_eq!(args.first(), None); + assert_eq!(args.consume_first(), None); + assert!(args.into_iter().next().is_none()); + } + + #[test] + fn test_split_flag_value_preserves_trailing_args() { + let args = Args::from_iter([ + "--target-dir", + "foo", + "cmd", + "--target-dir=bar", + "--", + "--target-dir", + "keep", + ]); + let mut iter = args.into_iter(); + let forwarded: Vec<_> = ArgSplitFlagValue::from_string_iter(&mut iter, "--target-dir") + .filter_map(Result::err) + .collect(); + assert_eq!(forwarded, vec!["cmd", "--"]); + let remaining: Vec<_> = iter.collect(); + assert_eq!(remaining, vec!["--target-dir", "keep"]); + } } diff --git a/src/tools/miri/cargo-miri/src/main.rs b/src/tools/miri/cargo-miri/src/main.rs index 4c01a81fdfdc9..9274f2a434ec3 100644 --- a/src/tools/miri/cargo-miri/src/main.rs +++ b/src/tools/miri/cargo-miri/src/main.rs @@ -5,25 +5,25 @@ mod phases; mod setup; mod util; -use std::{env, iter}; +use std::env; +use crate::arg::Args; use crate::phases::*; use crate::util::show_error; /// Returns `true` if our flags look like they may be for rustdoc, i.e., this is cargo calling us to /// be rustdoc. It's hard to be sure as cargo does not have a RUSTDOC_WRAPPER or an env var that /// would let us get a clear signal. -fn looks_like_rustdoc() -> bool { +fn looks_like_rustdoc(args: &Args) -> bool { // The `--test-run-directory` flag only exists for rustdoc and cargo always passes it. Perfect! - env::args().any(|arg| arg == "--test-run-directory") + // FIXME: use `has_arg_flag` instead? + args.iter().any(|arg| arg == "--test-run-directory") } fn main() { // Rustc does not support non-UTF-8 arguments so we make no attempt either. // (We do support non-UTF-8 environment variables though.) - let mut args = env::args(); - // Skip binary name. - args.next().unwrap(); + let mut args = Args::from_env(); // Dispatch to `cargo-miri` phase. Here is a rough idea of "who calls who". // @@ -63,10 +63,10 @@ fn main() { return; } - let Some(first) = args.next() else { + let Some(first) = args.first() else { show_error!( "`cargo-miri` called without first argument; please only invoke this binary through `cargo miri`" - ) + ); }; // The way rustdoc invokes rustc is indistinguishable from the way cargo invokes rustdoc by the @@ -74,19 +74,22 @@ fn main() { if env::var_os("MIRI_CALLED_FROM_RUSTDOC").is_some() { // ...however, we then also see this variable when rustdoc invokes us as the testrunner! // In that case the first argument is `runner` and there are no more arguments. - match first.as_str() { - "runner" => phase_runner(args, RunnerPhase::Rustdoc), - flag if flag.starts_with("--") || flag.starts_with("@") => { - // This is probably rustdoc invoking us to build the test. But we need to get `first` - // "back onto the iterator", it is some part of the rustc invocation. - phase_rustc(iter::once(first).chain(args), RustcPhase::Rustdoc); + match first { + "runner" => { + args.consume_first(); + phase_runner(args, RunnerPhase::Rustdoc); + } + flag if flag.starts_with("--") || flag.starts_with('@') => { + // This is probably rustdoc invoking us to build the test. + // Do NOT consume the first argument! It is meant for rustc. + phase_rustc(args, RustcPhase::Rustdoc); } _ => { show_error!( "`cargo-miri` failed to recognize which phase of the build process this is, please report a bug.\n\ We are inside MIRI_CALLED_FROM_RUSTDOC.\n\ The command-line arguments were: {:#?}", - Vec::from_iter(env::args()), + args.as_slice(), ); } } @@ -94,9 +97,15 @@ fn main() { return; } - match first.as_str() { - "miri" => phase_cargo_miri(args), - "runner" => phase_runner(args, RunnerPhase::Cargo), + match first { + "miri" => { + args.consume_first(); + phase_cargo_miri(args); + } + "runner" => { + args.consume_first(); + phase_runner(args, RunnerPhase::Cargo); + } arg if arg == env::var("RUSTC").unwrap_or_else(|_| { show_error!( "`cargo-miri` called without RUSTC set; please only invoke this binary through `cargo miri`" @@ -106,17 +115,17 @@ fn main() { // point), then we need to behave as rustc. This is the somewhat counter-intuitive // behavior of having both RUSTC and RUSTC_WRAPPER set // (see https://github.com/rust-lang/cargo/issues/10886). - phase_rustc(args, RustcPhase::Build) + args.consume_first(); + phase_rustc(args, RustcPhase::Build); } - _ if looks_like_rustdoc() => { - // This is probably rustdoc. But we need to get `first` "back onto the iterator", - // it is some part of the rustdoc invocation. - phase_rustdoc(iter::once(first).chain(args)); + _ if looks_like_rustdoc(&args) => { + // This is probably rustdoc. Do NOT consume the first argument! It is meant for rustdoc. + phase_rustdoc(args); } _ => { show_error!( "`cargo-miri` failed to recognize which phase of the build process this is, please report a bug.\nThe command-line arguments were: {:#?}", - Vec::from_iter(env::args()), + args.as_slice(), ); } } diff --git a/src/tools/miri/cargo-miri/src/phases.rs b/src/tools/miri/cargo-miri/src/phases.rs index 5b8f0d6ddab7c..628bc39e7bf7b 100644 --- a/src/tools/miri/cargo-miri/src/phases.rs +++ b/src/tools/miri/cargo-miri/src/phases.rs @@ -56,11 +56,11 @@ fn show_version() { println!(); } -pub fn phase_cargo_miri(mut args: impl Iterator) { +pub fn phase_cargo_miri(mut args: Args) { // Require a subcommand before any flags. // We cannot know which of those flags take arguments and which do not, // so we cannot detect subcommands later. - let Some(subcommand) = args.next() else { + let Some(subcommand) = args.consume_first() else { show_error!("`cargo miri` needs to be called with a subcommand (`run`, `test`, `clean`)"); }; let subcommand = match &*subcommand { @@ -70,22 +70,21 @@ pub fn phase_cargo_miri(mut args: impl Iterator) { // For use by the `./miri test` dependency builder. "build" if env::var_os("MIRI_BUILD_TEST_DEPS").is_some() => MiriCommand::Forward("build".into()), + "--help" | "-h" => { + show_help(); + return; + } + "--version" | "-V" => { + show_version(); + return; + } _ => { - // Check for version and help flags. - if has_arg_flag("--help") || has_arg_flag("-h") { - show_help(); - return; - } - if has_arg_flag("--version") || has_arg_flag("-V") { - show_version(); - return; - } show_error!( "`cargo miri` supports the following subcommands: `run`, `test`, `nextest`, `clean`, and `setup`." ) } }; - if has_arg_flag("--help") || has_arg_flag("-h") { + if args.has_arg_flag("--help") || args.has_arg_flag("-h") { match subcommand { MiriCommand::Forward(verb) => { println!("`cargo miri {verb}` supports the same flags as `cargo {verb}`:\n"); @@ -102,8 +101,8 @@ pub fn phase_cargo_miri(mut args: impl Iterator) { } } } - let verbose = num_arg_flag("-v") + num_arg_flag("--verbose"); - let quiet = has_arg_flag("-q") || has_arg_flag("--quiet"); + let verbose = args.num_arg_flag("-v") + args.num_arg_flag("--verbose"); + let quiet = args.has_arg_flag("-q") || args.has_arg_flag("--quiet"); // Determine the involved architectures. let rustc_version = VersionMeta::for_command(miri_for_host()).unwrap_or_else(|err| { @@ -112,12 +111,12 @@ pub fn phase_cargo_miri(mut args: impl Iterator) { miri_for_host() ) }); - let mut targets = get_arg_flag_values("--target").collect::>(); + let mut targets = args.get_arg_flag_values("--target").collect::>(); // If `targets` is empty, we need to add a `--target $HOST` flag ourselves, and also ensure // that the host target is indeed setup. let target_flag = if targets.is_empty() { let host = &rustc_version.host; - targets.push(host.clone()); + targets.push(host); Some(host) } else { // We don't need to add a `--target` flag, we just forward the user's flags. @@ -128,15 +127,15 @@ pub fn phase_cargo_miri(mut args: impl Iterator) { // delete them then exit. There is no reason to setup a new // sysroot in this execution. if let MiriCommand::Clean = subcommand { - let metadata = get_cargo_metadata(); - clean_target_dir(&metadata); + let metadata = get_cargo_metadata(&args); + clean_target_dir(&args, &metadata); clean_sysroot(); return; } for target in &targets { // We always setup. - setup(&subcommand, target.as_str(), &rustc_version, verbose, quiet); + setup(&subcommand, target, &rustc_version, verbose, quiet, &args); } let miri_sysroot = get_sysroot_dir(); @@ -156,13 +155,13 @@ pub fn phase_cargo_miri(mut args: impl Iterator) { MiriCommand::Setup => return, // `cargo miri setup` stops here. MiriCommand::Clean => unreachable!(), }; - let metadata = get_cargo_metadata(); + let metadata = get_cargo_metadata(&args); let mut cmd = cargo(); cmd.arg(&cargo_cmd); // In nextest we have to also forward the main `verb`. if cargo_cmd == "nextest" { cmd.arg( - args.next() + args.consume_first() .unwrap_or_else(|| show_error!("`cargo miri nextest` expects a verb (e.g. `run`)")), ); } @@ -186,11 +185,12 @@ pub fn phase_cargo_miri(mut args: impl Iterator) { .arg(format!("target.'cfg(all())'.runner=[{cargo_miri_path_for_toml}, 'runner']")); // Set `--target-dir` to `miri` inside the original target directory. - let target_dir = get_target_dir(&metadata); + let target_dir = get_target_dir(&args, &metadata); cmd.arg("--target-dir").arg(target_dir); // *After* we set all the flags that need setting, forward everything else. Make sure to skip // `--target-dir` (which would otherwise be set twice). + let mut args = args.into_iter(); for arg in ArgSplitFlagValue::from_string_iter(&mut args, "--target-dir").filter_map(Result::err) { @@ -273,7 +273,7 @@ pub enum RustcPhase { Rustdoc, } -pub fn phase_rustc(args: impl Iterator, phase: RustcPhase) { +pub fn phase_rustc(args: Args, phase: RustcPhase) { /// Determines if we are being invoked (as rustc) to build a crate for /// the "target" architecture, in contrast to the "host" architecture. /// Host crates are for build scripts and proc macros and still need to @@ -284,49 +284,49 @@ pub fn phase_rustc(args: impl Iterator, phase: RustcPhase) { /// never set for host crates. This matches what rustc bootstrap does, /// which hopefully makes it "reliable enough". This relies on us always /// invoking cargo itself with `--target`, which `in_cargo_miri` ensures. - fn is_target_crate() -> bool { - get_arg_flag_value("--target").is_some() + fn is_target_crate(args: &Args) -> bool { + args.get_arg_flag_value("--target").is_some() } /// Returns whether or not Cargo invoked the wrapper (this binary) to compile /// the final, binary crate (either a test for 'cargo test', or a binary for 'cargo run') /// Cargo does not give us this information directly, so we need to check /// various command-line flags. - fn is_runnable_crate() -> bool { + fn is_runnable_crate(args: &Args) -> bool { // Determine whether this is cargo invoking rustc to get some infos. Ideally we'd check "is // there a filename passed to rustc", but that's very hard as we would have to know whether // e.g. `--print foo` is a booolean flag `--print` followed by filename `foo` or equivalent // to `--print=foo`. So instead we use this more fragile approach of detecting the presence // of a "query" flag rather than the absence of a filename. - let info_query = get_arg_flag_value("--print").is_some() || has_arg_flag("-vV"); + let info_query = args.get_arg_flag_value("--print").is_some() || args.has_arg_flag("-vV"); if info_query { // Nothing to run. return false; } - let is_bin = get_arg_flag_value("--crate-type").as_deref().unwrap_or("bin") == "bin"; - let is_test = has_arg_flag("--test"); + let is_bin = args.get_arg_flag_value("--crate-type").unwrap_or("bin") == "bin"; + let is_test = args.has_arg_flag("--test"); is_bin || is_test } - fn out_filenames() -> Vec { - if let Some(out_file) = get_arg_flag_value("-o") { + fn out_filenames(args: &Args) -> Vec { + if let Some(out_file) = args.get_arg_flag_value("-o") { // `-o` has precedence over `--out-dir`. vec![PathBuf::from(out_file)] } else { - let out_dir = get_arg_flag_value("--out-dir").unwrap_or_default(); + let out_dir = args.get_arg_flag_value("--out-dir").unwrap_or_default(); let path = PathBuf::from(out_dir); // Ask rustc for the filename (since that is target-dependent). let mut rustc = miri_for_host(); // sysroot doesn't matter for this so we just use the host rustc.arg("--print").arg("file-names"); rustc.arg("-Zunstable-options"); // needed for JSON targets for flag in ["--crate-name", "--crate-type", "--target"] { - for val in get_arg_flag_values(flag) { + for val in args.get_arg_flag_values(flag) { rustc.arg(flag).arg(val); } } // This is technically passed as `-C extra-filename=...`, but the prefix seems unique // enough... (and cargo passes this before the filename so it should be unique) - if let Some(extra) = get_arg_flag_value("extra-filename") { + if let Some(extra) = args.get_arg_flag_value("extra-filename") { rustc.arg("-C").arg(format!("extra-filename={extra}")); } rustc.arg("-"); @@ -344,28 +344,25 @@ pub fn phase_rustc(args: impl Iterator, phase: RustcPhase) { // Ensure we show an error if we encounter an argfile, rather than randomly misbehvaing. // We know rustdoc doesn't put anything important in the argfiles so we can ignore them there. - let args = args.inspect(|arg| { - if phase != RustcPhase::Rustdoc && arg.starts_with('@') { - show_error!( - "cargo uses an argfile to invoke rustc, which is not supported by cargo-miri" - ) - } - }); + if phase != RustcPhase::Rustdoc && args.iter().any(|arg| arg.starts_with('@')) { + show_error!("cargo uses an argfile to invoke rustc, which is not supported by cargo-miri"); + } let verbose = env::var("MIRI_VERBOSE") .map_or(0, |verbose| verbose.parse().expect("verbosity flag must be an integer")); - let target_crate = is_target_crate(); + let target_crate = is_target_crate(&args); let store_json = |info: &CrateRunInfo| { - if get_arg_flag_value("--emit").unwrap_or_default().split(',').any(|e| e == "dep-info") { + if args.get_arg_flag_value("--emit").unwrap_or_default().split(',').any(|e| e == "dep-info") + { // Create a stub .d file to stop Cargo from "rebuilding" the crate: // https://github.com/rust-lang/miri/issues/1724#issuecomment-787115693 // As we store a JSON file instead of building the crate here, an empty file is fine. - let mut dep_info_name = PathBuf::from(get_arg_flag_value("--out-dir").unwrap()); + let mut dep_info_name = PathBuf::from(args.get_arg_flag_value("--out-dir").unwrap()); dep_info_name.push(format!( "{}{}.d", - get_arg_flag_value("--crate-name").unwrap(), - get_arg_flag_value("extra-filename").unwrap_or_default(), + args.get_arg_flag_value("--crate-name").unwrap(), + args.get_arg_flag_value("extra-filename").unwrap_or_default(), )); if verbose > 0 { eprintln!( @@ -376,7 +373,7 @@ pub fn phase_rustc(args: impl Iterator, phase: RustcPhase) { File::create(dep_info_name).expect("failed to create fake .d file"); } - for filename in out_filenames() { + for filename in out_filenames(&args) { if verbose > 0 { eprintln!("[cargo-miri rustc] writing run info to `{}`", filename.display()); } @@ -384,7 +381,7 @@ pub fn phase_rustc(args: impl Iterator, phase: RustcPhase) { } }; - let runnable_crate = is_runnable_crate(); + let runnable_crate = is_runnable_crate(&args); if runnable_crate && target_crate { assert!( @@ -397,7 +394,7 @@ pub fn phase_rustc(args: impl Iterator, phase: RustcPhase) { // like we want them. // Instead of compiling, we write JSON into the output file with all the relevant command-line flags // and environment variables; this is used when cargo calls us again in the CARGO_TARGET_RUNNER phase. - let info = CrateRunInfo::collect(args, inside_rustdoc); + let info = CrateRunInfo::collect(args.iter().map(String::from), inside_rustdoc); store_json(&info); @@ -445,13 +442,13 @@ pub fn phase_rustc(args: impl Iterator, phase: RustcPhase) { } // Unit tests for `proc-macro` crates are always built for the host so they cannot run in Miri. - if runnable_crate && get_arg_flag_values("--extern").any(|krate| krate == "proc_macro") { + if runnable_crate && args.get_arg_flag_values("--extern").any(|krate| krate == "proc_macro") { // Ideally we'd entirely skip them... but we have no good way of doing that here. // So we run the tests natively on the host instead. eprintln!("warning: unit tests of `proc-macro` crates are executed outside Miri"); // We also create a marker file next to the binary to indicate that this is a proc macro // crate. We use this later when cargo asks us to run the tests. - for filename in out_filenames() { + for filename in out_filenames(&args) { let mut filename = OsString::from(filename); filename.push(".proc-macro-test"); File::create(filename).expect("failed to create .proc-macro-test marker file"); @@ -468,6 +465,10 @@ pub fn phase_rustc(args: impl Iterator, phase: RustcPhase) { cmd.arg("--sysroot").arg(env::var_os("MIRI_SYSROOT").unwrap()); } + // During setup, patch the panic runtime for `libpanic_abort` (mirroring what bootstrap usually does). + let is_panic_abort = phase == RustcPhase::Setup + && args.get_arg_flag_value("--crate-name") == Some("panic_abort"); + // Forward arguments, but patched. // This hack helps bootstrap run standard library tests in Miri. The issue is as follows: @@ -505,10 +506,7 @@ pub fn phase_rustc(args: impl Iterator, phase: RustcPhase) { cmd.arg(arg); } - // During setup, patch the panic runtime for `libpanic_abort` (mirroring what bootstrap usually does). - if phase == RustcPhase::Setup - && get_arg_flag_value("--crate-name").as_deref() == Some("panic_abort") - { + if is_panic_abort { cmd.arg("-C").arg("panic=abort"); } } else { @@ -542,17 +540,16 @@ pub enum RunnerPhase { Rustdoc, } -pub fn phase_runner(mut binary_args: impl Iterator, phase: RunnerPhase) { +pub fn phase_runner(mut binary_args: Args, phase: RunnerPhase) { let verbose = env::var("MIRI_VERBOSE") .map_or(0, |verbose| verbose.parse().expect("verbosity flag must be an integer")); - let binary = binary_args.next().unwrap(); + let binary = binary_args.consume_first().unwrap(); let file = File::open(&binary) .unwrap_or_else(|_| show_error!( "file {:?} not found or `cargo-miri` invoked incorrectly; please only invoke this binary through `cargo miri`", binary )); let file = BufReader::new(file); - let binary_args = binary_args.collect::>(); let Ok(info) = serde_json::from_reader::<_, CrateRunInfo>(file) else { // Sometimes cargo invokes us on proc macro tests even though those are actual binaries. @@ -560,7 +557,7 @@ pub fn phase_runner(mut binary_args: impl Iterator, phase: Runner // just run the file as a binary. if fs::exists(format!("{binary}.proc-macro-test")).is_ok_and(|b| b) { let mut cmd = Command::new(&binary); - cmd.args(&binary_args); + cmd.args(binary_args); exec(cmd); } show_error!("file {binary:?} contains outdated or invalid JSON; try `cargo clean`") @@ -630,7 +627,7 @@ pub fn phase_runner(mut binary_args: impl Iterator, phase: Runner // Then pass binary arguments. cmd.arg("--"); - cmd.args(&binary_args); + cmd.args(binary_args); // Make sure we use the build-time working directory for interpreting Miri/rustc arguments. // But then we need to switch to the run-time one, which we instruct Miri to do by setting `MIRI_CWD`. @@ -646,23 +643,23 @@ pub fn phase_runner(mut binary_args: impl Iterator, phase: Runner } } -pub fn phase_rustdoc(args: impl Iterator) { +pub fn phase_rustdoc(args: Args) { let verbose = env::var("MIRI_VERBOSE") .map_or(0, |verbose| verbose.parse().expect("verbosity flag must be an integer")); - // phase_cargo_miri sets the RUSTDOC env var to ourselves, and puts a backup - // of the old value into MIRI_ORIG_RUSTDOC. So that's what we have to invoke now. - let rustdoc = env::var("MIRI_ORIG_RUSTDOC").unwrap_or("rustdoc".to_string()); - let mut cmd = Command::new(rustdoc); - cmd.args(args); - // Documentation tests of `proc-macro` crates are always built for the host, so we are not able // to run them in Miri. - if get_arg_flag_values("--crate-type").any(|crate_type| crate_type == "proc-macro") { + if args.get_arg_flag_values("--crate-type").any(|crate_type| crate_type == "proc-macro") { eprintln!("warning: doc tests of `proc-macro` crates are not supported by Miri"); return; } + // phase_cargo_miri sets the RUSTDOC env var to ourselves, and puts a backup + // of the old value into MIRI_ORIG_RUSTDOC. So that's what we have to invoke now. + let rustdoc = env::var("MIRI_ORIG_RUSTDOC").unwrap_or("rustdoc".to_string()); + let mut cmd = Command::new(rustdoc); + cmd.args(args); + // For each doctest, rustdoc starts two child processes: first the test is compiled, // then the produced executable is invoked. We want to reroute both of these to cargo-miri, // such that the first time we'll enter phase_cargo_rustc, and phase_cargo_runner second. diff --git a/src/tools/miri/cargo-miri/src/setup.rs b/src/tools/miri/cargo-miri/src/setup.rs index 47c99f939254e..2a35262b8f160 100644 --- a/src/tools/miri/cargo-miri/src/setup.rs +++ b/src/tools/miri/cargo-miri/src/setup.rs @@ -19,10 +19,11 @@ pub fn setup( rustc_version: &VersionMeta, verbose: usize, quiet: bool, + args: &Args, ) -> PathBuf { let only_setup = matches!(subcommand, MiriCommand::Setup); let ask_user = !only_setup; - let print_sysroot = only_setup && has_arg_flag("--print-sysroot"); // whether we just print the sysroot path + let print_sysroot = only_setup && args.has_arg_flag("--print-sysroot"); // whether we just print the sysroot path let show_setup = only_setup && !print_sysroot; if !only_setup && let Some(sysroot) = std::env::var_os("MIRI_SYSROOT") { // Skip setup step if MIRI_SYSROOT is explicitly set, *unless* we are `cargo miri setup`. diff --git a/src/tools/miri/cargo-miri/src/util.rs b/src/tools/miri/cargo-miri/src/util.rs index 76ce452d4f48b..736900de560bf 100644 --- a/src/tools/miri/cargo-miri/src/util.rs +++ b/src/tools/miri/cargo-miri/src/util.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; use std::env; -use std::ffi::OsString; +use std::ffi::{OsStr, OsString}; use std::fs::File; use std::io::{self, BufWriter, Read, Write}; use std::ops::Not; @@ -195,20 +195,20 @@ pub fn ask_to_run(mut cmd: Command, ask: bool, text: &str) { // Computes the extra flags that need to be passed to cargo to make it behave like the current // cargo invocation. -fn cargo_extra_flags() -> Vec { +fn cargo_extra_flags(args: &Args) -> Vec { let mut flags = Vec::new(); // Forward `--config` flags. let config_flag = "--config"; - for arg in get_arg_flag_values(config_flag) { + for arg in args.get_arg_flag_values(config_flag) { flags.push(config_flag.to_string()); - flags.push(arg); + flags.push(arg.to_string()); } // Forward `--manifest-path`. let manifest_flag = "--manifest-path"; - if let Some(manifest) = get_arg_flag_value(manifest_flag) { + if let Some(manifest) = args.get_arg_flag_value(manifest_flag) { flags.push(manifest_flag.to_string()); - flags.push(manifest); + flags.push(manifest.to_string()); } // Forwarding `--target-dir` would make sense, but `cargo metadata` does not support that flag. @@ -216,11 +216,11 @@ fn cargo_extra_flags() -> Vec { flags } -pub fn get_cargo_metadata() -> Metadata { +pub fn get_cargo_metadata(args: &Args) -> Metadata { // This will honor the `CARGO` env var the same way our `cargo()` does. MetadataCommand::new() .no_deps() - .other_options(cargo_extra_flags()) + .other_options(cargo_extra_flags(args)) .exec() .unwrap_or_else(|err| show_error!("{}", err)) } @@ -251,8 +251,8 @@ pub fn debug_cmd(prefix: &str, verbose: usize, cmd: &Command) { /// Get the target directory for miri output. /// /// Either in an argument passed-in, or from cargo metadata. -pub fn get_target_dir(meta: &Metadata) -> PathBuf { - let mut output = match get_arg_flag_value("--target-dir") { +pub fn get_target_dir(args: &Args, meta: &Metadata) -> PathBuf { + let mut output = match args.get_arg_flag_value("--target-dir") { Some(dir) => PathBuf::from(dir), None => meta.target_directory.clone().into_std_path_buf(), }; @@ -260,6 +260,10 @@ pub fn get_target_dir(meta: &Metadata) -> PathBuf { output } +fn sysroot_cache_root() -> PathBuf { + directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap().cache_dir().to_owned() +} + /// Determines where the sysroot of this execution is /// /// Either in a user-specified spot by an envar, or in a default cache location. @@ -267,8 +271,14 @@ pub fn get_sysroot_dir() -> PathBuf { match std::env::var_os("MIRI_SYSROOT") { Some(dir) => PathBuf::from(dir), None => { - let user_dirs = directories::ProjectDirs::from("org", "rust-lang", "miri").unwrap(); - user_dirs.cache_dir().to_owned() + let toolchain = std::env::var_os("RUSTUP_TOOLCHAIN"); + // Toolchain can be an absolute path. Keep just the basename. + let toolchain = + toolchain.as_ref().and_then(|toolchain| Path::new(toolchain).file_name()); + + let mut path = sysroot_cache_root(); + path.push(toolchain.unwrap_or(OsStr::new("non-rustup"))); + path } } } @@ -293,17 +303,17 @@ pub fn clean_sysroot() { ) } - let sysroot_dir = get_sysroot_dir(); + let sysroot_cache = sysroot_cache_root(); - eprintln!("Cleaning sysroot cache at {}", sysroot_dir.display()); + eprintln!("Cleaning sysroot cache at {}", sysroot_cache.display()); // Keep it simple, just remove the directory. - remove_dir_all_idem(&sysroot_dir).unwrap_or_else(|err| show_error!("{}", err)); + remove_dir_all_idem(&sysroot_cache).unwrap_or_else(|err| show_error!("{}", err)); } /// Deletes the Miri target directory -pub fn clean_target_dir(meta: &Metadata) { - let target_dir = get_target_dir(meta); +pub fn clean_target_dir(args: &Args, meta: &Metadata) { + let target_dir = get_target_dir(args, meta); eprintln!("Cleaning target directory at {}", target_dir.display()); diff --git a/src/tools/miri/miri-script/src/commands.rs b/src/tools/miri/miri-script/src/commands.rs index 9026e1f9d0a5a..05a294d47e1bb 100644 --- a/src/tools/miri/miri-script/src/commands.rs +++ b/src/tools/miri/miri-script/src/commands.rs @@ -470,8 +470,7 @@ impl Command { // Make sure the flags are going to the test harness, not cargo. flags.insert(0, "--".into()); - // Then test, and let caller control flags. - // Only in root project as `cargo-miri` has no tests. + e.test("cargo-miri", &[], &flags)?; e.test(".", &features, &flags)?; if let Some(coverage) = &coverage { diff --git a/src/tools/miri/rust-version b/src/tools/miri/rust-version index 50081cdf0b411..cae5d98fd55d8 100644 --- a/src/tools/miri/rust-version +++ b/src/tools/miri/rust-version @@ -1 +1 @@ -349bba62f1838cbd9b453ffda272c6972754122d +249cb163c0d076be9e0d1a838d2156dfd490ecba diff --git a/src/tools/miri/src/alloc_addresses/mod.rs b/src/tools/miri/src/alloc_addresses/mod.rs index 72337a3e6bced..3e8cf42f046ed 100644 --- a/src/tools/miri/src/alloc_addresses/mod.rs +++ b/src/tools/miri/src/alloc_addresses/mod.rs @@ -111,8 +111,8 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { alloc_id: AllocId, memory_kind: MemoryKind, ) -> InterpResult<'tcx, u64> { - let this = self.eval_context_ref(); - let info = this.get_alloc_info(alloc_id); + let ecx = self.eval_context_ref(); + let info = ecx.get_alloc_info(alloc_id); // This is either called immediately after allocation (and then cached), or when // adjusting `tcx` pointers (which never get freed). So assert that we are looking @@ -129,17 +129,16 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { // Miri's address assignment leaks state across thread boundaries, which is incompatible // with GenMC execution. So we instead let GenMC assign addresses to allocations. - if let Some(genmc_ctx) = this.machine.data_race.as_genmc_ref() { - let addr = - genmc_ctx.handle_alloc(this, alloc_id, info.size, info.align, memory_kind)?; + if let Some(genmc_ctx) = ecx.machine.data_race.as_genmc_ref() { + let addr = genmc_ctx.handle_alloc(ecx, alloc_id, info.size, info.align, memory_kind)?; return interp_ok(addr); } // This allocation does not have a base address yet, pick or reuse one. - if !this.machine.native_lib.is_empty() { + if !ecx.machine.native_lib.is_empty() { // In native lib mode, we use the "real" address of the bytes for this allocation. // This ensures the interpreted program and native code have the same view of memory. - let params = this.machine.get_default_alloc_params(); + let params = ecx.machine.get_default_alloc_params(); let base_ptr = match info.kind { AllocKind::LiveData => { if memory_kind == MiriMemoryKind::Global.into() { @@ -160,21 +159,21 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { } else { // Non-global allocations are already in memory at this point so // we can just get a pointer to where their data is stored. - this.get_alloc_bytes_unchecked_raw(alloc_id)? + ecx.get_alloc_bytes_unchecked_raw(alloc_id)? } } #[cfg(all(feature = "native-lib", unix))] AllocKind::Function => { if let Some(GlobalAlloc::Function { instance, .. }) = - this.tcx.try_get_global_alloc(alloc_id) + ecx.tcx.try_get_global_alloc(alloc_id) { - let fn_sig = this.tcx.instantiate_bound_regions_with_erased( - this.tcx + let fn_sig = ecx.tcx.instantiate_bound_regions_with_erased( + ecx.tcx .fn_sig(instance.def_id()) - .instantiate(*this.tcx, instance.args) + .instantiate(*ecx.tcx, instance.args) .skip_norm_wip(), ); - let fn_ptr = crate::shims::native_lib::build_libffi_closure(this, fn_sig)?; + let fn_ptr = crate::shims::native_lib::build_libffi_closure(ecx, fn_sig)?; #[expect( clippy::as_conversions, @@ -197,13 +196,13 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { } // We are not in native lib or genmc mode, so we control the addresses ourselves. let (addr_gen, reuse) = global_state.address_generation.as_mut().unwrap(); - let mut rng = this.machine.rng.borrow_mut(); + let mut rng = ecx.machine.rng.borrow_mut(); if let Some((reuse_addr, clock)) = - reuse.take_addr(&mut *rng, info.size, info.align, memory_kind, this.active_thread()) + reuse.take_addr(&mut *rng, info.size, info.align, memory_kind, ecx.active_thread()) { // If we use some other thread's address, that implies a happens-before. if let Some(clock) = clock { - this.acquire_clock(&clock)?; + ecx.acquire_clock(&clock)?; } interp_ok(reuse_addr) } else { @@ -236,8 +235,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Returns the `AllocId` that corresponds to the specified addr, // or `None` if the addr is out of bounds. fn alloc_id_from_addr(&self, addr: u64, size: i64) -> Option { - let this = self.eval_context_ref(); - let global_state = this.machine.alloc_addresses.borrow(); + let ecx = self.eval_context_ref(); + let global_state = ecx.machine.alloc_addresses.borrow(); assert!(global_state.provenance_mode != ProvenanceMode::Strict); // We always search the allocation to the right of this address. So if the size is strictly @@ -259,7 +258,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // entered for addresses that are not the base address, so even zero-sized // allocations will get recognized at their base address -- but all other // allocations will *not* be recognized at their "end" address. - let size = this.get_alloc_info(alloc_id).size; + let size = ecx.get_alloc_info(alloc_id).size; if offset < size.bytes() { Some(alloc_id) } else { None } } }?; @@ -267,7 +266,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // We only use this provenance if it has been exposed. if global_state.exposed.contains(&alloc_id) { // This must still be live, since we remove allocations from `int_to_ptr_map` when they get freed. - debug_assert!(this.is_alloc_live(alloc_id)); + debug_assert!(ecx.is_alloc_live(alloc_id)); Some(alloc_id) } else { None @@ -283,8 +282,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { alloc_id: AllocId, memory_kind: Option, ) -> InterpResult<'tcx, u64> { - let this = self.eval_context_ref(); - let mut global_state = this.machine.alloc_addresses.borrow_mut(); + let ecx = self.eval_context_ref(); + let mut global_state = ecx.machine.alloc_addresses.borrow_mut(); let global_state = &mut *global_state; match global_state.base_addr.get(&alloc_id) { @@ -294,7 +293,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let memory_kind = memory_kind.expect("memory_kind is required since alloc_id is not cached"); let base_addr = - this.addr_from_alloc_id_uncached(global_state, alloc_id, memory_kind)?; + ecx.addr_from_alloc_id_uncached(global_state, alloc_id, memory_kind)?; trace!("Assigning base address {:#x} to allocation {:?}", base_addr, alloc_id); // Store address in cache. @@ -326,8 +325,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } fn expose_provenance(&self, provenance: Provenance) -> InterpResult<'tcx> { - let this = self.eval_context_ref(); - let mut global_state = this.machine.alloc_addresses.borrow_mut(); + let ecx = self.eval_context_ref(); + let mut global_state = ecx.machine.alloc_addresses.borrow_mut(); let (alloc_id, tag) = match provenance { Provenance::Concrete { alloc_id, tag } => (alloc_id, tag), @@ -344,7 +343,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } // Exposing a dead alloc is a no-op, because it's not possible to get a dead allocation // via int2ptr. - if !this.is_alloc_live(alloc_id) { + if !ecx.is_alloc_live(alloc_id) { return interp_ok(()); } trace!("Exposing allocation id {alloc_id:?}"); @@ -352,8 +351,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Release the global state before we call `expose_tag`, which may call `get_alloc_info_extra`, // which may need access to the global state. drop(global_state); - if this.machine.borrow_tracker.is_some() { - this.expose_tag(alloc_id, tag)?; + if ecx.machine.borrow_tracker.is_some() { + ecx.expose_tag(alloc_id, tag)?; } interp_ok(()) } @@ -361,15 +360,15 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { fn ptr_from_addr_cast(&self, addr: u64) -> InterpResult<'tcx, Pointer> { trace!("Casting {:#x} to a pointer", addr); - let this = self.eval_context_ref(); - let global_state = this.machine.alloc_addresses.borrow(); + let ecx = self.eval_context_ref(); + let global_state = ecx.machine.alloc_addresses.borrow(); // Potentially emit a warning. match global_state.provenance_mode { ProvenanceMode::Default => { // The first time this happens at a particular location, print a warning. static DEDUP: SpanDedupDiagnostic = SpanDedupDiagnostic::new(); - this.dedup_diagnostic(&DEDUP, |first| { + ecx.dedup_diagnostic(&DEDUP, |first| { NonHaltingDiagnostic::Int2Ptr { details: first } }); } @@ -395,19 +394,19 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { tag: BorTag, kind: MemoryKind, ) -> InterpResult<'tcx, interpret::Pointer> { - let this = self.eval_context_ref(); + let ecx = self.eval_context_ref(); let (prov, offset) = ptr.prov_and_relative_offset(); let alloc_id = prov.alloc_id(); // Get a pointer to the beginning of this allocation. - let base_addr = this.addr_from_alloc_id(alloc_id, Some(kind))?; + let base_addr = ecx.addr_from_alloc_id(alloc_id, Some(kind))?; let base_ptr = interpret::Pointer::new( Provenance::Concrete { alloc_id, tag }, Size::from_bytes(base_addr), ); // Add offset with the right kind of pointer-overflowing arithmetic. - interp_ok(base_ptr.wrapping_offset(offset, this)) + interp_ok(base_ptr.wrapping_offset(offset, ecx)) } // This returns some prepared `MiriAllocBytes`, either because `addr_from_alloc_id` reserved @@ -418,17 +417,17 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { bytes: &[u8], align: Align, ) -> InterpResult<'tcx, MiriAllocBytes> { - let this = self.eval_context_ref(); - assert!(this.tcx.try_get_global_alloc(id).is_some()); - if !this.machine.native_lib.is_empty() { + let ecx = self.eval_context_ref(); + assert!(ecx.tcx.try_get_global_alloc(id).is_some()); + if !ecx.machine.native_lib.is_empty() { // In native lib mode, MiriAllocBytes for global allocations are handled via `prepared_alloc_bytes`. // This additional call ensures that some `MiriAllocBytes` are always prepared, just in case // this function gets called before the first time `addr_from_alloc_id` gets called. - this.addr_from_alloc_id(id, Some(MiriMemoryKind::Global.into()))?; + ecx.addr_from_alloc_id(id, Some(MiriMemoryKind::Global.into()))?; // The memory we need here will have already been allocated during an earlier call to // `addr_from_alloc_id` for this allocation. So don't create a new `MiriAllocBytes` here, instead // fetch the previously prepared bytes from `prepared_alloc_bytes`. - let mut global_state = this.machine.alloc_addresses.borrow_mut(); + let mut global_state = ecx.machine.alloc_addresses.borrow_mut(); let mut prepared_alloc_bytes = global_state .prepared_alloc_bytes .as_mut() @@ -442,7 +441,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { prepared_alloc_bytes.copy_from_slice(bytes); interp_ok(prepared_alloc_bytes) } else { - let params = this.machine.get_default_alloc_params(); + let params = ecx.machine.get_default_alloc_params(); interp_ok(MiriAllocBytes::from_bytes(std::borrow::Cow::Borrowed(bytes), align, params)) } } @@ -454,7 +453,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ptr: interpret::Pointer, size: i64, ) -> Option<(AllocId, Size)> { - let this = self.eval_context_ref(); + let ecx = self.eval_context_ref(); let (tag, addr) = ptr.into_raw_parts(); // addr is absolute (Miri provenance) @@ -462,22 +461,22 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { alloc_id } else { // A wildcard pointer. - this.alloc_id_from_addr(addr.bytes(), size)? + ecx.alloc_id_from_addr(addr.bytes(), size)? }; // This cannot fail: since we already have a pointer with that provenance, adjust_alloc_root_pointer // must have been called in the past, so we can just look up the address in the map. - let base_addr = *this.machine.alloc_addresses.borrow().base_addr.get(&alloc_id).unwrap(); + let base_addr = *ecx.machine.alloc_addresses.borrow().base_addr.get(&alloc_id).unwrap(); // Wrapping "addr - base_addr" - let rel_offset = this.truncate_to_target_usize(addr.bytes().wrapping_sub(base_addr)); + let rel_offset = ecx.truncate_to_target_usize(addr.bytes().wrapping_sub(base_addr)); Some((alloc_id, Size::from_bytes(rel_offset))) } /// Return a list of all exposed allocations. fn exposed_allocs(&self) -> Vec { - let this = self.eval_context_ref(); - this.machine.alloc_addresses.borrow().exposed.iter().copied().collect() + let ecx = self.eval_context_ref(); + ecx.machine.alloc_addresses.borrow().exposed.iter().copied().collect() } } diff --git a/src/tools/miri/src/borrow_tracker/mod.rs b/src/tools/miri/src/borrow_tracker/mod.rs index 65660956220ea..89736bdadf6bf 100644 --- a/src/tools/miri/src/borrow_tracker/mod.rs +++ b/src/tools/miri/src/borrow_tracker/mod.rs @@ -275,14 +275,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ty: Ty<'tcx>, ) -> InterpResult<'tcx, Option>> { let _trace = enter_trace_span!(borrow_tracker::retag_ptr_value, ?ty); - let this = self.eval_context_mut(); - let state = this.machine.borrow_tracker.as_mut().unwrap().get_mut(); + let ecx = self.eval_context_mut(); + let state = ecx.machine.borrow_tracker.as_mut().unwrap().get_mut(); let method = state.borrow_tracker_method; let retag_mode = state.retag_mode; info!("retag_ptr_value: type={ty}, mode={retag_mode:?}, val={:?}", **val); match method { - BorrowTrackerMethod::StackedBorrows => this.sb_retag_ptr_value(val, ty, retag_mode), - BorrowTrackerMethod::TreeBorrows { .. } => this.tb_retag_ptr_value(val, ty, retag_mode), + BorrowTrackerMethod::StackedBorrows => ecx.sb_retag_ptr_value(val, ty, retag_mode), + BorrowTrackerMethod::TreeBorrows { .. } => ecx.tb_retag_ptr_value(val, ty, retag_mode), } } @@ -306,22 +306,22 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { fn protect_place(&mut self, place: &MPlaceTy<'tcx>) -> InterpResult<'tcx, MPlaceTy<'tcx>> { let _trace = enter_trace_span!(borrow_tracker::protect_place, ?place); - let this = self.eval_context_mut(); - let method = this.machine.borrow_tracker.as_mut().unwrap().get_mut().borrow_tracker_method; + let ecx = self.eval_context_mut(); + let method = ecx.machine.borrow_tracker.as_mut().unwrap().get_mut().borrow_tracker_method; match method { - BorrowTrackerMethod::StackedBorrows => this.sb_protect_place(place), - BorrowTrackerMethod::TreeBorrows { .. } => this.tb_protect_place(place), + BorrowTrackerMethod::StackedBorrows => ecx.sb_protect_place(place), + BorrowTrackerMethod::TreeBorrows { .. } => ecx.tb_protect_place(place), } } fn expose_tag(&self, alloc_id: AllocId, tag: BorTag) -> InterpResult<'tcx> { let _trace = enter_trace_span!(borrow_tracker::expose_tag, alloc_id = alloc_id.0, tag = tag.0); - let this = self.eval_context_ref(); - let method = this.machine.borrow_tracker.as_ref().unwrap().borrow().borrow_tracker_method; + let ecx = self.eval_context_ref(); + let method = ecx.machine.borrow_tracker.as_ref().unwrap().borrow().borrow_tracker_method; match method { - BorrowTrackerMethod::StackedBorrows => this.sb_expose_tag(alloc_id, tag), - BorrowTrackerMethod::TreeBorrows { .. } => this.tb_expose_tag(alloc_id, tag), + BorrowTrackerMethod::StackedBorrows => ecx.sb_expose_tag(alloc_id, tag), + BorrowTrackerMethod::TreeBorrows { .. } => ecx.tb_expose_tag(alloc_id, tag), } } @@ -331,28 +331,28 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { nth_parent: u8, name: &str, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); - let method = this.machine.borrow_tracker.as_mut().unwrap().get_mut().borrow_tracker_method; + let ecx = self.eval_context_mut(); + let method = ecx.machine.borrow_tracker.as_mut().unwrap().get_mut().borrow_tracker_method; match method { BorrowTrackerMethod::StackedBorrows => { - this.tcx.tcx.dcx().warn("Stacked Borrows does not support named pointers; `miri_pointer_name` is a no-op"); + ecx.tcx.tcx.dcx().warn("Stacked Borrows does not support named pointers; `miri_pointer_name` is a no-op"); interp_ok(()) } BorrowTrackerMethod::TreeBorrows { .. } => - this.tb_give_pointer_debug_name(ptr, nth_parent, name), + ecx.tb_give_pointer_debug_name(ptr, nth_parent, name), } } fn print_borrow_state(&mut self, alloc_id: AllocId, show_unnamed: bool) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); - let Some(borrow_tracker) = &mut this.machine.borrow_tracker else { + let ecx = self.eval_context_mut(); + let Some(borrow_tracker) = &mut ecx.machine.borrow_tracker else { eprintln!("attempted to print borrow state, but no borrow state is being tracked"); return interp_ok(()); }; let method = borrow_tracker.get_mut().borrow_tracker_method; match method { - BorrowTrackerMethod::StackedBorrows => this.print_stacks(alloc_id), - BorrowTrackerMethod::TreeBorrows { .. } => this.print_tree(alloc_id, show_unnamed), + BorrowTrackerMethod::StackedBorrows => ecx.print_stacks(alloc_id), + BorrowTrackerMethod::TreeBorrows { .. } => ecx.print_tree(alloc_id, show_unnamed), } } @@ -361,8 +361,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { frame: &Frame<'tcx, Provenance, FrameExtra<'tcx>>, ) -> InterpResult<'tcx> { let _trace = enter_trace_span!(borrow_tracker::on_stack_pop); - let this = self.eval_context_ref(); - let borrow_tracker = this.machine.borrow_tracker.as_ref().unwrap(); + let ecx = self.eval_context_ref(); + let borrow_tracker = ecx.machine.borrow_tracker.as_ref().unwrap(); // The body of this loop needs `borrow_tracker` immutably // so we can't move this code inside the following `end_call`. @@ -379,12 +379,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // If it does exist, then we have the guarantee that the // pointer is readable, and the implicit read access inserted // will never cause UB on the pointer itself. - let kind = this.get_alloc_info(*alloc_id).kind; + let kind = ecx.get_alloc_info(*alloc_id).kind; if matches!(kind, AllocKind::LiveData) { - let alloc_extra = this.get_alloc_extra(*alloc_id)?; // can still fail for `extern static` + let alloc_extra = ecx.get_alloc_extra(*alloc_id)?; // can still fail for `extern static` let alloc_borrow_tracker = &alloc_extra.borrow_tracker.as_ref().unwrap(); alloc_borrow_tracker.release_protector( - &this.machine, + &ecx.machine, borrow_tracker, *tag, *alloc_id, diff --git a/src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs b/src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs index d5c1167b7155d..85ebebf77f863 100644 --- a/src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs +++ b/src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs @@ -827,24 +827,24 @@ trait EvalContextPrivExt<'tcx, 'ecx>: crate::MiriInterpCxExt<'tcx> { new_perm: NewPermission, info: RetagInfo, // diagnostics info about this retag ) -> InterpResult<'tcx, MPlaceTy<'tcx>> { - let this = self.eval_context_mut(); - let size = this.size_and_align_of_val(place)?.map(|(size, _)| size); + let ecx = self.eval_context_mut(); + let size = ecx.size_and_align_of_val(place)?.map(|(size, _)| size); // FIXME: If we cannot determine the size (because the unsized tail is an `extern type`), // bail out -- we cannot reasonably figure out which memory range to reborrow. // See https://github.com/rust-lang/unsafe-code-guidelines/issues/276. let Some(size) = size else { static DEDUP: AtomicBool = AtomicBool::new(false); if !DEDUP.swap(true, std::sync::atomic::Ordering::Relaxed) { - this.emit_diagnostic(NonHaltingDiagnostic::ExternTypeReborrow); + ecx.emit_diagnostic(NonHaltingDiagnostic::ExternTypeReborrow); } return interp_ok(place.clone()); }; // Compute new borrow. - let new_tag = this.machine.borrow_tracker.as_mut().unwrap().get_mut().new_ptr(); + let new_tag = ecx.machine.borrow_tracker.as_mut().unwrap().get_mut().new_ptr(); // Reborrow. - let new_prov = this.sb_reborrow(place, size, new_perm, new_tag, info)?; + let new_prov = ecx.sb_reborrow(place, size, new_perm, new_tag, info)?; // Adjust place. // (If the closure gets called, that means the old provenance was `Some`, and hence the new @@ -861,7 +861,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ty: Ty<'tcx>, mode: RetagMode, ) -> InterpResult<'tcx, Option>> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); let cause = match mode { RetagMode::TwoPhase => RetagCause::TwoPhase, RetagMode::FnEntry => RetagCause::FnEntry, @@ -869,20 +869,20 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { RetagMode::None => return interp_ok(None), // no retagging }; let new_perm = if ty.is_box() { - if ty.is_box_global(*this.tcx) { - NewPermission::from_box_ty(val.layout.ty, mode, this) + if ty.is_box_global(*ecx.tcx) { + NewPermission::from_box_ty(val.layout.ty, mode, ecx) } else { // Boxes with custom allocator are not retagged. return interp_ok(None); } } else { - NewPermission::from_ref_ty(val.layout.ty, mode, this) + NewPermission::from_ref_ty(val.layout.ty, mode, ecx) }; let info = RetagInfo { cause }; - let place = this.imm_ptr_to_mplace(val)?; - let new_place = this.sb_retag_place(&place, new_perm, info)?; - interp_ok(Some(ImmTy::from_immediate(new_place.to_ref(this), val.layout))) + let place = ecx.imm_ptr_to_mplace(val)?; + let new_place = ecx.sb_retag_place(&place, new_perm, info)?; + interp_ok(Some(ImmTy::from_immediate(new_place.to_ref(ecx), val.layout))) } /// Protect a place so that it cannot be used any more for the duration of the current function @@ -890,7 +890,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// /// This is used to ensure soundness of in-place function argument/return passing. fn sb_protect_place(&mut self, place: &MPlaceTy<'tcx>) -> InterpResult<'tcx, MPlaceTy<'tcx>> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); // Retag it. With protection! That is the entire point. let new_perm = NewPermission::Uniform { @@ -898,23 +898,23 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { access: Some(AccessKind::Write), protector: Some(ProtectorKind::StrongProtector), }; - this.sb_retag_place(place, new_perm, RetagInfo { cause: RetagCause::InPlaceFnPassing }) + ecx.sb_retag_place(place, new_perm, RetagInfo { cause: RetagCause::InPlaceFnPassing }) } /// Mark the given tag as exposed. It was found on a pointer with the given AllocId. fn sb_expose_tag(&self, alloc_id: AllocId, tag: BorTag) -> InterpResult<'tcx> { - let this = self.eval_context_ref(); + let ecx = self.eval_context_ref(); // Function pointers and dead objects don't have an alloc_extra so we ignore them. // This is okay because accessing them is UB anyway, no need for any Stacked Borrows checks. // NOT using `get_alloc_extra_mut` since this might be a read-only allocation! - let kind = this.get_alloc_info(alloc_id).kind; + let kind = ecx.get_alloc_info(alloc_id).kind; match kind { AllocKind::LiveData => { // This should have alloc_extra data, but `get_alloc_extra` can still fail // if converting this alloc_id from a global to a local one // uncovers a non-supported `extern static`. - let alloc_extra = this.get_alloc_extra(alloc_id)?; + let alloc_extra = ecx.get_alloc_extra(alloc_id)?; trace!("Stacked Borrows tag {tag:?} exposed in {alloc_id:?}"); alloc_extra.borrow_tracker_sb().borrow_mut().exposed_tags.insert(tag); } @@ -930,8 +930,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } fn print_stacks(&self, alloc_id: AllocId) -> InterpResult<'tcx> { - let this = self.eval_context_ref(); - let alloc_extra = this.get_alloc_extra(alloc_id)?; + let ecx = self.eval_context_ref(); + let alloc_extra = ecx.get_alloc_extra(alloc_id)?; let stacks = alloc_extra.borrow_tracker_sb().borrow(); for (range, stack) in stacks.stacks.iter_all() { print!("{range:?}: ["); diff --git a/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs b/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs index adcba606d6f60..086430ad06cd1 100644 --- a/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs +++ b/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs @@ -229,8 +229,8 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { #[track_caller] #[inline] fn get_tree_borrows_params(&self) -> TreeBorrowsParams { - let this = self.eval_context_ref(); - let borrow_tracker = this.machine.borrow_tracker.as_ref().unwrap().borrow(); + let ecx = self.eval_context_ref(); + let borrow_tracker = ecx.machine.borrow_tracker.as_ref().unwrap().borrow(); borrow_tracker.borrow_tracker_method.get_tree_borrows_params() } @@ -438,7 +438,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { place: &MPlaceTy<'tcx>, new_perm: NewPermission, ) -> InterpResult<'tcx, MPlaceTy<'tcx>> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); // Determine the size of the reborrow. // For most types this is the entire size of the place, however @@ -446,7 +446,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // - if the pointer is not reborrowed (raw pointer) then we override the size // to do a zero-length reborrow. let reborrow_size = - this.size_and_align_of_val(place)?.map(|(size, _)| size).unwrap_or(place.layout.size); + ecx.size_and_align_of_val(place)?.map(|(size, _)| size).unwrap_or(place.layout.size); trace!("Creating new permission: {:?} with size {:?}", new_perm, reborrow_size); // This new tag is not guaranteed to actually be used. @@ -455,10 +455,10 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // so that rather than taking as input a fresh tag and deciding whether it uses this // one or the parent it instead just returns whether a new tag should be created. // This will avoid creating tags than end up never being used. - let new_tag = this.machine.borrow_tracker.as_mut().unwrap().get_mut().new_ptr(); + let new_tag = ecx.machine.borrow_tracker.as_mut().unwrap().get_mut().new_ptr(); // Compute the actual reborrow. - let new_prov = this.tb_reborrow(place, reborrow_size, new_perm, new_tag)?; + let new_prov = ecx.tb_reborrow(place, reborrow_size, new_perm, new_tag)?; // Adjust place. // (If the closure gets called, that means the old provenance was `Some`, and hence the new @@ -477,14 +477,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ty: Ty<'tcx>, mode: RetagMode, ) -> InterpResult<'tcx, Option>> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); let new_perm = match *ty.kind() { - _ if ty.is_box_global(*this.tcx) => { + _ if ty.is_box_global(*ecx.tcx) => { // The `None` marks this as a Box. - NewPermission::new(ty.builtin_deref(true).unwrap(), None, mode, this) + NewPermission::new(ty.builtin_deref(true).unwrap(), None, mode, ecx) } ty::Ref(_, pointee, mutability) => - NewPermission::new(pointee, Some(mutability), mode, this), + NewPermission::new(pointee, Some(mutability), mode, ecx), ty::RawPtr(..) => { assert!(mode == RetagMode::Raw); @@ -498,9 +498,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { _ => panic!("tb_retag_ptr_value: invalid type {ty}"), }; if let Some(new_perm) = new_perm { - let place = this.imm_ptr_to_mplace(val)?; - let new_place = this.tb_retag_place(&place, new_perm)?; - interp_ok(Some(ImmTy::from_immediate(new_place.to_ref(this), val.layout))) + let place = ecx.imm_ptr_to_mplace(val)?; + let new_place = ecx.tb_retag_place(&place, new_perm)?; + interp_ok(Some(ImmTy::from_immediate(new_place.to_ref(ecx), val.layout))) } else { interp_ok(None) } @@ -511,7 +511,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// /// This is used to ensure soundness of in-place function argument/return passing. fn tb_protect_place(&mut self, place: &MPlaceTy<'tcx>) -> InterpResult<'tcx, MPlaceTy<'tcx>> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); // Retag it. With protection! That is the entire point. let new_perm = NewPermission { @@ -524,26 +524,26 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { outside_perm: Permission::new_reserved_frz(), protector: Some(ProtectorKind::StrongProtector), }; - this.tb_retag_place(place, new_perm) + ecx.tb_retag_place(place, new_perm) } /// Mark the given tag as exposed. It was found on a pointer with the given AllocId. fn tb_expose_tag(&self, alloc_id: AllocId, tag: BorTag) -> InterpResult<'tcx> { - let this = self.eval_context_ref(); + let ecx = self.eval_context_ref(); // Function pointers and dead objects don't have an alloc_extra so we ignore them. // This is okay because accessing them is UB anyway, no need for any Tree Borrows checks. // NOT using `get_alloc_extra_mut` since this might be a read-only allocation! - let kind = this.get_alloc_info(alloc_id).kind; + let kind = ecx.get_alloc_info(alloc_id).kind; match kind { AllocKind::LiveData => { // This should have alloc_extra data, but `get_alloc_extra` can still fail // if converting this alloc_id from a global to a local one // uncovers a non-supported `extern static`. - let alloc_extra = this.get_alloc_extra(alloc_id)?; + let alloc_extra = ecx.get_alloc_extra(alloc_id)?; trace!("Tree Borrows tag {tag:?} exposed in {alloc_id:?}"); - let global = this.machine.borrow_tracker.as_ref().unwrap(); + let global = ecx.machine.borrow_tracker.as_ref().unwrap(); let protected_tags = &global.borrow().protected_tags; let protected = protected_tags.contains_key(&tag); alloc_extra.borrow_tracker_tb().borrow_mut().expose_tag(tag, protected); @@ -561,10 +561,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// Display the tree. fn print_tree(&self, alloc_id: AllocId, show_unnamed: bool) -> InterpResult<'tcx> { - let this = self.eval_context_ref(); - let alloc_extra = this.get_alloc_extra(alloc_id)?; + let ecx = self.eval_context_ref(); + let alloc_extra = ecx.get_alloc_extra(alloc_id)?; let tree_borrows = alloc_extra.borrow_tracker_tb().borrow(); - let borrow_tracker = &this.machine.borrow_tracker.as_ref().unwrap().borrow(); + let borrow_tracker = &ecx.machine.borrow_tracker.as_ref().unwrap().borrow(); tree_borrows.print_tree(&borrow_tracker.protected_tags, show_unnamed) } @@ -577,7 +577,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { nth_parent: u8, name: &str, ) -> InterpResult<'tcx> { - let this = self.eval_context_ref(); + let ecx = self.eval_context_ref(); let (tag, alloc_id) = match ptr.provenance { Some(Provenance::Concrete { tag, alloc_id }) => (tag, alloc_id), Some(Provenance::Wildcard) => { @@ -589,7 +589,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { return interp_ok(()); } }; - let alloc_extra = this.get_alloc_extra(alloc_id)?; + let alloc_extra = ecx.get_alloc_extra(alloc_id)?; let mut tree_borrows = alloc_extra.borrow_tracker_tb().borrow_mut(); tree_borrows.give_pointer_debug_name(tag, nth_parent, name) } diff --git a/src/tools/miri/src/concurrency/data_race.rs b/src/tools/miri/src/concurrency/data_race.rs index aa3b4cbcbe9d4..6feb2c81aaed8 100644 --- a/src/tools/miri/src/concurrency/data_race.rs +++ b/src/tools/miri/src/concurrency/data_race.rs @@ -779,7 +779,7 @@ pub trait EvalContextExt<'tcx>: MiriInterpCxExt<'tcx> { // Only metadata on the location itself is used. if let Some(genmc_ctx) = ecx.machine.data_race.as_genmc_ref() { - let old_val = ecx.ghost_run(|this| this.read_scalar(place)).discard_err(); + let old_val = ecx.ghost_run(|ecx| ecx.read_scalar(place)).discard_err(); return genmc_ctx.atomic_load( ecx, place.ptr().addr(), @@ -791,7 +791,7 @@ pub trait EvalContextExt<'tcx>: MiriInterpCxExt<'tcx> { trace!("read_scalar_atomic({:?}, {} bytes)", place.ptr(), place.layout.size.bytes()); - let scalar = ecx.allow_data_races_ref(move |this| this.read_scalar(place))?; + let scalar = ecx.allow_data_races_ref(move |ecx| ecx.read_scalar(place))?; let buffered_scalar = ecx.buffered_atomic_read(place, atomic, scalar, |sync_clock| { ecx.validate_atomic_load(place, atomic, sync_clock) })?; @@ -811,7 +811,7 @@ pub trait EvalContextExt<'tcx>: MiriInterpCxExt<'tcx> { // Read the previous value so we can put it in the store buffer later. // Both GenMC and Miri need this. This value is nonsense if there are concurrent writes // but the code consuming the value is aware of that. - let old_val = ecx.ghost_run(|this| this.read_scalar(dest)).discard_err(); + let old_val = ecx.ghost_run(|ecx| ecx.read_scalar(dest)).discard_err(); // Inform GenMC about the atomic store. if let Some(genmc_ctx) = ecx.machine.data_race.as_genmc_ref() { @@ -825,14 +825,14 @@ pub trait EvalContextExt<'tcx>: MiriInterpCxExt<'tcx> { )? { // The store might be the latest store in coherence order (determined by GenMC). // If it is, we need to update the value in Miri's memory: - ecx.allow_data_races_mut(|this| this.write_scalar(val, dest))?; + ecx.allow_data_races_mut(|ecx| ecx.write_scalar(val, dest))?; } return interp_ok(()); } trace!("write_scalar_atomic({:?}, {} bytes)", dest.ptr(), dest.layout.size.bytes()); - ecx.allow_data_races_mut(move |this| this.write_scalar(val, dest))?; + ecx.allow_data_races_mut(move |ecx| ecx.write_scalar(val, dest))?; ecx.validate_atomic_store(dest, atomic)?; ecx.buffered_atomic_write(val, dest, atomic, old_val) } @@ -848,7 +848,7 @@ pub trait EvalContextExt<'tcx>: MiriInterpCxExt<'tcx> { let ecx = self.eval_context_mut(); ecx.atomic_access_check(place, AtomicAccessType::Rmw)?; - let old = ecx.allow_data_races_mut(|this| this.read_immediate(place))?; + let old = ecx.allow_data_races_mut(|ecx| ecx.read_immediate(place))?; // Inform GenMC about the atomic rmw operation. if let Some(genmc_ctx) = ecx.machine.data_race.as_genmc_ref() { @@ -863,7 +863,7 @@ pub trait EvalContextExt<'tcx>: MiriInterpCxExt<'tcx> { old.to_scalar(), )?; if let Some(new_val) = new_val { - ecx.allow_data_races_mut(|this| this.write_scalar(new_val, place))?; + ecx.allow_data_races_mut(|ecx| ecx.write_scalar(new_val, place))?; } return interp_ok(old_val); } @@ -872,7 +872,7 @@ pub trait EvalContextExt<'tcx>: MiriInterpCxExt<'tcx> { let val = ecx.atomic_rmw_op(atomic_op, &old, rhs)?; - ecx.allow_data_races_mut(|this| this.write_immediate(*val, place))?; + ecx.allow_data_races_mut(|ecx| ecx.write_immediate(*val, place))?; ecx.validate_atomic_rmw(place, ord)?; ecx.buffered_atomic_rmw(val.to_scalar(), place, ord, old.to_scalar())?; interp_ok(old.to_scalar()) @@ -897,7 +897,7 @@ pub trait EvalContextExt<'tcx>: MiriInterpCxExt<'tcx> { ecx.atomic_access_check(place, AtomicAccessType::Rmw)?; // Read as immediate for the sake of `binary_op()` - let old = ecx.allow_data_races_mut(|this| this.read_immediate(place))?; + let old = ecx.allow_data_races_mut(|ecx| ecx.read_immediate(place))?; // Inform GenMC about the atomic atomic compare exchange. if let Some(genmc_ctx) = ecx.machine.data_race.as_genmc_ref() { @@ -915,7 +915,7 @@ pub trait EvalContextExt<'tcx>: MiriInterpCxExt<'tcx> { // The store might be the latest store in coherence order (determined by GenMC). // If it is, we need to update the value in Miri's memory: if let Some(new_value) = new_value { - ecx.allow_data_races_mut(|this| this.write_scalar(new_value, place))?; + ecx.allow_data_races_mut(|ecx| ecx.write_scalar(new_value, place))?; } return interp_ok((old_value, cmpxchg_success)); } @@ -944,7 +944,7 @@ pub trait EvalContextExt<'tcx>: MiriInterpCxExt<'tcx> { // if successful, perform a full rw-atomic validation // otherwise treat this as an atomic load with the fail ordering. if cmpxchg_success { - ecx.allow_data_races_mut(|this| this.write_scalar(new, place))?; + ecx.allow_data_races_mut(|ecx| ecx.write_scalar(new, place))?; ecx.validate_atomic_rmw(place, success)?; ecx.buffered_atomic_rmw(new, place, success, old.to_scalar())?; } else { diff --git a/src/tools/miri/src/concurrency/genmc/global_allocations.rs b/src/tools/miri/src/concurrency/genmc/global_allocations.rs index 76be8c3a4c9a8..989b43ef3c7f0 100644 --- a/src/tools/miri/src/concurrency/genmc/global_allocations.rs +++ b/src/tools/miri/src/concurrency/genmc/global_allocations.rs @@ -89,8 +89,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { global_allocation_handler: &GlobalAllocationHandler, alloc_id: AllocId, ) -> InterpResult<'tcx, u64> { - let this = self.eval_context_ref(); - let info = this.get_alloc_info(alloc_id); + let ecx = self.eval_context_ref(); + let info = ecx.get_alloc_info(alloc_id); let global_state = global_allocation_handler.0.read().unwrap(); if let Some(base_addr) = global_state.base_addr.get(&alloc_id) { diff --git a/src/tools/miri/src/concurrency/genmc/shims.rs b/src/tools/miri/src/concurrency/genmc/shims.rs index 30224b8a42815..3be7faeb88daf 100644 --- a/src/tools/miri/src/concurrency/genmc/shims.rs +++ b/src/tools/miri/src/concurrency/genmc/shims.rs @@ -61,7 +61,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { None, callback!( @capture<'tcx> {} - |_this, unblock: UnblockKind| { + |_ecx, unblock: UnblockKind| { assert_eq!(unblock, UnblockKind::Ready); unreachable!("GenMC should never unblock a thread blocked by an `assume`."); } @@ -97,10 +97,10 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { @capture<'tcx> { mutex: MPlaceTy<'tcx>, } - |this, unblock: crate::UnblockKind| { + |ecx, unblock: crate::UnblockKind| { debug!("GenMC: Mutex::lock: unblocking callback called, attempting to lock the Mutex again."); assert_eq!(unblock, crate::UnblockKind::Ready); - this.intercept_mutex_lock(mutex)?; + ecx.intercept_mutex_lock(mutex)?; interp_ok(()) } ), @@ -121,7 +121,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { @capture<'tcx> { mutex: MPlaceTy<'tcx>, } - |_this, _unblock: crate::UnblockKind| { + |_ecx, _unblock: crate::UnblockKind| { unreachable!("A thread blocked on `Mutex::lock` should not be unblocked again."); } ), diff --git a/src/tools/miri/src/concurrency/sync.rs b/src/tools/miri/src/concurrency/sync.rs index d4611033b817c..c9bab2d8dba50 100644 --- a/src/tools/miri/src/concurrency/sync.rs +++ b/src/tools/miri/src/concurrency/sync.rs @@ -335,14 +335,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { mutex_ref: MutexRef, retval_dest: Option<(Scalar, MPlaceTy<'tcx>)>, } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { assert_eq!(unblock, UnblockKind::Ready); assert!(mutex_ref.owner().is_none()); - this.mutex_lock(&mutex_ref)?; + ecx.mutex_lock(&mutex_ref)?; if let Some((retval, dest)) = retval_dest { - this.write_scalar(retval, &dest)?; + ecx.write_scalar(retval, &dest)?; } interp_ok(()) @@ -428,10 +428,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { retval: Scalar, dest: MPlaceTy<'tcx>, } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { assert_eq!(unblock, UnblockKind::Ready); - this.rwlock_reader_lock(&rwlock_ref)?; - this.write_scalar(retval, &dest)?; + ecx.rwlock_reader_lock(&rwlock_ref)?; + ecx.write_scalar(retval, &dest)?; interp_ok(()) } ), @@ -515,10 +515,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { retval: Scalar, dest: MPlaceTy<'tcx>, } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { assert_eq!(unblock, UnblockKind::Ready); - this.rwlock_writer_lock(&rwlock_ref)?; - this.write_scalar(retval, &dest)?; + ecx.rwlock_writer_lock(&rwlock_ref)?; + ecx.write_scalar(retval, &dest)?; interp_ok(()) } ), @@ -563,24 +563,24 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { retval_timeout: Scalar, dest: MPlaceTy<'tcx>, } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { match unblock { UnblockKind::Ready => { // The condvar was signaled. Make sure we get the clock for that. - this.acquire_clock( + ecx.acquire_clock( &condvar_ref.0.borrow().clock, )?; // Try to acquire the mutex. // The timeout only applies to the first wait (until the signal), not for mutex acquisition. - this.condvar_reacquire_mutex(mutex_ref, retval_succ, dest) + ecx.condvar_reacquire_mutex(mutex_ref, retval_succ, dest) } UnblockKind::TimedOut => { // We have to remove the waiter from the queue again. - let thread = this.active_thread(); + let thread = ecx.active_thread(); let waiters = &mut condvar_ref.0.borrow_mut().waiters; waiters.retain(|waiter| *waiter != thread); // Now get back the lock. - this.condvar_reacquire_mutex(mutex_ref, retval_timeout, dest) + ecx.condvar_reacquire_mutex(mutex_ref, retval_timeout, dest) } } } @@ -630,22 +630,22 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { futex_ref: FutexRef, callback: DynUnblockCallback<'tcx>, } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { match unblock { UnblockKind::Ready => { let futex = futex_ref.0.borrow(); // Acquire the clock of the futex. - this.acquire_clock(&futex.clock)?; + ecx.acquire_clock(&futex.clock)?; }, UnblockKind::TimedOut => { // Remove the waiter from the futex. - let thread = this.active_thread(); + let thread = ecx.active_thread(); let mut futex = futex_ref.0.borrow_mut(); futex.waiters.retain(|waiter| waiter.thread != thread); }, } - callback.call(this, unblock) + callback.call(ecx, unblock) } ), ); @@ -714,20 +714,20 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { deadline: Option, callback: DynUnblockCallback<'tcx>, } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { match unblock { UnblockKind::TimedOut => { // Remove the waiter. - let thread = this.active_thread(); + let thread = ecx.active_thread(); let mut semaphore = semaphore_ref.0.borrow_mut(); semaphore.waiters.retain(|&waiter| waiter != thread); // Finish with callback. - return callback.call(this, UnblockKind::TimedOut); + return callback.call(ecx, UnblockKind::TimedOut); } UnblockKind::Ready => { // Try again! This time it will definitely work. // (But it's too much of a hassle to assert that.) - this.semaphore_decrement(semaphore_ref, deadline, callback) + ecx.semaphore_decrement(semaphore_ref, deadline, callback) } } } diff --git a/src/tools/miri/src/concurrency/thread.rs b/src/tools/miri/src/concurrency/thread.rs index 163fcc9d10cf0..53e3a10abef50 100644 --- a/src/tools/miri/src/concurrency/thread.rs +++ b/src/tools/miri/src/concurrency/thread.rs @@ -991,9 +991,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { dest: MPlaceTy<'tcx>, success_retval: Scalar, } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { assert_eq!(unblock, UnblockKind::Ready); - after_join(this, joined_thread_id, success_retval, &dest) + after_join(ecx, joined_thread_id, success_retval, &dest) } ), ); diff --git a/src/tools/miri/src/diagnostics.rs b/src/tools/miri/src/diagnostics.rs index 8c65a7a3a8cf6..780c0542df079 100644 --- a/src/tools/miri/src/diagnostics.rs +++ b/src/tools/miri/src/diagnostics.rs @@ -4,7 +4,7 @@ use std::sync::Mutex; use rustc_abi::{Align, Size}; use rustc_data_structures::fx::{FxBuildHasher, FxHashSet}; -use rustc_errors::{Diag, Level}; +use rustc_errors::{Diag, Level, MultiSpan, Sublevel}; use rustc_span::{DUMMY_SP, Span, Symbol}; use crate::borrow_tracker::stacked_borrows::diagnostics::TagHistory; @@ -157,19 +157,32 @@ pub enum NonHaltingDiagnostic { } /// Level of Miri specific diagnostics -pub enum DiagLevel { +enum DiagLevel { Error, Warning, Note, } +/// The kind of extra annotations. +enum ExtraKind { + Note, + Help, +} + /// Generate a note/help text without a span. macro_rules! note { - ($($tt:tt)*) => { (None, format!($($tt)*)) }; + ($($tt:tt)*) => { (ExtraKind::Note, None, format!($($tt)*)) }; +} +macro_rules! help { + ($($tt:tt)*) => { (ExtraKind::Help, None, format!($($tt)*)) }; } /// Generate a note/help text with a span. +#[allow(unused)] macro_rules! note_span { - ($span:expr, $($tt:tt)*) => { (Some($span), format!($($tt)*)) }; + ($span:expr, $($tt:tt)*) => { (ExtraKind::Note, Some($span), format!($($tt)*)) }; +} +macro_rules! help_span { + ($span:expr, $($tt:tt)*) => { (ExtraKind::Help, Some($span), format!($($tt)*)) }; } /// Attempts to prune a stacktrace to omit the Rust runtime, and returns a bool indicating if any @@ -240,9 +253,9 @@ pub fn report_result<'tcx>( use InterpErrorKind::*; use UndefinedBehaviorInfo::*; - let mut labels = vec![]; + let mut main_span_labels = vec![]; - let (title, helps) = if let MachineStop(info) = res.kind() { + let (title, extras) = if let MachineStop(info) = res.kind() { let info = info.downcast_ref::().expect("invalid MachineStop payload"); use TerminationInfo::*; let title = match info { @@ -258,7 +271,7 @@ pub fn report_result<'tcx>( return Some((0, false)); } LocalDeadlock => { - labels.push(format!("thread got stuck here")); + main_span_labels.push(format!("thread got stuck here")); None } GlobalDeadlock => { @@ -274,7 +287,6 @@ pub fn report_result<'tcx>( format!("the evaluated program deadlocked"), vec![format!("thread got stuck here")], vec![], - vec![], &stacktrace, Some(thread), &ecx.machine, @@ -290,76 +302,76 @@ pub fn report_result<'tcx>( MultipleSymbolDefinitions { .. } | SymbolShimClashing { .. } => None, }; #[rustfmt::skip] - let helps = match info { + let extras = match info { UnsupportedInIsolation(_) => vec![ - note!("set `MIRIFLAGS=-Zmiri-disable-isolation` to disable isolation;"), - note!("or set `MIRIFLAGS=-Zmiri-isolation-error=warn` to make Miri return an error code from isolated operations (if supported for that operation) and continue with a warning"), + help!("set `MIRIFLAGS=-Zmiri-disable-isolation` to disable isolation;"), + help!("or set `MIRIFLAGS=-Zmiri-isolation-error=warn` to make Miri return an error code from isolated operations (if supported for that operation) and continue with a warning"), ], UnsupportedForeignItem(_) => { vec![ - note!("this means the program tried to do something Miri does not support; it does not indicate a bug in the program"), + help!("this means the program tried to do something Miri does not support; it does not indicate a bug in the program"), ] } StackedBorrowsUb { help, history, .. } => { - labels.extend(help.clone()); + main_span_labels.extend(help.clone()); let mut helps = vec![ - note!("this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental"), - note!("see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information"), + help!("this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental"), + help!("see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information"), ]; if let Some(TagHistory {created, invalidated, protected}) = history.clone() { - helps.push((Some(created.1), created.0)); + helps.push((ExtraKind::Help, Some(created.1), created.0)); if let Some((msg, span)) = invalidated { - helps.push(note_span!(span, "{msg}")); + helps.push(help_span!(span, "{msg}")); } if let Some((protector_msg, protector_span)) = protected { - helps.push(note_span!(protector_span, "{protector_msg}")); + helps.push(help_span!(protector_span, "{protector_msg}")); } } helps }, TreeBorrowsUb { title: _, details, history } => { let mut helps = vec![ - note!("this indicates a potential bug in the program: it performed an invalid operation, but the Tree Borrows rules it violated are still experimental"), - note!("see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/tree-borrows.md for further information"), + help!("this indicates a potential bug in the program: it performed an invalid operation, but the Tree Borrows rules it violated are still experimental"), + help!("see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/tree-borrows.md for further information"), ]; for m in details { - helps.push(note!("{m}")); + helps.push(help!("{m}")); } - for event in history.events.clone() { - helps.push(event); + for (span, msg) in history.events.clone() { + helps.push((ExtraKind::Help, span, msg)); } helps } MultipleSymbolDefinitions { first, first_crate, second, second_crate, .. } => vec![ - note_span!(*first, "it's first defined here, in crate `{first_crate}`"), - note_span!(*second, "then it's defined here again, in crate `{second_crate}`"), + help_span!(*first, "it's first defined here, in crate `{first_crate}`"), + help_span!(*second, "then it's defined here again, in crate `{second_crate}`"), ], SymbolShimClashing { link_name, span } => - vec![note_span!(*span, "the `{link_name}` symbol is defined here")], + vec![help_span!(*span, "the `{link_name}` symbol is defined here")], Int2PtrWithStrictProvenance => - vec![note!("use Strict Provenance APIs (https://doc.rust-lang.org/nightly/std/ptr/index.html#strict-provenance, https://crates.io/crates/sptr) instead")], + vec![help!("use Strict Provenance APIs (https://doc.rust-lang.org/nightly/std/ptr/index.html#strict-provenance, https://crates.io/crates/sptr) instead")], DataRace { op1, extra, retag_explain, .. } => { - labels.push(format!("(2) just happened here")); - let mut helps = vec![note_span!(op1.span, "and (1) occurred earlier here")]; + main_span_labels.push(format!("(2) just happened here")); + let mut helps = vec![help_span!(op1.span, "and (1) occurred earlier here")]; if let Some(extra) = extra { - helps.push(note!("{extra}")); - helps.push(note!("see https://doc.rust-lang.org/nightly/std/sync/atomic/index.html#memory-model-for-atomic-accesses for more information about the Rust memory model")); + helps.push(help!("{extra}")); + helps.push(help!("see https://doc.rust-lang.org/nightly/std/sync/atomic/index.html#memory-model-for-atomic-accesses for more information about the Rust memory model")); } if *retag_explain { - helps.push(note!("retags occur on all (re)borrows and as well as when references are copied or moved")); - helps.push(note!("retags permit optimizations that insert speculative reads or writes")); - helps.push(note!("therefore from the perspective of data races, a retag has the same implications as a read or write")); + helps.push(help!("retags occur on all (re)borrows and as well as when references are copied or moved")); + helps.push(help!("retags permit optimizations that insert speculative reads or writes")); + helps.push(help!("therefore from the perspective of data races, a retag has the same implications as a read or write")); } - helps.push(note!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior")); - helps.push(note!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information")); + helps.push(help!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior")); + helps.push(help!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information")); helps } , _ => vec![], }; - (title, helps) + (title, extras) } else { let title = match res.kind() { UndefinedBehavior(UndefinedBehaviorInfo::ValidationError { @@ -387,39 +399,39 @@ pub fn report_result<'tcx>( } }; #[rustfmt::skip] - let helps = match res.kind() { + let extras = match res.kind() { Unsupported(_) => vec![ - note!("this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support"), + help!("this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support"), ], ResourceExhaustion(ResourceExhaustionInfo::AddressSpaceFull) if ecx.machine.data_race.as_genmc_ref().is_some() => vec![ - note!("in GenMC mode, the address space is limited to 4GB per thread, and addresses cannot be reused") + help!("in GenMC mode, the address space is limited to 4GB per thread, and addresses cannot be reused") ], UndefinedBehavior(AlignmentCheckFailed { .. }) if ecx.machine.check_alignment == AlignmentCheck::Symbolic => vec![ - note!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior"), - note!("but due to `-Zmiri-symbolic-alignment-check`, alignment errors can also be false positives"), + help!("this usually indicates that your program performed an invalid operation and caused Undefined Behavior"), + help!("but due to `-Zmiri-symbolic-alignment-check`, alignment errors can also be false positives"), ], UndefinedBehavior(info) => { let mut helps = vec![ - note!("this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior"), - note!("see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information"), + 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"), ]; match info { PointerUseAfterFree(alloc_id, _) | PointerOutOfBounds { alloc_id, .. } => { if let Some(span) = ecx.machine.allocated_span(*alloc_id) { - helps.push(note_span!(span, "{alloc_id} was allocated here:")); + helps.push(help_span!(span, "{alloc_id} was allocated here:")); } if let Some(span) = ecx.machine.deallocated_span(*alloc_id) { - helps.push(note_span!(span, "{alloc_id} was deallocated here:")); + helps.push(help_span!(span, "{alloc_id} was deallocated here:")); } } AbiMismatchArgument { .. } | AbiMismatchReturn { .. } => { - helps.push(note!("this means these two types are not *guaranteed* to be ABI-compatible across all targets")); - helps.push(note!("if you think this code should be accepted anyway, please report an issue with Miri")); + helps.push(help!("this means these two types are not *guaranteed* to be ABI-compatible across all targets")); + helps.push(help!("if you think this code should be accepted anyway, please report an issue with Miri")); } _ => {}, } @@ -434,7 +446,7 @@ pub fn report_result<'tcx>( _ => vec![], }; - (Some(title), helps) + (Some(title), extras) }; let stacktrace = ecx.generate_stacktrace(); @@ -442,16 +454,16 @@ pub fn report_result<'tcx>( // We want to dump the allocation if this is `InvalidUninitBytes`. // Since `format_interp_error` consumes `e`, we compute the outut early. - let mut extra = String::new(); + let mut extra_stderr = String::new(); match res.kind() { UndefinedBehavior(InvalidUninitBytes(Some((alloc_id, access)))) => { writeln!( - extra, + extra_stderr, "Uninitialized memory occurred at {alloc_id}{range}, in this allocation:", range = access.bad, ) .unwrap(); - writeln!(extra, "{:?}", ecx.dump_alloc(*alloc_id)).unwrap(); + writeln!(extra_stderr, "{:?}", ecx.dump_alloc(*alloc_id)).unwrap(); } _ => {} } @@ -462,8 +474,8 @@ pub fn report_result<'tcx>( } write!(primary_msg, "{}", res.to_string()).unwrap(); - if labels.is_empty() { - labels.push(format!( + if main_span_labels.is_empty() { + main_span_labels.push(format!( "{} occurred {}", title.unwrap_or("error"), if stacktrace.is_empty() { "due to this code" } else { "here" } @@ -473,15 +485,14 @@ pub fn report_result<'tcx>( report_msg( DiagLevel::Error, primary_msg, - labels, - vec![], - helps, + main_span_labels, + extras, &stacktrace, Some(ecx.active_thread()), &ecx.machine, ); - eprint!("{extra}"); // newlines are already in the string + eprint!("{extra_stderr}"); // newlines are already in the string // Include a note like `std` does when we omit frames from a backtrace if pruned { @@ -527,7 +538,6 @@ pub fn report_leaks<'tcx>( title, vec![], vec![], - vec![], &backtrace, None, // we don't know the thread this is from &ecx.machine, @@ -548,9 +558,8 @@ pub fn report_leaks<'tcx>( fn report_msg<'tcx>( diag_level: DiagLevel, title: String, - span_msg: Vec, - notes: Vec<(Option, String)>, - helps: Vec<(Option, String)>, + main_span_labels: Vec, + extras: Vec<(ExtraKind, Option, String)>, stacktrace: &[FrameInfo<'tcx>], thread: Option, machine: &MiriMachine<'tcx>, @@ -571,24 +580,21 @@ fn report_msg<'tcx>( err.span(span); // Show main message. - for line in span_msg { + for line in main_span_labels { err.span_label(span, line); } // Show note and help messages. - for (span, note) in notes { - if let Some(span) = span { - err.span_note(span, note); - } else { - err.note(note); - } - } - for (span, help) in helps { - if let Some(span) = span { - err.span_help(span, help); - } else { - err.help(help); - } + for (kind, span, msg) in extras { + let sublevel = match kind { + ExtraKind::Note => Sublevel::Note, + ExtraKind::Help => Sublevel::Help, + }; + let spans = match span { + Some(sp) => sp.into(), + None => MultiSpan::new(), + }; + err.sub(sublevel, msg, spans); } // Only print thread name if there are multiple threads. if let Some(thread) = thread @@ -638,31 +644,6 @@ impl<'tcx> MiriMachine<'tcx> { Frame::generate_stacktrace_from_stack(self.threads.active_thread_stack(), self.tcx); let (stacktrace, _was_pruned) = prune_stacktrace(stacktrace, self); - let (label, diag_level) = match &e { - RejectedIsolatedOp(_) => - ("operation rejected by isolation".to_string(), DiagLevel::Warning), - Int2Ptr { .. } => ("integer-to-pointer cast".to_string(), DiagLevel::Warning), - NativeCallSharedMem { .. } => - ("sharing memory with a native function".to_string(), DiagLevel::Warning), - ExternTypeReborrow => - ("reborrow of reference to `extern type`".to_string(), DiagLevel::Warning), - GenmcCompareExchangeWeak => - ("GenMC might miss possible behaviors of this code".to_string(), DiagLevel::Warning), - CreatedPointerTag(..) - | PoppedPointerTag(..) - | TrackingAlloc(..) - | AccessedAlloc(..) - | FreedAlloc(..) - | ProgressReport { .. } - | WeakMemoryOutdatedLoad { .. } => - ("tracking was triggered here".to_string(), DiagLevel::Note), - FileInProcOpened => ("open a file in `/proc`".to_string(), DiagLevel::Warning), - ConnectingSocketGetsockname => - ("Called `getsockname` on connecting socket".to_string(), DiagLevel::Warning), - SocketAddressResolution { .. } => - ("error during address resolution".to_string(), DiagLevel::Warning), - }; - let title = match &e { CreatedPointerTag(tag, None, _) => format!("created base tag {tag:?}"), CreatedPointerTag(tag, Some(perm), None) => @@ -699,7 +680,32 @@ impl<'tcx> MiriMachine<'tcx> { SocketAddressResolution { error } => format!("address resolution failed: {error}"), }; - let notes = match &e { + let (main_span_label, diag_level) = match &e { + RejectedIsolatedOp(_) => + ("operation rejected by isolation".to_string(), DiagLevel::Warning), + Int2Ptr { .. } => ("integer-to-pointer cast".to_string(), DiagLevel::Warning), + NativeCallSharedMem { .. } => + ("sharing memory with a native function".to_string(), DiagLevel::Warning), + ExternTypeReborrow => + ("reborrow of reference to `extern type`".to_string(), DiagLevel::Warning), + GenmcCompareExchangeWeak => + ("GenMC might miss possible behaviors of this code".to_string(), DiagLevel::Warning), + CreatedPointerTag(..) + | PoppedPointerTag(..) + | TrackingAlloc(..) + | AccessedAlloc(..) + | FreedAlloc(..) + | ProgressReport { .. } + | WeakMemoryOutdatedLoad { .. } => + ("tracking was triggered here".to_string(), DiagLevel::Note), + FileInProcOpened => ("open a file in `/proc`".to_string(), DiagLevel::Warning), + ConnectingSocketGetsockname => + ("Called `getsockname` on connecting socket".to_string(), DiagLevel::Warning), + SocketAddressResolution { .. } => + ("error during address resolution".to_string(), DiagLevel::Warning), + }; + + let extras = match &e { ProgressReport { block_count } => { vec![note!("so far, {block_count} basic blocks have been executed")] } @@ -711,27 +717,24 @@ impl<'tcx> MiriMachine<'tcx> { note!( "an unspecified socket address (e.g. `0.0.0.0:0`) will be returned instead" ), + note!("this warning is only shown once per program execution"), ], SocketAddressResolution { .. } => vec![note!( "Miri cannot return proper error information from this call; only a generic error code is being returned" )], - _ => vec![], - }; - - let helps = match &e { Int2Ptr { details: true } => { let mut v = vec![ - note!( + help!( "this program is using integer-to-pointer casts or (equivalently) `ptr::with_exposed_provenance`, which means that Miri might miss pointer bugs in this program" ), - note!( + help!( "see https://doc.rust-lang.org/nightly/std/ptr/fn.with_exposed_provenance.html for more details on that operation" ), - note!( + help!( "to ensure that Miri does not miss bugs in your program, use Strict Provenance APIs (https://doc.rust-lang.org/nightly/std/ptr/index.html#strict-provenance, https://crates.io/crates/sptr) instead" ), - note!( + help!( "you can then set `MIRIFLAGS=-Zmiri-strict-provenance` to ensure you are not relying on `with_exposed_provenance` semantics" ), ]; @@ -742,11 +745,11 @@ impl<'tcx> MiriMachine<'tcx> { ) }) { v.push( - note!("Tree Borrows does not support integer-to-pointer casts, so the program is likely to go wrong when this pointer gets used") + help!("Tree Borrows does not support integer-to-pointer casts, so the program is likely to go wrong when this pointer gets used") ); } else { v.push( - note!("alternatively, `MIRIFLAGS=-Zmiri-permissive-provenance` disables this warning") + help!("alternatively, `MIRIFLAGS=-Zmiri-permissive-provenance` disables this warning") ); } v @@ -754,36 +757,38 @@ impl<'tcx> MiriMachine<'tcx> { NativeCallSharedMem { tracing } => if *tracing { vec![ - note!( + help!( "when memory is shared with a native function call, Miri can only track initialisation and provenance on a best-effort basis" ), - note!( + help!( "in particular, Miri assumes that the native call initializes all memory it has written to" ), - note!( + help!( "Miri also assumes that any part of this memory may be a pointer that is permitted to point to arbitrary exposed memory" ), - note!( + help!( "what this means is that Miri will easily miss Undefined Behavior related to incorrect usage of this shared memory, so you should not take a clean Miri run as a signal that your FFI code is UB-free" ), - note!( + help!( "tracing memory accesses in native code is not yet fully implemented, so there can be further imprecisions beyond what is documented here" ), + note!("this warning is only shown once per program execution"), ] } else { vec![ - note!( + help!( "when memory is shared with a native function call, Miri stops tracking initialization and provenance for that memory" ), - note!( + help!( "in particular, Miri assumes that the native call initializes all memory it has access to" ), - note!( + help!( "Miri also assumes that any part of this memory may be a pointer that is permitted to point to arbitrary exposed memory" ), - note!( + help!( "what this means is that Miri will easily miss Undefined Behavior related to incorrect usage of this shared memory, so you should not take a clean Miri run as a signal that your FFI code is UB-free" ), + note!("this warning is only shown once per program execution"), ] }, ExternTypeReborrow => { @@ -794,16 +799,17 @@ impl<'tcx> MiriMachine<'tcx> { ) })); vec![ - note!( + help!( "`extern type` are not compatible with the Stacked Borrows aliasing model implemented by Miri; Miri may miss bugs in this code" ), - note!( + help!( "try running with `MIRIFLAGS=-Zmiri-tree-borrows` to use the more permissive but also even more experimental Tree Borrows aliasing checks instead" ), + note!("this warning is only shown once per program execution"), ] } GenmcCompareExchangeWeak => - vec![note!( + vec![help!( "add `-Zmiri-genmc-weak-cas-spurious-failures` to MIRIFLAGS to explore spurious failures; all retry loops around `compare_exchange_weak` then need to be bounded" )], _ => vec![], @@ -812,9 +818,8 @@ impl<'tcx> MiriMachine<'tcx> { report_msg( diag_level, title, - vec![label], - notes, - helps, + vec![main_span_label], + extras, &stacktrace, Some(self.threads.active_thread()), self, @@ -842,7 +847,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "the place in the program where the ICE was triggered".to_string(), vec![], vec![], - vec![], &stacktrace, Some(this.active_thread()), &this.machine, diff --git a/src/tools/miri/src/helpers.rs b/src/tools/miri/src/helpers.rs index 9ab122ecfc7c5..2ca635f7410d9 100644 --- a/src/tools/miri/src/helpers.rs +++ b/src/tools/miri/src/helpers.rs @@ -1,6 +1,6 @@ use std::num::NonZero; use std::sync::Mutex; -use std::{cmp, iter}; +use std::{assert_matches, cmp, iter}; use rand::Rng; use rustc_abi::{Align, ExternAbi, FieldIdx, FieldsShape, Size, Variants}; @@ -367,11 +367,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { interp_ok(()) } - /// Write a 0 of the appropriate size to `dest`. - fn write_null(&mut self, dest: &impl Writeable<'tcx, Provenance>) -> InterpResult<'tcx> { - self.write_int(0, dest) - } - /// Test if this pointer equals 0. fn ptr_is_null(&self, ptr: Pointer) -> InterpResult<'tcx, bool> { interp_ok(ptr.addr().bytes() == 0) @@ -476,11 +471,11 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { size: Size, mut action: impl FnMut(AllocRange, bool) -> InterpResult<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_ref(); + let ecx = self.eval_context_ref(); trace!("visit_frozen(place={:?}, size={:?})", *place, size); debug_assert_eq!( size, - this.size_and_align_of_val(place)? + ecx.size_and_align_of_val(place)? .map(|(size, _)| size) .unwrap_or_else(|| place.layout.size) ); @@ -516,11 +511,11 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Run a visitor { let mut visitor = UnsafeCellVisitor { - ecx: this, + ecx, unsafe_cell_action: |place| { trace!("unsafe_cell_action on {:?}", place.ptr()); // We need a size to go on. - let unsafe_cell_size = this + let unsafe_cell_size = ecx .size_and_align_of_val(place)? .map(|(size, _)| size) // for extern types, just cover what we can @@ -537,7 +532,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } // The part between the end_ptr and the end of the place is also frozen. // So pretend there is a 0-sized `UnsafeCell` at the end. - unsafe_cell_action(&place.ptr().wrapping_offset(size, this), Size::ZERO)?; + unsafe_cell_action(&place.ptr().wrapping_offset(size, ecx), Size::ZERO)?; // Done! return interp_ok(()); @@ -666,6 +661,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ) } + fn assert_target_os_is_linux_like(&self, name: &str) { + assert_matches!( + self.eval_context_ref().tcx.sess.target.os, + Os::Linux | Os::Android, + "`{name}` is only available on Linux-like targets", + ) + } + /// Helper function used inside shims of foreign functions to check that the target OS /// is one of `target_oses`. It returns an error containing the `name` of the foreign function /// in a message if this is not the case. diff --git a/src/tools/miri/src/intrinsics/loongarch.rs b/src/tools/miri/src/intrinsics/loongarch.rs index 7acdb57ddb3f1..2b1c1bce415e4 100644 --- a/src/tools/miri/src/intrinsics/loongarch.rs +++ b/src/tools/miri/src/intrinsics/loongarch.rs @@ -12,7 +12,7 @@ pub(super) 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(); // Prefix should have already been checked. let unprefixed_name = link_name.as_str().strip_prefix("llvm.loongarch.").unwrap(); match unprefixed_name { @@ -23,7 +23,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // require a target feature to be enabled. "crc.w.b.w" | "crc.w.h.w" | "crc.w.w.w" | "crc.w.d.w" | "crcc.w.b.w" | "crcc.w.h.w" | "crcc.w.w.w" | "crcc.w.d.w" - if this.tcx.pointer_size().bits() == 64 => + if ecx.tcx.pointer_size().bits() == 64 => { // The polynomial constants below include the leading 1 bit // (e.g. 0x104C11DB7 instead of 0x04C11DB7) which the the @@ -44,9 +44,9 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { _ => unreachable!(), }; - let [data, crc] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; - let data = this.read_scalar(data)?; - let crc = this.read_scalar(crc)?; + let [data, crc] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; + let data = ecx.read_scalar(data)?; + let crc = ecx.read_scalar(crc)?; // The CRC accumulator is always i32. The data argument is i32 for // b/h/w variants and i64 for the d variant, per the LLVM intrinsic @@ -65,7 +65,7 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }; let result = compute_crc32(crc, data, bit_size, polynomial); - this.write_scalar(Scalar::from_u32(result), dest)?; + ecx.write_scalar(Scalar::from_u32(result), dest)?; } _ => return interp_ok(EmulateItemResult::NotSupported), } diff --git a/src/tools/miri/src/intrinsics/math.rs b/src/tools/miri/src/intrinsics/math.rs index 686deaf190a09..9945f1a9ed57f 100644 --- a/src/tools/miri/src/intrinsics/math.rs +++ b/src/tools/miri/src/intrinsics/math.rs @@ -96,7 +96,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { args: &[OpTy<'tcx>], dest: &PlaceTy<'tcx>, ) -> InterpResult<'tcx, EmulateItemResult> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); match intrinsic_name { // Operations we can do with soft-floats. @@ -105,10 +105,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { bug!("`sqrt` intrinsic called on non-float type"); }; match float_ty { - FloatTy::F16 => sqrt::(this, args, dest)?, - FloatTy::F32 => sqrt::(this, args, dest)?, - FloatTy::F64 => sqrt::(this, args, dest)?, - FloatTy::F128 => sqrt::(this, args, dest)?, + FloatTy::F16 => sqrt::(ecx, args, dest)?, + FloatTy::F32 => sqrt::(ecx, args, dest)?, + FloatTy::F64 => sqrt::(ecx, args, dest)?, + FloatTy::F128 => sqrt::(ecx, args, dest)?, } } @@ -120,8 +120,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { | "frem_fast" => { let [a, b] = check_intrinsic_arg_count(args)?; - let a = this.read_immediate(a)?; - let b = this.read_immediate(b)?; + let a = ecx.read_immediate(a)?; + let b = ecx.read_immediate(b)?; let op = match intrinsic_name { "fadd_fast" => mir::BinOp::Add, "fsub_fast" => mir::BinOp::Sub, @@ -153,7 +153,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ), _ => {} } - let res = this.binary_op(op, &a, &b)?; + let res = ecx.binary_op(op, &a, &b)?; // This cannot be a NaN so we also don't have to apply any non-determinism. // (Also, `binary_op` already called `generate_nan` if needed.) if !float_finite(&res)? { @@ -161,15 +161,15 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } // Apply a relative error of 4ULP to simulate non-deterministic precision loss // due to optimizations. - let res = math::apply_random_float_error_to_imm(this, res, 4)?; - this.write_immediate(*res, dest)?; + let res = math::apply_random_float_error_to_imm(ecx, res, 4)?; + ecx.write_immediate(*res, dest)?; } "float_to_int_unchecked" => { let [val] = check_intrinsic_arg_count(args)?; - let val = this.read_immediate(val)?; + let val = ecx.read_immediate(val)?; - let res = this + let res = ecx .float_to_int_checked(&val, dest.layout, Round::TowardZero)? .ok_or_else(|| { err_ub_format!( @@ -178,7 +178,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ) })?; - this.write_immediate(*res, dest)?; + ecx.write_immediate(*res, dest)?; } // Operations that need host floats. @@ -187,9 +187,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { { let [f] = check_intrinsic_arg_count(args)?; match float_ty { - FloatTy::F16 => host_unary_float_op::(this, f, op, dest)?, - FloatTy::F32 => host_unary_float_op::(this, f, op, dest)?, - FloatTy::F64 => host_unary_float_op::(this, f, op, dest)?, + FloatTy::F16 => host_unary_float_op::(ecx, f, op, dest)?, + FloatTy::F32 => host_unary_float_op::(ecx, f, op, dest)?, + FloatTy::F64 => host_unary_float_op::(ecx, f, op, dest)?, FloatTy::F128 => todo!("f128"), // FIXME(f128) }; } @@ -199,9 +199,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { bug!("`powf` intrinsic called on non-float type"); }; match float_ty { - FloatTy::F16 => pow_intrinsic::(this, args, dest)?, - FloatTy::F32 => pow_intrinsic::(this, args, dest)?, - FloatTy::F64 => pow_intrinsic::(this, args, dest)?, + FloatTy::F16 => pow_intrinsic::(ecx, args, dest)?, + FloatTy::F32 => pow_intrinsic::(ecx, args, dest)?, + FloatTy::F64 => pow_intrinsic::(ecx, args, dest)?, FloatTy::F128 => todo!("f128"), // FIXME(f128) } } @@ -211,9 +211,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { bug!("`powf` intrinsic called on non-float type"); }; match float_ty { - FloatTy::F16 => powi_intrinsic::(this, args, dest)?, - FloatTy::F32 => powi_intrinsic::(this, args, dest)?, - FloatTy::F64 => powi_intrinsic::(this, args, dest)?, + FloatTy::F16 => powi_intrinsic::(ecx, args, dest)?, + FloatTy::F32 => powi_intrinsic::(ecx, args, dest)?, + FloatTy::F64 => powi_intrinsic::(ecx, args, dest)?, FloatTy::F128 => todo!("f128"), // FIXME(f128) } } diff --git a/src/tools/miri/src/intrinsics/mod.rs b/src/tools/miri/src/intrinsics/mod.rs index cef8f592151ac..5b5104731ac0b 100644 --- a/src/tools/miri/src/intrinsics/mod.rs +++ b/src/tools/miri/src/intrinsics/mod.rs @@ -44,22 +44,22 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ret: Option, unwind: mir::UnwindAction, ) -> InterpResult<'tcx, Option>> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); // See if the core engine can handle this intrinsic. - if this.eval_intrinsic(instance, args, dest, ret)? { + if ecx.eval_intrinsic(instance, args, dest, ret)? { return interp_ok(None); } - let intrinsic_name = this.tcx.item_name(instance.def_id()); + let intrinsic_name = ecx.tcx.item_name(instance.def_id()); let intrinsic_name = intrinsic_name.as_str(); - let res = this.emulate_intrinsic_by_name(intrinsic_name, instance.args, args, dest, ret)?; - res.jump_to_next_block(this, dest, ret, Some(unwind), |this| { + let res = ecx.emulate_intrinsic_by_name(intrinsic_name, instance.args, args, dest, ret)?; + 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 this.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden { + if ecx.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden { throw_unsup_format!("unimplemented intrinsic: `{intrinsic_name}`") } - let intrinsic_fallback_is_spec = this + let intrinsic_fallback_is_spec = ecx .tcx .tool_attrs( instance.def_id(), @@ -89,10 +89,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { dest: &PlaceTy<'tcx>, ret: Option, ) -> InterpResult<'tcx, EmulateItemResult> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); if let Some(name) = intrinsic_name.strip_prefix("simd_") { - return this.emulate_simd_intrinsic(name, args, dest); + return ecx.emulate_simd_intrinsic(name, args, dest); } match intrinsic_name { @@ -105,7 +105,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "catch_unwind" => { let [try_fn, data, catch_fn] = check_intrinsic_arg_count(args)?; - this.handle_catch_unwind(try_fn, data, catch_fn, dest, ret)?; + ecx.handle_catch_unwind(try_fn, data, catch_fn, dest, ret)?; // This pushed a stack frame, don't jump to `ret`. return interp_ok(EmulateItemResult::AlreadyJumped); } @@ -114,12 +114,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { "ptr_mask" => { let [ptr, mask] = check_intrinsic_arg_count(args)?; - let ptr = this.read_pointer(ptr)?; - let mask = this.read_target_usize(mask)?; + let ptr = ecx.read_pointer(ptr)?; + let mask = ecx.read_target_usize(mask)?; let masked_addr = Size::from_bytes(ptr.addr().bytes() & mask); - this.write_pointer(Pointer::new(ptr.provenance, masked_addr), dest)?; + ecx.write_pointer(Pointer::new(ptr.provenance, masked_addr), dest)?; } // We want to return either `true` or `false` at random, or else something like @@ -132,8 +132,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // FIXME: should we check for validity here? It's tricky because we do not have a // place. Codegen does not seem to set any attributes like `noundef` for intrinsic // calls, so we don't *have* to do anything. - let branch: bool = this.machine.rng.get_mut().random(); - this.write_scalar(Scalar::from_bool(branch), dest)?; + let branch: bool = ecx.machine.rng.get_mut().random(); + ecx.write_scalar(Scalar::from_bool(branch), dest)?; } // Other @@ -147,7 +147,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Make these a NOP, so we get the better Miri-native error messages. } - _ => return this.emulate_math_intrinsic(intrinsic_name, generic_args, args, dest), + _ => return ecx.emulate_math_intrinsic(intrinsic_name, generic_args, args, dest), } interp_ok(EmulateItemResult::NeedsReturn) @@ -160,23 +160,23 @@ 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(); - let link_name = this.tcx.codegen_fn_attrs(instance.def_id()).symbol_name.unwrap(); + let link_name = ecx.tcx.codegen_fn_attrs(instance.def_id()).symbol_name.unwrap(); // These are anyway mostly vector intrinsics and vectors live in memory. - let dest = this.force_allocation(dest)?; + let dest = ecx.force_allocation(dest)?; let res = 'handled: { match link_name.as_str() { // LLVM intrinsics "llvm.prefetch.p0" => { - let [p, rw, loc, ty] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; + let [p, rw, loc, ty] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; - let _ = this.read_pointer(p)?; - let rw = this.read_scalar(rw)?.to_i32()?; - let loc = this.read_scalar(loc)?.to_i32()?; - let ty = this.read_scalar(ty)?.to_i32()?; + let _ = ecx.read_pointer(p)?; + let rw = ecx.read_scalar(rw)?.to_i32()?; + let loc = ecx.read_scalar(loc)?.to_i32()?; + let ty = ecx.read_scalar(ty)?.to_i32()?; if ty == 1 { // Data cache prefetch. @@ -199,49 +199,49 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Used to implement the x86 `_mm{,256,512}_popcnt_epi{8,16,32,64}` and wasm // `{i,u}8x16_popcnt` functions. name if name.starts_with("llvm.ctpop.v") - && this.tcx.sess.target.endian == Endian::Little => + && ecx.tcx.sess.target.endian == Endian::Little => { - 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)?; assert_eq!(dest_len, op_len); for i in 0..dest_len { - let op = this.read_immediate(&this.project_index(&op, i)?)?; + let op = ecx.read_immediate(&ecx.project_index(&op, i)?)?; // Use `to_uint` to get a zero-extended `u128`. Those // extra zeros will not affect `count_ones`. let res = op.to_scalar().to_uint(op.layout.size)?.count_ones(); - this.write_scalar( + ecx.write_scalar( Scalar::from_uint(res, op.layout.size), - &this.project_index(&dest, i)?, + &ecx.project_index(&dest, i)?, )?; } } // Target-specific shims name if name.starts_with("llvm.x86.") - && matches!(this.tcx.sess.target.arch, Arch::X86 | Arch::X86_64) - && this.tcx.sess.target.endian == Endian::Little => + && matches!(ecx.tcx.sess.target.arch, Arch::X86 | Arch::X86_64) + && ecx.tcx.sess.target.endian == Endian::Little => break 'handled x86::EvalContextExt::emulate_x86_intrinsic( - this, link_name, args, &dest, + ecx, link_name, args, &dest, )?, name if name.starts_with("llvm.aarch64.") - && this.tcx.sess.target.arch == Arch::AArch64 - && this.tcx.sess.target.endian == Endian::Little => + && ecx.tcx.sess.target.arch == Arch::AArch64 + && ecx.tcx.sess.target.endian == Endian::Little => break 'handled aarch64::EvalContextExt::emulate_aarch64_intrinsic( - this, link_name, args, &dest, + ecx, link_name, args, &dest, )?, name if name.starts_with("llvm.loongarch.") && matches!( - this.tcx.sess.target.arch, + ecx.tcx.sess.target.arch, Arch::LoongArch32 | Arch::LoongArch64 ) - && this.tcx.sess.target.endian == Endian::Little => + && ecx.tcx.sess.target.endian == Endian::Little => break 'handled loongarch::EvalContextExt::emulate_loongarch_intrinsic( - this, link_name, args, &dest, + ecx, link_name, args, &dest, )?, _ => break 'handled EmulateItemResult::NotSupported, } @@ -249,10 +249,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }; // The rest either implements the logic, or falls back to `lookup_exported_symbol`. - res.jump_to_next_block(this, &dest.clone().into(), ret, None, |this| { + res.jump_to_next_block(ecx, &dest.clone().into(), ret, None, |ecx| { throw_machine_stop!(TerminationInfo::UnsupportedForeignItem(format!( "can't call LLVM intrinsic `{link_name}` on architecture `{arch}`", - arch = this.tcx.sess.target.arch, + arch = ecx.tcx.sess.target.arch, ))); }) } diff --git a/src/tools/miri/src/intrinsics/simd.rs b/src/tools/miri/src/intrinsics/simd.rs index 1f2fd9a8a64df..8689d800dd46f 100644 --- a/src/tools/miri/src/intrinsics/simd.rs +++ b/src/tools/miri/src/intrinsics/simd.rs @@ -16,27 +16,27 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { args: &[OpTy<'tcx>], dest: &PlaceTy<'tcx>, ) -> InterpResult<'tcx, EmulateItemResult> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); match intrinsic_name { // Operations we can do with soft-floats. "fsqrt" => { let [op] = check_intrinsic_arg_count(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)?; assert_eq!(dest_len, op_len); for i in 0..dest_len { - let op = this.project_index(&op, i)?; - let dest = this.project_index(&dest, i)?; + let op = ecx.project_index(&op, i)?; + let dest = ecx.project_index(&dest, i)?; let ty::Float(float_ty) = op.layout.ty.kind() else { - span_bug!(this.cur_span(), "{} operand is not a float", intrinsic_name) + span_bug!(ecx.cur_span(), "{} operand is not a float", intrinsic_name) }; match float_ty { - FloatTy::F16 => math::sqrt_op::>(this, &op, &dest)?, - FloatTy::F32 => math::sqrt_op::>(this, &op, &dest)?, - FloatTy::F64 => math::sqrt_op::>(this, &op, &dest)?, - FloatTy::F128 => math::sqrt_op::>(this, &op, &dest)?, + FloatTy::F16 => math::sqrt_op::>(ecx, &op, &dest)?, + FloatTy::F32 => math::sqrt_op::>(ecx, &op, &dest)?, + FloatTy::F64 => math::sqrt_op::>(ecx, &op, &dest)?, + FloatTy::F128 => math::sqrt_op::>(ecx, &op, &dest)?, }; } } @@ -44,8 +44,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Operations that need host floats. "fsin" | "fcos" | "fexp" | "fexp2" | "flog" | "flog2" | "flog10" => { let [op] = check_intrinsic_arg_count(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)?; assert_eq!(dest_len, op_len); @@ -61,36 +61,36 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }; for i in 0..dest_len { - let op = this.project_index(&op, i)?; - let dest = this.project_index(&dest, i)?; + let op = ecx.project_index(&op, i)?; + let dest = ecx.project_index(&dest, i)?; let ty::Float(float_ty) = op.layout.ty.kind() else { - span_bug!(this.cur_span(), "{} operand is not a float", intrinsic_name) + span_bug!(ecx.cur_span(), "{} operand is not a float", intrinsic_name) }; // Using host floats except for sqrt (but it's fine, these operations do not // have guaranteed precision). match float_ty { - FloatTy::F16 => host_unary_float_op::(this, &op, host_op, &dest)?, - FloatTy::F32 => host_unary_float_op::(this, &op, host_op, &dest)?, - FloatTy::F64 => host_unary_float_op::(this, &op, host_op, &dest)?, + FloatTy::F16 => host_unary_float_op::(ecx, &op, host_op, &dest)?, + FloatTy::F32 => host_unary_float_op::(ecx, &op, host_op, &dest)?, + FloatTy::F64 => host_unary_float_op::(ecx, &op, host_op, &dest)?, FloatTy::F128 => unimplemented!("f128"), // FIXME(f128) } } } "expose_provenance" => { let [op] = check_intrinsic_arg_count(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)?; assert_eq!(dest_len, op_len); for i in 0..dest_len { - let op = this.read_immediate(&this.project_index(&op, i)?)?; - let dest = this.project_index(&dest, i)?; + let op = ecx.read_immediate(&ecx.project_index(&op, i)?)?; + let dest = ecx.project_index(&dest, i)?; let val = match (op.layout.ty.kind(), dest.layout.ty.kind()) { // Ptr/Int casts (ty::RawPtr(..), ty::Int(_) | ty::Uint(_)) => - this.pointer_expose_provenance_cast(&op, dest.layout)?, + ecx.pointer_expose_provenance_cast(&op, dest.layout)?, // Error otherwise _ => throw_unsup_format!( @@ -99,7 +99,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { to_ty = dest.layout.ty, ), }; - this.write_immediate(*val, &dest)?; + ecx.write_immediate(*val, &dest)?; } } diff --git a/src/tools/miri/src/intrinsics/x86/aesni.rs b/src/tools/miri/src/intrinsics/x86/aesni.rs index d36261ca5b87a..bf6ba6f78900e 100644 --- a/src/tools/miri/src/intrinsics/x86/aesni.rs +++ b/src/tools/miri/src/intrinsics/x86/aesni.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, "aes")?; + let ecx = self.eval_context_mut(); + ecx.expect_target_feature_for_intrinsic(link_name, "aes")?; // Prefix should have already been checked. let unprefixed_name = link_name.as_str().strip_prefix("llvm.x86.aesni.").unwrap(); @@ -23,8 +23,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // `state` with the corresponding 128-bit key of `key`. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesdec_si128 "aesdec" | "aesdec.256" | "aesdec.512" => { - let [state, key] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; - aes_round(this, state, key, dest, |state, key| { + let [state, key] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; + aes_round(ecx, state, key, dest, |state, key| { let key = aes::Block::from(key.to_le_bytes()); let mut state = aes::Block::from(state.to_le_bytes()); // `aes::hazmat::equiv_inv_cipher_round` documentation states that @@ -39,9 +39,9 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // `state` with the corresponding 128-bit key of `key`. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesdeclast_si128 "aesdeclast" | "aesdeclast.256" | "aesdeclast.512" => { - let [state, key] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; + let [state, key] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; - aes_round(this, state, key, dest, |state, key| { + aes_round(ecx, state, key, dest, |state, key| { let mut state = aes::Block::from(state.to_le_bytes()); // `aes::hazmat::equiv_inv_cipher_round` does the following operations: // state = InvShiftRows(state) @@ -63,8 +63,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // `state` with the corresponding 128-bit key of `key`. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesenc_si128 "aesenc" | "aesenc.256" | "aesenc.512" => { - let [state, key] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; - aes_round(this, state, key, dest, |state, key| { + let [state, key] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; + aes_round(ecx, state, key, dest, |state, key| { let key = aes::Block::from(key.to_le_bytes()); let mut state = aes::Block::from(state.to_le_bytes()); // `aes::hazmat::cipher_round` documentation states that @@ -79,8 +79,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // `state` with the corresponding 128-bit key of `key`. // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesenclast_si128 "aesenclast" | "aesenclast.256" | "aesenclast.512" => { - let [state, key] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; - aes_round(this, state, key, dest, |state, key| { + let [state, key] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; + aes_round(ecx, state, key, dest, |state, key| { let mut state = aes::Block::from(state.to_le_bytes()); // `aes::hazmat::cipher_round` does the following operations: // state = ShiftRows(state) @@ -99,31 +99,31 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Used to implement the _mm_aesimc_si128 function. // Performs the AES InvMixColumns operation on `op` "aesimc" => { - let [op] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; + let [op] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; // Transmute to `u128` - let op = op.transmute(this.machine.layouts.u128, this)?; - let dest = dest.transmute(this.machine.layouts.u128, this)?; + let op = op.transmute(ecx.machine.layouts.u128, ecx)?; + let dest = dest.transmute(ecx.machine.layouts.u128, ecx)?; - let state = this.read_scalar(&op)?.to_u128()?; + let state = ecx.read_scalar(&op)?.to_u128()?; let mut state = aes::Block::from(state.to_le_bytes()); aes::hazmat::inv_mix_columns(&mut state); - this.write_scalar(Scalar::from_u128(u128::from_le_bytes(state.into())), &dest)?; + ecx.write_scalar(Scalar::from_u128(u128::from_le_bytes(state.into())), &dest)?; } // Used to implement the _mm_aeskeygenassist_si128 function. // Assists in expanding the AES cipher key. "aeskeygenassist" => { - let [ckey, rcon] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; + let [ckey, rcon] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?; // Transmute `__m128i` to `u128`. - let ckey = ckey.transmute(this.machine.layouts.u128, this)?; - let dest = dest.transmute(this.machine.layouts.u128, this)?; + let ckey = ckey.transmute(ecx.machine.layouts.u128, ecx)?; + let dest = dest.transmute(ecx.machine.layouts.u128, ecx)?; - let rcon = this.read_scalar(rcon)?.to_u8()?; - let ckey = this.read_scalar(&ckey)?.to_u128()?; + let rcon = ecx.read_scalar(rcon)?.to_u8()?; + let ckey = ecx.read_scalar(&ckey)?.to_u128()?; let res = aeskeygenassist(ckey, rcon); - this.write_scalar(Scalar::from_u128(res), &dest)?; + ecx.write_scalar(Scalar::from_u128(res), &dest)?; } _ => return interp_ok(EmulateItemResult::NotSupported), } diff --git a/src/tools/miri/src/intrinsics/x86/avx512.rs b/src/tools/miri/src/intrinsics/x86/avx512.rs index 077ae76a8f63a..06e6990aca6ff 100644 --- a/src/tools/miri/src/intrinsics/x86/avx512.rs +++ b/src/tools/miri/src/intrinsics/x86/avx512.rs @@ -1,8 +1,8 @@ use rustc_span::Symbol; use super::{ - packssdw, packsswb, packusdw, packuswb, pavg, permute, permute2, pmaddbw, pmaddwd, psadbw, - pshufb, + ShiftOp, packssdw, packsswb, packusdw, packuswb, pavg, permute, permute2, pmaddbw, pmaddwd, + psadbw, pshufb, shift_simd_by_simd, }; use crate::*; @@ -19,6 +19,17 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let unprefixed_name = link_name.as_str().strip_prefix("llvm.x86.avx512.").unwrap(); match unprefixed_name { + // Used by _mm512_{sllv,srlv}_epi64. + "psllv.q.512" | "psrlv.q.512" => { + this.expect_target_feature_for_intrinsic(link_name, "avx512f")?; + let [left, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; + let which = match unprefixed_name { + "psllv.q.512" => ShiftOp::Left, + "psrlv.q.512" => ShiftOp::RightLogic, + _ => unreachable!(), + }; + shift_simd_by_simd(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" => { @@ -122,15 +133,19 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { permute(this, left, right, dest)?; } - // Used to implement the _mm512_permutex2var_epi64 intrinsic. - "vpermi2var.q.512" => { + // Used to implement the _mm512_permutex2var_epi{32,64} intrinsics. + "vpermi2var.d.512" | "vpermi2var.q.512" => { + this.expect_target_feature_for_intrinsic(link_name, "avx512f")?; let [left, indices, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; permute2(this, left, indices, right, dest)?; } - // Used to implement the _mm512_permutex2var_epi8 intrinsic. - "vpermi2var.qi.512" => { + // Used to implement the _mm{256,512}_permutex2var_epi8 intrinsics. + "vpermi2var.qi.256" | "vpermi2var.qi.512" => { this.expect_target_feature_for_intrinsic(link_name, "avx512vbmi")?; + if unprefixed_name.ends_with(".256") { + this.expect_target_feature_for_intrinsic(link_name, "avx512vl")?; + } let [left, indices, right] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; diff --git a/src/tools/miri/src/intrinsics/x86/sse42.rs b/src/tools/miri/src/intrinsics/x86/sse42.rs index 27057d1449d89..39603d201d47a 100644 --- a/src/tools/miri/src/intrinsics/x86/sse42.rs +++ b/src/tools/miri/src/intrinsics/x86/sse42.rs @@ -8,13 +8,13 @@ use crate::intrinsics::math::compute_crc32; use crate::*; /// A bitmask constant for scrutinizing the immediate byte provided -/// to the string comparison intrinsics. It distinuishes between +/// to the string comparison intrinsics. It distinguishes between /// 16-bit integers and 8-bit integers. See [`compare_strings`] /// for more details about the immediate byte. const USE_WORDS: u8 = 1; /// A bitmask constant for scrutinizing the immediate byte provided -/// to the string comparison intrinsics. It distinuishes between +/// to the string comparison intrinsics. It distinguishes between /// signed integers and unsigned integers. See [`compare_strings`] /// for more details about the immediate byte. const USE_SIGNED: u8 = 2; @@ -55,8 +55,8 @@ const USE_SIGNED: u8 = 2; /// || /// ||- Output selection. This bit has two meanings depending on the instruction. /// | If the instruction is generating a mask, it distinguishes between a bit mask -/// | and a byte mask. Otherwise it distinguishes between the most significand bit -/// | and the least significand bit when generating an index. +/// | and a byte mask. Otherwise it distinguishes between the most significant bit +/// | and the least significant bit when generating an index. /// | /// |- This bit is ignored. It is expected that this bit is set to zero, but it is /// not a requirement. @@ -68,7 +68,12 @@ const USE_SIGNED: u8 = 2; /// fulfills the test as defined inside the immediate byte. /// The mask may be negated if negation flags inside the immediate byte are set. /// -/// For more information, see the Intel Software Developer's Manual, Vol. 2b, Chapter 4.1. +/// For more information, see the Intel Software Developer's Manual, Vol. 2b, Chapter 4.1, +/// as well as the online SDM reference for [PCMPxSTRx_Decode_Immediate], [PCMPxSTRx_Compare], and [PCMPxSTRx_Update_Flags]. +/// +/// [PCMPxSTRx_Decode_Immediate]: https://intel.github.io/SDM/definition/PCMPxSTRx_Decode_Immediate.html +/// [PCMPxSTRx_Compare]: https://intel.github.io/SDM/definition/PCMPxSTRx_Compare.html +/// [PCMPxSTRx_Update_Flags]: https://intel.github.io/SDM/definition/PCMPxSTRx_Update_Flags.html #[expect(clippy::arithmetic_side_effects)] fn compare_strings<'tcx>( ecx: &mut MiriInterpCx<'tcx>, @@ -148,16 +153,21 @@ fn compare_strings<'tcx>( result = (1 << default_len) - 1; } else if len1 <= len2 { for i in 0..len2 { - if len1 > len2 - i { - break; - } - - result |= 1 << i; + // By default, assume that there is a match. + let mut has_match = true; for j in 0..len1 { let k = i + j; if k >= default_len { + // The string ends before the match is completed, but the end + // is defined by the register size, not the string. + // This situation counts as a match. + break; + } else if k >= len2 { + // The string ends before the match is completed. + // This means that there is no match. + has_match = false; break; } else { let ch1 = ecx.read_immediate(&ecx.project_index(str1, j)?)?; @@ -165,11 +175,17 @@ fn compare_strings<'tcx>( let ne = ecx.binary_op(mir::BinOp::Ne, &ch1, &ch2)?; if ne.to_scalar().to_bool()? { - result &= !(1 << i); + // Two characters are not equal, so there can't be a match. + has_match = false; break; } } } + + // Accumulate the match result inside the bit mask. + if has_match { + result |= 1 << i; + } } } } @@ -178,7 +194,7 @@ fn compare_strings<'tcx>( // Polarity: Possibly perform a bitwise complement on the result. match (imm >> 4) & 3 { - 3 => result ^= (1 << len1) - 1, + 3 => result ^= (1 << len2) - 1, 1 => result ^= (1 << default_len) - 1, _ => (), } @@ -226,8 +242,10 @@ fn deconstruct_args<'tcx>( let imm = ecx.read_scalar(imm)?.to_u8()?; let default_len = default_len::(imm); - let len1 = u64::from(ecx.read_scalar(len1)?.to_u32()?.min(default_len)); - let len2 = u64::from(ecx.read_scalar(len2)?.to_u32()?.min(default_len)); + // 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 len1 = u64::from(ecx.read_scalar(len1)?.to_i32()?.unsigned_abs().min(default_len)); + let len2 = u64::from(ecx.read_scalar(len2)?.to_i32()?.unsigned_abs().min(default_len)); let array_layout = array_layout_fn(ecx, imm)?; let str1 = str1.transmute(array_layout, ecx)?; @@ -328,7 +346,8 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } else if let Some((_, len)) = len { len >= default_len::(imm) } else { - implicit_len(this, &str1, imm)?.is_some() + // Test if the second string has no null-terminator. + implicit_len(this, &str2, imm)?.is_none() }; this.write_scalar(Scalar::from_i32(i32::from(result)), dest)?; @@ -407,10 +426,12 @@ pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let [_, len1, _, len2, imm] = this.check_shim_sig_llvm_intrinsic(link_name, args)?; let len = if unprefixed_name == "pcmpestris128" { len1 } else { len2 }; - let len = this.read_scalar(len)?.to_i32()?; + // 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))), + Scalar::from_i32(i32::from(len < default_len::(imm))), dest, )?; } diff --git a/src/tools/miri/src/lib.rs b/src/tools/miri/src/lib.rs index d7706ff5a000a..1143e932a4871 100644 --- a/src/tools/miri/src/lib.rs +++ b/src/tools/miri/src/lib.rs @@ -8,6 +8,7 @@ ), feature(abort_unwind) )] +#![cfg_attr(windows, feature(windows_by_handle))] #![feature(array_try_from_fn)] #![feature(rustc_private)] #![feature(dirfd)] @@ -31,6 +32,7 @@ // Configure clippy and other lints #![allow( clippy::collapsible_if, + clippy::needless_ifs, clippy::enum_variant_names, clippy::manual_map, clippy::neg_cmp_op_on_partial_ord, @@ -51,6 +53,7 @@ // We are not implementing queries here so it's fine rustc::potential_query_instability, )] +#![cfg_attr(not(unix), allow(clippy::permissions_set_readonly_false))] #![warn( rust_2018_idioms, unqualified_local_imports, diff --git a/src/tools/miri/src/shims/cpu_affinity.rs b/src/tools/miri/src/shims/cpu_affinity.rs index 955adb2cf3b12..265a6cac2106e 100644 --- a/src/tools/miri/src/shims/cpu_affinity.rs +++ b/src/tools/miri/src/shims/cpu_affinity.rs @@ -140,7 +140,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // we only copy whole chunks of size_of::() let byte_count = Ord::min(cpuset.as_slice().len(), cpusetsize.try_into().unwrap()); this.write_bytes_ptr(mask, cpuset.as_slice()[..byte_count].iter().copied())?; - this.write_null(dest)?; + this.write_int(0, dest)?; } else { unreachable!("we validated the thread ID above"); } @@ -194,7 +194,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { match CpuAffinityMask::from_array(this, this.machine.num_cpus, bits_array) { Some(cpuset) => { this.machine.thread_cpu_affinity.as_mut().unwrap().insert(thread_id, cpuset); - this.write_null(dest)?; + this.write_int(0, dest)?; } None => { // The intersection between the mask and the available CPUs was empty. diff --git a/src/tools/miri/src/shims/extern_static.rs b/src/tools/miri/src/shims/extern_static.rs index 5e7a391aa8451..b27a527e6f61f 100644 --- a/src/tools/miri/src/shims/extern_static.rs +++ b/src/tools/miri/src/shims/extern_static.rs @@ -60,7 +60,10 @@ impl<'tcx> MiriMachine<'tcx> { match &ecx.tcx.sess.target.os { Os::Linux => { - Self::weak_fn_symbols(ecx, &["getrandom", "gettid", "statx", "strlen"])?; + Self::weak_fn_symbols( + ecx, + &["copy_file_range", "getrandom", "gettid", "statx", "strlen"], + )?; if ecx.tcx.sess.target.env == Env::Gnu { // FIXME: enabling this with genmc causes test failures because of how // std then uses pthread keys and genmc does not know about their state. @@ -94,7 +97,7 @@ impl<'tcx> MiriMachine<'tcx> { // Also initialize `missing_weak_symbol`. let place = ecx.allocate(ecx.machine.layouts.usize, MiriMemoryKind::ExternStatic.into())?; - ecx.write_null(&place)?; + ecx.write_int(0, &place)?; ecx.machine.extern_static_weak_import_default = Some(place.ptr().into_pointer_or_addr().unwrap()); diff --git a/src/tools/miri/src/shims/files.rs b/src/tools/miri/src/shims/files.rs index 42da48b20700d..1c216b0b0a771 100644 --- a/src/tools/miri/src/shims/files.rs +++ b/src/tools/miri/src/shims/files.rs @@ -464,6 +464,7 @@ pub struct FileHandle { pub(crate) file: File, pub(crate) readable: bool, pub(crate) writable: bool, + pub(crate) append: bool, } impl FileDescription for FileHandle { diff --git a/src/tools/miri/src/shims/foreign_items.rs b/src/tools/miri/src/shims/foreign_items.rs index 1c86cc6c91598..f40ebcce3aa86 100644 --- a/src/tools/miri/src/shims/foreign_items.rs +++ b/src/tools/miri/src/shims/foreign_items.rs @@ -76,14 +76,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // The rest either implements the logic, or falls back to `lookup_exported_symbol`. let res = ecx.emulate_foreign_item_inner(link_name, abi, args, &dest)?; - res.jump_to_next_block(ecx, &dest.clone().into(), ret, Some(unwind), |this| { - if let Some(body) = this.lookup_exported_fn(link_name)? { + res.jump_to_next_block(ecx, &dest.clone().into(), ret, Some(unwind), |ecx| { + if let Some(body) = ecx.lookup_exported_fn(link_name)? { return interp_ok(Some(body)); } throw_machine_stop!(TerminationInfo::UnsupportedForeignItem(format!( "can't call foreign function `{link_name}` on OS `{os}`", - os = this.tcx.sess.target.os, + os = ecx.tcx.sess.target.os, ))); }) } @@ -652,7 +652,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { if ecx.target_os_is_unix() { ecx.set_last_error(LibcError("ENOMEM"))?; } - ecx.write_null(dest)?; + ecx.write_int(0, dest)?; } } "calloc" => { @@ -670,7 +670,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { if ecx.target_os_is_unix() { ecx.set_last_error(LibcError("ENOMEM"))?; } - ecx.write_null(dest)?; + ecx.write_int(0, dest)?; } } "free" => { @@ -694,7 +694,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { if ecx.target_os_is_unix() { ecx.set_last_error(LibcError("ENOMEM"))?; } - ecx.write_null(dest)?; + ecx.write_int(0, dest)?; } } "malloc_usable_size" => { @@ -783,7 +783,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { if let Some(needle_ptr) = needle_ptr { ecx.write_pointer(needle_ptr, dest)?; } else { - ecx.write_null(dest)?; + ecx.write_int(0, dest)?; } } "memrchr" => { @@ -809,7 +809,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { if let Some(needle_ptr) = needle_ptr { ecx.write_pointer(needle_ptr, dest)?; } else { - ecx.write_null(dest)?; + ecx.write_int(0, dest)?; } } "strlen" => { diff --git a/src/tools/miri/src/shims/io_error.rs b/src/tools/miri/src/shims/io_error.rs index 4d1ffb1d9b15f..b9b60125ea68e 100644 --- a/src/tools/miri/src/shims/io_error.rs +++ b/src/tools/miri/src/shims/io_error.rs @@ -314,6 +314,18 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { interp_ok(()) } + fn return_io_result_via_errno, E: Into>( + &mut self, + res: Result, + dest: &MPlaceTy<'tcx>, + ) -> InterpResult<'tcx> { + let ecx = self.eval_context_mut(); + match res { + Ok(ret) => ecx.write_int(ret, dest), + Err(err) => ecx.set_errno_and_return_neg1(err, dest), + } + } + /// Sets the last OS error and return `-1` as a `i32`-typed Scalar fn set_errno_and_return_neg1_i32( &mut self, diff --git a/src/tools/miri/src/shims/native_lib/mod.rs b/src/tools/miri/src/shims/native_lib/mod.rs index 90f4fc9601ba2..1dd113766d6ad 100644 --- a/src/tools/miri/src/shims/native_lib/mod.rs +++ b/src/tools/miri/src/shims/native_lib/mod.rs @@ -529,9 +529,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { dest: &MPlaceTy<'tcx>, args: &[OpTy<'tcx>], ) -> InterpResult<'tcx, bool> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); // Get the pointer to the function in the shared object file if it exists. - let Some(code_ptr) = this.get_func_ptr_explicitly_from_lib(link_name) else { + let Some(code_ptr) = ecx.get_func_ptr_explicitly_from_lib(link_name) else { // Shared object file does not export this function -- try the shims next. return interp_ok(false); }; @@ -542,23 +542,23 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Get the function arguments, copy them, and prepare the type descriptions. let mut libffi_args = Vec::::with_capacity(args.len()); for arg in args.iter() { - libffi_args.push(this.op_to_ffi_arg(arg, tracing)?); + libffi_args.push(ecx.op_to_ffi_arg(arg, tracing)?); } - let ret_ty = this + let ret_ty = ecx .ty_to_ffitype(dest.layout) .map_err(|ty| err_unsup_format!("unsupported return type for native call: {ty}"))?; // Prepare all exposed memory (both previously exposed, and just newly exposed since a // pointer was passed as argument). Uninitialised memory is left as-is, but any data // exposed this way is garbage anyway. - this.visit_reachable_allocs(this.exposed_allocs(), |this, alloc_id, info| { + ecx.visit_reachable_allocs(ecx.exposed_allocs(), |ecx, alloc_id, info| { // If there is no data behind this pointer, skip this. if !matches!(info.kind, AllocKind::LiveData) { return interp_ok(()); } // It's okay to get raw access, what we do does not correspond to any actual // AM operation, it just approximates the state to account for the native call. - let alloc = this.get_alloc_raw(alloc_id)?; + let alloc = ecx.get_alloc_raw(alloc_id)?; // Also expose the provenance of the interpreter-level allocation, so it can // be read by FFI. The `black_box` is defensive programming as LLVM likes // to (incorrectly) optimize away ptr2int casts whose result is unused. @@ -569,13 +569,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // $whatever. Can be skipped when tracing; in that case we'll expose just the // actually-read parts later. for prov in alloc.provenance().provenances() { - this.expose_provenance(prov)?; + ecx.expose_provenance(prov)?; } } // Prepare for possible write from native code if mutable. if info.mutbl.is_mut() { - let (alloc, cx) = this.get_alloc_raw_mut(alloc_id)?; + let (alloc, cx) = ecx.get_alloc_raw_mut(alloc_id)?; // These writes could initialize everything and wreck havoc with the pointers. // We can skip that when tracing; in that case we'll later do that only for the // memory that got actually written. @@ -591,11 +591,11 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Call the function and store its output. let (ret, maybe_memevents) = - this.call_native_raw(code_ptr, &mut libffi_args, (ret_ty, dest.layout.size))?; + ecx.call_native_raw(code_ptr, &mut libffi_args, (ret_ty, dest.layout.size))?; if tracing { - this.tracing_apply_accesses(maybe_memevents.unwrap())?; + ecx.tracing_apply_accesses(maybe_memevents.unwrap())?; } - this.ffi_ret_to_mem(ret, dest)?; + ecx.ffi_ret_to_mem(ret, dest)?; interp_ok(true) } } diff --git a/src/tools/miri/src/shims/sig.rs b/src/tools/miri/src/shims/sig.rs index 0a431ff0d113c..92448e0212110 100644 --- a/src/tools/miri/src/shims/sig.rs +++ b/src/tools/miri/src/shims/sig.rs @@ -29,12 +29,12 @@ pub struct ShimSig<'tcx, const ARGS: usize> { #[macro_export] macro_rules! shim_sig { (extern $abi:literal fn($($args:tt)*) -> $($ret:tt)*) => { - |this| { - let (args, c_variadic) = shim_sig_args_sep!(this, [$($args)*]); + |ecx| { + let (args, c_variadic) = shim_sig_args_sep!(ecx, [$($args)*]); $crate::shims::sig::ShimSig { abi: std::str::FromStr::from_str($abi).expect("incorrect abi specified"), args, - ret: shim_sig_arg!(this, $($ret)*), + ret: shim_sig_arg!(ecx, $($ret)*), c_variadic, } } @@ -45,8 +45,8 @@ macro_rules! shim_sig { #[macro_export] macro_rules! shim_varargs { ($($args:tt)*) => { - |this| { - let (args, c_variadic) = shim_sig_args_sep!(this, [$($args)*]); + |ecx| { + let (args, c_variadic) = shim_sig_args_sep!(ecx, [$($args)*]); assert!(!c_variadic); // don't accept `...` here args } diff --git a/src/tools/miri/src/shims/time.rs b/src/tools/miri/src/shims/time.rs index 0719e7da35e70..97127d8e34a97 100644 --- a/src/tools/miri/src/shims/time.rs +++ b/src/tools/miri/src/shims/time.rs @@ -337,7 +337,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { Some(deadline.into()), callback!( @capture<'tcx> {} - |_this, unblock: UnblockKind| { + |_ecx, unblock: UnblockKind| { assert_eq!(unblock, UnblockKind::TimedOut); interp_ok(()) } @@ -365,7 +365,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { Some(deadline.into()), callback!( @capture<'tcx> {} - |_this, unblock: UnblockKind| { + |_ecx, unblock: UnblockKind| { assert_eq!(unblock, UnblockKind::TimedOut); interp_ok(()) } @@ -420,7 +420,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { Some(deadline), callback!( @capture<'tcx> {} - |_this, unblock: UnblockKind| { + |_ecx, unblock: UnblockKind| { assert_eq!(unblock, UnblockKind::TimedOut); interp_ok(()) } @@ -445,7 +445,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { Some(deadline.into()), callback!( @capture<'tcx> {} - |_this, unblock: UnblockKind| { + |_ecx, unblock: UnblockKind| { assert_eq!(unblock, UnblockKind::TimedOut); interp_ok(()) } diff --git a/src/tools/miri/src/shims/unix/android/foreign_items.rs b/src/tools/miri/src/shims/unix/android/foreign_items.rs index 73bb23364106d..52d66c5b329b8 100644 --- a/src/tools/miri/src/shims/unix/android/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/android/foreign_items.rs @@ -124,6 +124,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Threading "prctl" => prctl(ecx, link_name, abi, args, dest)?, + // std-only stubs + "sendfile" if ecx.frame_in_std() => { + let [_out_fd, _in_fd, _offset, _count] = &ecx.check_shim_sig( + shim_sig!(extern "C" fn(i32, i32, *libc::off_t, usize) -> isize), + (link_name, abi, args), + )?; + // Force std to use a fallback path. + ecx.set_errno_and_return_neg1(LibcError("ENOSYS"), dest)?; + } + _ => return interp_ok(EmulateItemResult::NotSupported), } interp_ok(EmulateItemResult::NeedsReturn) diff --git a/src/tools/miri/src/shims/unix/fd.rs b/src/tools/miri/src/shims/unix/fd.rs index d081c47be173e..e16c06a7b7ec5 100644 --- a/src/tools/miri/src/shims/unix/fd.rs +++ b/src/tools/miri/src/shims/unix/fd.rs @@ -413,14 +413,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { count: usize, dest: MPlaceTy<'tcx>, } - |this, result: Result| { + |ecx, result: Result| { match result { Ok(read_size) => { assert!(read_size <= count); // This must fit since `count` fits. - this.write_int(u64::try_from(read_size).unwrap(), &dest) + ecx.write_int(u64::try_from(read_size).unwrap(), &dest) } - Err(e) => this.set_errno_and_return_neg1(e, &dest) + Err(e) => ecx.set_errno_and_return_neg1(e, &dest) }} ), ) @@ -464,14 +464,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { count: usize, dest: MPlaceTy<'tcx>, } - |this, result: Result| { + |ecx, result: Result| { match result { Ok(write_size) => { assert!(write_size <= count); // This must fit since `count` fits. - this.write_int(u64::try_from(write_size).unwrap(), &dest) + ecx.write_int(u64::try_from(write_size).unwrap(), &dest) } - Err(e) => this.set_errno_and_return_neg1(e, &dest) + Err(e) => ecx.set_errno_and_return_neg1(e, &dest) }} ), @@ -542,15 +542,15 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { tmp_ptr: Pointer, buffers: Vec<(Pointer, u64)>, dest: MPlaceTy<'tcx> - } |this, result: Result| { + } |ecx, result: Result| { let bytes_read = match result { Ok(size) => { - this.write_scalar(Scalar::from_target_isize(size.try_into().unwrap(), this), &dest)?; + ecx.write_scalar(Scalar::from_target_isize(size.try_into().unwrap(), ecx), &dest)?; u64::try_from(size).unwrap() }, Err(e) => { - this.deallocate_ptr(tmp_ptr, None, MemoryKind::Stack)?; - return this.set_errno_and_return_neg1(e, &dest) + ecx.deallocate_ptr(tmp_ptr, None, MemoryKind::Stack)?; + return ecx.set_errno_and_return_neg1(e, &dest) } }; let mut remaining_bytes = bytes_read; @@ -561,12 +561,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { for (buffer_ptr, buffer_len) in buffers { // Offset temporary buffer by the amount of bytes we already copied into previous buffers. let tmp_ptr_with_offset = - this.ptr_offset_inbounds(tmp_ptr, i64::try_from(bytes_read.strict_sub(remaining_bytes)).unwrap())?; + ecx.ptr_offset_inbounds(tmp_ptr, i64::try_from(bytes_read.strict_sub(remaining_bytes)).unwrap())?; // Copy at most as many bytes as the buffer fits but without reading // any uninitialized bytes from the temporary buffer. let copy_amount = buffer_len.min(remaining_bytes); - this.mem_copy( + ecx.mem_copy( tmp_ptr_with_offset, buffer_ptr, Size::from_bytes(copy_amount), @@ -583,7 +583,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } } - this.deallocate_ptr(tmp_ptr, None, MemoryKind::Stack) + ecx.deallocate_ptr(tmp_ptr, None, MemoryKind::Stack) }), ) } @@ -672,11 +672,11 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { tmp_ptr: Pointer, dest: MPlaceTy<'tcx>, } - |this, result: Result| { - this.deallocate_ptr(tmp_ptr, None, MemoryKind::Stack)?; + |ecx, result: Result| { + ecx.deallocate_ptr(tmp_ptr, None, MemoryKind::Stack)?; match result { - Ok(size) => this.write_scalar(Scalar::from_target_isize(size.try_into().unwrap(), this), &dest), - Err(e) => this.set_errno_and_return_neg1(e, &dest) + Ok(size) => ecx.write_scalar(Scalar::from_target_isize(size.try_into().unwrap(), ecx), &dest), + Err(e) => ecx.set_errno_and_return_neg1(e, &dest) } }), ) diff --git a/src/tools/miri/src/shims/unix/foreign_items.rs b/src/tools/miri/src/shims/unix/foreign_items.rs index ed2403f5d538a..314bb4ee878a6 100644 --- a/src/tools/miri/src/shims/unix/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/foreign_items.rs @@ -53,31 +53,31 @@ impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {} pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Querying system information fn sysconf(&self, val: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> { - let this = self.eval_context_ref(); + let ecx = self.eval_context_ref(); - let name = this.read_scalar(val)?.to_i32()?; + let name = ecx.read_scalar(val)?.to_i32()?; // FIXME: Which of these are POSIX, and which are GNU/Linux? // At least the names seem to all also exist on macOS. static SYSCONFS: &[(&str, fn(&MiriInterpCx<'_>) -> i64)] = &[ - ("_SC_PAGESIZE", |this| this.machine.page_size.try_into().unwrap()), - ("_SC_PAGE_SIZE", |this| this.machine.page_size.try_into().unwrap()), - ("_SC_NPROCESSORS_CONF", |this| this.machine.num_cpus.into()), - ("_SC_NPROCESSORS_ONLN", |this| this.machine.num_cpus.into()), + ("_SC_PAGESIZE", |ecx| ecx.machine.page_size.try_into().unwrap()), + ("_SC_PAGE_SIZE", |ecx| ecx.machine.page_size.try_into().unwrap()), + ("_SC_NPROCESSORS_CONF", |ecx| ecx.machine.num_cpus.into()), + ("_SC_NPROCESSORS_ONLN", |ecx| ecx.machine.num_cpus.into()), // 512 seems to be a reasonable default. The value is not critical, in // the sense that getpwuid_r takes and checks the buffer length. - ("_SC_GETPW_R_SIZE_MAX", |_this| 512), + ("_SC_GETPW_R_SIZE_MAX", |_ecx| 512), // Miri doesn't have a fixed limit on FDs, but we may be limited in terms of how // many *host* FDs we can open. Just use some arbitrary, pretty big value; // this can be adjusted if it causes problems. // The spec imposes a minimum of `_POSIX_OPEN_MAX` (20). - ("_SC_OPEN_MAX", |_this| 2_i32.pow(16).into()), + ("_SC_OPEN_MAX", |_ecx| 2_i32.pow(16).into()), // Our hard-coded hostname is just 4 bytes so we don't need anything big here. - ("_SC_HOST_NAME_MAX", |_this| 255), + ("_SC_HOST_NAME_MAX", |_ecx| 255), ]; for &(sysconf_name, value) in SYSCONFS { - let sysconf_name = this.eval_libc_i32(sysconf_name); + let sysconf_name = ecx.eval_libc_i32(sysconf_name); if sysconf_name == name { - let value = Scalar::from_target_isize(value(this), this); + let value = Scalar::from_target_isize(value(ecx), ecx); return interp_ok(value); } } @@ -152,7 +152,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(result, dest)?; } "getcwd" => { - // FIXME: This does not have a direct test (#3179). let [buf, size] = &this.check_shim_sig( shim_sig!(extern "C" fn(*_, usize) -> *_), (link_name, abi, args), @@ -169,7 +168,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(result, dest)?; } "chdir" => { - // FIXME: This does not have a direct test (#3179). let [path] = &this .check_shim_sig(shim_sig!(extern "C" fn(*_) -> i32), (link_name, abi, args))?; let result = this.chdir(path)?; @@ -504,14 +502,17 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(result, dest)?; } "fsync" => { - // FIXME: This does not have a direct test (#3179). let [fd] = &this .check_shim_sig(shim_sig!(extern "C" fn(i32) -> i32), (link_name, abi, args))?; let result = this.fsync(fd)?; this.write_scalar(result, dest)?; } "fdatasync" => { - // FIXME: This does not have a direct test (#3179). + // fdatasync is not supported by macos. + this.check_target_os( + &[Os::Linux, Os::FreeBsd, Os::NetBsd, Os::Solaris, Os::Illumos, Os::Android], + link_name, + )?; let [fd] = &this .check_shim_sig(shim_sig!(extern "C" fn(i32) -> i32), (link_name, abi, args))?; let result = this.fdatasync(fd)?; @@ -551,7 +552,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.read_scalar(len)?.to_int(len.layout.size)?; this.read_scalar(advice)?.to_i32()?; // fadvise is only informational, we can ignore it. - this.write_null(dest)?; + this.write_int(0, dest)?; } "posix_fallocate" => { @@ -657,14 +658,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "accept" => { let [socket, address, address_len] = &this.check_shim_sig( - shim_sig!(extern "C" fn(i32, *_, *_) -> i32), + 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)?; } "accept4" => { let [socket, address, address_len, flags] = &this.check_shim_sig( - shim_sig!(extern "C" fn(i32, *_, *_, i32) -> i32), + 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)?; @@ -681,14 +682,28 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { shim_sig!(extern "C" fn(i32, *_, libc::size_t, i32) -> libc::ssize_t), (link_name, abi, args), )?; - this.send(socket, buffer, length, flags, dest)?; + this.send(socket, buffer, length, flags, /* dest_addr */ None, dest)?; + } + "sendto" => { + let [socket, buffer, length, flags, dest_addr, dest_addr_len] = &this.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)?; } "recv" => { let [socket, buffer, length, flags] = &this.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)?; + this.recv(socket, buffer, length, flags, /* dest_addr */ None, dest)?; + } + "recvfrom" => { + let [socket, buffer, length, flags, dest_addr, dest_addr_len] = &this.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)?; } "setsockopt" => { let [socket, level, option_name, option_value, option_len] = &this.check_shim_sig( @@ -710,7 +725,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "getsockname" => { let [socket, address, address_len] = &this.check_shim_sig( - shim_sig!(extern "C" fn(i32, *_, *_) -> i32), + shim_sig!(extern "C" fn(i32, *libc::sockaddr, *libc::socklen_t) -> i32), (link_name, abi, args), )?; let result = this.getsockname(socket, address, address_len)?; @@ -718,7 +733,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } "getpeername" => { let [socket, address, address_len] = &this.check_shim_sig( - shim_sig!(extern "C" fn(i32, *_, *_) -> i32), + shim_sig!(extern "C" fn(i32, *libc::sockaddr, *libc::socklen_t) -> i32), (link_name, abi, args), )?; this.getpeername(socket, address, address_len, dest)?; @@ -833,7 +848,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { match this.compute_size_in_bytes(Size::from_bytes(size), nmemb) { None => { this.set_last_error(LibcError("ENOMEM"))?; - this.write_null(dest)?; + this.write_int(0, dest)?; } Some(len) => { let res = this.realloc(ptr, len.bytes())?; @@ -870,7 +885,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } else if let Some(&ptr) = this.machine.extern_statics.get(&Symbol::intern(name)) { this.write_pointer(ptr, dest)?; } else { - this.write_null(dest)?; + this.write_int(0, dest)?; } } @@ -898,7 +913,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_scalar(Scalar::from_uint(key, key_place.layout.size), &key_place)?; // Return success (`0`). - this.write_null(dest)?; + this.write_int(0, dest)?; } "pthread_key_delete" => { let [key] = &this.check_shim_sig( @@ -908,7 +923,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let key = this.read_scalar(key)?.to_bits(key.layout.size)?; this.machine.tls.delete_tls_key(key)?; // Return success (0) - this.write_null(dest)?; + this.write_int(0, dest)?; } "pthread_getspecific" => { let [key] = &this.check_shim_sig( @@ -931,7 +946,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.machine.tls.store_tls_key(key, active_thread, new_data)?; // Return success (`0`). - this.write_null(dest)?; + this.write_int(0, dest)?; } // Synchronization primitives @@ -941,7 +956,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; this.pthread_mutexattr_init(attr)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "pthread_mutexattr_settype" => { let [attr, kind] = &this.check_shim_sig( @@ -957,7 +972,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; this.pthread_mutexattr_destroy(attr)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "pthread_mutex_init" => { let [mutex, attr] = &this.check_shim_sig( @@ -965,7 +980,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; this.pthread_mutex_init(mutex, attr)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "pthread_mutex_lock" => { let [mutex] = &this.check_shim_sig( @@ -1034,7 +1049,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; this.pthread_rwlock_unlock(rwlock)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "pthread_rwlock_destroy" => { let [rwlock] = &this.check_shim_sig( @@ -1042,7 +1057,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; this.pthread_rwlock_destroy(rwlock)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "pthread_condattr_init" => { let [attr] = &this.check_shim_sig( @@ -1050,7 +1065,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; this.pthread_condattr_init(attr)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "pthread_condattr_setclock" => { let [attr, clock_id] = &this.check_shim_sig( @@ -1066,7 +1081,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; this.pthread_condattr_getclock(attr, clock_id)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "pthread_condattr_destroy" => { let [attr] = &this.check_shim_sig( @@ -1074,7 +1089,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; this.pthread_condattr_destroy(attr)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "pthread_cond_init" => { let [cond, attr] = &this.check_shim_sig( @@ -1082,7 +1097,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; this.pthread_cond_init(cond, attr)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "pthread_cond_signal" => { let [cond] = &this.check_shim_sig( @@ -1090,7 +1105,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; this.pthread_cond_signal(cond)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "pthread_cond_broadcast" => { let [cond] = &this.check_shim_sig( @@ -1098,7 +1113,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; this.pthread_cond_broadcast(cond)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "pthread_cond_wait" => { let [cond, mutex] = &this.check_shim_sig( @@ -1122,7 +1137,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; this.pthread_cond_destroy(cond)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "sem_init" => { let [sem, pshared, value] = &this.check_shim_sig( @@ -1167,7 +1182,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; this.pthread_create(thread, attr, start, arg)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "pthread_join" => { let [thread, retval] = &this.check_shim_sig( @@ -1197,7 +1212,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let [] = &this .check_shim_sig(shim_sig!(extern "C" fn() -> i32), (link_name, abi, args))?; this.sched_yield()?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "nanosleep" => { let [duration, rem] = &this.check_shim_sig( @@ -1259,7 +1274,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.read_pointer(parent)?; this.read_pointer(child)?; // We do not support forking, so there is nothing to do here. - this.write_null(dest)?; + this.write_int(0, dest)?; } "strerror_r" => { let [errnum, buf, buflen] = &this.check_shim_sig( @@ -1293,7 +1308,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.set_errno_and_return_neg1(LibcError("EIO"), dest)?; } else { this.gen_random(buf, bufsize)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } } "getrandom" => { @@ -1374,7 +1389,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { BlockReason::Pause, None, callback!(@capture<'tcx> {} - |_this, _unblock: UnblockKind| { + |_ecx, _unblock: UnblockKind| { panic!("should never unblock") }), ); @@ -1394,13 +1409,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; // Return success (`0`). - this.write_null(dest)?; + 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_null(dest)?; + this.write_int(0, dest)?; } "pthread_attr_setstacksize" if this.frame_in_std() => { @@ -1408,7 +1423,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { shim_sig!(extern "C" fn(*_, usize) -> i32), (link_name, abi, args), )?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "pthread_attr_getstack" if this.frame_in_std() => { @@ -1432,7 +1447,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; // Return success (`0`). - this.write_null(dest)?; + this.write_int(0, dest)?; } "signal" if this.frame_in_std() => { @@ -1440,21 +1455,21 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { shim_sig!(extern "C" fn(i32, libc::sighandler_t) -> libc::sighandler_t), (link_name, abi, args), )?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "sigaltstack" if this.frame_in_std() => { let [_, _] = &this.check_shim_sig( shim_sig!(extern "C" fn(*_, *_) -> i32), (link_name, abi, args), )?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "sigaction" if this.frame_in_std() => { let [_, _, _] = &this.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, *_) -> i32), (link_name, abi, args), )?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "getpwuid_r" | "__posix_getpwuid_r" if this.frame_in_std() => { @@ -1489,9 +1504,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { if written { this.write_pointer(pwd.ptr(), &result)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } else { - this.write_null(&result)?; + this.write_int(0, &result)?; this.write_scalar(this.eval_libc("ERANGE"), dest)?; } } 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 d00f2bb956916..1ca4570477049 100644 --- a/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs @@ -132,7 +132,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { mask, cpuset.as_slice()[..byte_count].iter().copied(), )?; - this.write_null(dest)?; + this.write_int(0, dest)?; } } else { // `id` is always that of the active thread, so this is currently unreachable. @@ -175,7 +175,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { shim_sig!(extern "C" fn(libc::pthread_t, *_) -> i32), (link_name, abi, args), )?; - this.write_null(dest)?; + this.write_int(0, 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 2ea6d31d5cea1..0de6430f0ad0c 100644 --- a/src/tools/miri/src/shims/unix/fs.rs +++ b/src/tools/miri/src/shims/unix/fs.rs @@ -14,7 +14,7 @@ use rustc_target::spec::Os; use self::shims::time::system_time_to_duration; use crate::shims::FdId; -use crate::shims::files::{DirHandle, FdNum, FileHandle, open_file_or_dir}; +use crate::shims::files::{DirHandle, DynFileDescriptionRef, FdNum, FileHandle, open_file_or_dir}; use crate::shims::os_str::{PathConversion, bytes_to_os_str}; use crate::shims::sig::Varargs; use crate::shims::unix::fd::{EvalContextExt as _, FlockOp, UnixFileDescription}; @@ -262,6 +262,20 @@ fn host_file_times_from_updates(access: TimeUpdate, modified: TimeUpdate) -> Fil filetimes } +fn same_host_file(file1: &fs::Metadata, file2: &fs::Metadata) -> bool { + cfg_select! { + unix => { + use std::os::unix::fs::MetadataExt; + file1.dev() == file2.dev() && file1.ino() == file2.ino() + } + windows => { + use std::os::windows::fs::MetadataExt; + file1.volume_serial_number().unwrap() == file2.volume_serial_number().unwrap() + && file1.file_index().unwrap() == file2.file_index().unwrap() + } + } +} + impl<'tcx> EvalContextExtPrivate<'tcx> for crate::MiriInterpCx<'tcx> {} trait EvalContextExtPrivate<'tcx>: crate::MiriInterpCxExt<'tcx> { /// Decode one `futimens` `timespec`, handling the `UTIME_NOW`/`UTIME_OMIT` `tv_nsec` values. @@ -424,15 +438,44 @@ trait EvalContextExtPrivate<'tcx>: crate::MiriInterpCxExt<'tcx> { }) } - fn host_permissions_from_mode(&self, mode: u32) -> InterpResult<'tcx, fs::Permissions> { + fn host_permissions_from_mode( + &self, + mode: u32, + old_permissions: impl FnOnce() -> io::Result, + ) -> InterpResult<'tcx, io::Result> { cfg_select! { unix => { use std::os::unix::fs::PermissionsExt; - interp_ok(fs::Permissions::from_mode(mode)) + + let _ = old_permissions; + interp_ok(Ok(fs::Permissions::from_mode(mode))) } _ => { - let _ = mode; - throw_unsup_format!("setting file permissions is only supported on Unix hosts") + let ecx = self.eval_context_ref(); + + let mut permissions = match old_permissions() { + Ok(p) => p, + Err(err) => return interp_ok(Err(err)), + }; + // Only support default mode for non-UNIX (i.e. Windows) host. + // Ignore the "regular file" bit which is a NOP. + let s_ifreg = ecx.eval_libc("S_IFREG"); + let s_ifreg = u32::try_from(s_ifreg.to_bits(s_ifreg.size())?).unwrap(); + match mode & !s_ifreg { + 0o666 => { + permissions.set_readonly(false); + } + 0o444 => { + permissions.set_readonly(true); + } + _ => { + throw_unsup_format!( + "changing permissions to mode 0o{:o} is not supported on non-Unix hosts", + mode + ); + } + } + interp_ok(Ok(permissions)) } } } @@ -497,8 +540,11 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { _ => { let _unused = options; - // Only support default mode for non-UNIX (i.e. Windows) host - if mode != 0o666 { + // Only support default mode for non-UNIX (i.e. Windows) host. + // Ignore the "regular file" bit which is a NOP. + let s_ifreg = ecx.eval_libc("S_IFREG"); + let s_ifreg = u32::try_from(s_ifreg.to_bits(s_ifreg.size())?).unwrap(); + if mode & !s_ifreg != 0o666 { throw_unsup_format!( "{open_name}: non-default mode 0o{:o} is not supported on non-Unix hosts", mode @@ -583,7 +629,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } } let o_append = ecx.eval_libc_i32("O_APPEND"); - if flag & o_append == o_append { + let append = flag & o_append == o_append; + if append { flag &= !o_append; options.append(true); } @@ -729,7 +776,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { panic!("we should not get a symlink here"); } - let Some(fd) = ecx.machine.fds.insert_new(FileHandle { file, writable, readable }) + let Some(fd) = + ecx.machine.fds.insert_new(FileHandle { file, writable, readable, append }) else { return ecx.set_errno_and_return_neg1_i32(LibcError("EMFILE")); }; @@ -1042,8 +1090,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { statxbuf_op: &OpTy<'tcx>, // Should be a `struct statx *` ) -> InterpResult<'tcx, Scalar> { let this = self.eval_context_mut(); - - this.assert_target_os(Os::Linux, "statx"); + this.assert_target_os_is_linux_like("statx"); let dirfd = this.read_scalar(dirfd_op)?.to_i32()?; let pathname_ptr = this.read_pointer(pathname_op)?; @@ -1214,8 +1261,15 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { return this.set_errno_and_return_neg1_i32(LibcError("EACCES")); } - let permissions = this.host_permissions_from_mode(mode.try_into().unwrap())?; - if let Err(err) = fs::set_permissions(path, permissions) { + let permissions = this.host_permissions_from_mode(mode.try_into().unwrap(), || { + // We get here if we need to read the old permissions before we can set new ones. + // This is fundamentally racy. We cannot even use a file handle to make it less racy: + // setting permissions requires opening for writing, but opening for writing fails + // if the file is not already writable... so how do we make a read-only file writable? + fs::metadata(&path).map(|m| m.permissions()) + })?; + let res = permissions.and_then(|permissions| fs::set_permissions(path, permissions)); + if let Err(err) = res { return this.set_errno_and_return_neg1_i32(err); } @@ -1242,8 +1296,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } assert!(this.machine.communicate(), "isolation should have prevented even opening a file"); - let permissions = this.host_permissions_from_mode(mode.try_into().unwrap())?; - if let Err(err) = file.file.set_permissions(permissions) { + let permissions = this.host_permissions_from_mode(mode.try_into().unwrap(), || { + // We get here if we need to read the old permissions before we can set new ones. + // This is fundamentally racy. + file.file.metadata().map(|m| m.permissions()) + })?; + let res = permissions.and_then(|permissions| file.file.set_permissions(permissions)); + if let Err(err) = res { return this.set_errno_and_return_neg1_i32(err); } @@ -1416,7 +1475,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op { this.reject_in_isolation("`readdir`", reject_with)?; this.set_last_error(LibcError("EBADF"))?; - this.write_null(dest)?; + this.write_int(0, dest)?; return interp_ok(()); } @@ -1508,10 +1567,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Write "optional" fields. if let Some(d_off) = this.try_project_field_named(&entry, "d_off")? { - this.write_null(&d_off)?; + this.write_int(0, &d_off)?; } if let Some(d_seekoff) = this.try_project_field_named(&entry, "d_seekoff")? { - this.write_null(&d_seekoff)?; + this.write_int(0, &d_seekoff)?; } if let Some(d_namlen) = this.try_project_field_named(&entry, "d_namlen")? { this.write_int(name_len.strict_sub(1), &d_namlen)?; @@ -1654,6 +1713,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ) -> InterpResult<'tcx, Scalar> { // This is mostly a copy of `posix_fallocate` except that errors are returned via errno. let this = self.eval_context_mut(); + this.assert_target_os_is_linux_like("fallocate"); // Reject if isolation is enabled. if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op { @@ -1862,7 +1922,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result.map(|()| 0i32))?)) } - fn sync_file_range( + fn linux_sync_file_range( &mut self, fd_op: &OpTy<'tcx>, offset_op: &OpTy<'tcx>, @@ -1870,6 +1930,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { flags_op: &OpTy<'tcx>, ) -> InterpResult<'tcx, Scalar> { let this = self.eval_context_mut(); + this.assert_target_os_is_linux_like("sync_file_range"); let fd = this.read_scalar(fd_op)?.to_i32()?; let offset = this.read_scalar(offset_op)?.to_i64()?; @@ -2144,6 +2205,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { file: f, writable: true, readable: true, + append: false, }) else { return this.set_errno_and_return_neg1_i32(LibcError("EMFILE")); }; @@ -2166,6 +2228,81 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // We ran out of attempts to create the file, return an error. this.set_errno_and_return_neg1_i32(LibcError("EEXIST")) } + + /// Only supports null offset pointers, i.e. copying from and advancing the file positions. + fn linux_copy_file_range( + &mut self, + fd_in_op: &OpTy<'tcx>, + off_in_op: &OpTy<'tcx>, + fd_out_op: &OpTy<'tcx>, + off_out_op: &OpTy<'tcx>, + len_op: &OpTy<'tcx>, + flags_op: &OpTy<'tcx>, + dest: &MPlaceTy<'tcx>, + ) -> InterpResult<'tcx> { + let ecx = self.eval_context_mut(); + ecx.assert_target_os_is_linux_like("copy_file_range"); + + let fd_in = ecx.read_scalar(fd_in_op)?.to_i32()?; + let off_in = ecx.read_pointer(off_in_op)?; + let fd_out = ecx.read_scalar(fd_out_op)?.to_i32()?; + let off_out = ecx.read_pointer(off_out_op)?; + let len = ecx.read_target_usize(len_op)?; + let flags = ecx.read_scalar(flags_op)?.to_u32()?; + + let (Some(fd_in), Some(fd_out)) = (ecx.machine.fds.get(fd_in), ecx.machine.fds.get(fd_out)) + else { + return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest); + }; + if flags != 0 { + throw_unsup_format!("`copy_file_range` with non-zero flags is not supported"); + } + if !ecx.ptr_is_null(off_in)? || !ecx.ptr_is_null(off_out)? { + throw_unsup_format!("`copy_file_range` with non-null offset pointers is not supported"); + } + // Like Linux, check for directories (EISDIR), then other non-regular files (EINVAL), + // then the access modes (EBADF). + let is_dir = |fd: &DynFileDescriptionRef| fd.clone().downcast::().is_some(); + let as_regular_file = |fd: DynFileDescriptionRef| { + let file = fd.downcast::()?; + // Ensure we catch on-disk FIFOs and unix domain sockets. + file.file.metadata().is_ok_and(|metadata| metadata.is_file()).then_some(file) + }; + if is_dir(&fd_in) || is_dir(&fd_out) { + return ecx.set_errno_and_return_neg1(LibcError("EISDIR"), dest); + } + let (Some(file_in), Some(file_out)) = (as_regular_file(fd_in), as_regular_file(fd_out)) + else { + return ecx.set_errno_and_return_neg1(LibcError("EINVAL"), dest); + }; + if !file_in.readable || !file_out.writable || file_out.append { + // The docs explicitly say that O_APPEND on the output file is forbidden. + return ecx.set_errno_and_return_neg1(LibcError("EBADF"), dest); + } + assert!(ecx.machine.communicate(), "isolation should have prevented even opening a file"); + + let copy = || -> io::Result { + let (mut input, mut output) = (&file_in.file, &file_out.file); + let (pos_in, pos_out) = (input.stream_position()?, output.stream_position()?); + + // Error if both FDs refer to the same file and the ranges overlap. + let (meta_in, meta_out) = (input.metadata()?, output.metadata()?); + if same_host_file(&meta_in, &meta_out) + && (pos_in.checked_add(len).is_none_or(|end_in| end_in > pos_out) + && pos_out.checked_add(len).is_none_or(|end_out| end_out > pos_in)) + { + return Err(io::ErrorKind::InvalidInput.into()); + } + + io::copy(&mut input.take(len), &mut output).inspect_err(|_| { + // Like Linux, leave the file positions unchanged on error. See + // . + let _ = input.seek(SeekFrom::Start(pos_in)); + let _ = output.seek(SeekFrom::Start(pos_out)); + }) + }; + ecx.return_io_result_via_errno(copy(), dest) + } } /// Extracts the number of seconds and nanoseconds elapsed between `time` and the unix epoch when 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 774eead50e44b..ea5fccac00d4a 100644 --- a/src/tools/miri/src/shims/unix/linux/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/linux/foreign_items.rs @@ -19,7 +19,7 @@ use crate::*; const TASK_COMM_LEN: u64 = 16; pub fn is_dyn_sym(name: &str, target: &Target) -> bool { - matches!(name, "gettid" | "statx") + matches!(name, "copy_file_range" | "gettid" | "statx") || (target.env == rustc_target::spec::Env::Gnu && matches!(name, "__cxa_thread_atexit_impl")) } @@ -40,7 +40,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { match link_name.as_str() { // File related shims "open64" => { - // FIXME: This does not have a direct test (#3179). // "open64" means that the file is opened with O_LARGEFILE, which we always do. let ([path_raw, flag], varargs) = ecx.check_shim_sig_variadic( shim_sig!(extern "C" fn(*_, i32, ...) -> i32), @@ -50,7 +49,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ecx.write_scalar(result, dest)?; } "openat64" => { - // FIXME: This does not have a direct test (#3179). // "openat64" means that the file is opened with O_LARGEFILE, which we always do. let ([dirfd, path_raw, flag], varargs) = ecx.check_shim_sig_variadic( shim_sig!(extern "C" fn(i32, *_, i32, ...) -> i32), @@ -150,9 +148,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { shim_sig!(extern "C" fn(i32, libc::off64_t, libc::off64_t, u32) -> i32), (link_name, abi, args), )?; - let result = ecx.sync_file_range(fd, offset, nbytes, flags)?; + let result = ecx.linux_sync_file_range(fd, offset, nbytes, flags)?; ecx.write_scalar(result, dest)?; } + "copy_file_range" => { + let [fd_in, off_in, fd_out, off_out, len, flags] = &ecx.check_shim_sig( + shim_sig!(extern "C" fn(i32, *libc::off_t, i32, *libc::off_t, libc::size_t, u32) -> libc::ssize_t), + (link_name, abi, args), + )?; + ecx.linux_copy_file_range(fd_in, off_in, fd_out, off_out, len, flags, dest)?; + } "statx" => { let [dirfd, pathname, flags, mask, statxbuf] = &ecx.check_shim_sig( shim_sig!(extern "C" fn(i32, *_, i32, u32, *libc::statx) -> i32), @@ -282,7 +287,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ecx.machine.current_user_relevant_span(), )?; - ecx.write_null(dest)?; + ecx.write_int(0, dest)?; } // Dynamically invoked syscalls @@ -342,7 +347,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { shim_sig!(extern "C" fn(libc::pthread_t, *_) -> i32), (link_name, abi, args), )?; - ecx.write_null(dest)?; + ecx.write_int(0, dest)?; } "gnu_get_libc_version" if ecx.frame_in_std() @@ -356,6 +361,22 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let version = ecx.allocate_str_dedup(version)?; ecx.write_pointer(version.ptr(), dest)?; } + "sendfile64" if ecx.frame_in_std() => { + let [_out_fd, _in_fd, _offset, _count] = &ecx.check_shim_sig( + shim_sig!(extern "C" fn(i32, i32, *libc::off64_t, usize) -> isize), + (link_name, abi, args), + )?; + // Force std to use a fallback path. + ecx.set_errno_and_return_neg1(LibcError("ENOSYS"), dest)?; + } + "splice" if ecx.frame_in_std() => { + let [_src_fd, _src_offset, _dst_fd, _dst_offset, _len, _flags] = &ecx.check_shim_sig( + shim_sig!(extern "C" fn(i32, *libc::off_t, i32, *libc::off_t, usize, u32) -> isize), + (link_name, abi, args), + )?; + // Force std to use a fallback path. + ecx.set_errno_and_return_neg1(LibcError("ENOSYS"), dest)?; + } _ => return interp_ok(EmulateItemResult::NotSupported), }; diff --git a/src/tools/miri/src/shims/unix/linux_like/epoll.rs b/src/tools/miri/src/shims/unix/linux_like/epoll.rs index cc4afaeddd003..ae5803101539d 100644 --- a/src/tools/miri/src/shims/unix/linux_like/epoll.rs +++ b/src/tools/miri/src/shims/unix/linux_like/epoll.rs @@ -293,17 +293,17 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { events: MPlaceTy<'tcx>, maxevents: u32, } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { match unblock { UnblockKind::Ready => { - let events = this.return_ready_list(&epfd, &dest, &events, maxevents)?; + let events = ecx.return_ready_list(&epfd, &dest, &events, maxevents)?; assert!(events > 0, "we got woken up with no events to deliver"); interp_ok(()) }, UnblockKind::TimedOut => { // Remove the current active thread id from the blocked threads list. - epfd.watcher.remove_blocked_thread(this.active_thread()); - this.write_int(0, &dest)?; + epfd.watcher.remove_blocked_thread(ecx.active_thread()); + ecx.write_int(0, &dest)?; interp_ok(()) }, } diff --git a/src/tools/miri/src/shims/unix/linux_like/eventfd.rs b/src/tools/miri/src/shims/unix/linux_like/eventfd.rs index b68f844b83e65..789dd10fe1342 100644 --- a/src/tools/miri/src/shims/unix/linux_like/eventfd.rs +++ b/src/tools/miri/src/shims/unix/linux_like/eventfd.rs @@ -251,9 +251,9 @@ fn eventfd_write<'tcx>( finish: DynMachineCallback<'tcx, Result>, eventfd: FileDescriptionRef, } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { assert_eq!(unblock, UnblockKind::Ready); - eventfd_write(buf_place, eventfd, this, finish) + eventfd_write(buf_place, eventfd, ecx, finish) } ), ); @@ -290,9 +290,9 @@ fn eventfd_read<'tcx>( finish: DynMachineCallback<'tcx, Result>, eventfd: FileDescriptionRef, } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { assert_eq!(unblock, UnblockKind::Ready); - eventfd_read(buf_place, eventfd, this, finish) + eventfd_read(buf_place, eventfd, ecx, finish) } ), ); diff --git a/src/tools/miri/src/shims/unix/linux_like/syscall.rs b/src/tools/miri/src/shims/unix/linux_like/syscall.rs index 7e3295c8468a9..8f759b6244089 100644 --- a/src/tools/miri/src/shims/unix/linux_like/syscall.rs +++ b/src/tools/miri/src/shims/unix/linux_like/syscall.rs @@ -2,7 +2,8 @@ use rustc_middle::ty::Ty; use rustc_span::Symbol; use rustc_target::callconv::FnAbi; -use crate::shims::unix::env::EvalContextExt; +use crate::shims::unix::env::EvalContextExt as _; +use crate::shims::unix::fs::EvalContextExt as _; use crate::shims::unix::linux_like::eventfd::EvalContextExt as _; use crate::shims::unix::linux_like::sync::futex; use crate::shims::unix::socket::EvalContextExt as _; @@ -29,7 +30,10 @@ pub fn syscall<'tcx>( let sys_eventfd2 = ecx.eval_libc("SYS_eventfd2").to_target_usize(ecx)?; let sys_gettid = ecx.eval_libc("SYS_gettid").to_target_usize(ecx)?; let sys_accept4 = ecx.eval_libc("SYS_accept4").to_target_usize(ecx)?; + let sys_copy_file_range = ecx.eval_libc("SYS_copy_file_range").to_target_usize(ecx)?; + let sys_splice = ecx.eval_libc("SYS_splice").to_target_usize(ecx)?; + // FIXME: Do these all have direct tests (#3179)? match ecx.read_target_usize(&op)? { // `libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)` // is called if a `HashMap` is created the regular way (e.g. HashMap). @@ -76,6 +80,18 @@ pub fn syscall<'tcx>( )?; ecx.accept4(&socket, &address, &address_len, Some(&flags), dest)?; } + num if num == sys_copy_file_range => { + let ([fd_in, off_in, fd_out, off_out, len, flags], _) = &ecx.check_varargs( + shim_varargs![i32, *libc::off_t, i32, *libc::off_t, libc::size_t, u32], + varargs, + "syscall(SYS_copy_file_range, ...)", + )?; + ecx.linux_copy_file_range(fd_in, off_in, fd_out, off_out, len, flags, dest)?; + } + num if num == sys_splice => { + // Force std to use a fallback path. + ecx.set_errno_and_return_neg1(LibcError("ENOSYS"), dest)?; + } num => { throw_unsup_format!("syscall: unsupported syscall number {num}"); } 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 5f2ebfdbe7bad..875abab202c6b 100644 --- a/src/tools/miri/src/shims/unix/macos/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/macos/foreign_items.rs @@ -183,7 +183,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; if written { - this.write_null(dest)?; + this.write_int(0, dest)?; } else { this.write_scalar(Scalar::from_u32(size_needed.try_into().unwrap()), &bufsize)?; this.write_int(-1, dest)?; @@ -447,7 +447,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; // We just pretend that no configuration key exists, and return EINVAL. this.set_last_error(LibcError("EINVAL"))?; - this.write_null(dest)?; + this.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 24476b2e00ed3..8cb0f8b14c177 100644 --- a/src/tools/miri/src/shims/unix/macos/sync.rs +++ b/src/tools/miri/src/shims/unix/macos/sync.rs @@ -116,15 +116,15 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { { // `os_unfair_lock_s` wraps a single `u32` field. We use the first byte to store the "init" // flag. Due to macOS always being little endian, that's the least significant byte. - let this = self.eval_context_mut(); - assert!(this.tcx.data_layout.endian == Endian::Little); + let ecx = self.eval_context_mut(); + assert!(ecx.tcx.data_layout.endian == Endian::Little); - let lock = this.deref_pointer(lock_ptr)?; - this.get_or_insert_meta( + let lock = ecx.deref_pointer(lock_ptr)?; + ecx.get_or_insert_meta( &lock, - |this| { - let field = this.project_field(&lock, FieldIdx::from_u32(0))?; - let val = this.read_scalar(&field)?.to_u32()?; + |ecx| { + let field = ecx.project_field(&lock, FieldIdx::from_u32(0))?; + let val = ecx.read_scalar(&field)?.to_u32()?; if val == 0 { interp_ok(MacOsUnfairLock::Active { mutex_ref: MutexRef::new() }) } else if val == u32::from_ne_bytes([OPAQUE_OBJ_COOKIE; 4]) { @@ -176,25 +176,25 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { timeout: MacOsFutexTimeout<'_, 'tcx>, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); - let none = this.eval_libc_u32("OS_SYNC_WAIT_ON_ADDRESS_NONE"); - let absolute_clock = this.eval_libc_u32("OS_CLOCK_MACH_ABSOLUTE_TIME"); + let ecx = self.eval_context_mut(); + let none = ecx.eval_libc_u32("OS_SYNC_WAIT_ON_ADDRESS_NONE"); + let absolute_clock = ecx.eval_libc_u32("OS_CLOCK_MACH_ABSOLUTE_TIME"); - let ptr = this.read_pointer(addr_op)?; - let value = this.read_scalar(value_op)?.to_u64()?; - let size = this.read_target_usize(size_op)?; - let flags = this.read_scalar(flags_op)?.to_u32()?; + let ptr = ecx.read_pointer(addr_op)?; + let value = ecx.read_scalar(value_op)?.to_u64()?; + let size = ecx.read_target_usize(size_op)?; + let flags = ecx.read_scalar(flags_op)?.to_u32()?; let clock_timeout = match timeout { MacOsFutexTimeout::None => None, MacOsFutexTimeout::Relative { clock_op, timeout_op } => { - let clock = this.read_scalar(clock_op)?.to_u32()?; - let timeout = this.read_scalar(timeout_op)?.to_u64()?; + let clock = ecx.read_scalar(clock_op)?.to_u32()?; + let timeout = ecx.read_scalar(timeout_op)?.to_u64()?; Some((clock, TimeoutStyle::Relative, timeout)) } MacOsFutexTimeout::Absolute { clock_op, timeout_op } => { - let clock = this.read_scalar(clock_op)?.to_u32()?; - let timeout = this.read_scalar(timeout_op)?.to_u64()?; + let clock = ecx.read_scalar(clock_op)?.to_u32()?; + let timeout = ecx.read_scalar(timeout_op)?.to_u64()?; Some((clock, TimeoutStyle::Absolute, timeout)) } }; @@ -208,7 +208,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { || clock_timeout .is_some_and(|(clock, _, timeout)| clock != absolute_clock || timeout == 0) { - this.set_errno_and_return_neg1(LibcError("EINVAL"), dest)?; + ecx.set_errno_and_return_neg1(LibcError("EINVAL"), dest)?; return interp_ok(()); } @@ -217,19 +217,19 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // While the deadline argument of `os_sync_wait_on_address_with_deadline` // is actually not in nanoseconds but in the units of `mach_current_time`, // the two are equivalent in miri. - this.machine.timeout(TimeoutClock::Monotonic, style, Duration::from_nanos(timeout)) + ecx.machine.timeout(TimeoutClock::Monotonic, style, Duration::from_nanos(timeout)) }); // See the Linux futex implementation for why this fence exists. - this.atomic_fence(AtomicFenceOrd::SeqCst)?; + ecx.atomic_fence(AtomicFenceOrd::SeqCst)?; - let layout = this.machine.layouts.uint(Size::from_bytes(size)).unwrap(); - let futex_place = this.ptr_to_mplace(ptr, layout); - let futex_val = this + let layout = ecx.machine.layouts.uint(Size::from_bytes(size)).unwrap(); + let futex_place = ecx.ptr_to_mplace(ptr, layout); + let futex_val = ecx .read_scalar_atomic(&futex_place, AtomicReadOrd::Acquire)? .to_bits(Size::from_bytes(size))?; - let futex = this.get_or_insert_meta(&futex_place, |_| { + let futex = ecx.get_or_insert_meta(&futex_place, |_| { interp_ok(MacOsFutex { futex: Default::default(), size: Cell::new(size) }) })?; @@ -240,7 +240,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { if futex.futex.waiters() == 0 { futex.size.set(size); } else if futex.size.get() != size { - this.set_errno_and_return_neg1(LibcError("EINVAL"), dest)?; + ecx.set_errno_and_return_neg1(LibcError("EINVAL"), dest)?; return interp_ok(()); } @@ -248,7 +248,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // If the values are the same, we have to block. let futex_ref = futex.futex.clone(); let dest = dest.clone(); - this.futex_wait( + ecx.futex_wait( futex_ref.clone(), u32::MAX, // bitset deadline, @@ -257,14 +257,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { dest: MPlaceTy<'tcx>, futex_ref: FutexRef, } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { match unblock { UnblockKind::Ready => { let remaining = futex_ref.waiters().try_into().unwrap(); - this.write_scalar(Scalar::from_i32(remaining), &dest) + ecx.write_scalar(Scalar::from_i32(remaining), &dest) } UnblockKind::TimedOut => { - this.set_errno_and_return_neg1(LibcError("ETIMEDOUT"), &dest) + ecx.set_errno_and_return_neg1(LibcError("ETIMEDOUT"), &dest) } } } @@ -273,7 +273,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } else { // else retrieve the current number of waiters. let waiters = futex.futex.waiters().try_into().unwrap(); - this.write_scalar(Scalar::from_i32(waiters), dest)?; + ecx.write_scalar(Scalar::from_i32(waiters), dest)?; } interp_ok(()) @@ -291,40 +291,40 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { all: bool, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); - let none = this.eval_libc_u32("OS_SYNC_WAKE_BY_ADDRESS_NONE"); + let ecx = self.eval_context_mut(); + let none = ecx.eval_libc_u32("OS_SYNC_WAKE_BY_ADDRESS_NONE"); - let ptr = this.read_pointer(addr_op)?; - let size = this.read_target_usize(size_op)?; - let flags = this.read_scalar(flags_op)?.to_u32()?; + let ptr = ecx.read_pointer(addr_op)?; + let size = ecx.read_target_usize(size_op)?; + let flags = ecx.read_scalar(flags_op)?.to_u32()?; // Perform validation of the arguments. let addr = ptr.addr().bytes(); if addr == 0 || !matches!(size, 4 | 8) || (flags != none) { - this.set_errno_and_return_neg1(LibcError("EINVAL"), dest)?; + ecx.set_errno_and_return_neg1(LibcError("EINVAL"), dest)?; return interp_ok(()); } // See the Linux futex implementation for why this fence exists. - this.atomic_fence(AtomicFenceOrd::SeqCst)?; + ecx.atomic_fence(AtomicFenceOrd::SeqCst)?; - let Ok(futex) = this.try_get_meta::(ptr) else { + let Ok(futex) = ecx.try_get_meta::(ptr) else { // Same behavior for dangling pointers and when no futex has been put here yet. - return this.set_errno_and_return_neg1(LibcError("ENOENT"), dest); + return ecx.set_errno_and_return_neg1(LibcError("ENOENT"), dest); }; if futex.futex.waiters() == 0 { - return this.set_errno_and_return_neg1(LibcError("ENOENT"), dest); + return ecx.set_errno_and_return_neg1(LibcError("ENOENT"), dest); // If there are waiters in the queue, they have all used the parameters // stored in `futex` (we check this in `os_sync_wait_on_address` above). // Detect mismatches between "our" parameters and the parameters used by // the waiters and return an error in that case. } else if futex.size.get() != size { - return this.set_errno_and_return_neg1(LibcError("EINVAL"), dest); + return ecx.set_errno_and_return_neg1(LibcError("EINVAL"), dest); } - this.futex_wake(&futex.futex.clone(), u32::MAX, if all { usize::MAX } else { 1 })?; - this.write_scalar(Scalar::from_i32(0), dest)?; + ecx.futex_wake(&futex.futex.clone(), u32::MAX, if all { usize::MAX } else { 1 })?; + ecx.write_scalar(Scalar::from_i32(0), dest)?; interp_ok(()) } @@ -384,9 +384,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } fn os_unfair_lock_unlock(&mut self, lock_op: &OpTy<'tcx>) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let MacOsUnfairLock::Active { mutex_ref } = this.os_unfair_lock_get_data(lock_op)? else { + let MacOsUnfairLock::Active { mutex_ref } = ecx.os_unfair_lock_get_data(lock_op)? else { // We don't know who the owner is so we cannot proceed. throw_unsup_format!( "attempted to unlock an os_unfair_lock that was copied while being locked" @@ -395,7 +395,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let mutex_ref = mutex_ref.clone(); // Now, unlock. - if this.mutex_unlock(&mutex_ref)?.is_none() { + if ecx.mutex_unlock(&mutex_ref)?.is_none() { // Matching the current macOS implementation: abort. throw_machine_stop!(TerminationInfo::Abort( "attempted to unlock an os_unfair_lock not owned by the current thread".to_owned() @@ -406,17 +406,17 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Reset to zero so that it can be moved and initialized again for the next phase. if mutex_ref.owner().is_none() { let lock_place = - this.project_field(&this.deref_pointer(lock_op)?, FieldIdx::from_u32(0))?; - this.write_scalar_atomic(Scalar::from_u32(0), &lock_place, AtomicWriteOrd::Relaxed)?; + ecx.project_field(&ecx.deref_pointer(lock_op)?, FieldIdx::from_u32(0))?; + ecx.write_scalar_atomic(Scalar::from_u32(0), &lock_place, AtomicWriteOrd::Relaxed)?; } interp_ok(()) } fn os_unfair_lock_assert_owner(&mut self, lock_op: &OpTy<'tcx>) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let MacOsUnfairLock::Active { mutex_ref } = this.os_unfair_lock_get_data(lock_op)? else { + let MacOsUnfairLock::Active { mutex_ref } = ecx.os_unfair_lock_get_data(lock_op)? else { // We don't know who the owner is so we cannot proceed. throw_unsup_format!( "attempted to assert the owner of an os_unfair_lock that was copied while being locked" @@ -424,7 +424,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { }; let mutex_ref = mutex_ref.clone(); - if mutex_ref.owner().is_none_or(|o| o != this.active_thread()) { + if mutex_ref.owner().is_none_or(|o| o != ecx.active_thread()) { throw_machine_stop!(TerminationInfo::Abort( "called os_unfair_lock_assert_owner on an os_unfair_lock not owned by the current thread".to_owned() )); @@ -495,10 +495,10 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { timeout: &OpTy<'tcx>, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let sem_ptr = this.read_pointer(sem_ptr)?; - let timeout = this.read_scalar(timeout)?.to_u64()?; + let sem_ptr = ecx.read_pointer(sem_ptr)?; + let timeout = ecx.read_scalar(timeout)?.to_u64()?; let deadline = if timeout == DISPATCH_TIME_FOREVER { None @@ -506,23 +506,23 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // `timeout` is an absolute nanosecond value on the monotone clock. // (This also handles `DISPATCH_TIME_NOW` as that is 0.) let deadline = - this.machine.monotonic_clock.epoch().add_lossy(Duration::from_nanos(timeout)); + ecx.machine.monotonic_clock.epoch().add_lossy(Duration::from_nanos(timeout)); Some(deadline.into()) }; - let data = this.dispatch_semaphore_get_data(sem_ptr)?.clone(); + let data = ecx.dispatch_semaphore_get_data(sem_ptr)?.clone(); let dest = dest.clone(); - this.semaphore_decrement( + ecx.semaphore_decrement( data.semaphore, deadline, callback!( @capture<'tcx> { dest: MPlaceTy<'tcx>, } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { match unblock { - UnblockKind::Ready => this.write_null(&dest), - UnblockKind::TimedOut => this.write_int(/* KERN_OPERATION_TIMED_OUT */ 49, &dest), + UnblockKind::Ready => ecx.write_int(0, &dest), + UnblockKind::TimedOut => ecx.write_int(/* KERN_OPERATION_TIMED_OUT */ 49, &dest), } } ), diff --git a/src/tools/miri/src/shims/unix/poll.rs b/src/tools/miri/src/shims/unix/poll.rs index da58a0e365c79..92929a790bdec 100644 --- a/src/tools/miri/src/shims/unix/poll.rs +++ b/src/tools/miri/src/shims/unix/poll.rs @@ -30,11 +30,11 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { timeout: &OpTy<'tcx>, dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { - let this = self.eval_context_mut(); + let ecx = self.eval_context_mut(); - let nfds: u64 = this.read_scalar(nfds)?.to_int(nfds.layout.size)?.try_into().unwrap(); - let timeout = this.read_scalar(timeout)?.to_i32()?; - let fds_arr = this.deref_pointer(fds)?; + let nfds: u64 = ecx.read_scalar(nfds)?.to_int(nfds.layout.size)?.try_into().unwrap(); + let timeout = ecx.read_scalar(timeout)?.to_i32()?; + let fds_arr = ecx.deref_pointer(fds)?; // The provided interests indexed by the file descriptor they're for. let mut interests = BTreeMap::>::new(); @@ -47,16 +47,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // We iterate over the fds array of the `poll` syscall. For each fd, we check its // output field, the relevant events, and whether they are currently fulfilled. for idx in 0..nfds { - let pollfd = this.project_c_array_field(&fds_arr, idx)?; - let fd_field = this.project_field_named(&pollfd, "fd")?; - let fd_num = this.read_scalar(&fd_field)?.to_i32()?; - let events_field = this.project_field_named(&pollfd, "events")?; - let events = this.read_scalar(&events_field)?.to_u16()?; - let revents_field = this.project_field_named(&pollfd, "revents")?; + let pollfd = ecx.project_c_array_field(&fds_arr, idx)?; + let fd_field = ecx.project_field_named(&pollfd, "fd")?; + let fd_num = ecx.read_scalar(&fd_field)?.to_i32()?; + let events_field = ecx.project_field_named(&pollfd, "events")?; + let events = ecx.read_scalar(&events_field)?.to_u16()?; + let revents_field = ecx.project_field_named(&pollfd, "revents")?; - let relevant_events = this.poll_bitflag_to_readiness(events)?; + let relevant_events = ecx.poll_bitflag_to_readiness(events)?; - let revents = if this.machine.fds.get(fd_num).is_some() { + let revents = if ecx.machine.fds.get(fd_num).is_some() { // A file description for this file descriptor exists; the interest is thus not ignored. let interest = PollInterest { revents_place: revents_field.clone() }; if interests.try_insert(fd_num, interest).is_err() { @@ -70,7 +70,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { relevant_events, /* is_edge_triggered */ false, u64::try_from(fd_num).unwrap(), - this, + ecx, )? // We just ensured that no file descriptor is registered twice. .unwrap(); @@ -90,37 +90,37 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // and thus returns from the `poll` invocation. invalid_interests = invalid_interests.strict_add(1); - this.eval_libc_u16("POLLNVAL") + ecx.eval_libc_u16("POLLNVAL") }; - this.write_scalar(Scalar::from_u16(revents), &revents_field)?; + ecx.write_scalar(Scalar::from_u16(revents), &revents_field)?; } if timeout == 0 || invalid_interests > 0 || watcher.ready_count() > 0 { // Some interests are already fulfilled or a zero timeout was provided. // We thus don't need to block the thread and can just return here. - let count = this.write_ready_events(watcher, interests)?; + let count = ecx.write_ready_events(watcher, interests)?; // The Linux implementation also counts invalid interests as fulfilled. let total = count.strict_add(invalid_interests); - return this.write_scalar(Scalar::from_u32(total), dest); + return ecx.write_scalar(Scalar::from_u32(total), dest); } // None of the interests are currently fulfilled; we thus need to // block the thread until any interest gets fulfilled. - watcher.add_blocked_thread(this.machine.threads.active_thread()); + watcher.add_blocked_thread(ecx.machine.threads.active_thread()); let deadline = if timeout.is_positive() { let timeout_duration = Duration::from_millis(u64::try_from(timeout).unwrap()); - Some(this.machine.monotonic_clock.now().add_lossy(timeout_duration).into()) + Some(ecx.machine.monotonic_clock.now().add_lossy(timeout_duration).into()) } else { // Negative timeout means block indefinitely. None }; let dest = dest.clone(); - this.block_thread( + ecx.block_thread( BlockReason::Readiness, deadline, callback!( @@ -128,13 +128,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { watcher: Rc, interests: BTreeMap>, dest: MPlaceTy<'tcx>, - } |this, reason: UnblockKind| { + } |ecx, reason: UnblockKind| { if let UnblockKind::TimedOut = reason { - return this.write_scalar(Scalar::from_u32(0), &dest); + return ecx.write_scalar(Scalar::from_u32(0), &dest); } - let count = this.write_ready_events(watcher, interests)?; - this.write_scalar(Scalar::from_u32(count), &dest) + let count = ecx.write_ready_events(watcher, interests)?; + ecx.write_scalar(Scalar::from_u32(count), &dest) } ), ); diff --git a/src/tools/miri/src/shims/unix/socket.rs b/src/tools/miri/src/shims/unix/socket.rs index a1922f5332554..0d2e0c90a6b8a 100644 --- a/src/tools/miri/src/shims/unix/socket.rs +++ b/src/tools/miri/src/shims/unix/socket.rs @@ -65,12 +65,15 @@ pub trait UnixSocketFileDescription: UnixFileDescription { throw_unsup_format!("cannot connect {}", self.name()); } - /// Receive data on the socket into the given buffer `ptr`. + /// Receive data on the socket into the given buffer `ptr` and return the socket + /// address from where the data originated. /// `len` indicates how many bytes we should try to receive. /// `is_peek` specifies whether the receive removes the bytes from the receive buffer /// ([`false`]) or leaves them in the receive buffer ([`true`]). /// `is_non_block` specifies whether the receive operation is non-blocking. - /// After a successful receive, `finish` should be called with the amount of bytes received. + /// After a successful receive, `finish` should be called with a tuple containing the + /// amount of bytes received and the socket address from where the data originated, should + /// it be provided by the protocol. fn recv<'tcx>( self: FileDescriptionRef, _communicate_allowed: bool, @@ -79,7 +82,7 @@ pub trait UnixSocketFileDescription: UnixFileDescription { _is_peek: bool, _is_non_block: bool, _ecx: &mut MiriInterpCx<'tcx>, - _finish: DynMachineCallback<'tcx, Result>, + _finish: DynMachineCallback<'tcx, Result<(usize, Option), IoError>>, ) -> InterpResult<'tcx> { throw_unsup_format!("cannot receive from {}", self.name()); } @@ -87,6 +90,8 @@ pub trait UnixSocketFileDescription: UnixFileDescription { /// Send data from the given buffer `ptr` into the socket. /// `len` indicates how many bytes we should try to send. /// `is_non_block` specifies whether the send operation is non-blocking. + /// `dest_addr` optionally contains a socket address to which the data + /// should be sent instead of the default destination address. /// After a successful send, `finish` should be called with the amount of bytes sent. fn send<'tcx>( self: FileDescriptionRef, @@ -94,6 +99,7 @@ pub trait UnixSocketFileDescription: UnixFileDescription { _ptr: Pointer, _len: usize, _is_non_block: bool, + _dest_addr: Option, _ecx: &mut MiriInterpCx<'tcx>, _finish: DynMachineCallback<'tcx, Result>, ) -> InterpResult<'tcx> { @@ -367,7 +373,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let socket = this.read_scalar(socket)?.to_i32()?; let address_ptr = this.read_pointer(address)?; - let address_len_ptr = this.read_pointer(address_len)?; + let address_len_place = this.deref_pointer(address_len)?; let mut flags = if let Some(flags) = flags { this.read_scalar(flags)?.to_i32()? } else { 0 }; @@ -417,26 +423,26 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { callback!( @capture<'tcx> { address_ptr: Pointer, - address_len_ptr: Pointer, + address_len_place: MPlaceTy<'tcx>, dest: MPlaceTy<'tcx> - } |this, result: Result<(FdNum, SocketAddr), IoError>| { + } |ecx, result: Result<(FdNum, SocketAddr), IoError>| { let (client_sockfd, address) = match result { Ok(data) => data, - Err(e) => return this.set_errno_and_return_neg1(e, &dest), + Err(e) => return ecx.set_errno_and_return_neg1(e, &dest), }; if address_ptr != Pointer::null() { // We only attempt a write if the address pointer is not a null pointer. // If the address pointer is a null pointer the user isn't interested in the // address and we don't need to write anything. - this.write_socket_address(&address, address_ptr, address_len_ptr, "accept4")?; + ecx.write_socket_address(Some(&address), address_ptr, &address_len_place)?; } // We need to create the scalar using the destination size since // `syscall(SYS_accept4, ...)` returns a long which doesn't match // the int returned from the `accept`/`accept4` syscalls. // See . - this.write_scalar(Scalar::from_int(client_sockfd, dest.layout.size), &dest) + ecx.write_scalar(Scalar::from_int(client_sockfd, dest.layout.size), &dest) } ), ) @@ -476,12 +482,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { callback!( @capture<'tcx> { dest: MPlaceTy<'tcx> - } |this, result: Result<(), IoError>| { - match result { - Ok(()) => this.write_null(&dest), - Err(e) => this.set_errno_and_return_neg1(e, &dest) - } - } + } |ecx, result: Result<(), IoError>| { + ecx.return_io_result_via_errno(result.map(|()| 0), &dest) + } ), ) } @@ -492,6 +495,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { buffer: &OpTy<'tcx>, length: &OpTy<'tcx>, flags: &OpTy<'tcx>, + dest_addr: Option<(&OpTy<'tcx>, &OpTy<'tcx>)>, // Location where the output scalar is written to. dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { @@ -504,6 +508,31 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.read_scalar(length)?.to_uint(size_layout.size)?.try_into().unwrap(); let mut flags = this.read_scalar(flags)?.to_i32()?; + let dest_addr = match dest_addr { + Some((dest_addr, dest_addr_len)) => { + let dest_addr_ptr = this.read_pointer(dest_addr)?; + let socklen_layout = this.libc_ty_layout("socklen_t"); + let dest_addr_len_int = + this.read_scalar(dest_addr_len)?.to_uint(socklen_layout.size)?; + + // 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 dest_addr_ptr == Pointer::null() || 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")? { + Ok(dest_addr) => Some(dest_addr), + Err(e) => return this.set_errno_and_return_neg1(e, dest), + } + } + } + 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); @@ -550,15 +579,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { buffer_ptr, length, is_non_block, + dest_addr, this, callback!( @capture<'tcx> { dest: MPlaceTy<'tcx>, - } |this, result: Result| { + } |ecx, result: Result| { match result { Ok(bytes_sent) => - this.write_scalar(Scalar::from_target_usize(bytes_sent.try_into().unwrap(), this), &dest), - Err(e) => this.set_errno_and_return_neg1(e, &dest) + ecx.write_scalar(Scalar::from_target_usize(bytes_sent.try_into().unwrap(), ecx), &dest), + Err(e) => ecx.set_errno_and_return_neg1(e, &dest) } } ) @@ -571,6 +601,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { buffer: &OpTy<'tcx>, length: &OpTy<'tcx>, flags: &OpTy<'tcx>, + dest_addr: Option<(&OpTy<'tcx>, &OpTy<'tcx>)>, // Location where the output scalar is written to. dest: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { @@ -583,6 +614,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.read_scalar(length)?.to_uint(size_layout.size)?.try_into().unwrap(); let mut flags = this.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)?)), + 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); @@ -645,13 +682,29 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this, callback!( @capture<'tcx> { + dest_addr: Option<(Pointer, MPlaceTy<'tcx>)>, dest: MPlaceTy<'tcx>, - } |this, result: Result| { - match result { - Ok(bytes_sent) => - this.write_scalar(Scalar::from_target_usize(bytes_sent.try_into().unwrap(), this), &dest), - Err(e) => this.set_errno_and_return_neg1(e, &dest) + } |ecx, result: Result<(usize, Option), IoError>| { + let (bytes_received, mut origin_addr_opt) = match result { + Ok(data) => data, + Err(e) => return ecx.set_errno_and_return_neg1(e, &dest) + }; + + if let Some((addr_ptr, addr_len_mplace)) = dest_addr { + if addr_ptr == Pointer::null() { + // When the `addr_ptr` is a null pointer the caller is not interested in + // the socket address. + origin_addr_opt = None; + } + // The recvfrom(3) man page specifies that "[...] the value stored in the object pointed to + // `address` is unspecified [...]" should the protocol not provide the source address of the message. + // In this case we do the same thing as the Linux implementation and simply don't write anything to the + // `addr_ptr` pointer and zero the `addr_len_mplace` place. + ecx.write_socket_address(origin_addr_opt.as_ref(), addr_ptr, &addr_len_mplace)?; } + + ecx.write_scalar(Scalar::from_target_usize(bytes_received.try_into().unwrap(), ecx), &dest) + } ), ) @@ -778,7 +831,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let socket = this.read_scalar(socket)?.to_i32()?; let address_ptr = this.read_pointer(address)?; - let address_len_ptr = this.read_pointer(address_len)?; + let address_len_place = this.deref_pointer(address_len)?; // Get the file handle let Some(fd) = this.machine.fds.get(socket) else { @@ -794,8 +847,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { Err(e) => return this.set_errno_and_return_neg1_i32(e), }; - this.write_socket_address(&address, address_ptr, address_len_ptr, "getsockname") - .map(|_| Scalar::from_i32(0)) + this.write_socket_address(Some(&address), address_ptr, &address_len_place) + .map(|()| Scalar::from_i32(0)) } fn getpeername( @@ -810,7 +863,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let socket = this.read_scalar(socket)?.to_i32()?; let address_ptr = this.read_pointer(address)?; - let address_len_ptr = this.read_pointer(address_len)?; + let address_len_place = this.deref_pointer(address_len)?; // Get the file handle let Some(fd) = this.machine.fds.get(socket) else { @@ -829,21 +882,20 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { callback!( @capture<'tcx> { address_ptr: Pointer, - address_len_ptr: Pointer, + address_len_place: MPlaceTy<'tcx>, dest: MPlaceTy<'tcx>, - } |this, result: Result| { + } |ecx, result: Result| { let address = match result { 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) }; - this.write_socket_address( - &address, + ecx.write_socket_address( + Some(&address), address_ptr, - address_len_ptr, - "getpeername", + &address_len_place, )?; - this.write_scalar(Scalar::from_i32(0), &dest) + ecx.write_scalar(Scalar::from_i32(0), &dest) } ), ) diff --git a/src/tools/miri/src/shims/unix/socket_address.rs b/src/tools/miri/src/shims/unix/socket_address.rs index 841eabb3fe52b..64ec52e2e52aa 100644 --- a/src/tools/miri/src/shims/unix/socket_address.rs +++ b/src/tools/miri/src/shims/unix/socket_address.rs @@ -1,8 +1,7 @@ -use std::iter; use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}; use rustc_abi::Size; -use rustc_target::spec::Env; +use rustc_target::spec::{Env, Os}; use crate::*; @@ -134,14 +133,20 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ) -> InterpResult<'tcx, Result> { let this = self.eval_context_ref(); - let socklen_layout = this.libc_ty_layout("socklen_t"); // 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 address_len: u64 = - this.read_scalar(address_len)?.to_int(socklen_layout.size)?.try_into().unwrap(); + this.read_scalar(address_len)?.to_int(address_len.layout.size)?.try_into().unwrap(); + let address = this.deref_pointer(address)?; + + // Ensure the pointer is actually dereferenceable for that length. + this.check_ptr_access( + address.ptr(), + Size::from_bytes(address_len), + CheckInAllocMsg::MemoryAccess, + )?; // Initially, treat address as generic sockaddr just to extract the family field. - let address = this.deref_pointer(address)?; if address_len < address.layout.size.bytes() { // Address length should be at least as big as the generic sockaddr return interp_ok(Err(LibcError("EINVAL"))); @@ -178,6 +183,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { .unwrap(); let addr_bits = u32::from_be_bytes(addr_bytes); + // We entirely ignore the sin_zero field as it disappeared from modern POSIX. + // 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"); @@ -216,6 +224,8 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // and not in network byte order. let scope_id = this.read_scalar(&scope_id_field)?.to_u32()?; + // We ignore the `sin6_len` field as it isn't respected by any of the supported targets. + SocketAddr::V6(SocketAddrV6::new( Ipv6Addr::from_bits(addr_bits), port, @@ -241,35 +251,52 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { /// on output it points to the non-truncated size of the written address in the /// buffer pointed to by `address_ptr`. /// + /// If `address` is [`None`] we write an "empty" address (i.e., the `address_len_ptr` + /// is set to zero and the `address_ptr` is left untouched). + /// If `address` is `Some`, both output pointers must be valid! + /// /// If the address buffer doesn't fit the whole address, the address is truncated to not /// overflow the buffer. fn write_socket_address( &mut self, - address: &SocketAddr, + address: Option<&SocketAddr>, address_ptr: Pointer, - address_len_ptr: Pointer, - foreign_name: &'static str, + address_len_place: &MPlaceTy<'tcx>, ) -> InterpResult<'tcx> { let this = self.eval_context_mut(); - if address_ptr == Pointer::null() || address_len_ptr == Pointer::null() { - // The POSIX man page doesn't account for the cases where the `address_ptr` or - // `address_len_ptr` could be null pointers. Thus, this behavior is undefined! - throw_ub_format!( - "{foreign_name}: writing a socket address but the address or the length pointer is a null pointer" - ) + if address.is_none() && this.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(()); } - let socklen_layout = this.libc_ty_layout("socklen_t"); - let address_buffer_len_place = this.ptr_to_mplace(address_len_ptr, socklen_layout); + // If the len ptr is not null or if we have an address to write, the length must be valid. + // This is intended to implement what POSIX says about the length pointer in `recvfrom``: + // > Either a null pointer, if address is a null pointer, or a pointer to a socklen_t object + // > which on input specifies the length of the supplied sockaddr structure, and on output + // > specifies the length of the sending address. + // We only support buffer lengths which can be stored in a u64 since the // size of a layout in bytes is also stored in a u64. let address_buffer_len: u64 = this - .read_scalar(&address_buffer_len_place)? - .to_int(socklen_layout.size)? + .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( + address_ptr, + Size::from_bytes(address_buffer_len), + CheckInAllocMsg::MemoryAccess, + )?; + + 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); + }; + let address_buffer = match address { SocketAddr::V4(address) => { // IPv4 address bytes; already stored in network byte order. @@ -282,12 +309,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // 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)?; - // Zero the whole buffer as some libc targets have additional fields which we fill - // with zero bytes (just like the standard library does it). - this.write_bytes_ptr( - address_buffer.ptr(), - iter::repeat_n(0, address_buffer.layout.size.bytes_usize()), - )?; let sin_family_field = this.project_field_named(&address_buffer, "sin_family")?; // We cannot simply write the `AF_INET` scalar into the `sin_family_field` because on most @@ -308,6 +329,21 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let s_addr_field = this.project_field_named(&sin_addr_field, "s_addr")?; this.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)?; + } + + // 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)?; + } + address_buffer } SocketAddr::V6(address) => { @@ -325,12 +361,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // 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)?; - // Zero the whole buffer as some libc targets have additional fields which we fill - // with zero bytes (just like the standard library does it). - this.write_bytes_ptr( - address_buffer.ptr(), - iter::repeat_n(0, address_buffer.layout.size.bytes_usize()), - )?; let sin6_family_field = this.project_field_named(&address_buffer, "sin6_family")?; // We cannot simply write the `AF_INET6` scalar into the `sin6_family_field` because on most @@ -361,6 +391,16 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let s6_addr_field = this.project_field_named(&sin6_addr_field, "s6_addr")?; this.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) { + 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)?; + } + address_buffer } }; @@ -378,13 +418,9 @@ 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)?; - // Size of the non-truncated address. - let address_len = address_buffer.layout.size.bytes(); - this.write_scalar( - Scalar::from_uint(address_len, socklen_layout.size), - &address_buffer_len_place, - )?; + // Store size of the non-truncated address. + this.write_int(address_buffer.layout.size.bytes(), address_len_place)?; interp_ok(()) } @@ -445,17 +481,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { this.write_int(sockaddr_layout.size.bytes(), &addrlen_mplace)?; let sockaddr_mplace = this.allocate(sockaddr_layout, MiriMemoryKind::Machine.into())?; - // Zero the newly allocated socket address struct. - this.write_bytes_ptr( - sockaddr_mplace.ptr(), - iter::repeat_n(0, sockaddr_mplace.layout.size.bytes_usize()), - )?; - this.write_socket_address( - &address, - sockaddr_mplace.ptr(), - addrlen_mplace.ptr(), - "getaddrinfo", - )?; + this.write_socket_address(Some(&address), sockaddr_mplace.ptr(), &addrlen_mplace)?; this.write_pointer(sockaddr_mplace.ptr(), &addr_mplace)?; let canonname_mplace = this.project_field_named(&addrinfo_mplace, "ai_canonname")?; 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 fc5a0b055fbd5..3628ec259af69 100644 --- a/src/tools/miri/src/shims/unix/solarish/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/solarish/foreign_items.rs @@ -132,6 +132,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; this.connect(socket, address, address_len, dest)?; } + "__xnet_sendto" => { + let [socket, buffer, length, flags, dest_addr, dest_addr_len] = &this.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)?; + } "__xnet_getaddrinfo" => { let [node, service, hints, res] = &this.check_shim_sig( shim_sig!(extern "C" fn(*_, *_, *_, **_) -> i32), @@ -177,7 +184,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { &stack, )?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "pset_info" => { @@ -210,7 +217,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let cpus = this.deref_pointer(cpus)?; this.write_scalar(Scalar::from_u32(this.machine.num_cpus), &cpus)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } "__sysconf_xpg7" => { diff --git a/src/tools/miri/src/shims/unix/sync.rs b/src/tools/miri/src/shims/unix/sync.rs index 7ad362c3efa7a..7579d358158e3 100644 --- a/src/tools/miri/src/shims/unix/sync.rs +++ b/src/tools/miri/src/shims/unix/sync.rs @@ -588,7 +588,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ); } else { this.rwlock_reader_lock(&rwlock.rwlock_ref)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } interp_ok(()) @@ -636,7 +636,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ); } else { this.rwlock_writer_lock(&rwlock.rwlock_ref)?; - this.write_null(dest)?; + this.write_int(0, dest)?; } interp_ok(()) @@ -873,7 +873,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { sem_create(this, sem_op, value)?; - this.write_null(dest)?; // we always succeed + this.write_int(0, dest)?; // we always succeed interp_ok(()) } @@ -893,9 +893,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { @capture<'tcx> { dest: MPlaceTy<'tcx>, } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { assert_eq!(unblock, UnblockKind::Ready); - this.write_null(&dest)?; + ecx.write_int(0,&dest)?; interp_ok(()) } ), @@ -929,12 +929,12 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { @capture<'tcx> { dest: MPlaceTy<'tcx>, } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { match unblock { UnblockKind::Ready => - this.write_null(&dest), + ecx.write_int(0,&dest), UnblockKind::TimedOut => - this.set_errno_and_return_neg1(LibcError("ETIMEDOUT"), &dest), + ecx.set_errno_and_return_neg1(LibcError("ETIMEDOUT"), &dest), } } ), @@ -953,7 +953,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let data = sem_get_data(this, sem_op)?.clone(); this.semaphore_increment(&data.sem_ref)?; - this.write_null(dest)?; // we always succeed + this.write_int(0, dest)?; // we always succeed interp_ok(()) } @@ -974,7 +974,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let sem_place = this.deref_pointer(sem_op)?; this.write_uninit(&sem_place)?; - this.write_null(dest)?; // we always succeed + this.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 07f7ac7d7f8d4..69d88f077febd 100644 --- a/src/tools/miri/src/shims/unix/tcp_socket.rs +++ b/src/tools/miri/src/shims/unix/tcp_socket.rs @@ -170,7 +170,13 @@ impl FileDescription for TcpSocket { /* is_peek */ false, /* is_non_block */ false, ecx, - finish, + callback!( + @capture<'tcx> { + finish: DynMachineCallback<'tcx, Result>, + } |this, result: Result<(usize, Option), IoError>| { + finish.call(this, result.map(|(bytes, _)| bytes)) + } + ), ) } @@ -182,7 +188,15 @@ impl FileDescription for TcpSocket { ecx: &mut MiriInterpCx<'tcx>, finish: DynMachineCallback<'tcx, Result>, ) -> InterpResult<'tcx> { - self.send(communicate_allowed, ptr, len, /* is_non_block */ false, ecx, finish) + self.send( + communicate_allowed, + ptr, + len, + /* is_non_block */ false, + /* dest_addr */ None, + ecx, + finish, + ) } fn short_fd_operations(&self) -> bool { @@ -563,15 +577,15 @@ impl UnixSocketFileDescription for TcpSocket { @capture<'tcx> { socket: FileDescriptionRef, finish: DynMachineCallback<'tcx, Result<(), IoError>>, - } |this, result: Result<(), ()>| { + } |ecx, result: Result<(), ()>| { if result.is_err() { // An error occurred whilst connecting. We know // that it has been consumed by `ensure_connected` // and is now stored in `socket.error`. let err = socket.error.take().unwrap(); - finish.call(this, Err(IoError::HostError(err))) + finish.call(ecx, Err(IoError::HostError(err))) } else { - finish.call(this, Ok(())) + finish.call(ecx, Ok(())) } } ), @@ -585,6 +599,9 @@ impl UnixSocketFileDescription for TcpSocket { ptr: Pointer, len: usize, is_non_block: bool, + // For stream-based sockets `send` and `sendto` are equivalent and + // we can thus ignore the destination address. + _dest_addr: Option, ecx: &mut MiriInterpCx<'tcx>, finish: DynMachineCallback<'tcx, Result>, ) -> InterpResult<'tcx> { @@ -606,20 +623,20 @@ impl UnixSocketFileDescription for TcpSocket { len: usize, is_non_block: bool, finish: DynMachineCallback<'tcx, Result>, - } |this, result: Result<(), ()>| { + } |ecx, result: Result<(), ()>| { if result.is_err() { - return finish.call(this, Err(LibcError("ENOTCONN"))) + return finish.call(ecx, Err(LibcError("ENOTCONN"))) } 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 = this.try_non_block_send(&socket, ptr, len)?; - finish.call(this, result) + let result = ecx.try_non_block_send(&socket, ptr, len)?; + finish.call(ecx, result) } else { // 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. - this.block_for_send(socket, deadline, ptr, len, finish) + ecx.block_for_send(socket, deadline, ptr, len, finish) } } ), @@ -634,13 +651,21 @@ impl UnixSocketFileDescription for TcpSocket { is_peek: bool, is_non_block: bool, ecx: &mut MiriInterpCx<'tcx>, - finish: DynMachineCallback<'tcx, Result>, + finish: DynMachineCallback<'tcx, Result<(usize, Option), IoError>>, ) -> InterpResult<'tcx> { 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<(usize, 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 socket = self; ecx.ensure_connected( socket.clone(), @@ -655,20 +680,20 @@ impl UnixSocketFileDescription for TcpSocket { is_peek: bool, is_non_block: bool, finish: DynMachineCallback<'tcx, Result>, - } |this, result: Result<(), ()>| { + } |ecx, result: Result<(), ()>| { if result.is_err() { - return finish.call(this, Err(LibcError("ENOTCONN"))) + return finish.call(ecx, Err(LibcError("ENOTCONN"))) } 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 = this.try_non_block_recv(&socket, ptr, len, is_peek)?; - finish.call(this, result) + let result = ecx.try_non_block_recv(&socket, ptr, len, is_peek)?; + finish.call(ecx, result) } 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. - this.block_for_recv(socket, deadline, ptr, len, is_peek, finish) + ecx.block_for_recv(socket, deadline, ptr, len, is_peek, finish) } } ), @@ -796,9 +821,9 @@ impl UnixSocketFileDescription for TcpSocket { @capture<'tcx> { socket: FileDescriptionRef, finish: DynMachineCallback<'tcx, Result>, - } |this, result: Result<(), ()>| { + } |ecx, result: Result<(), ()>| { if result.is_err() { - return finish.call(this, Err(LibcError("ENOTCONN"))) + return finish.call(ecx, Err(LibcError("ENOTCONN"))) }; let SocketState::Connected(stream) = &*socket.state.borrow() else { @@ -806,7 +831,7 @@ impl UnixSocketFileDescription for TcpSocket { }; let result = stream.peer_addr().map_err(IoError::HostError); - finish.call(this, result) + finish.call(ecx, result) } ), ) @@ -961,23 +986,23 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { socket: FileDescriptionRef, is_client_sock_nonblock: bool, finish: DynMachineCallback<'tcx, Result<(FdNum, SocketAddr), IoError>>, - } |this, kind: UnblockKind| { + } |ecx, kind: UnblockKind| { // Remove the blocking I/O interest for unblocking this thread. - this.machine.blocking_io.remove_blocked_thread(socket.id(), this.machine.threads.active_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(this, Err(LibcError("EWOULDBLOCK"))) + UnblockKind::TimedOut => return finish.call(ecx, Err(LibcError("EWOULDBLOCK"))) } - match this.try_non_block_accept(&socket, is_client_sock_nonblock)? { - Ok((sockfd, addr)) => finish.call(this, Ok((sockfd, addr))), + match ecx.try_non_block_accept(&socket, is_client_sock_nonblock)? { + Ok((sockfd, addr)) => finish.call(ecx, Ok((sockfd, addr))), Err(IoError::HostError(e)) if e.kind() == io::ErrorKind::WouldBlock => { // We need to block the thread again as it would still block. - this.block_for_accept(socket, is_client_sock_nonblock, finish) + ecx.block_for_accept(socket, is_client_sock_nonblock, finish) } - Err(e) => finish.call(this, Err(e)), + Err(e) => finish.call(ecx, Err(e)), } }), ) @@ -1070,22 +1095,22 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { buffer_ptr: Pointer, length: usize, finish: DynMachineCallback<'tcx, Result>, - } |this, kind: UnblockKind| { + } |ecx, kind: UnblockKind| { // Remove the blocking I/O interest for unblocking this thread. - this.machine.blocking_io.remove_blocked_thread(socket.id(), this.machine.threads.active_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(this, Err(LibcError("EWOULDBLOCK"))) + UnblockKind::TimedOut => return finish.call(ecx, Err(LibcError("EWOULDBLOCK"))) } - match this.try_non_block_send(&socket, buffer_ptr, length)? { + match ecx.try_non_block_send(&socket, buffer_ptr, length)? { Err(IoError::HostError(e)) if e.kind() == io::ErrorKind::WouldBlock => { // We need to block the thread again as it would still block. - this.block_for_send(socket, deadline, buffer_ptr, length, finish) + ecx.block_for_send(socket, deadline, buffer_ptr, length, finish) }, - result => finish.call(this, result) + result => finish.call(ecx, result) } }), ) @@ -1204,22 +1229,22 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { length: usize, should_peek: bool, finish: DynMachineCallback<'tcx, Result>, - } |this, kind: UnblockKind| { + } |ecx, kind: UnblockKind| { // Remove the blocking I/O interest for unblocking this thread. - this.machine.blocking_io.remove_blocked_thread(socket.id(), this.machine.threads.active_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(this, Err(LibcError("EWOULDBLOCK"))) + UnblockKind::TimedOut => return finish.call(ecx, Err(LibcError("EWOULDBLOCK"))) } - match this.try_non_block_recv(&socket, buffer_ptr, length, should_peek)? { + 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. - this.block_for_recv(socket, deadline, buffer_ptr, length, should_peek, finish) + ecx.block_for_recv(socket, deadline, buffer_ptr, length, should_peek, finish) }, - result => finish.call(this, result) + result => finish.call(ecx, result) } }), ) @@ -1367,13 +1392,13 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { socket: FileDescriptionRef, foreign_name: &'static str, action: DynMachineCallback<'tcx, Result<(), ()>>, - } |this, kind: UnblockKind| { + } |ecx, kind: UnblockKind| { // Remove the blocking I/O interest for unblocking this thread. - this.machine.blocking_io.remove_blocked_thread(socket.id(), this.machine.threads.active_thread()); + ecx.machine.blocking_io.remove_blocked_thread(socket.id(), ecx.machine.threads.active_thread()); if UnblockKind::TimedOut == kind { // This then means that the socket is not yet connected. - return action.call(this, Err(())) + return action.call(ecx, Err(())) } // The thread woke up because it's ready, indicating a writeable or error event. @@ -1385,7 +1410,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { drop(state); // This can happen because we blocked the thread: // maybe another thread "upgraded" the connection in the meantime. - return action.call(this, Ok(())) + return action.call(ecx, Ok(())) }, _ => { drop(state); @@ -1393,20 +1418,20 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Since this thread just got rescheduled, it could be that another // thread realized that the connection failed and we're thus in // an "invalid 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(())) } }; drop(state); // Set `socket.error` if `socket` currently has an error. - this.update_last_error(&socket); + ecx.update_last_error(&socket); if socket.error.borrow().is_some() { // There was an error during connecting. // It's the program's responsibility to read SO_ERROR itself. - return action.call(this, Err(())) + return action.call(ecx, Err(())) } // There was no error during connecting. Mio advises also reading the peer address @@ -1435,7 +1460,7 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { *state = SocketState::Connected(stream); drop(state); - action.call(this, Ok(())) + action.call(ecx, Ok(())) } ), ) diff --git a/src/tools/miri/src/shims/unix/virtual_socket.rs b/src/tools/miri/src/shims/unix/virtual_socket.rs index e712bb35aa206..60f3eb88d664f 100644 --- a/src/tools/miri/src/shims/unix/virtual_socket.rs +++ b/src/tools/miri/src/shims/unix/virtual_socket.rs @@ -5,6 +5,7 @@ use std::cell::{Cell, OnceCell, RefCell}; use std::collections::VecDeque; use std::io::{self, ErrorKind, Read}; +use std::net::SocketAddr; use std::rc::Rc; use rustc_target::spec::Os; @@ -273,6 +274,9 @@ impl UnixSocketFileDescription for VirtualSocket { ptr: Pointer, len: usize, is_non_block: bool, + // For stream-based sockets `send` and `sendto` are equivalent and + // we can thus ignore the destination address. + _dest_addr: Option, ecx: &mut MiriInterpCx<'tcx>, finish: DynMachineCallback<'tcx, Result>, ) -> InterpResult<'tcx> { @@ -287,12 +291,20 @@ impl UnixSocketFileDescription for VirtualSocket { is_peek: bool, is_non_block: bool, ecx: &mut MiriInterpCx<'tcx>, - finish: DynMachineCallback<'tcx, Result>, + finish: DynMachineCallback<'tcx, Result<(usize, Option), IoError>>, ) -> InterpResult<'tcx> { if is_peek { throw_unsup_format!("socketpair: virtual sockets don't support peeking") } + let finish = callback!( + @capture<'tcx> { + finish: DynMachineCallback<'tcx, Result<(usize, 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))) + } + ); ecx.virtual_socket_read(self, ptr, len, is_non_block, finish) } } @@ -352,9 +364,9 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { is_non_block: bool, finish: DynMachineCallback<'tcx, Result>, } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { assert_eq!(unblock, UnblockKind::Ready); - this.virtual_socket_write(socket, ptr, len, is_non_block, finish) + ecx.virtual_socket_write(socket, ptr, len, is_non_block, finish) } ), ); @@ -443,9 +455,9 @@ trait EvalContextPrivExt<'tcx>: crate::MiriInterpCxExt<'tcx> { is_non_block: bool, finish: DynMachineCallback<'tcx, Result>, } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { assert_eq!(unblock, UnblockKind::Ready); - this.virtual_socket_read(socket, ptr, len, is_non_block, finish) + ecx.virtual_socket_read(socket, ptr, len, is_non_block, finish) } ), ); diff --git a/src/tools/miri/src/shims/unwind.rs b/src/tools/miri/src/shims/unwind.rs index 820a78725eedc..dcb2ae74b8cb5 100644 --- a/src/tools/miri/src/shims/unwind.rs +++ b/src/tools/miri/src/shims/unwind.rs @@ -98,7 +98,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; // We ourselves will return `0`, eventually (will be overwritten if we catch a panic). - this.write_null(&dest)?; + this.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 diff --git a/src/tools/miri/src/shims/windows/foreign_items.rs b/src/tools/miri/src/shims/windows/foreign_items.rs index 6e72668c48575..efaf79af02e88 100644 --- a/src/tools/miri/src/shims/windows/foreign_items.rs +++ b/src/tools/miri/src/shims/windows/foreign_items.rs @@ -519,7 +519,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { if !ecx.ptr_is_null(ptr)? { ecx.deallocate_ptr(ptr, None, MiriMemoryKind::WinLocal.into())?; } - ecx.write_null(dest)?; + ecx.write_int(0, dest)?; } // errno @@ -768,7 +768,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // Unimplemented. Always return failure. let not_supported = ecx.eval_windows("c", "ERROR_NOT_SUPPORTED"); ecx.set_last_error(not_supported)?; - ecx.write_null(dest)?; + ecx.write_int(0, dest)?; } // Synchronization primitives @@ -833,7 +833,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { let ptr = ecx.fn_ptr(FnVal::Other(DynSym::from_str(name))); ecx.write_pointer(ptr, dest)?; } else { - ecx.write_null(dest)?; + ecx.write_int(0, dest)?; } } @@ -1026,7 +1026,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { } } ecx.gen_random(ptr, len.into())?; - ecx.write_null(dest)?; // STATUS_SUCCESS + ecx.write_int(0, dest)?; // STATUS_SUCCESS } "GetConsoleScreenBufferInfo" => { // FIXME: This does not have a direct test (#3179). @@ -1039,7 +1039,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ecx.read_pointer(buffer_info)?; // Indicate an error. ecx.set_last_error(io::ErrorKind::Unsupported)?; - ecx.write_null(dest)?; + ecx.write_int(0, dest)?; } "GetStdHandle" => { // FIXME: This does not have a direct test (#3179). @@ -1220,7 +1220,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { (link_name, abi, args), )?; // Pretend these does not exist / nothing happened, by returning zero. - ecx.write_null(dest)?; + ecx.write_int(0, dest)?; } "AddVectoredExceptionHandler" if ecx.frame_in_std() => { let [_first, _handler] = &ecx.check_shim_sig( @@ -1248,7 +1248,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { ecx.yield_active_thread(); // FIXME: this should return a nonzero value if this call does result in switching to another thread. - ecx.write_null(dest)?; + ecx.write_int(0, dest)?; } "GetFinalPathNameByHandleW" if ecx.frame_in_std() => { // Std uses this when debug-printing `File`. We stub it out by returning an error. @@ -1258,7 +1258,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { )?; ecx.set_last_error(IoError::WindowsError("ERROR_NOT_SUPPORTED"))?; - ecx.write_null(dest)?; + ecx.write_int(0, dest)?; } _ => return interp_ok(EmulateItemResult::NotSupported), diff --git a/src/tools/miri/src/shims/windows/fs.rs b/src/tools/miri/src/shims/windows/fs.rs index 709d6cec6d330..fcc93a4e7e36b 100644 --- a/src/tools/miri/src/shims/windows/fs.rs +++ b/src/tools/miri/src/shims/windows/fs.rs @@ -226,6 +226,7 @@ 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 @@ -248,6 +249,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // https://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.create_new if !desired_write { options.append(true); + append = true; } } OpenExisting => { @@ -319,6 +321,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { file, writable: desired_write, readable: desired_read, + append, }) else { throw_unsup_format!("we ran out of FD numbers") }; @@ -646,20 +649,20 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { io_status_info: MPlaceTy<'tcx>, dest: MPlaceTy<'tcx>, } - |this, result: Result| { + |ecx, result: Result| { match result { Ok(read_size) => { assert!(read_size <= count.try_into().unwrap()); // This must fit since `count` fits. - this.write_int(u64::try_from(read_size).unwrap(), &io_status_info)?; - this.write_int(0, &io_status)?; - this.write_int(0, &dest) + ecx.write_int(u64::try_from(read_size).unwrap(), &io_status_info)?; + ecx.write_int(0, &io_status)?; + ecx.write_int(0, &dest) } Err(e) => { - this.write_int(0, &io_status_info)?; + ecx.write_int(0, &io_status_info)?; let status = e.into_ntstatus(); - this.write_int(status, &io_status)?; - this.write_int(status, &dest) + ecx.write_int(status, &io_status)?; + ecx.write_int(status, &dest) } }} ) @@ -746,20 +749,20 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { io_status_info: MPlaceTy<'tcx>, dest: MPlaceTy<'tcx>, } - |this, result: Result| { + |ecx, result: Result| { match result { Ok(read_size) => { assert!(read_size <= count.try_into().unwrap()); // This must fit since `count` fits. - this.write_int(u64::try_from(read_size).unwrap(), &io_status_info)?; - this.write_int(0, &io_status)?; - this.write_int(0, &dest) + ecx.write_int(u64::try_from(read_size).unwrap(), &io_status_info)?; + ecx.write_int(0, &io_status)?; + ecx.write_int(0, &dest) } Err(e) => { - this.write_int(0, &io_status_info)?; + ecx.write_int(0, &io_status_info)?; let status = e.into_ntstatus(); - this.write_int(status, &io_status)?; - this.write_int(status, &dest) + 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 8d7efc0d2113d..55addb2468df8 100644 --- a/src/tools/miri/src/shims/windows/sync.rs +++ b/src/tools/miri/src/shims/windows/sync.rs @@ -134,9 +134,9 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { pending_place: MPlaceTy<'tcx>, dest: MPlaceTy<'tcx>, } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { assert_eq!(unblock, UnblockKind::Ready); - let ret = this.init_once_try_begin(&init_once, &pending_place, &dest)?; + let ret = ecx.init_once_try_begin(&init_once, &pending_place, &dest)?; assert!(ret, "we were woken up but init_once_try_begin still failed"); interp_ok(()) } @@ -242,14 +242,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { @capture<'tcx> { dest: MPlaceTy<'tcx> } - |this, unblock: UnblockKind| { + |ecx, unblock: UnblockKind| { match unblock { UnblockKind::Ready => { - this.write_int(1, &dest) + ecx.write_int(1, &dest) } UnblockKind::TimedOut => { - this.set_last_error(IoError::WindowsError("ERROR_TIMEOUT"))?; - this.write_int(0, &dest) + ecx.set_last_error(IoError::WindowsError("ERROR_TIMEOUT"))?; + ecx.write_int(0, &dest) } } } diff --git a/src/tools/miri/tests/fail/extern-type-field-offset.stderr b/src/tools/miri/tests/fail/extern-type-field-offset.stderr index 187f14faf408b..2452454a91869 100644 --- a/src/tools/miri/tests/fail/extern-type-field-offset.stderr +++ b/src/tools/miri/tests/fail/extern-type-field-offset.stderr @@ -6,6 +6,7 @@ LL | let x: &Newtype = unsafe { &*(&buf as *const _ as *const Newtype) }; | = help: `extern type` are not compatible with the Stacked Borrows aliasing model implemented by Miri; Miri may miss bugs in this code = help: try running with `MIRIFLAGS=-Zmiri-tree-borrows` to use the more permissive but also even more experimental Tree Borrows aliasing checks instead + = note: this warning is only shown once per program execution error: unsupported operation: `extern type` field does not have a known offset --> tests/fail/extern-type-field-offset.rs:LL:CC diff --git a/src/tools/miri/tests/native-lib/fail/call_fn_ptr.notrace.stderr b/src/tools/miri/tests/native-lib/fail/call_fn_ptr.notrace.stderr index 5e7764652fa74..877b232c4cf6f 100644 --- a/src/tools/miri/tests/native-lib/fail/call_fn_ptr.notrace.stderr +++ b/src/tools/miri/tests/native-lib/fail/call_fn_ptr.notrace.stderr @@ -8,6 +8,7 @@ LL | call_fn_ptr(Some(nop)); = help: in particular, Miri assumes that the native call initializes all memory it has access to = help: Miri also assumes that any part of this memory may be a pointer that is permitted to point to arbitrary exposed memory = help: what this means is that Miri will easily miss Undefined Behavior related to incorrect usage of this shared memory, so you should not take a clean Miri run as a signal that your FFI code is UB-free + = note: this warning is only shown once per program execution = note: stack backtrace: 0: pass_fn_ptr at tests/native-lib/fail/call_fn_ptr.rs:LL:CC diff --git a/src/tools/miri/tests/native-lib/fail/call_fn_ptr.trace.stderr b/src/tools/miri/tests/native-lib/fail/call_fn_ptr.trace.stderr index 7418b08ebe110..70767f5590258 100644 --- a/src/tools/miri/tests/native-lib/fail/call_fn_ptr.trace.stderr +++ b/src/tools/miri/tests/native-lib/fail/call_fn_ptr.trace.stderr @@ -9,6 +9,7 @@ LL | call_fn_ptr(Some(nop)); = help: Miri also assumes that any part of this memory may be a pointer that is permitted to point to arbitrary exposed memory = help: what this means is that Miri will easily miss Undefined Behavior related to incorrect usage of this shared memory, so you should not take a clean Miri run as a signal that your FFI code is UB-free = help: tracing memory accesses in native code is not yet fully implemented, so there can be further imprecisions beyond what is documented here + = note: this warning is only shown once per program execution = note: stack backtrace: 0: pass_fn_ptr at tests/native-lib/fail/call_fn_ptr.rs:LL:CC diff --git a/src/tools/miri/tests/native-lib/fail/call_fn_ptr_with_generic.notrace.stderr b/src/tools/miri/tests/native-lib/fail/call_fn_ptr_with_generic.notrace.stderr index e0536a4afe583..3b0d7adc3bcb4 100644 --- a/src/tools/miri/tests/native-lib/fail/call_fn_ptr_with_generic.notrace.stderr +++ b/src/tools/miri/tests/native-lib/fail/call_fn_ptr_with_generic.notrace.stderr @@ -8,6 +8,7 @@ LL | call_fn_ptr(id::); = help: in particular, Miri assumes that the native call initializes all memory it has access to = help: Miri also assumes that any part of this memory may be a pointer that is permitted to point to arbitrary exposed memory = help: what this means is that Miri will easily miss Undefined Behavior related to incorrect usage of this shared memory, so you should not take a clean Miri run as a signal that your FFI code is UB-free + = note: this warning is only shown once per program execution = note: stack backtrace: 0: pass_fn_ptr at tests/native-lib/fail/call_fn_ptr_with_generic.rs:LL:CC diff --git a/src/tools/miri/tests/native-lib/fail/call_fn_ptr_with_generic.trace.stderr b/src/tools/miri/tests/native-lib/fail/call_fn_ptr_with_generic.trace.stderr index 24a33e6458685..021a563406e75 100644 --- a/src/tools/miri/tests/native-lib/fail/call_fn_ptr_with_generic.trace.stderr +++ b/src/tools/miri/tests/native-lib/fail/call_fn_ptr_with_generic.trace.stderr @@ -9,6 +9,7 @@ LL | call_fn_ptr(id::); = help: Miri also assumes that any part of this memory may be a pointer that is permitted to point to arbitrary exposed memory = help: what this means is that Miri will easily miss Undefined Behavior related to incorrect usage of this shared memory, so you should not take a clean Miri run as a signal that your FFI code is UB-free = help: tracing memory accesses in native code is not yet fully implemented, so there can be further imprecisions beyond what is documented here + = note: this warning is only shown once per program execution = note: stack backtrace: 0: pass_fn_ptr at tests/native-lib/fail/call_fn_ptr_with_generic.rs:LL:CC diff --git a/src/tools/miri/tests/native-lib/fail/call_fn_ptr_with_unsupported.notrace.stderr b/src/tools/miri/tests/native-lib/fail/call_fn_ptr_with_unsupported.notrace.stderr index a3e98a162ea25..37e22833efb80 100644 --- a/src/tools/miri/tests/native-lib/fail/call_fn_ptr_with_unsupported.notrace.stderr +++ b/src/tools/miri/tests/native-lib/fail/call_fn_ptr_with_unsupported.notrace.stderr @@ -8,6 +8,7 @@ LL | call_fn_ptr(std::mem::transmute(f)); = help: in particular, Miri assumes that the native call initializes all memory it has access to = help: Miri also assumes that any part of this memory may be a pointer that is permitted to point to arbitrary exposed memory = help: what this means is that Miri will easily miss Undefined Behavior related to incorrect usage of this shared memory, so you should not take a clean Miri run as a signal that your FFI code is UB-free + = note: this warning is only shown once per program execution = note: stack backtrace: 0: pass_fn_ptr at tests/native-lib/fail/call_fn_ptr_with_unsupported.rs:LL:CC diff --git a/src/tools/miri/tests/native-lib/fail/call_fn_ptr_with_unsupported.trace.stderr b/src/tools/miri/tests/native-lib/fail/call_fn_ptr_with_unsupported.trace.stderr index 72448b2ab0ffb..bd415e22dac1f 100644 --- a/src/tools/miri/tests/native-lib/fail/call_fn_ptr_with_unsupported.trace.stderr +++ b/src/tools/miri/tests/native-lib/fail/call_fn_ptr_with_unsupported.trace.stderr @@ -9,6 +9,7 @@ LL | call_fn_ptr(std::mem::transmute(f)); = help: Miri also assumes that any part of this memory may be a pointer that is permitted to point to arbitrary exposed memory = help: what this means is that Miri will easily miss Undefined Behavior related to incorrect usage of this shared memory, so you should not take a clean Miri run as a signal that your FFI code is UB-free = help: tracing memory accesses in native code is not yet fully implemented, so there can be further imprecisions beyond what is documented here + = note: this warning is only shown once per program execution = note: stack backtrace: 0: pass_fn_ptr at tests/native-lib/fail/call_fn_ptr_with_unsupported.rs:LL:CC diff --git a/src/tools/miri/tests/native-lib/fail/pass_struct_expose_only_range.stderr b/src/tools/miri/tests/native-lib/fail/pass_struct_expose_only_range.stderr index 8ef41fce35e6a..e90ff2104c3ec 100644 --- a/src/tools/miri/tests/native-lib/fail/pass_struct_expose_only_range.stderr +++ b/src/tools/miri/tests/native-lib/fail/pass_struct_expose_only_range.stderr @@ -8,6 +8,7 @@ LL | let r = access_struct_ptr(structs[1]); = help: in particular, Miri assumes that the native call initializes all memory it has access to = help: Miri also assumes that any part of this memory may be a pointer that is permitted to point to arbitrary exposed memory = help: what this means is that Miri will easily miss Undefined Behavior related to incorrect usage of this shared memory, so you should not take a clean Miri run as a signal that your FFI code is UB-free + = note: this warning is only shown once per program execution error: Undefined Behavior: memory access failed: attempting to access 1 byte, but got $HEX[noalloc] which is a dangling pointer (it has no provenance) --> tests/native-lib/fail/pass_struct_expose_only_range.rs:LL:CC diff --git a/src/tools/miri/tests/native-lib/fail/tracing/partial_init.stderr b/src/tools/miri/tests/native-lib/fail/tracing/partial_init.stderr index 032461b6ed3f6..7e8a9dd5191b5 100644 --- a/src/tools/miri/tests/native-lib/fail/tracing/partial_init.stderr +++ b/src/tools/miri/tests/native-lib/fail/tracing/partial_init.stderr @@ -9,6 +9,7 @@ LL | init_n(2, slice_ptr); = help: Miri also assumes that any part of this memory may be a pointer that is permitted to point to arbitrary exposed memory = help: what this means is that Miri will easily miss Undefined Behavior related to incorrect usage of this shared memory, so you should not take a clean Miri run as a signal that your FFI code is UB-free = help: tracing memory accesses in native code is not yet fully implemented, so there can be further imprecisions beyond what is documented here + = note: this warning is only shown once per program execution = note: stack backtrace: 0: partial_init at tests/native-lib/fail/tracing/partial_init.rs:LL:CC diff --git a/src/tools/miri/tests/native-lib/fail/tracing/unexposed_reachable_alloc.stderr b/src/tools/miri/tests/native-lib/fail/tracing/unexposed_reachable_alloc.stderr index 773d2dd63c3e7..ab1923a51d3ec 100644 --- a/src/tools/miri/tests/native-lib/fail/tracing/unexposed_reachable_alloc.stderr +++ b/src/tools/miri/tests/native-lib/fail/tracing/unexposed_reachable_alloc.stderr @@ -9,6 +9,7 @@ LL | unsafe { do_one_deref(exposed) }; = help: Miri also assumes that any part of this memory may be a pointer that is permitted to point to arbitrary exposed memory = help: what this means is that Miri will easily miss Undefined Behavior related to incorrect usage of this shared memory, so you should not take a clean Miri run as a signal that your FFI code is UB-free = help: tracing memory accesses in native code is not yet fully implemented, so there can be further imprecisions beyond what is documented here + = note: this warning is only shown once per program execution = note: stack backtrace: 0: unexposed_reachable_alloc at tests/native-lib/fail/tracing/unexposed_reachable_alloc.rs:LL:CC diff --git a/src/tools/miri/tests/native-lib/pass/ptr_read_access.notrace.stderr b/src/tools/miri/tests/native-lib/pass/ptr_read_access.notrace.stderr index e1b6ce12fac90..312fc39f2dc62 100644 --- a/src/tools/miri/tests/native-lib/pass/ptr_read_access.notrace.stderr +++ b/src/tools/miri/tests/native-lib/pass/ptr_read_access.notrace.stderr @@ -8,6 +8,7 @@ LL | unsafe { print_pointer(&x) }; = help: in particular, Miri assumes that the native call initializes all memory it has access to = help: Miri also assumes that any part of this memory may be a pointer that is permitted to point to arbitrary exposed memory = help: what this means is that Miri will easily miss Undefined Behavior related to incorrect usage of this shared memory, so you should not take a clean Miri run as a signal that your FFI code is UB-free + = note: this warning is only shown once per program execution = note: stack backtrace: 0: test_access_pointer at tests/native-lib/pass/ptr_read_access.rs:LL:CC diff --git a/src/tools/miri/tests/native-lib/pass/ptr_read_access.trace.stderr b/src/tools/miri/tests/native-lib/pass/ptr_read_access.trace.stderr index 3295eda01fffc..2d21ba2725a47 100644 --- a/src/tools/miri/tests/native-lib/pass/ptr_read_access.trace.stderr +++ b/src/tools/miri/tests/native-lib/pass/ptr_read_access.trace.stderr @@ -9,6 +9,7 @@ LL | unsafe { print_pointer(&x) }; = help: Miri also assumes that any part of this memory may be a pointer that is permitted to point to arbitrary exposed memory = help: what this means is that Miri will easily miss Undefined Behavior related to incorrect usage of this shared memory, so you should not take a clean Miri run as a signal that your FFI code is UB-free = help: tracing memory accesses in native code is not yet fully implemented, so there can be further imprecisions beyond what is documented here + = note: this warning is only shown once per program execution = note: stack backtrace: 0: test_access_pointer at tests/native-lib/pass/ptr_read_access.rs:LL:CC diff --git a/src/tools/miri/tests/native-lib/pass/ptr_write_access.notrace.stderr b/src/tools/miri/tests/native-lib/pass/ptr_write_access.notrace.stderr index c86cf783f5d04..a0965bcd1128b 100644 --- a/src/tools/miri/tests/native-lib/pass/ptr_write_access.notrace.stderr +++ b/src/tools/miri/tests/native-lib/pass/ptr_write_access.notrace.stderr @@ -8,6 +8,7 @@ LL | unsafe { increment_int(&mut x) }; = help: in particular, Miri assumes that the native call initializes all memory it has access to = help: Miri also assumes that any part of this memory may be a pointer that is permitted to point to arbitrary exposed memory = help: what this means is that Miri will easily miss Undefined Behavior related to incorrect usage of this shared memory, so you should not take a clean Miri run as a signal that your FFI code is UB-free + = note: this warning is only shown once per program execution = note: stack backtrace: 0: test_increment_int at tests/native-lib/pass/ptr_write_access.rs:LL:CC diff --git a/src/tools/miri/tests/native-lib/pass/ptr_write_access.trace.stderr b/src/tools/miri/tests/native-lib/pass/ptr_write_access.trace.stderr index 1c62afa09c799..0501495991fd5 100644 --- a/src/tools/miri/tests/native-lib/pass/ptr_write_access.trace.stderr +++ b/src/tools/miri/tests/native-lib/pass/ptr_write_access.trace.stderr @@ -9,6 +9,7 @@ LL | unsafe { increment_int(&mut x) }; = help: Miri also assumes that any part of this memory may be a pointer that is permitted to point to arbitrary exposed memory = help: what this means is that Miri will easily miss Undefined Behavior related to incorrect usage of this shared memory, so you should not take a clean Miri run as a signal that your FFI code is UB-free = help: tracing memory accesses in native code is not yet fully implemented, so there can be further imprecisions beyond what is documented here + = note: this warning is only shown once per program execution = note: stack backtrace: 0: test_increment_int at tests/native-lib/pass/ptr_write_access.rs:LL:CC diff --git a/src/tools/miri/tests/pass-dep/libc/env.rs b/src/tools/miri/tests/pass-dep/libc/env.rs index 62ccd4b673e3b..0f4c4c3c2cc2b 100644 --- a/src/tools/miri/tests/pass-dep/libc/env.rs +++ b/src/tools/miri/tests/pass-dep/libc/env.rs @@ -1,7 +1,13 @@ //@ignore-target: windows # No libc //@compile-flags: -Zmiri-disable-isolation +#[path = "../../utils/libc.rs"] +mod libc_utils; + use std::ffi::CStr; +use std::os::unix::ffi::OsStrExt; + +use libc_utils::{errno, errno_check, errno_result}; fn test_getenv() { let s = unsafe { libc::getenv(c"MIRI_ENV_VAR_TEST".as_ptr()) }; @@ -83,8 +89,44 @@ fn test_unsetenv() { assert_eq!(result, -1); } +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]; + + let result = unsafe { libc::getcwd(buf.as_mut_ptr().cast(), buf.len()) }; + assert_eq!(result, buf.as_mut_ptr().cast()); + + let cstr = CStr::from_bytes_until_nul(&buf).unwrap(); + assert_eq!(cstr.to_bytes(), std::env::current_dir().unwrap().as_os_str().as_bytes()); + + let len = cstr.count_bytes(); + + // ERANGE: The pathname fits into the buffer, + // but there isn't enough space for the `\0` terminator + let result = unsafe { libc::getcwd(buf.as_mut_ptr().cast(), len) }; + assert!(result.is_null()); + assert_eq!(errno(), libc::ERANGE); +} + +fn test_chdir() { + let old_cwd = std::env::current_dir().unwrap(); + + errno_check(unsafe { libc::chdir(c"..".as_ptr()) }); + + let parent = old_cwd.parent().unwrap_or(&old_cwd); + assert_eq!(std::env::current_dir().unwrap(), parent); + + // If the cwd isn't restored, subsequent tests would run in the wrong directory + std::env::set_current_dir(old_cwd).unwrap(); + + let err = errno_result(unsafe { libc::chdir(c"thisdoesnotexist".as_ptr()) }).unwrap_err(); + assert_eq!(err.raw_os_error().unwrap(), libc::ENOENT); +} + fn main() { test_getenv(); test_setenv(); test_unsetenv(); + test_getcwd(); + test_chdir(); } diff --git a/src/tools/miri/tests/pass-dep/libc/fs-permissions.rs b/src/tools/miri/tests/pass-dep/libc/fs-permissions.rs index 4705b8931a63a..fc8b4c33989b4 100644 --- a/src/tools/miri/tests/pass-dep/libc/fs-permissions.rs +++ b/src/tools/miri/tests/pass-dep/libc/fs-permissions.rs @@ -1,5 +1,5 @@ //@ignore-target: windows # libc bits exist, but we don't support them -//@ignore-host: windows # shim needs unix PermissionExt on the host +//@ignore-host: windows # on Windows hosts we only supports 0o444 and 0o666 //@compile-flags: -Zmiri-disable-isolation //@run-native @@ -19,10 +19,10 @@ fn main() { } #[track_caller] -fn getmod(path: &CStr) -> u32 { +fn getmod(path: &CStr) -> libc::mode_t { let mut stat = MaybeUninit::::uninit(); unsafe { errno_check(libc::stat(path.as_ptr(), stat.as_mut_ptr())) }; - u32::from(unsafe { stat.assume_init_ref().st_mode & !libc::S_IFMT }) + unsafe { stat.assume_init_ref().st_mode } } fn test_chmod() { @@ -30,9 +30,12 @@ fn test_chmod() { let c_path = utils::into_c_string(path); unsafe { errno_check(libc::chmod(c_path.as_ptr(), 0o777)) }; - assert_eq!(getmod(&c_path), 0o777); + assert_eq!(getmod(&c_path) & !libc::S_IFMT, 0o777); unsafe { errno_check(libc::chmod(c_path.as_ptr(), 0o610)) }; - assert_eq!(getmod(&c_path), 0o610); + assert_eq!(getmod(&c_path) & !libc::S_IFMT, 0o610); + // We can leave the file type in the mode that we pass to `chmod`. + unsafe { errno_check(libc::chmod(c_path.as_ptr(), getmod(&c_path) | 0o111)) }; + assert_eq!(getmod(&c_path) & !libc::S_IFMT, 0o711); } fn test_fchmod() { @@ -41,7 +44,10 @@ fn test_fchmod() { let fd = unsafe { errno_result(libc::open(c_path.as_ptr(), libc::O_RDONLY)).unwrap() }; unsafe { errno_check(libc::fchmod(fd, 0o777)) }; - assert_eq!(getmod(&c_path), 0o777); + assert_eq!(getmod(&c_path) & !libc::S_IFMT, 0o777); unsafe { errno_check(libc::fchmod(fd, 0o610)) }; - assert_eq!(getmod(&c_path), 0o610); + assert_eq!(getmod(&c_path) & !libc::S_IFMT, 0o610); + // We can leave the file type in the mode that we pass to `fchmod`. + unsafe { errno_check(libc::fchmod(fd, getmod(&c_path) | 0o111)) }; + assert_eq!(getmod(&c_path) & !libc::S_IFMT, 0o711); } diff --git a/src/tools/miri/tests/pass-dep/libc/fs.rs b/src/tools/miri/tests/pass-dep/libc/fs.rs index a8dd2d3159e04..11524bb0f5c38 100644 --- a/src/tools/miri/tests/pass-dep/libc/fs.rs +++ b/src/tools/miri/tests/pass-dep/libc/fs.rs @@ -2,6 +2,7 @@ //@compile-flags: -Zmiri-disable-isolation //@run-native +// temporary hack until is fixed. //@revisions: windows_host unix_host //@[unix_host] ignore-host: windows //@[windows_host] only-host: windows @@ -40,12 +41,16 @@ fn main() { test_ftruncate::(libc::ftruncate64); test_create_read_write(); test_read_and_uninit(); - test_open_args(); + test_open_args(libc::open); + #[cfg(target_os = "linux")] + test_open_args(libc::open64); test_open_nofollow(); test_open_dangling_symlink(); test_open_directory(); test_open_exclusive(); - test_openat(); + test_openat(libc::openat); + #[cfg(target_os = "linux")] + test_openat(libc::openat64); #[cfg(target_os = "linux")] test_o_tmpfile_flag(); test_posix_mkstemp(); @@ -64,6 +69,11 @@ fn main() { test_fallocate::(libc::fallocate64); #[cfg(target_os = "linux")] test_sync_file_range(); + test_fsync(libc::fsync); + #[cfg(not(target_os = "macos"))] + test_fsync(libc::fdatasync); + #[cfg(target_os = "linux")] + test_copy_file_range(); test_opendir_closedir(); test_readdir(); test_dirfd(); @@ -331,13 +341,15 @@ fn test_statx_on_empty_path() { } } -fn test_open_args() { +fn test_open_args( + open: unsafe extern "C" fn(path: *const libc::c_char, oflag: libc::c_int, ...) -> libc::c_int, +) { let path = utils::prepare_with_content("miri_test_open_args.txt", &[]); let name = utils::into_c_string(path); // Works with 2 or 3 arguments. - let _fd = errno_result(unsafe { libc::open(name.as_ptr(), libc::O_RDONLY) }).unwrap(); - let _fd = errno_result(unsafe { libc::open(name.as_ptr(), libc::O_RDONLY, 42) }).unwrap(); + let _fd = errno_result(unsafe { open(name.as_ptr(), libc::O_RDONLY) }).unwrap(); + let _fd = errno_result(unsafe { open(name.as_ptr(), libc::O_RDONLY, 42) }).unwrap(); } fn test_open_nofollow() { @@ -348,8 +360,8 @@ fn test_open_nofollow() { let fd = errno_result(unsafe { libc::open(cpath.as_ptr(), libc::O_NOFOLLOW | libc::O_CLOEXEC) }) .unwrap(); - let data = libc_utils::read_exact_array::<5>(fd).unwrap(); - assert!(bytes.starts_with(&data)); + let data = libc_utils::read_to_end(fd).unwrap(); + assert_eq!(*bytes, *data); errno_check(unsafe { libc::close(fd) }); // But trying to open a symlink errors. @@ -484,7 +496,14 @@ fn test_open_exclusive() { assert_eq!(exist_err.raw_os_error().unwrap(), libc::EEXIST, "unexpected errno: {exist_err}"); } -fn test_openat() { +fn test_openat( + openat: unsafe extern "C" fn( + dirfd: libc::c_int, + pathname: *const libc::c_char, + flags: libc::c_int, + ... + ) -> libc::c_int, +) { let path = utils::prepare("miri_test_openat"); fs::create_dir(&path).unwrap(); fs::create_dir(&path.join("dir")).unwrap(); @@ -492,36 +511,31 @@ fn test_openat() { let cpath = utils::into_c_string(&path); // Absolute path, can use garbage dirfd. - let dirfd = - errno_result(unsafe { libc::openat(999, cpath.as_ptr(), libc::O_DIRECTORY) }).unwrap(); + let dirfd = errno_result(unsafe { openat(999, cpath.as_ptr(), libc::O_DIRECTORY) }).unwrap(); // Open file relative to dirfd. - let fd = - errno_result(unsafe { libc::openat(dirfd, c"file.txt".as_ptr(), libc::O_RDWR) }).unwrap(); - let data = libc_utils::read_exact_array::<4>(fd).unwrap(); + let fd = errno_result(unsafe { openat(dirfd, c"file.txt".as_ptr(), libc::O_RDWR) }).unwrap(); + let data = libc_utils::read_to_end(fd).unwrap(); assert_eq!(&data, b"data"); errno_check(unsafe { libc::close(fd) }); // That should error with O_DIRECTORY. - let err = errno_result(unsafe { libc::openat(dirfd, c"file.txt".as_ptr(), libc::O_DIRECTORY) }) + let err = errno_result(unsafe { openat(dirfd, c"file.txt".as_ptr(), libc::O_DIRECTORY) }) .unwrap_err(); assert_eq!(err.raw_os_error().unwrap(), libc::ENOTDIR); // Open dir relative to handle. let dirfd2 = - errno_result(unsafe { libc::openat(dirfd, c"dir".as_ptr(), libc::O_DIRECTORY) }).unwrap(); + errno_result(unsafe { openat(dirfd, c"dir".as_ptr(), libc::O_DIRECTORY) }).unwrap(); errno_check(unsafe { libc::close(dirfd2) }); // Re-open dir relative to itself. Even without O_DIRECTORY. - let dirfd2 = - errno_result(unsafe { libc::openat(dirfd, c".".as_ptr(), libc::O_RDONLY) }).unwrap(); - let fd = - errno_result(unsafe { libc::openat(dirfd2, c"file.txt".as_ptr(), libc::O_RDWR) }).unwrap(); + let dirfd2 = errno_result(unsafe { openat(dirfd, c".".as_ptr(), libc::O_RDONLY) }).unwrap(); + let fd = errno_result(unsafe { openat(dirfd2, c"file.txt".as_ptr(), libc::O_RDWR) }).unwrap(); errno_check(unsafe { libc::close(fd) }); errno_check(unsafe { libc::close(dirfd2) }); // Empty path errors. - let err = - errno_result(unsafe { libc::openat(dirfd, c"".as_ptr(), libc::O_RDONLY) }).unwrap_err(); + let err = errno_result(unsafe { openat(dirfd, c"".as_ptr(), libc::O_RDONLY) }).unwrap_err(); assert_eq!(err.raw_os_error().unwrap(), libc::ENOENT); // Open things via symlink. @@ -529,13 +543,11 @@ fn test_openat() { fs::symlink("dir", path.join("dirlink")).unwrap(); fs::symlink("../file.txt", path.join("dir/filelink")).unwrap(); let dirfd2 = - errno_result(unsafe { libc::openat(dirfd, c"dirlink".as_ptr(), libc::O_RDONLY) }) - .unwrap(); + errno_result(unsafe { openat(dirfd, c"dirlink".as_ptr(), libc::O_RDONLY) }).unwrap(); // This link points to above `dirfd2` but that should still work. let fd = - errno_result(unsafe { libc::openat(dirfd2, c"filelink".as_ptr(), libc::O_RDONLY) }) - .unwrap(); - let data = libc_utils::read_exact_array::<4>(fd).unwrap(); + errno_result(unsafe { openat(dirfd2, c"filelink".as_ptr(), libc::O_RDONLY) }).unwrap(); + let data = libc_utils::read_to_end(fd).unwrap(); assert_eq!(&data, b"data"); errno_check(unsafe { libc::close(fd) }); errno_check(unsafe { libc::close(dirfd2) }); @@ -544,17 +556,15 @@ fn test_openat() { // See . if cfg!(not(windows_host)) { // That should fail with O_NOFOLLOW. - let err = - errno_result(unsafe { libc::openat(dirfd, c"dirlink".as_ptr(), libc::O_NOFOLLOW) }) - .unwrap_err(); + let err = errno_result(unsafe { openat(dirfd, c"dirlink".as_ptr(), libc::O_NOFOLLOW) }) + .unwrap_err(); assert!( matches!(err.raw_os_error().unwrap(), libc::ELOOP | libc::EMLINK), "unexpected errno: {err}" ); - let err = errno_result(unsafe { - libc::openat(dirfd, c"dir/filelink".as_ptr(), libc::O_NOFOLLOW) - }) - .unwrap_err(); + let err = + errno_result(unsafe { openat(dirfd, c"dir/filelink".as_ptr(), libc::O_NOFOLLOW) }) + .unwrap_err(); assert!( matches!(err.raw_os_error().unwrap(), libc::ELOOP | libc::EMLINK), "unexpected errno: {err}" @@ -562,10 +572,10 @@ fn test_openat() { // But if only the first component is a symlink, that works fine. fs::rename(path.join("file.txt"), path.join("dir/file.txt")).unwrap(); let fd = errno_result(unsafe { - libc::openat(dirfd, c"dirlink/file.txt".as_ptr(), libc::O_NOFOLLOW) + openat(dirfd, c"dirlink/file.txt".as_ptr(), libc::O_NOFOLLOW) }) .unwrap(); - let data = libc_utils::read_exact_array::<4>(fd).unwrap(); + let data = libc_utils::read_to_end(fd).unwrap(); assert_eq!(&data, b"data"); errno_check(unsafe { libc::close(fd) }); } @@ -582,7 +592,7 @@ fn test_create_read_write() { let fd = errno_result(unsafe { libc::open(cpath.as_ptr(), libc::O_WRONLY | libc::O_CREAT, 0o666) }) .unwrap(); - let read_err = libc_utils::read_exact_array::<4>(fd).unwrap_err(); + let read_err = libc_utils::read_to_end(fd).unwrap_err(); // cannot read from WRONLY assert_eq!(read_err.raw_os_error().unwrap(), libc::EBADF, "unexpected errno: {read_err}"); libc_utils::write_all(fd, content).unwrap(); errno_check(unsafe { libc::close(fd) }); @@ -590,8 +600,8 @@ fn test_create_read_write() { let fd = errno_result(unsafe { libc::open(cpath.as_ptr(), libc::O_RDONLY) }).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_exact_array::<8>(fd).unwrap(); - assert!(content.starts_with(&data)); + let data = libc_utils::read_to_end(fd).unwrap(); + assert_eq!(*content, *data); errno_check(unsafe { libc::close(fd) }); } @@ -1137,6 +1147,113 @@ fn test_sync_file_range() { fs::remove_file(&path).unwrap(); } +fn test_fsync(fsync: unsafe extern "C" fn(fd: libc::c_int) -> libc::c_int) { + let path = utils::prepare_with_content("miri-pass-libc-fsync.txt", b"hello"); + let c_path = utils::into_c_string(&path); + let fd = errno_result(unsafe { libc::open(c_path.as_ptr(), libc::O_RDONLY) }).unwrap(); + + // Test calling fsync or fdatasync on the file. + errno_check(unsafe { fsync(fd) }); + + // invalid fd + let err = errno_result(unsafe { fsync(-1) }).unwrap_err(); + assert_eq!(err.raw_os_error().unwrap(), libc::EBADF); +} + +#[cfg(target_os = "linux")] +fn test_copy_file_range() { + use std::io::{Seek, SeekFrom}; + + let copy = |fd_in: i32, fd_out: i32, len: usize| { + errno_result(unsafe { + libc::copy_file_range(fd_in, ptr::null_mut(), fd_out, ptr::null_mut(), len, 0) + }) + }; + let copy_syscall = |fd_in: i32, fd_out: i32, len: usize| unsafe { + errno_result(libc::syscall( + libc::SYS_copy_file_range, + fd_in, + ptr::null_mut::(), + fd_out, + ptr::null_mut::(), + len, + 0, + )) + }; + + let src_path = + utils::prepare_with_content("miri_test_libc_copy_file_range_src.txt", b"Hello, World!\n"); + let dst_path = utils::prepare("miri_test_libc_copy_file_range_dst.txt"); + let mut src = File::open(&src_path).unwrap(); + let mut dst = File::create(&dst_path).unwrap(); + + // Copying starts at the current file positions and advances both of them. + src.seek(SeekFrom::Start(7)).unwrap(); + dst.write_all(b"Hi ").unwrap(); + // Asking for more bytes than are left copies up to the end of the input. + assert_eq!(copy(src.as_raw_fd(), dst.as_raw_fd(), 100).unwrap(), 7); + assert_eq!(src.stream_position().unwrap(), 14); + assert_eq!(dst.stream_position().unwrap(), 10); + // At the end of the input, nothing is copied. + assert_eq!(copy(src.as_raw_fd(), dst.as_raw_fd(), 100).unwrap(), 0); + assert_eq!(fs::read(&dst_path).unwrap(), b"Hi World!\n"); + + // Same file, overlapping ranges. + // Using the syscall here, for a change. + dst.rewind().unwrap(); + let dst2 = File::open(&dst_path).unwrap(); + let err = copy_syscall(dst2.as_raw_fd(), dst.as_raw_fd(), 5).unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EINVAL)); + // Same file, non-overlapping ranges. + dst.seek(SeekFrom::Current(5)).unwrap(); + let res = copy_syscall(dst2.as_raw_fd(), dst.as_raw_fd(), 3).unwrap(); + assert_eq!(res, 3); + assert_eq!(fs::read(&dst_path).unwrap(), b"Hi WoHi !\n"); + drop(dst2); + + // Invalid file descriptors. + let err = copy(-1, -1, 1).unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EBADF)); + + // Directories. + let dir = errno_result(unsafe { + libc::open(utils::into_c_string(utils::tmp()).as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY) + }) + .unwrap(); + let err = copy(dir, dst.as_raw_fd(), 1).unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EISDIR)); + let err = copy(src.as_raw_fd(), dir, 1).unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EISDIR)); + errno_check(unsafe { libc::close(dir) }); + + // Other non-regular files. + let mut pipe = [0; 2]; + errno_check(unsafe { libc::pipe(pipe.as_mut_ptr()) }); + let err = copy(src.as_raw_fd(), pipe[1], 1).unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EINVAL)); + // The file type is checked before the access mode: the read end is not writable either. + let err = copy(src.as_raw_fd(), pipe[0], 1).unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EINVAL)); + errno_check(unsafe { libc::close(pipe[0]) }); + errno_check(unsafe { libc::close(pipe[1]) }); + + // Wrong access modes. + let write_only = fs::OpenOptions::new().write(true).open(&src_path).unwrap(); + let err = copy(write_only.as_raw_fd(), dst.as_raw_fd(), 1).unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EBADF)); + let read_only = File::open(&dst_path).unwrap(); + let err = copy(src.as_raw_fd(), read_only.as_raw_fd(), 1).unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EBADF)); + let append = fs::OpenOptions::new().append(true).open(&dst_path).unwrap(); + let err = copy(src.as_raw_fd(), append.as_raw_fd(), 1).unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EBADF)); + drop((write_only, read_only, append)); + + drop((src, dst)); + fs::remove_file(&src_path).unwrap(); + fs::remove_file(&dst_path).unwrap(); +} + fn test_fstat() { use std::os::unix::io::AsRawFd; diff --git a/src/tools/miri/tests/pass-dep/libc/pipe.rs b/src/tools/miri/tests/pass-dep/libc/pipe.rs index a179ec1d61ec2..143cc69e18af2 100644 --- a/src/tools/miri/tests/pass-dep/libc/pipe.rs +++ b/src/tools/miri/tests/pass-dep/libc/pipe.rs @@ -76,8 +76,9 @@ fn test_pipe_threaded() { let thread2 = thread::spawn(move || { yield_now(); write_all(fds[1], b"12345").unwrap(); + errno_check(unsafe { libc::close(fds[1]) }); // signal EOF }); - let buf = read_exact_array::<5>(fds[0]).unwrap(); + let buf = read_to_end(fds[0]).unwrap(); assert_eq!(&buf, b"12345"); thread2.join().unwrap(); } 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 28116b10f9150..8850a04abc6a2 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 @@ -6,6 +6,7 @@ LL | libc::getsockname(client_sockfd, storage, len) | = note: Windows hosts do not provide `local_addr` information while the socket is still connecting, which might break the assumptions of code compiled for Unix targets = note: an unspecified socket address (e.g. `0.0.0.0:0`) will be returned instead + = note: this warning is only shown once per program execution = note: this is on thread `main` = note: stack backtrace: 0: test_getsockname_ipv4_connect_nonblock::{closure#0} 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 f5d24319eba17..3c3f81bae9075 100644 --- a/src/tools/miri/tests/pass-dep/libc/socket-tcp.rs +++ b/src/tools/miri/tests/pass-dep/libc/socket-tcp.rs @@ -9,7 +9,7 @@ mod utils; use std::io::ErrorKind; use std::time::{Duration, Instant}; -use std::{ptr, thread}; +use std::{mem, ptr, thread}; use libc_utils::*; @@ -34,11 +34,14 @@ fn main() { test_listen_listening(); test_accept_connect(); + test_accept_addr_nullptr(); test_connect_error(); test_connect_connected(); test_connect_listening(); test_send_peek_recv(); test_write_read(); + test_recvfrom(); + test_sendto(); test_readv(); test_writev(); @@ -189,7 +192,18 @@ fn test_accept_connect() { // Spawn the server thread. let server_thread = thread::spawn(move || { - let (peerfd, _) = net::accept_ipv4(server_sockfd).unwrap(); + let (peerfd, peeraddr) = net::accept_ipv4(server_sockfd).unwrap(); + + // IP should match the server, it's all localhost. Port will be different of course. + assert_eq!(addr.sin_family, peeraddr.sin_family); + assert_ne!(addr.sin_port, peeraddr.sin_port); + assert_eq!(addr.sin_addr.s_addr, peeraddr.sin_addr.s_addr); + #[cfg(any(target_os = "freebsd", target_vendor = "apple"))] + { + // Ensure that the `sin_len` field is populated on a socket address + // and that it matches `sizeof(sockaddr_in)`. + assert_eq!(peeraddr.sin_len as usize, size_of::()); + } let flags = unsafe { errno_result(libc::fcntl(peerfd, libc::F_GETFL, 0)).unwrap() }; @@ -220,6 +234,25 @@ fn test_accept_connect() { server_thread.join().unwrap(); } +/// Test accepting an incoming connection where the `address` pointer +/// 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 client_sockfd = + unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; + + net::connect_ipv4(client_sockfd, addr).unwrap(); + unsafe { + errno_result(libc::accept( + server_sockfd, + ptr::null_mut::().cast(), + ptr::without_provenance_mut::(0x200), + )) + .unwrap(); + } +} + /// Test connecting to an address where nothing is listening and ensure the error matches what /// the standard library expects. fn test_connect_error() { @@ -356,17 +389,206 @@ fn test_write_read() { // Write some bytes into the stream. libc_utils::write_all(peerfd, TEST_BYTES).unwrap(); + // Make sure the other side sees an EOF. + errno_check(unsafe { libc::close(peerfd) }); + }); + + net::connect_ipv4(client_sockfd, addr).unwrap(); + + let data = libc_utils::read_to_end(client_sockfd).unwrap(); + assert_eq!(&data, TEST_BYTES); + + server_thread.join().unwrap(); +} + +/// Test receiving data from a TCP socket using `recvfrom`. +/// 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 client_sockfd = + unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; + + // Spawn the server thread. + let server_thread = thread::spawn(move || { + let (peerfd, _) = net::accept_ipv4(server_sockfd).unwrap(); + + // Write some bytes into the stream. + + libc_utils::write_all(peerfd, TEST_BYTES).unwrap(); + libc_utils::write_all(peerfd, TEST_BYTES).unwrap(); }); net::connect_ipv4(client_sockfd, addr).unwrap(); let mut buffer = [0; TEST_BYTES.len()]; - libc_utils::read_exact(client_sockfd, &mut buffer).unwrap(); + + // It is legal to make both the addr and addr_len pointers null. + unsafe { + errno_result(libc::recvfrom( + client_sockfd, + buffer.as_mut_ptr().cast(), + buffer.len(), + /* flags */ 0, + ptr::null_mut::(), + ptr::null_mut::(), + )) + .unwrap(); + } + + assert_eq!(&buffer, TEST_BYTES); + + let mut buffer: [u8; 26] = [0; TEST_BYTES.len()]; + + // If address pointer is non-null, `address_len` should be zeroed (but address itself is not accessed). + let mut addr = unsafe { mem::zeroed::() }; + let mut addr_len = mem::size_of_val(&addr) as libc::socklen_t; + unsafe { + errno_result(libc::recvfrom( + client_sockfd, + buffer.as_mut_ptr().cast(), + buffer.len(), + /* flags */ 0, + &mut addr, + &mut addr_len, + )) + .unwrap(); + } + // Ensure the `address_len` pointer gets zeroed. + assert_eq!(addr_len, 0); + assert_eq!(&buffer, TEST_BYTES); server_thread.join().unwrap(); } +/// Test sending data into a TCP socket using `sendto`. +/// We provide a nullptr as destination address, which should not be +/// 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 client_sockfd = + unsafe { errno_result(libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0)).unwrap() }; + + // Spawn the server thread. + let server_thread = thread::spawn(move || { + let (peerfd, _) = net::accept_ipv4(server_sockfd).unwrap(); + + // Write some bytes into the stream using `sendto`. + + // When the address pointer and the length are valid, the destination + // address should be ignored since we're using TCP. + let valid_addr = net::sock_addr_ipv4([127, 0, 0, 1], 5555); + unsafe { + libc_utils::write_all_generic( + TEST_BYTES.as_ptr().cast(), + TEST_BYTES.len(), + libc_utils::NoRetry, + |buf, count| { + libc::sendto( + peerfd, + buf, + count, + /* flags */ 0, + (&valid_addr as *const libc::sockaddr_in).cast::(), + size_of::() as libc::socklen_t, + ) + }, + ) + .unwrap(); + } + + // Setting both to null/zero should also work. + unsafe { + libc_utils::write_all_generic( + TEST_BYTES.as_ptr().cast(), + TEST_BYTES.len(), + libc_utils::NoRetry, + |buf, count| { + libc::sendto( + peerfd, + buf, + count, + /* flags */ 0, + ptr::null_mut::(), + /* address_len */ 0, + ) + }, + ) + .unwrap(); + } + + // In fact when the address is null, the length is entirely ignored. + unsafe { + libc_utils::write_all_generic( + TEST_BYTES.as_ptr().cast(), + TEST_BYTES.len(), + libc_utils::NoRetry, + |buf, count| { + libc::sendto( + peerfd, + buf, + count, + /* flags */ 0, + ptr::null_mut::(), + /* address_len */ 16, + ) + }, + ) + .unwrap(); + }; + + // But when the pointer is non-null and the length null, behavior differs between OSes. + let res = unsafe { + libc_utils::write_all_generic( + TEST_BYTES.as_ptr().cast(), + TEST_BYTES.len(), + libc_utils::NoRetry, + |buf, count| { + libc::sendto( + peerfd, + buf, + count, + /* flags */ 0, + ptr::without_provenance_mut::(16), + /* address_len */ 0, + ) + }, + ) + }; + + if cfg!(miri) || !cfg!(any(target_os = "freebsd", target_vendor = "apple")) { + res.unwrap(); + } else { + // Native FreeBSD and macOS return EINVAL when the address pointer is invalid even when + // the address length is zero. + assert_eq!(res.unwrap_err().raw_os_error().unwrap(), libc::EINVAL); + } + + errno_check(unsafe { libc::close(peerfd) }); + }); + + net::connect_ipv4(client_sockfd, addr).unwrap(); + + // We sent the test data at least 3 times. + for _ in 0..3 { + let mut buffer = [0; TEST_BYTES.len()]; + libc_utils::read_exact(client_sockfd, &mut buffer).unwrap(); + assert_eq!(&buffer, TEST_BYTES); + } + let rest = libc_utils::read_to_end(client_sockfd).unwrap(); + if cfg!(miri) || !cfg!(any(target_os = "freebsd", target_vendor = "apple")) { + // it was sent a 4th time. + assert_eq!(*rest, *TEST_BYTES); + } else { + assert_eq!(*rest, []); + } + + server_thread.join().unwrap(); + errno_check(unsafe { libc::close(client_sockfd) }); +} + /// Test vectored reads with multiple buffers on a connected socket. fn test_readv() { let (server_sockfd, addr) = net::make_listener_ipv4().unwrap(); @@ -481,6 +703,12 @@ fn test_getpeername_ipv4() { assert_eq!(addr.sin_family, peer_addr.sin_family); assert_eq!(addr.sin_port, peer_addr.sin_port); assert_eq!(addr.sin_addr.s_addr, peer_addr.sin_addr.s_addr); + #[cfg(any(target_os = "freebsd", target_vendor = "apple"))] + { + // Ensure that the `sin_len` field is populated on a socket address + // and that it matches `sizeof(sockaddr_in)`. + assert_eq!(peer_addr.sin_len as usize, size_of::()); + } } /// Test the `getpeername` syscall on an IPv6 socket. @@ -504,6 +732,12 @@ fn test_getpeername_ipv6() { assert_eq!(addr.sin6_flowinfo, peer_addr.sin6_flowinfo); assert_eq!(addr.sin6_scope_id, peer_addr.sin6_scope_id); assert_eq!(addr.sin6_addr.s6_addr, peer_addr.sin6_addr.s6_addr); + #[cfg(any(target_os = "freebsd", target_vendor = "apple"))] + { + // Ensure that the `sin6_len` field is populated on a socket address + // and that it matches `sizeof(sockaddr_in6)`. + assert_eq!(peer_addr.sin6_len as usize, size_of::()); + } } /// Test shutting down TCP streams. diff --git a/src/tools/miri/tests/pass-dep/libc/socket.rs b/src/tools/miri/tests/pass-dep/libc/socket.rs index a8ed32066d2b7..2dd9f7311672e 100644 --- a/src/tools/miri/tests/pass-dep/libc/socket.rs +++ b/src/tools/miri/tests/pass-dep/libc/socket.rs @@ -112,19 +112,20 @@ fn test_bind_ipv4_invalid_addr_len() { }; assert_eq!(err.raw_os_error(), Some(libc::EINVAL)); - if cfg!(miri) { - // A too big size is also invalid. Some native hosts (e.g. Linux) - // allow too big sizes, so we skip this test on native hosts: - // - let err = unsafe { - errno_result(libc::bind( - sockfd, - (&addr as *const libc::sockaddr_in).cast::(), - (size_of::() + 1) as libc::socklen_t, - )) - .unwrap_err() - }; - assert_eq!(err.raw_os_error(), Some(libc::EINVAL)); + // A too big size is also invalid according to the spec, but accepted on Linux. + // Make sure the bigger size is still fully in-bounds. + let addrs = [addr; 2]; + let res = unsafe { + errno_result(libc::bind( + sockfd, + addrs.as_ptr().cast::(), + (size_of::() + 1) as libc::socklen_t, + )) + }; + if cfg!(miri) || cfg!(not(target_os = "linux")) { + assert_eq!(res.unwrap_err().raw_os_error().unwrap(), libc::EINVAL); + } else { + assert_eq!(res.unwrap(), 0); } } diff --git a/src/tools/miri/tests/pass-dep/libc/socketpair.rs b/src/tools/miri/tests/pass-dep/libc/socketpair.rs index 533c27a2905d0..deb33db8c57c5 100644 --- a/src/tools/miri/tests/pass-dep/libc/socketpair.rs +++ b/src/tools/miri/tests/pass-dep/libc/socketpair.rs @@ -155,13 +155,15 @@ fn test_blocking_read() { errno_check(unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM, 0, fds.as_mut_ptr()) }); let thread1 = thread::spawn(move || { // Let this thread block on read. - let buf = read_exact_array::<3>(fds[1]).unwrap(); + let buf = read_to_end(fds[1]).unwrap(); assert_eq!(&buf, b"abc"); }); let thread2 = thread::spawn(move || { yield_now(); // thread1 should go first // Unblock thread1 by doing writing something. write_all(fds[0], b"abc").unwrap(); + // Signal EOF. + errno_check(unsafe { libc::close(fds[0]) }); }); thread1.join().unwrap(); thread2.join().unwrap(); diff --git a/src/tools/miri/tests/pass/extern_types.stack.stderr b/src/tools/miri/tests/pass/extern_types.stack.stderr index c1a66d92a7241..a71a075c51394 100644 --- a/src/tools/miri/tests/pass/extern_types.stack.stderr +++ b/src/tools/miri/tests/pass/extern_types.stack.stderr @@ -6,6 +6,7 @@ LL | let x: &Foo = unsafe { &*(ptr::without_provenance::<()>(16) as *const F | = help: `extern type` are not compatible with the Stacked Borrows aliasing model implemented by Miri; Miri may miss bugs in this code = help: try running with `MIRIFLAGS=-Zmiri-tree-borrows` to use the more permissive but also even more experimental Tree Borrows aliasing checks instead + = note: this warning is only shown once per program execution warning: 1 warning emitted diff --git a/src/tools/miri/tests/pass/shims/fs-permissions.rs b/src/tools/miri/tests/pass/shims/fs-permissions.rs deleted file mode 100644 index bef1339623b7a..0000000000000 --- a/src/tools/miri/tests/pass/shims/fs-permissions.rs +++ /dev/null @@ -1,60 +0,0 @@ -//@compile-flags: -Zmiri-disable-isolation -//@ignore-target: windows # shim not supported -//@ignore-host: windows # needs unix PermissionExt -//@run-native - -use std::fs::{self, File}; - -#[path = "../../utils/mod.rs"] -mod utils; - -macro_rules! check { - ($e:expr) => { - match $e { - Ok(t) => t, - Err(e) => panic!("{} failed with: {e}", stringify!($e)), - } - }; -} - -fn main() { - chmod_works(); - fchmod_works(); -} - -fn chmod_works() { - let file = utils::prepare("miri_test_fs_set_permissions.txt"); - - check!(File::create(&file)); - let attr = check!(fs::metadata(&file)); - assert!(!attr.permissions().readonly()); - let mut p = attr.permissions(); - p.set_readonly(true); - check!(fs::set_permissions(&file, p.clone())); - let attr = check!(fs::metadata(&file)); - assert!(attr.permissions().readonly()); - - match fs::set_permissions(&file.with_file_name("foo"), p.clone()) { - Ok(..) => panic!("wanted an error"), - Err(..) => {} - } - - p.set_readonly(false); - check!(fs::set_permissions(&file, p)); -} - -fn fchmod_works() { - let path = utils::prepare("miri_test_file_set_permissions.txt"); - - let file = check!(File::create(&path)); - let attr = check!(fs::metadata(&path)); - assert!(!attr.permissions().readonly()); - let mut p = attr.permissions(); - p.set_readonly(true); - check!(file.set_permissions(p.clone())); - let attr = check!(fs::metadata(&path)); - assert!(attr.permissions().readonly()); - - p.set_readonly(false); - check!(file.set_permissions(p)); -} diff --git a/src/tools/miri/tests/pass/shims/fs.rs b/src/tools/miri/tests/pass/shims/fs.rs index d1003bc8fb76f..2c6c6023203f5 100644 --- a/src/tools/miri/tests/pass/shims/fs.rs +++ b/src/tools/miri/tests/pass/shims/fs.rs @@ -4,6 +4,7 @@ #![feature(io_error_more)] #![feature(io_error_uncategorized)] #![feature(dirfd)] +#![feature(seek_stream_len)] #![cfg_attr(unix, feature(unix_file_vectored_at))] #![allow(unused_features)] // feature use depends on target @@ -68,6 +69,9 @@ fn main() { } // Windows file handling is very incomplete. if cfg!(not(windows)) || cfg!(not(miri)) { + test_fs_set_permissions(); + test_file_set_permissions(); + test_create_new_dangling_symlink(); test_directory(); test_canonicalize(); @@ -75,6 +79,10 @@ fn main() { test_flock(); test_symlink(); test_hard_link(); + // Uses different shims on apple that we do not support. + if cfg!(not(all(miri, target_vendor = "apple"))) { + test_copy(); + } test_readv_writev(); #[cfg(unix)] @@ -253,6 +261,10 @@ fn test_seek() { let mut file = File::open(&path).unwrap(); let mut contents = Vec::new(); assert_eq!(file.stream_position().unwrap(), 0); + if cfg!(not(windows)) { + // FIXME: stream_len not supported on Windows + assert_eq!(file.stream_len().unwrap(), bytes.len() as u64); + } file.read_to_end(&mut contents).unwrap(); assert_eq!(bytes, contents.as_slice()); assert_eq!(file.stream_position().unwrap(), bytes.len() as u64); @@ -851,3 +863,58 @@ fn test_directory_handle() { fs::create_dir(dirname.join("subdir")).unwrap(); let _subdir = dir.open_dir("subdir").unwrap(); } + +fn test_fs_set_permissions() { + let file = utils::prepare("miri_test_fs_set_permissions.txt"); + drop(File::create(&file).unwrap()); + + // Make file read-only + let mut p = fs::metadata(&file).unwrap().permissions(); + assert!(!p.readonly()); + p.set_readonly(true); + fs::set_permissions(&file, p.clone()).unwrap(); + assert!(fs::metadata(&file).unwrap().permissions().readonly()); + + // Make it writable again + p.set_readonly(false); + fs::set_permissions(&file, p.clone()).unwrap(); + assert!(!fs::metadata(&file).unwrap().permissions().readonly()); + + // Test error for non-existing file + match fs::set_permissions(&file.with_file_name("foo"), p) { + Ok(..) => panic!("wanted an error"), + Err(err) => assert_eq!(err.kind(), ErrorKind::NotFound), + } +} + +fn test_file_set_permissions() { + let path = utils::prepare("miri_test_file_set_permissions.txt"); + + let file = File::create(&path).unwrap(); + let attr = fs::metadata(&path).unwrap(); + assert!(!attr.permissions().readonly()); + let mut p = attr.permissions(); + p.set_readonly(true); + file.set_permissions(p.clone()).unwrap(); + let attr = fs::metadata(&path).unwrap(); + assert!(attr.permissions().readonly()); + + p.set_readonly(false); + file.set_permissions(p).unwrap(); +} + +fn test_copy() { + // This efficiently allocates a lot of zeros, even in Miri. + let mut bytes = vec![0u8; 10_000]; + // Make it not all-zero so we notice if some data goes missing. + for i in 0..200u8 { + bytes[(i as usize) * 47] = i; + } + + let src_path = utils::prepare_with_content("miri_test_fs_copy_src.txt", &bytes); + let dst_path = utils::prepare("miri_test_fs_copy_dst.txt"); + assert_eq!(fs::copy(&src_path, &dst_path).unwrap(), bytes.len() as u64); + assert_eq!(fs::read(&dst_path).unwrap(), bytes); + fs::remove_file(&src_path).unwrap(); + fs::remove_file(&dst_path).unwrap(); +} diff --git a/src/tools/miri/tests/pass/shims/io_copy.rs b/src/tools/miri/tests/pass/shims/io_copy.rs new file mode 100644 index 0000000000000..5467f6a6a05ec --- /dev/null +++ b/src/tools/miri/tests/pass/shims/io_copy.rs @@ -0,0 +1,72 @@ +//! io::copy on Linux has lots of specializations. Try to hit all relevant codepaths. +//@ignore-target: windows +//@compile-flags: -Zmiri-disable-isolation +//@run-native + +use std::fs; +use std::io::{self, Read, Seek, Write, pipe}; + +#[path = "../../utils/mod.rs"] +mod utils; + +fn main() { + test_copy_file_range(); + test_sendfile(); + test_splice(); +} + +fn test_copy_file_range() { + // copy_file_range is used when src and dst are files. + + let bytes = b"123abc"; + let src_path = utils::prepare_with_content("miri_test_io_copy_src.txt", bytes); + let dst_path = utils::prepare("miri_test_io_copy_dst.txt"); + + let mut src = fs::File::open(&src_path).unwrap(); + let mut dst = + fs::OpenOptions::new().create_new(true).read(true).write(true).open(&dst_path).unwrap(); + io::copy(&mut src, &mut dst).unwrap(); + + // dst should be at end of file now + let n = dst.read(&mut [0u8]).unwrap(); + assert_eq!(n, 0); + // same for src + assert_eq!(src.stream_position().unwrap(), bytes.len() as u64); + + // if we seek to the beginning we can find the contents + dst.rewind().unwrap(); + let mut out = vec![]; + dst.read_to_end(&mut out).unwrap(); + assert_eq!(&*out, bytes); +} + +fn test_sendfile() { + // It is not possible to hit the sendfile path: the source has to be a file, and the destination + // cannot be a fifo or socket. It also cannot be a file as then we use copy_file_range. + // sendfile is therefore unreachable when copy_file_range is supported, and already + // being tested above when copy_file_range is supported. +} + +fn test_splice() { + // splice is used when src or dst is a fifo, and (src is fifo or socket, and dest is file). + // We go for a pipe-to-file copy. + let bytes = b"123abc"; + let dst_path = utils::prepare("miri_test_io_copy_dst.txt"); + let mut dst = + fs::OpenOptions::new().create_new(true).read(true).write(true).open(&dst_path).unwrap(); + + let (mut pipe_rx, mut pipe_tx) = pipe().unwrap(); + pipe_tx.write_all(bytes).unwrap(); // fits into buffer, no need for a thread + drop(pipe_tx); + + io::copy(&mut pipe_rx, &mut dst).unwrap(); + + // dst should be at end of file now + assert_eq!(dst.stream_position().unwrap(), bytes.len() as u64); + + // if we seek to the beginning we can find the contents + dst.rewind().unwrap(); + let mut out = vec![]; + dst.read_to_end(&mut out).unwrap(); + assert_eq!(&*out, bytes); +} 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 89f882a44167e..2c05fdbd3a21d 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 @@ -33,9 +33,36 @@ fn main() { test_avx512ternarylogic(); test_avx512vnni(); test_avx512vbmi(); + test_avx512_shifts(); + test_mm512_permutex2var_epi32(); } } +#[target_feature(enable = "avx512f")] +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]); + assert_eq!( + transmute::<_, [u64; 8]>(_mm512_sllv_epi64(a, counts)), + [1, u64::MAX - 1, 1 << 63, 0, 0, 0, 0, 0], + ); + assert_eq!( + transmute::<_, [u64; 8]>(_mm512_srlv_epi64(a, counts)), + [1, u64::MAX >> 1, 1, 0, 0, 0, 0, 0], + ); +} + +#[target_feature(enable = "avx512f")] +unsafe fn test_mm512_permutex2var_epi32() { + let a = transmute([0i32, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); + let b = transmute([16i32, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]); + let indices = transmute([0i32, 15, 16, 31, 32, 47, 48, 63, -1, i32::MIN, 17, 2, 30, 13, 29, 4]); + assert_eq!( + transmute::<_, [i32; 16]>(_mm512_permutex2var_epi32(a, indices, b)), + [0, 15, 16, 31, 0, 15, 16, 31, 31, 0, 17, 2, 30, 13, 29, 4], + ); +} + #[target_feature(enable = "avx512bw")] unsafe fn test_avx512() { #[target_feature(enable = "avx512bw")] @@ -890,6 +917,30 @@ unsafe fn test_avx512bw() { #[target_feature(enable = "avx512vbmi,avx512vl")] unsafe fn test_avx512vbmi() { + #[target_feature(enable = "avx512vbmi,avx512vl")] + unsafe fn test_mm256_permutex2var_epi8() { + let a = transmute([ + 0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + ]); + let b = transmute([ + 32u8, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, + ]); + let indices = transmute([ + 0u8, 15, 16, 31, 32, 47, 48, 63, 64, 95, 96, 127, 128, 159, 160, 191, 192, 223, 224, + 255, 1, 17, 33, 49, 14, 30, 46, 62, 2, 18, 34, 50, + ]); + assert_eq!( + transmute::<_, [u8; 32]>(_mm256_permutex2var_epi8(a, indices, b)), + [ + 0, 15, 16, 31, 32, 47, 48, 63, 0, 31, 32, 63, 0, 31, 32, 63, 0, 31, 32, 63, 1, 17, + 33, 49, 14, 30, 46, 62, 2, 18, 34, 50, + ], + ); + } + test_mm256_permutex2var_epi8(); + #[target_feature(enable = "avx512vbmi")] unsafe fn test_mm512_permutex2var_epi8() { // For each index byte in `idx`: the low 6 bits (bits [5:0]) select diff --git a/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-sse42.rs b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-sse42.rs index c998fe800df45..e23388ebe9bb4 100644 --- a/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-sse42.rs +++ b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-sse42.rs @@ -206,8 +206,15 @@ unsafe fn test_str() { unsafe fn test_mm_cmpistra() { let a = str_to_m128i(b""); let b = str_to_m128i(b"Hello!!!!!!!!!!!"); + let i = _mm_cmpistra::<_SIDD_UNIT_MASK>(a, b); assert_eq!(1, i); + let i = _mm_cmpistra::<_SIDD_UNIT_MASK>(b, a); + assert_eq!(0, i); + let i = _mm_cmpistra::<_SIDD_UNIT_MASK>(a, a); + assert_eq!(0, i); + let i = _mm_cmpistra::<_SIDD_UNIT_MASK>(b, b); + assert_eq!(0, i); } test_mm_cmpistra(); @@ -288,6 +295,10 @@ unsafe fn test_str() { let b = str_to_m128i(b"Null after 14"); let i = _mm_cmpestra::<{ _SIDD_CMP_EQUAL_EACH | _SIDD_UNIT_MASK }>(a, 14, b, 16); assert_eq!(1, i); + let i = _mm_cmpestra::<{ _SIDD_CMP_EQUAL_EACH | _SIDD_UNIT_MASK | _SIDD_NEGATIVE_POLARITY }>( + a, 14, a, 14, + ); + assert_eq!(0, i); } test_mm_cmpestra(); @@ -339,6 +350,17 @@ unsafe fn test_str() { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ); assert_eq_m128i(i, res); + + let a = str_to_m128i(b"Hello"); + let b = str_to_m128i(b"Hello Hello Hell"); + + let i = _mm_cmpistrm::<{ _SIDD_CMP_EQUAL_ORDERED | _SIDD_UNIT_MASK }>(a, b); + #[rustfmt::skip] + let res = _mm_setr_epi8( + !0, 0x00, 0x00, 0x00, 0x00, 0x00, !0, 0x00, + 0x00, 0x00, 0x00, 0x00, !0, 0x00, 0x00, 0x00, + ); + assert_eq_m128i(i, res); } test_substring(); @@ -407,6 +429,15 @@ unsafe fn test_str() { !0, !0, !0, !0, !0, !0, !0, !0, ); assert_eq_m128i(i, res); + + // Test strings of unequal length. + let i = _mm_cmpestrm::<{ _SIDD_MASKED_NEGATIVE_POLARITY | _SIDD_UNIT_MASK }>(a, 4, b, 7); + #[rustfmt::skip] + let res = _mm_setr_epi8( + !0, 0x00, 0x00, 0x00, !0, !0, !0, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ); + assert_eq_m128i(i, res); } test_polarity(); @@ -428,6 +459,50 @@ unsafe fn test_str() { assert_eq_m128i(i, res); } test_bitmask(); + + #[target_feature(enable = "sse4.2")] + unsafe fn test_negative_length() { + let va = str_to_m128i(b"!!!!!!!!"); + let vb = str_to_m128i(b" "); + + let i = _mm_cmpestrc::<_SIDD_UNIT_MASK>(va, 7, vb, -7); + assert_eq!(0, i); + let i = _mm_cmpestrc::<_SIDD_UNIT_MASK>(va, -7, vb, 7); + assert_eq!(0, i); + + let i = _mm_cmpestrc::<_SIDD_UNIT_MASK>(va, 7, va, -7); + assert_eq!(1, i); + let i = _mm_cmpestrc::<_SIDD_UNIT_MASK>(vb, -7, vb, 7); + assert_eq!(1, i); + } + test_negative_length(); + + // Test case for #5541. + #[target_feature(enable = "sse4.2")] + unsafe fn issue_5541() { + let a = _mm_set1_epi8(b'a' as i8); + let b = _mm_set1_epi8(b'b' as i8); + + assert_eq!(_mm_cmpestrz::<_SIDD_CMP_EQUAL_ANY>(a, 16, a, -16), 0); + assert_eq!(_mm_cmpestrs::<_SIDD_CMP_EQUAL_ANY>(a, -16, a, 16), 0); + + let mask = _mm_cmpestrm::<{ _SIDD_MASKED_POSITIVE_POLARITY | _SIDD_NEGATIVE_POLARITY }>( + a, 1, b, 3, + ); + #[rustfmt::skip] + let res = _mm_setr_epi8( + 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ); + assert_eq_m128i(mask, res); + + const B: i8 = b'b' as i8; + let h = _mm_setr_epi8(B, B, B, B, B, B, B, B, B, B, B, B, B, B, B, b'a' as i8); + + assert_eq!(_mm_cmpestri::<_SIDD_CMP_EQUAL_ORDERED>(a, 2, h, 16), 15); + assert_eq!(_mm_cmpistra::<_SIDD_CMP_EQUAL_ANY>(a, b), 1); + } + issue_5541(); } #[track_caller] diff --git a/src/tools/miri/tests/utils/libc.rs b/src/tools/miri/tests/utils/libc.rs index 25165289c93ed..0b8e0a822c246 100644 --- a/src/tools/miri/tests/utils/libc.rs +++ b/src/tools/miri/tests/utils/libc.rs @@ -91,6 +91,24 @@ pub fn read_partial(fd: libc::c_int, buf: &mut [u8]) -> io::Result<(&mut [u8], & Ok(buf.split_at_mut(res as usize)) } +/// Read `fd` until EOF, return the data. +pub fn read_to_end(fd: libc::c_int) -> io::Result> { + let mut buf = Vec::new(); + loop { + // Make sure we have at least 32 bytes of spare capacity (`Vec` is smart about avoid too + // frequent reallocations). + buf.reserve(32); + // Read into spare capacity. + let spare = buf.spare_capacity_mut(); + let res = errno_result(unsafe { libc::read(fd, spare.as_mut_ptr().cast(), spare.len()) })?; + if res == 0 { + // EOF has been reached. + return Ok(buf); + } + unsafe { buf.set_len(buf.len() + res as usize) }; + } +} + /// Invoke the `write` function until `buf` is full. `retry` controls the behavior on EAGAIN. pub unsafe fn write_all_generic( buf: *const libc::c_void, diff --git a/tests/codegen-llvm/loop-vectorize-in-opt-sz.rs b/tests/codegen-llvm/loop-vectorize-in-opt-sz.rs new file mode 100644 index 0000000000000..f26a558f17ea4 --- /dev/null +++ b/tests/codegen-llvm/loop-vectorize-in-opt-sz.rs @@ -0,0 +1,23 @@ +//@ revisions: O2 S Z +//@[O2] compile-flags: -Copt-level=2 +//@[S] compile-flags: -Copt-level=s +//@[Z] compile-flags: -Copt-level=z +//@ only-x86_64 + +// Loop vectorization is enabled only for the speed objective, so both `-Copt-level=s` and `z` leave +// it off. The loop below is long enough that LLVM at `-O2` does vectorize it. + +#![crate_type = "lib"] + +// CHECK-LABEL: @scale_add( +// O2: fmul <4 x float> +// O2: fadd <4 x float> +// O2: store <4 x float> +// S-NOT: <4 x float> +// Z-NOT: <4 x float> +#[no_mangle] +pub fn scale_add(a: &[f32], b: &[f32], c: &mut [f32]) { + for i in 0..64 { + c[i] = a[i] * b[i] + 3.0; + } +} diff --git a/tests/codegen-llvm/merge-functions.rs b/tests/codegen-llvm/merge-functions.rs index b9d3727ce112e..8c15791c5ae74 100644 --- a/tests/codegen-llvm/merge-functions.rs +++ b/tests/codegen-llvm/merge-functions.rs @@ -1,5 +1,6 @@ -//@ revisions: O Os +//@ revisions: O Os Oz //@[Os] compile-flags: -Copt-level=s +//@[Oz] compile-flags: -Copt-level=z //@[O] compile-flags: -Copt-level=3 #![crate_type = "lib"] diff --git a/tests/codegen-llvm/opt-size-attr-shim.rs b/tests/codegen-llvm/opt-size-attr-shim.rs new file mode 100644 index 0000000000000..a82a3219ca5b1 --- /dev/null +++ b/tests/codegen-llvm/opt-size-attr-shim.rs @@ -0,0 +1,30 @@ +//@ revisions: O2 S Z +//@[O2] compile-flags: -Copt-level=2 +//@[S] compile-flags: -Copt-level=s +//@[Z] compile-flags: -Copt-level=z +//@ ignore-wasi wasi codegens the main symbol differently + +// The C entry shim has no item behind it, so it does not go through the per-item attribute path. +// It still has to carry the size attributes, or `main` is the one definition in a size build that +// LLVM optimizes for speed. + +#![crate_type = "bin"] + +// CHECK-LABEL: define {{.*}} @main( +// CHECK-SAME: [[MAIN_ATTRS:#[0-9]+]] + +// O2: attributes [[MAIN_ATTRS]] = +// O2-NOT: optsize +// O2-NOT: minsize + +// S: attributes [[MAIN_ATTRS]] = +// S-NOT: minsize +// S-SAME: optsize + +// Z: attributes [[MAIN_ATTRS]] = +// Z-SAME: minsize +// Z-SAME: optsize + +fn main() { + std::hint::black_box(0); +} diff --git a/tests/codegen-llvm/opt-size-attr.rs b/tests/codegen-llvm/opt-size-attr.rs new file mode 100644 index 0000000000000..7784e8d1c8e47 --- /dev/null +++ b/tests/codegen-llvm/opt-size-attr.rs @@ -0,0 +1,29 @@ +//@ revisions: O2 S Z +//@[O2] compile-flags: -Copt-level=2 +//@[S] compile-flags: -Copt-level=s +//@[Z] compile-flags: -Copt-level=z + +// `s` gives `optsize` while `z` gives both `minsize` and `optsize`. This is the only coverage of +// the `-Copt-level` path; `optimize-attr-1.rs` reaches these via `#[optimize(size)]`. + +#![crate_type = "lib"] + +// CHECK-LABEL: @f( +// CHECK-SAME: [[F_ATTRS:#[0-9]+]] + +// O2: attributes [[F_ATTRS]] = +// O2-NOT: optsize +// O2-NOT: minsize + +// S: attributes [[F_ATTRS]] = +// S-NOT: minsize +// S-SAME: optsize + +// Z: attributes [[F_ATTRS]] = +// Z-SAME: minsize +// Z-SAME: optsize + +#[no_mangle] +pub fn f(x: u32) -> u32 { + x + 1 +} diff --git a/tests/codegen-llvm/unroll-in-opt-sz.rs b/tests/codegen-llvm/unroll-in-opt-sz.rs new file mode 100644 index 0000000000000..a76c8b3fba51c --- /dev/null +++ b/tests/codegen-llvm/unroll-in-opt-sz.rs @@ -0,0 +1,31 @@ +//@ revisions: O2 S Z +//@[O2] compile-flags: -Copt-level=2 +//@[S] compile-flags: -Copt-level=s +//@[Z] compile-flags: -Copt-level=z + +// `-Copt-level=s`/`z` pass `PTO.LoopUnrolling = false`, so LLVM's unroller runs `OnlyWhenForced`. +// The O2 side is asserted too, so disabling unrolling everywhere cannot pass. Calls are counted +// because this knob emits no `llvm.loop.unroll.*` metadata. + +#![crate_type = "lib"] + +unsafe extern "C" { + fn side_effect(i: u32); +} + +// O2-LABEL: @four_iters( +// O2-COUNT-4: tail call void @side_effect +// S-LABEL: @four_iters( +// S: phi i32 +// S: tail call void @side_effect +// S-NOT: tail call void @side_effect +// Z-LABEL: @four_iters( +// Z: phi i32 +// Z: tail call void @side_effect +// Z-NOT: tail call void @side_effect +#[no_mangle] +pub fn four_iters() { + for i in 0..4u32 { + unsafe { side_effect(i) } + } +} diff --git a/tests/rustdoc-html/deref-to-alias.rs b/tests/rustdoc-html/deref-to-alias.rs new file mode 100644 index 0000000000000..696c7dcf7c29f --- /dev/null +++ b/tests/rustdoc-html/deref-to-alias.rs @@ -0,0 +1,32 @@ +// This test ensures that dereferencing to a type alias will still list +// matching methods of the type alias. + +#![crate_name = "foo"] + +use std::ops::Deref; + +pub struct Foo(T); + +impl Foo { + pub fn get_i32(&self) -> i32 { self.0 } +} + +impl Foo { + pub fn get_u32(&self) -> u32 { self.0 } +} + +pub type X = Foo; + +//@ has 'foo/struct.Bar.html' +// FIXME: Only `get_i32` should be listed, this is a bug. +//@ count - '//*[@id="deref-methods-X-1"]//h4' 2 +//@ has - '//*[@id="deref-methods-X-1"]//h4' 'get_i32' +//@ has - '//*[@id="deref-methods-X-1"]//h4' 'get_u32' +pub struct Bar; + +impl Deref for Bar { + type Target = X; + fn deref(&self) -> &Self::Target { + &X(0) + } +} diff --git a/tests/rustdoc-html/deref/deref-methods-aliased-type.rs b/tests/rustdoc-html/deref/deref-methods-aliased-type.rs new file mode 100644 index 0000000000000..35d3a7eb2433e --- /dev/null +++ b/tests/rustdoc-html/deref/deref-methods-aliased-type.rs @@ -0,0 +1,114 @@ +// Ensures that aliased types get the "Methods from Deref" but only when it matches +// the aliased type. +// Regression test for . + +// ignore-tidy-file-linelength + +#![crate_name = "foo"] + +use std::ops::{Deref, DerefMut}; + +pub struct Target; + +impl Target { + pub fn target_ref(&self) {} + pub fn target_mut(&mut self) {} +} + +pub struct Other; + +impl Other { + pub fn other_ref(&self) {} + pub fn other_mut(&mut self) {} +} + +pub struct Wrapper(T); + +impl Deref for Wrapper { + type Target = Target; + fn deref(&self) -> &Target { + &Target + } +} + +impl Deref for Wrapper { + type Target = Other; + fn deref(&self) -> &Other { + &Other + } +} + +impl DerefMut for Wrapper { + fn deref_mut(&mut self) -> &mut Other { + &mut Other + } +} + +//@ has 'foo/type.Byte.html' +// Only one deref. +//@ count - '//h2[@id="deref-methods-Target"]' 1 +// Which makes two section headers. One for the "Aliased Type" and one for "Methods from Deref<>". +//@ count - '//*[@class="section-header"]' 2 +//@ has - '//*[@class="section-header"]' 'Aliased Type' +//@ has - '//*[@class="section-header"]' 'Methods from Deref' +// Only one method from the deref (not the one taking `&mut` since `DerefMut` is not +// implemented for `Wrapper`. +//@ count - '//*[@id="deref-methods-Target-1"]/*[@class="method"]' 1 +//@ has - '//*[@id="method.target_ref"]//h4' 'pub fn target_ref(&self)' + +// Same checks but in the sidebar. +//@ count - '//*[@class="sidebar-elems"]//*[@class="block deref-methods"]//a' 1 +//@ has - '//*[@class="sidebar-elems"]//*[@class="block deref-methods"]//a[@href="#method.target_ref"]' 'target_ref' +pub type Byte = Wrapper; + +//@ has 'foo/type.Word.html' +// There should be only one `Deref` block (for both `Deref` and `DerefMut`). +//@ count - '//h2[@id="deref-methods-Other"]' 1 +// Which makes two section headers. One for the "Aliased Type" and one for "Methods from Deref<>". +//@ count - '//*[@class="section-header"]' 2 +//@ has - '//*[@class="section-header"]' 'Aliased Type' +//@ has - '//*[@class="section-header"]' 'Methods from Deref' +// Since it implements both `Deref` and `DerefMut`, we should see both methods. +//@ count - '//*[@id="deref-methods-Other-1"]/*[@class="method"]' 2 +//@ has - '//*[@id="method.other_ref"]//h4' 'pub fn other_ref(&self)' +//@ has - '//*[@id="method.other_mut"]//h4' 'pub fn other_mut(&mut self)' + +// Same checks but in the sidebar. +//@ count - '//*[@class="sidebar-elems"]//*[@class="block deref-methods"]//a' 2 +//@ has - '//*[@class="sidebar-elems"]//*[@class="block deref-methods"]//a[@href="#method.other_ref"]' 'other_ref' +//@ has - '//*[@class="sidebar-elems"]//*[@class="block deref-methods"]//a[@href="#method.other_mut"]' 'other_mut' +pub type Word = Wrapper; + +//@ has 'foo/type.Dword.html' +// There is no `Deref` implementation for `Wrapper` so we confirm that. +// Which makes two section headers. One for the "Aliased Type" and one for "Methods from Deref<>". +//@ count - '//*[@class="section-header"]' 1 +//@ has - '//*[@class="section-header"]' 'Aliased Type' +pub type Dword = Wrapper; + +pub struct Foo(T); + +impl Foo { + pub fn tada(&self) {} +} + +impl Deref for Foo { + type Target = T; + fn deref(&self) -> &T { + &self.0 + } +} + +// Checks that traversal `Deref` is working. +//@ has 'foo/struct.FooBar.html' +//@ has - '//*[@id="deref-methods-Foo%3CFoo%3CT%3E%3E-1"]//*[@class="code-header"]' \ +// 'pub fn tada(&self)' +//@ has - '//*[@id="deref-methods-Foo%3CFoo%3CT%3E%3E"]' 'Methods from Deref>>' +pub struct FooBar(Foo>); + +impl Deref for FooBar { + type Target = Foo>; + fn deref(&self) -> &Foo> { + &self.0 + } +} diff --git a/tests/rustdoc-html/deref/deref-on-aliased.rs b/tests/rustdoc-html/deref/deref-on-aliased.rs new file mode 100644 index 0000000000000..cf9f189ecc710 --- /dev/null +++ b/tests/rustdoc-html/deref/deref-on-aliased.rs @@ -0,0 +1,30 @@ +// Ensures that aliased types also get the "methods from deref" content. +// Regression test for . + +#![crate_name = "foo"] + +use std::ops::Deref; + +// First we check for the `Col` struct. +//@ has 'foo/struct.Col.html' +//@ has - '//*[@id="main-content"]//h2[@id="deref-methods-%5BT%5D"]' 'Methods from Deref' +//@ has - '//*[@id="rustdoc-toc"]//a[@href="#deref-methods-%5BT%5D"]' 'Methods from Deref' + +pub struct Col { + data: [T; N], +} + +// Then for the type alias. +//@ has 'foo/type.Mat.html' +//@ has - '//*[@id="main-content"]//h2[@id="deref-methods-%5BT%5D"]' 'Methods from Deref' +//@ has - '//*[@id="rustdoc-toc"]//a[@href="#deref-methods-%5BT%5D"]' 'Methods from Deref' + +pub type Mat = Col; + +impl Deref for Col { + type Target = [T]; + + fn deref(&self) -> &Self::Target { + &self.data + } +} diff --git a/tests/rustdoc-html/deref/not-mut-deref.rs b/tests/rustdoc-html/deref/not-mut-deref.rs new file mode 100644 index 0000000000000..02aac49e46935 --- /dev/null +++ b/tests/rustdoc-html/deref/not-mut-deref.rs @@ -0,0 +1,35 @@ +// This test ensures that `get_u32` is not listed as the `Deref` impl +// doesn't match it. +// Regression test for . + +#![crate_name = "foo"] + +//@ has 'foo/struct.Bar.html' +//@ count - '//*[@id="deref-methods-Foo%3Ci32%3E-1"]/*[@class="method"]' 1 +//@ has - '//*[@id="deref-methods-Foo%3Ci32%3E-1"]/*[@class="method"]/h4' \ +// 'pub fn get_i32(&self) -> i32' + +// Same check for the sidebar. +//@ count - '//*[@id="rustdoc-toc"]/*[@class="block deref-methods"]//a' 1 +//@ has - '//*[@id="rustdoc-toc"]/*[@class="block deref-methods"]//a' 'get_i32' + +use std::ops::Deref; + +pub struct Foo(T); + +impl Foo { + pub fn get_i32(&self) -> i32 { self.0 } +} + +impl Foo { + pub fn get_u32(&self) -> u32 { self.0 } +} + +pub struct Bar(Foo); + +impl Deref for Bar { + type Target = Foo; + fn deref(&self) -> &Foo { + &self.0 + } +} diff --git a/tests/rustdoc-html/typedef/deref-32077.rs b/tests/rustdoc-html/typedef/deref-32077.rs index faab4b6f522ba..5c6949936e43e 100644 --- a/tests/rustdoc-html/typedef/deref-32077.rs +++ b/tests/rustdoc-html/typedef/deref-32077.rs @@ -54,7 +54,7 @@ impl std::ops::Deref for GenericStruct { pub struct Wrap(GenericStruct); //@ has 'foo/type.Alias.html' -//@ !has - '//h2' 'Methods from Deref' +//@ has - '//h2' 'Methods from Deref' //@ !has - '//*[@id="impl-Deref-for-Wrap%3CT%3E"]/h3' 'impl Deref for Wrap' //@ hasraw 'type.impl/foo/struct.Wrap.js' 'impl-Deref-for-Wrap%3CT%3E' // Deref Methods aren't gathered for type aliases, though the actual impl is. diff --git a/tests/ui/attributes/z-crate-attr/ordering-cli.rs b/tests/ui/attributes/z-crate-attr/ordering-cli.rs new file mode 100644 index 0000000000000..877a25939b9f3 --- /dev/null +++ b/tests/ui/attributes/z-crate-attr/ordering-cli.rs @@ -0,0 +1,6 @@ +// Multiple `-Zcrate-attr` flags apply in command-line order, so the later `deny` wins. +//@ compile-flags: -Zcrate-attr=warn(unused) -Zcrate-attr=deny(unused) + +fn foo() {} //~ ERROR function `foo` is never used + +fn main() {} diff --git a/tests/ui/attributes/z-crate-attr/ordering-cli.stderr b/tests/ui/attributes/z-crate-attr/ordering-cli.stderr new file mode 100644 index 0000000000000..84c47716e62fb --- /dev/null +++ b/tests/ui/attributes/z-crate-attr/ordering-cli.stderr @@ -0,0 +1,15 @@ +error: function `foo` is never used + --> $DIR/ordering-cli.rs:4:4 + | +LL | fn foo() {} + | ^^^ + | +note: the lint level is defined here + --> :1:9 + | +LL | #![deny(unused)] + | ^^^^^^ + = note: `#[deny(dead_code)]` implied by `#[deny(unused)]` + +error: aborting due to 1 previous error + diff --git a/tests/ui/attributes/z-crate-attr/ordering-source.rs b/tests/ui/attributes/z-crate-attr/ordering-source.rs new file mode 100644 index 0000000000000..914851d3bb055 --- /dev/null +++ b/tests/ui/attributes/z-crate-attr/ordering-source.rs @@ -0,0 +1,9 @@ +// RFC 3791: `-Zcrate-attr` applies before the crate's own attributes, so `warn` here wins. +//@ check-pass +//@ compile-flags: -Zcrate-attr=deny(unused) + +#![warn(unused)] + +fn foo() {} //~ WARN function `foo` is never used + +fn main() {} diff --git a/tests/ui/attributes/z-crate-attr/ordering-source.stderr b/tests/ui/attributes/z-crate-attr/ordering-source.stderr new file mode 100644 index 0000000000000..66cf78738bf7c --- /dev/null +++ b/tests/ui/attributes/z-crate-attr/ordering-source.stderr @@ -0,0 +1,15 @@ +warning: function `foo` is never used + --> $DIR/ordering-source.rs:7:4 + | +LL | fn foo() {} + | ^^^ + | +note: the lint level is defined here + --> $DIR/ordering-source.rs:5:9 + | +LL | #![warn(unused)] + | ^^^^^^ + = note: `#[warn(dead_code)]` implied by `#[warn(unused)]` + +warning: 1 warning emitted + diff --git a/tests/ui/const-generics/issues/issue-86820.rs b/tests/ui/const-generics/issues/issue-86820.rs index c2c0c1a8d0390..51a160cb213b3 100644 --- a/tests/ui/const-generics/issues/issue-86820.rs +++ b/tests/ui/const-generics/issues/issue-86820.rs @@ -5,7 +5,7 @@ use std::ops::BitAnd; const C: fn() = || is_set(); fn is_set() { - 0xffu8.bit::<0>(); + Bits::bit::<0>(0xffu8); } trait Bits {