diff --git a/bootstrap.example.toml b/bootstrap.example.toml index 6740de03eb800..fd1dd589b5b79 100644 --- a/bootstrap.example.toml +++ b/bootstrap.example.toml @@ -474,9 +474,13 @@ # linked or not. #build.cargo-native-static = false -# Run the build with low priority, by setting the process group's "nice" value -# to +10 on Unix platforms, and by using a "low priority" job object on Windows. -#build.low-priority = false +# Run the build with low priority, by setting the process's "nice" value to +10 +# on Unix platforms, and by using a "low priority" job object on Windows. +# This will improve the responsiveness of foreground tasks and will not slow the +# build down unless there are competing CPU-saturating jobs, so there is +# typically no reason to opt out of this behavior. See the discussion in +# https://github.com/rust-lang/rust/pull/165707 for more details. +#build.low-priority = true # Arguments passed to the `./configure` script, used during distcheck. You # probably won't fill this in but rather it's filled in by the `./configure` diff --git a/compiler/rustc_const_eval/src/const_eval/intrinsics.rs b/compiler/rustc_const_eval/src/const_eval/intrinsics.rs new file mode 100644 index 0000000000000..db35a60967f37 --- /dev/null +++ b/compiler/rustc_const_eval/src/const_eval/intrinsics.rs @@ -0,0 +1,172 @@ +use rustc_abi::{Align, Size}; +use rustc_middle::ty::layout::{HasTypingEnv, ValidityRequirement}; +use rustc_middle::ty::{self, FieldInfo}; +use rustc_middle::{mir, throw_machine_stop}; +use rustc_span::{Symbol, bug, span_bug, sym}; + +use super::error::*; +use crate::const_eval::{CompileTimeMachine, MemoryKind}; +use crate::interpret::{ + self, AllocInit, CtfeProvenance, InterpCx, InterpResult, OpTy, PlaceTy, Scalar, + ensure_monomorphic_enough, err_inval, interp_ok, throw_ub_format, +}; + +impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { + pub(crate) fn call_ctfe_intrinsic( + &mut self, + intrinsic_name: Symbol, + instance: ty::Instance<'tcx>, + args: &[OpTy<'tcx>], + dest: &PlaceTy<'tcx, CtfeProvenance>, + target: Option, + ) -> InterpResult<'tcx, bool> { + match intrinsic_name { + sym::abort_immediate => { + // Note that `abort_immediate` is also hooked separately in Miri. + throw_machine_stop!(ConstEvalErrKind::Abort); + } + sym::ptr_guaranteed_cmp => { + let a = self.read_scalar(&args[0])?; + let b = self.read_scalar(&args[1])?; + let cmp = self.guaranteed_cmp(a, b)?; + self.write_scalar(Scalar::from_u8(cmp), dest)?; + } + sym::const_allocate => { + let size = self.read_scalar(&args[0])?.to_target_usize(self)?; + let align = self.read_scalar(&args[1])?.to_target_usize(self)?; + + let align = match Align::from_bytes(align) { + Ok(a) => a, + Err(err) => { + throw_ub_format!("invalid align passed to `const_allocate`: {err}") + } + }; + + let ptr = self.allocate_ptr( + Size::from_bytes(size), + align, + interpret::MemoryKind::Machine(MemoryKind::Heap { was_made_global: false }), + AllocInit::Uninit, + )?; + self.write_pointer(ptr, dest)?; + } + sym::const_deallocate => { + let ptr = self.read_pointer(&args[0])?; + let size = self.read_scalar(&args[1])?.to_target_usize(self)?; + let align = self.read_scalar(&args[2])?.to_target_usize(self)?; + + let size = Size::from_bytes(size); + let align = match Align::from_bytes(align) { + Ok(a) => a, + Err(err) => { + throw_ub_format!("invalid align passed to `const_deallocate`: {err}") + } + }; + + // If an allocation is created in an another const, + // we don't deallocate it. + let (alloc_id, _, _) = self.ptr_get_alloc_id(ptr, 0)?; + let is_allocated_in_another_const = matches!( + self.tcx.try_get_global_alloc(alloc_id), + Some(interpret::GlobalAlloc::Memory(_)) + ); + + if !is_allocated_in_another_const { + self.deallocate_ptr( + ptr, + Some((size, align)), + interpret::MemoryKind::Machine(MemoryKind::Heap { was_made_global: false }), + )?; + } + } + + sym::const_make_global => { + let ptr = self.read_pointer(&args[0])?; + self.make_const_heap_ptr_global(ptr)?; + self.write_pointer(ptr, dest)?; + } + + // The intrinsic represents whether the value is known to the optimizer (LLVM). + // We're not doing any optimizations here, so there is no optimizer that could know the value. + // (We know the value here in the machine of course, but this is the runtime of that code, + // not the optimization stage.) + sym::is_val_statically_known => self.write_scalar(Scalar::from_bool(false), dest)?, + + // We handle these here since Miri does not want to have them. + sym::assert_inhabited + | sym::assert_zero_valid + | sym::assert_mem_uninitialized_valid => { + let ty = instance.args.type_at(0); + let requirement = + ValidityRequirement::from_rustc_intrinsic(intrinsic_name).unwrap(); + + let should_panic = !self + .tcx + .check_validity_requirement((requirement, self.typing_env().as_query_input(ty))) + .map_err(|_| err_inval!(TooGeneric))?; + + if should_panic { + let layout = self.layout_of(ty)?; + + let msg = Symbol::intern(&match requirement { + // For *all* intrinsics we first check `is_uninhabited` to give a more specific + // error message. + _ if layout.is_uninhabited() => format!( + "aborted execution: attempted to instantiate uninhabited type `{ty}`" + ), + ValidityRequirement::Inhabited => bug!("handled earlier"), + ValidityRequirement::Zero => format!( + "aborted execution: attempted to zero-initialize type `{ty}`, which is invalid" + ), + ValidityRequirement::UninitMitigated0x01Fill => format!( + "aborted execution: attempted to leave type `{ty}` uninitialized, which is invalid" + ), + ValidityRequirement::Uninit => bug!("assert_uninit_valid doesn't exist"), + }); + + let span = self.caller_location(); + let (file, line, col) = self.location_triple_for_span(span); + + InterpResult::from(Err::<(), _>(ConstEvalErrKind::Panic { + msg, + file, + line, + col, + }))?; + + // Skip the `return_to_block` at the end (we panicked, we do not return). + return interp_ok(true); + } + } + + sym::field_offset => { + let frt_ty = instance.args.type_at(0); + ensure_monomorphic_enough(frt_ty)?; + + let (ty, variant, field) = if let ty::Adt(def, args) = frt_ty.kind() + && let Some(FieldInfo { base, variant_idx, field_idx, .. }) = + def.field_representing_type_info(self.tcx.tcx, *args) + { + (base, variant_idx, field_idx) + } else { + span_bug!(self.cur_span(), "expected field representing type, got {frt_ty}") + }; + let layout = self.layout_of(ty)?; + let cx = ty::layout::LayoutCx::new(self.tcx.tcx, self.typing_env()); + + let layout = layout.for_variant(&cx, variant); + let offset = layout.fields.offset(field.index()).bytes(); + + self.write_scalar(Scalar::from_target_usize(offset, self), dest)?; + } + + _ => { + return interp_ok(false); + } + } + + // Intrinsic is done, jump to next block. + self.return_to_block(target)?; + interp_ok(true) + } +} diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index fa9424f1d4dc1..49a48c539b670 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -2,32 +2,31 @@ use std::borrow::{Borrow, Cow}; use std::hash::Hash; use std::{fmt, mem}; -use rustc_abi::{Align, FIRST_VARIANT, FieldIdx, Size, VariantIdx}; +use rustc_abi::{Align, Size}; use rustc_ast::Mutability; +use rustc_attr_ir::find_attr; use rustc_attr_ir::lang_items::LangItem; -use rustc_attr_ir::{HasAttrs, find_attr}; use rustc_data_structures::fx::{FxHashMap, FxIndexMap, IndexEntry}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::{CRATE_HIR_ID, HirId}; use rustc_lint_defs::builtin::LONG_RUNNING_CONST_EVAL; +use rustc_middle::mir; use rustc_middle::mir::AssertMessage; use rustc_middle::mir::interpret::ReportedErrorInfo; use rustc_middle::query::TyCtxtAt; -use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, TyAndLayout, ValidityRequirement}; -use rustc_middle::ty::{self, FieldInfo, Intrinsic, ScalarInt, Ty, TyCtxt}; -use rustc_middle::{mir, throw_machine_stop}; -use rustc_span::{Span, Symbol, bug, span_bug, sym}; +use rustc_middle::ty::layout::{HasTypingEnv, TyAndLayout}; +use rustc_middle::ty::{self, Intrinsic, Ty, TyCtxt}; +use rustc_span::{Span, Symbol, bug, span_bug}; use rustc_target::callconv::FnAbi; use tracing::debug; use super::error::*; use crate::diagnostics::{LongRunning, LongRunningWarn}; use crate::interpret::{ - self, AllocId, AllocInit, AllocRange, ConstAllocation, CtfeProvenance, FnArg, Frame, - GlobalAlloc, ImmTy, Immediate, InterpCx, InterpResult, OpTy, PlaceTy, Pointer, RangeSet, - RetagMode, Scalar, compile_time_machine, ensure_monomorphic_enough, err_inval, interp_ok, - throw_exhaust, throw_inval, throw_ub, throw_ub_format, throw_unsup, throw_unsup_format, - type_implements_dyn_trait, + self, AllocId, AllocRange, ConstAllocation, CtfeProvenance, FnArg, Frame, GlobalAlloc, ImmTy, + InterpCx, InterpResult, OpTy, PlaceTy, Pointer, RangeSet, RetagMode, Scalar, + compile_time_machine, interp_ok, throw_exhaust, throw_inval, throw_ub, throw_unsup, + throw_unsup_format, }; /// When hitting this many interpreted terminators we emit a deny by default lint @@ -211,7 +210,7 @@ impl interpret::MayLeak for ! { } impl<'tcx> CompileTimeInterpCx<'tcx> { - fn location_triple_for_span(&self, span: Span) -> (Symbol, u32, u32) { + pub(crate) fn location_triple_for_span(&self, span: Span) -> (Symbol, u32, u32) { let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span); let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo()); @@ -278,7 +277,7 @@ impl<'tcx> CompileTimeInterpCx<'tcx> { /// /// Note that this intrinsic is exposed on stable for comparison with null. In other words, any /// change to this function that affects comparison with null is insta-stable! - fn guaranteed_cmp(&mut self, a: Scalar, b: Scalar) -> InterpResult<'tcx, u8> { + pub(crate) fn guaranteed_cmp(&mut self, a: Scalar, b: Scalar) -> InterpResult<'tcx, u8> { interp_ok(match (a, b) { // Comparisons between integers are always known. (Scalar::Int(a), Scalar::Int(b)) => (a == b) as u8, @@ -488,7 +487,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { } let intrinsic_name = ecx.tcx.intrinsic(instance.def_id()).unwrap().name; - let do_fallback = || { + let do_fallback = |ecx: &mut InterpCx<'tcx, Self>| { // We haven't handled the intrinsic, let's see if we can use a fallback body. if ecx.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden { throw_unsup_format!( @@ -504,538 +503,15 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { // Backend intrinsics are not supported in const eval except with their fallback // bodies. let Intrinsic::Rustc(intrinsic_name) = intrinsic_name else { - return do_fallback(); + return do_fallback(ecx); }; - // CTFE-specific intrinsics. - match intrinsic_name { - sym::abort_immediate => { - // Note that `abort_immediate` is also hooked separately in Miri. - throw_machine_stop!(ConstEvalErrKind::Abort); - } - sym::ptr_guaranteed_cmp => { - let a = ecx.read_scalar(&args[0])?; - let b = ecx.read_scalar(&args[1])?; - let cmp = ecx.guaranteed_cmp(a, b)?; - ecx.write_scalar(Scalar::from_u8(cmp), dest)?; - } - sym::const_allocate => { - let size = ecx.read_scalar(&args[0])?.to_target_usize(ecx)?; - let align = ecx.read_scalar(&args[1])?.to_target_usize(ecx)?; - - let align = match Align::from_bytes(align) { - Ok(a) => a, - Err(err) => { - throw_ub_format!("invalid align passed to `const_allocate`: {err}") - } - }; - - let ptr = ecx.allocate_ptr( - Size::from_bytes(size), - align, - interpret::MemoryKind::Machine(MemoryKind::Heap { was_made_global: false }), - AllocInit::Uninit, - )?; - ecx.write_pointer(ptr, dest)?; - } - sym::const_deallocate => { - let ptr = ecx.read_pointer(&args[0])?; - let size = ecx.read_scalar(&args[1])?.to_target_usize(ecx)?; - let align = ecx.read_scalar(&args[2])?.to_target_usize(ecx)?; - - let size = Size::from_bytes(size); - let align = match Align::from_bytes(align) { - Ok(a) => a, - Err(err) => { - throw_ub_format!("invalid align passed to `const_deallocate`: {err}") - } - }; - - // If an allocation is created in an another const, - // we don't deallocate it. - let (alloc_id, _, _) = ecx.ptr_get_alloc_id(ptr, 0)?; - let is_allocated_in_another_const = matches!( - ecx.tcx.try_get_global_alloc(alloc_id), - Some(interpret::GlobalAlloc::Memory(_)) - ); - - if !is_allocated_in_another_const { - ecx.deallocate_ptr( - ptr, - Some((size, align)), - interpret::MemoryKind::Machine(MemoryKind::Heap { was_made_global: false }), - )?; - } - } - - sym::const_make_global => { - let ptr = ecx.read_pointer(&args[0])?; - ecx.make_const_heap_ptr_global(ptr)?; - ecx.write_pointer(ptr, dest)?; - } - - // The intrinsic represents whether the value is known to the optimizer (LLVM). - // We're not doing any optimizations here, so there is no optimizer that could know the value. - // (We know the value here in the machine of course, but this is the runtime of that code, - // not the optimization stage.) - sym::is_val_statically_known => ecx.write_scalar(Scalar::from_bool(false), dest)?, - - // We handle these here since Miri does not want to have them. - sym::assert_inhabited - | sym::assert_zero_valid - | sym::assert_mem_uninitialized_valid => { - let ty = instance.args.type_at(0); - let requirement = - ValidityRequirement::from_rustc_intrinsic(intrinsic_name).unwrap(); - - let should_panic = !ecx - .tcx - .check_validity_requirement((requirement, ecx.typing_env().as_query_input(ty))) - .map_err(|_| err_inval!(TooGeneric))?; - - if should_panic { - let layout = ecx.layout_of(ty)?; - - let msg = match requirement { - // For *all* intrinsics we first check `is_uninhabited` to give a more specific - // error message. - _ if layout.is_uninhabited() => format!( - "aborted execution: attempted to instantiate uninhabited type `{ty}`" - ), - ValidityRequirement::Inhabited => bug!("handled earlier"), - ValidityRequirement::Zero => format!( - "aborted execution: attempted to zero-initialize type `{ty}`, which is invalid" - ), - ValidityRequirement::UninitMitigated0x01Fill => format!( - "aborted execution: attempted to leave type `{ty}` uninitialized, which is invalid" - ), - ValidityRequirement::Uninit => bug!("assert_uninit_valid doesn't exist"), - }; - - Self::panic_nounwind(ecx, &msg)?; - // Skip the `return_to_block` at the end (we panicked, we do not return). - return interp_ok(None); - } - } - - sym::type_id_vtable => { - let tp_ty = ecx.read_type_id(&args[0])?; - let result_ty = ecx.read_type_id(&args[1])?; - - let (implements_trait, preds) = type_implements_dyn_trait(ecx, tp_ty, result_ty)?; - - if implements_trait { - let vtable_ptr = ecx.get_vtable_ptr(tp_ty, preds)?; - // Writing a non-null pointer into an `Option` will automatically make it `Some`. - ecx.write_pointer(vtable_ptr, dest)?; - } else { - // Write `None` - ecx.write_discriminant(FIRST_VARIANT, dest)?; - } - } - - sym::type_id_type_of => { - let ty = ecx.read_type_id(&args[0])?; - ecx.write_type_kind(ty, dest)?; - } - - sym::type_id_is_signed => { - let ty = ecx.read_type_id(&args[0])?; - ecx.write_scalar(Scalar::from_bool(ty.is_signed()), dest)?; - } - - sym::type_id_points_mutably => { - let ty = ecx.read_type_id(&args[0])?; - let is_mutable = matches!( - ty.kind(), - ty::RawPtr(_, Mutability::Mut) | &ty::Ref(_, _, Mutability::Mut) - ); - ecx.write_scalar(Scalar::from_bool(is_mutable), dest)?; - } - - sym::type_id_size_of => { - let ty = ecx.read_type_id(&args[0])?; - let layout = ecx.layout_of(ty)?; - - ecx.write_option(layout.is_sized().then(|| ()), dest, |ecx, field, _| { - ecx.write_scalar( - ScalarInt::try_from_target_usize(layout.size.bytes(), ecx.tcx.tcx).unwrap(), - &field, - ) - })? - } - - sym::type_id_element_ty => { - let ty = ecx.read_type_id(&args[0])?; - - ecx.write_option( - match ty.kind() { - ty::Array(ty, _) | ty::Slice(ty) => Some(ty), - _ => None, - }, - dest, - |ecx, place, ty| ecx.write_type_id(*ty, &place), - )? - } - - sym::type_id_array_len => { - let ty = ecx.read_type_id(&args[0])?; - let len = if let ty::Array(_, len) = ty.kind() { - len.to_leaf().to_target_usize(ecx.tcx.tcx()) - } else { - 0 - }; - ecx.write_scalar(Scalar::from_target_usize(len, ecx), dest)?; - } - - sym::type_id_fields => { - let ty = ecx.read_type_id(&args[0])?; - let variant_idx = ecx.read_target_usize(&args[1])? as usize; - - let variants_num = - ty.ty_adt_def().map(|adt_def| adt_def.variants().len()).unwrap_or(1); - if variant_idx >= variants_num { - throw_ub!(BoundsCheckFailed { - len: variants_num as u64, - index: variant_idx as u64 - }); - } - - let fields_num = match ty.kind() { - ty::Adt(adt_def, _) => { - let variant_def = &adt_def.variants()[VariantIdx::from_usize(variant_idx)]; - variant_def.fields.len() - } - ty::Tuple(fields) => fields.len(), - _ => 0, // Other types have no fields - }; - - ecx.write_scalar(Scalar::from_target_usize(fields_num as u64, ecx), dest)?; - } - - sym::type_id_field_representing_type => { - let ty = ecx.read_type_id(&args[0])?; - let variant_idx = ecx.read_target_usize(&args[1])? as usize; - let field_idx = ecx.read_target_usize(&args[2])? as usize; - - let variants_num = - ty.ty_adt_def().map(|adt_def| adt_def.variants().len()).unwrap_or(1); - if variant_idx >= variants_num { - throw_ub!(BoundsCheckFailed { - len: variants_num as u64, - index: variant_idx as u64 - }); - } - - let fields_num = match ty.kind() { - ty::Adt(adt_def, _) => { - let variant_def = &adt_def.variants()[VariantIdx::from_usize(variant_idx)]; - variant_def.fields.len() - } - ty::Tuple(fields) => fields.len(), - _ => 0, // Other types have no fields - }; - if field_idx >= fields_num { - throw_ub!(BoundsCheckFailed { - len: fields_num as u64, - index: field_idx as u64 - }); - } - - let frt = Ty::new_field_representing_type( - *ecx.tcx, - ty, - VariantIdx::from_usize(variant_idx), - FieldIdx::from_usize(field_idx), - ); - ecx.write_type_id(frt, dest)?; - } - sym::type_id_function_ptr => { - let ty = ecx.read_type_id(&args[0])?; - - ecx.write_option( - match ty.kind() { - ty::FnPtr(sig, fn_header) => Some((sig, fn_header)), - _ => None, - }, - dest, - |ecx, place, (sig, fn_header)| { - let sig = sig.skip_binder(); // FIXME: handle lifetime bounds - ecx.write_fn_ptr_type_info(place, &sig, fn_header) - }, - )? - } - sym::type_id_dyn_trait => { - let ty: Ty<'tcx> = ecx.read_type_id(&args[0])?; - ecx.write_option( - match ty.kind() { - ty::Dynamic(p, r) => Some((p, r)), - _ => None, - }, - dest, - |ecx, place, (p, r)| ecx.write_dyn_trait_type_info(place, *p, *r), - )? - } - sym::type_id_points_to => { - let ty = ecx.read_type_id(&args[0])?; - ecx.write_option( - match ty.kind() { - ty::RawPtr(pointee_ty, _) | ty::Ref(_, pointee_ty, _) => Some(pointee_ty), - _ => None, - }, - dest, - |ecx, place, pointee_ty| ecx.write_type_id(*pointee_ty, &place), - )? - } - - sym::type_id_variants => { - let ty = ecx.read_type_id(&args[0])?; - let variants_num = ty.ty_adt_def().map(|def| def.variants().len()).unwrap_or(1); - ecx.write_scalar(Scalar::from_target_usize(variants_num as u64, ecx), dest)?; - } - - sym::type_id_variant_name => { - let base = ecx.read_type_id(&args[0])?; - - let field_name = if let ty::Adt(def, _) = base.kind() { - let variant_idx = ecx.read_target_usize(&args[1])? as usize; - if variant_idx >= def.variants().len() { - throw_ub!(BoundsCheckFailed { - len: def.variants().len() as u64, - index: variant_idx as u64 - }); - } - let variant_idx = VariantIdx::from_usize(variant_idx); - def.variant(variant_idx).name - } else { - span_bug!(ecx.cur_span(), "expected enum type, got {base}") - }; - let ptr = ecx.allocate_bytes_dedup(field_name.as_str().as_bytes())?; - ecx.write_immediate( - Immediate::ScalarPair( - Scalar::from_pointer(ptr, ecx), - Scalar::from_target_usize(field_name.as_str().len() as u64, ecx), - ), - dest, - )?; - } - - sym::type_id_variant_reflected_attrs => { - let base = ecx.read_type_id(&args[0])?; - - if let ty::Adt(def, _) = base.kind() { - let variant_idx = ecx.read_target_usize(&args[1])? as usize; - if variant_idx >= def.variants().len() { - throw_ub!(BoundsCheckFailed { - len: def.variants().len() as u64, - index: variant_idx as u64 - }); - } - let variant_idx = VariantIdx::from_usize(variant_idx); - - ecx.write_reflect_attributes( - dest, - def.variant(variant_idx).def_id.get_attrs(&ecx.tcx), - )?; - } else { - span_bug!(ecx.cur_span(), "expected enum type, got {base}") - }; - } - - sym::type_id_docs => { - let ty = ecx.read_type_id(&args[0])?; - let attrs = match ty.kind() { - ty::Adt(def, args) - if let Some(FieldInfo { base, variant_idx, field_idx, .. }) = - def.field_representing_type_info(ecx.tcx(), *args) => - { - match base.kind() { - ty::Adt(base_def, _) => { - let field = &base_def.variants()[variant_idx].fields[field_idx]; - Some(field.did) - } - ty::Tuple(_) => None, - _ => { - // only adts and tuples have fields - span_bug!(ecx.cur_span(), "expected adt or tuple type, got {ty}"); - } - } - } - ty::Adt(def, _) => Some(def.did()), - _ => None, - }; - - ecx.write_doc_attributes(dest, attrs)?; - } - - sym::type_id_variant_docs => { - let base = ecx.read_type_id(&args[0])?; - - if let ty::Adt(def, _) = base.kind() { - let variant_idx = ecx.read_target_usize(&args[1])? as usize; - if variant_idx >= def.variants().len() { - throw_ub!(BoundsCheckFailed { - len: def.variants().len() as u64, - index: variant_idx as u64 - }); - } - let var = def.variant(VariantIdx::from_usize(variant_idx)).def_id; - ecx.write_doc_attributes(dest, Some(var))?; - } else { - span_bug!(ecx.cur_span(), "expected enum type, got {base}") - }; - } - - sym::type_id_variant_non_exhaustive => { - let base = ecx.read_type_id(&args[0])?; - - let non_exhaustive = if let ty::Adt(def, _) = base.kind() { - let variant_idx = ecx.read_target_usize(&args[1])? as usize; - if variant_idx >= def.variants().len() { - throw_ub!(BoundsCheckFailed { - len: def.variants().len() as u64, - index: variant_idx as u64 - }); - } - let variant_idx = VariantIdx::from_usize(variant_idx); - def.variant(variant_idx).is_field_list_non_exhaustive() - } else { - span_bug!(ecx.cur_span(), "expected enum type, got {base}") - }; - ecx.write_scalar(Scalar::from_bool(non_exhaustive), dest)?; - } - - sym::field_offset => { - let frt_ty = instance.args.type_at(0); - ensure_monomorphic_enough(frt_ty)?; - - let (ty, variant, field) = if let ty::Adt(def, args) = frt_ty.kind() - && let Some(FieldInfo { base, variant_idx, field_idx, .. }) = - def.field_representing_type_info(ecx.tcx.tcx, *args) - { - (base, variant_idx, field_idx) - } else { - span_bug!(ecx.cur_span(), "expected field representing type, got {frt_ty}") - }; - let layout = ecx.layout_of(ty)?; - let cx = ty::layout::LayoutCx::new(ecx.tcx.tcx, ecx.typing_env()); - - let layout = layout.for_variant(&cx, variant); - let offset = layout.fields.offset(field.index()).bytes(); - - ecx.write_scalar(Scalar::from_target_usize(offset, ecx), dest)?; - } - - sym::field_representing_type_name => { - let frt_ty = ecx.read_type_id(&args[0])?; - - let field_name = if let ty::Adt(def, args) = frt_ty.kind() - && let Some(FieldInfo { name, .. }) = - def.field_representing_type_info(ecx.tcx.tcx, *args) - { - name - } else { - span_bug!(ecx.cur_span(), "expected field representing type, got {frt_ty}") - }; - let ptr = ecx.allocate_bytes_dedup(field_name.as_str().as_bytes())?; - ecx.write_immediate( - Immediate::ScalarPair( - Scalar::from_pointer(ptr, ecx), - Scalar::from_target_usize(field_name.as_str().len() as u64, ecx), - ), - dest, - )?; - } - - sym::field_representing_type_offset => { - let frt_ty = ecx.read_type_id(&args[0])?; - - let (ty, variant, field) = if let ty::Adt(def, args) = frt_ty.kind() - && let Some(FieldInfo { base, variant_idx, field_idx, .. }) = - def.field_representing_type_info(ecx.tcx.tcx, *args) - { - (base, variant_idx, field_idx) - } else { - span_bug!(ecx.cur_span(), "expected field representing type, got {frt_ty}") - }; - let layout = ecx.layout_of(ty)?; - let cx = ty::layout::LayoutCx::new(ecx.tcx.tcx, ecx.typing_env()); - - let layout = layout.for_variant(&cx, variant); - let offset = layout.fields.offset(field.index()).bytes(); - - ecx.write_scalar(Scalar::from_target_usize(offset, ecx), dest)?; - } - - sym::field_representing_type_actual_type_id => { - let frt_ty = ecx.read_type_id(&args[0])?; - - let field_ty = if let ty::Adt(def, args) = frt_ty.kind() - && let Some(FieldInfo { ty, .. }) = - def.field_representing_type_info(ecx.tcx.tcx, *args) - { - ecx.tcx.erase_and_anonymize_regions(ty) - } else { - span_bug!(ecx.cur_span(), "expected field representing type, got {frt_ty}") - }; - ecx.write_type_id(field_ty, dest)?; - } - - sym::type_id_reflected_attrs => { - let ty = ecx.read_type_id(&args[0])?; - let attrs = match ty.kind() { - ty::Adt(def, args) - if let Some(FieldInfo { base, variant_idx, field_idx, .. }) = - def.field_representing_type_info(ecx.tcx(), *args) => - { - match base.kind() { - ty::Adt(base_def, _) => { - let field = &base_def.variants()[variant_idx].fields[field_idx]; - field.did.get_attrs(&ecx.tcx) - } - ty::Tuple(_) => &[], - _ => { - // only adts and tuples have fields - span_bug!(ecx.cur_span(), "expected adt or tuple type, got {ty}"); - } - } - } - ty::Adt(def, _) => def.did().get_attrs(&ecx.tcx), - _ => &[], - }; - - ecx.write_reflect_attributes(dest, attrs)?; - } - - sym::type_id_generics => { - let ty = ecx.read_type_id(&args[0])?; - ecx.write_type_id_generics(dest, ty)?; - } - - sym::type_id_non_exhaustive => { - let ty = ecx.read_type_id(&args[0])?; - - // FIXME(reflection): need a way to obtain non-exhaustiveness of a variant's fields. - let non_exhaustive = if let ty::Adt(def, _) = ty.kind() { - if def.is_enum() { - def.is_variant_list_non_exhaustive() - } else { - def.non_enum_variant().is_field_list_non_exhaustive() - } - } else { - false - }; - - ecx.write_scalar(Scalar::from_bool(non_exhaustive), dest)?; - } - - _ => { - return do_fallback(); - } + if !ecx.call_type_info_intrinsic(intrinsic_name, instance, args, dest, target)? + && !ecx.call_ctfe_intrinsic(intrinsic_name, instance, args, dest, target)? + { + return do_fallback(ecx); } - // Intrinsic is done, jump to next block. - ecx.return_to_block(target)?; interp_ok(None) } diff --git a/compiler/rustc_const_eval/src/const_eval/mod.rs b/compiler/rustc_const_eval/src/const_eval/mod.rs index 58b8418707eff..bf238c7719a0c 100644 --- a/compiler/rustc_const_eval/src/const_eval/mod.rs +++ b/compiler/rustc_const_eval/src/const_eval/mod.rs @@ -13,6 +13,7 @@ mod dyn_trait; mod error; mod eval_queries; mod fn_queries; +mod intrinsics; mod machine; mod type_info; mod valtrees; diff --git a/compiler/rustc_const_eval/src/const_eval/type_info.rs b/compiler/rustc_const_eval/src/const_eval/type_info.rs index fc2f7f3c5ac5c..b3f15f410861f 100644 --- a/compiler/rustc_const_eval/src/const_eval/type_info.rs +++ b/compiler/rustc_const_eval/src/const_eval/type_info.rs @@ -1,4 +1,5 @@ mod adt; +mod intrinsics; use rustc_abi::{ExternAbi, FieldIdx}; use rustc_attr_ir::Attribute::Tool; diff --git a/compiler/rustc_const_eval/src/const_eval/type_info/intrinsics.rs b/compiler/rustc_const_eval/src/const_eval/type_info/intrinsics.rs new file mode 100644 index 0000000000000..081d6715dd1d1 --- /dev/null +++ b/compiler/rustc_const_eval/src/const_eval/type_info/intrinsics.rs @@ -0,0 +1,424 @@ +use rustc_abi::{FIRST_VARIANT, FieldIdx, VariantIdx}; +use rustc_ast::Mutability; +use rustc_attr_ir::HasAttrs; +use rustc_middle::mir; +use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv}; +use rustc_middle::ty::{self, FieldInfo, ScalarInt, Ty}; +use rustc_span::{Symbol, span_bug, sym}; + +use crate::const_eval::CompileTimeMachine; +use crate::interpret::{ + CtfeProvenance, Immediate, InterpCx, InterpResult, OpTy, PlaceTy, Scalar, interp_ok, throw_ub, + type_implements_dyn_trait, +}; + +impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { + /// intrinsics related to type_info + pub(crate) fn call_type_info_intrinsic( + &mut self, + intrinsic_name: Symbol, + _instance: ty::Instance<'tcx>, + args: &[OpTy<'tcx>], + dest: &PlaceTy<'tcx, CtfeProvenance>, + target: Option, + ) -> InterpResult<'tcx, bool> { + match intrinsic_name { + sym::type_id_vtable => { + let tp_ty = self.read_type_id(&args[0])?; + let result_ty = self.read_type_id(&args[1])?; + + let (implements_trait, preds) = type_implements_dyn_trait(self, tp_ty, result_ty)?; + + if implements_trait { + let vtable_ptr = self.get_vtable_ptr(tp_ty, preds)?; + // Writing a non-null pointer into an `Option` will automatically make it `Some`. + self.write_pointer(vtable_ptr, dest)?; + } else { + // Write `None` + self.write_discriminant(FIRST_VARIANT, dest)?; + } + } + + sym::type_id_type_of => { + let ty = self.read_type_id(&args[0])?; + self.write_type_kind(ty, dest)?; + } + + sym::type_id_is_signed => { + let ty = self.read_type_id(&args[0])?; + self.write_scalar(Scalar::from_bool(ty.is_signed()), dest)?; + } + + sym::type_id_points_mutably => { + let ty: Ty<'tcx> = self.read_type_id(&args[0])?; + let is_mutable = matches!( + ty.kind(), + ty::RawPtr(_, Mutability::Mut) | &ty::Ref(_, _, Mutability::Mut) + ); + self.write_scalar(Scalar::from_bool(is_mutable), dest)?; + } + + sym::type_id_size_of => { + let ty = self.read_type_id(&args[0])?; + let layout = self.layout_of(ty)?; + + self.write_option(layout.is_sized().then(|| ()), dest, |ecx, field, _| { + ecx.write_scalar( + ScalarInt::try_from_target_usize(layout.size.bytes(), ecx.tcx.tcx).unwrap(), + &field, + ) + })? + } + + sym::type_id_element_ty => { + let ty = self.read_type_id(&args[0])?; + + self.write_option( + match ty.kind() { + ty::Array(ty, _) | ty::Slice(ty) => Some(ty), + _ => None, + }, + dest, + |ecx, place, ty| ecx.write_type_id(*ty, &place), + )? + } + + sym::type_id_array_len => { + let ty = self.read_type_id(&args[0])?; + let len = if let ty::Array(_, len) = ty.kind() { + len.to_leaf().to_target_usize(self.tcx.tcx()) + } else { + 0 + }; + self.write_scalar(Scalar::from_target_usize(len, self), dest)?; + } + + sym::type_id_fields => { + let ty = self.read_type_id(&args[0])?; + let variant_idx = self.read_target_usize(&args[1])? as usize; + + let variants_num = + ty.ty_adt_def().map(|adt_def| adt_def.variants().len()).unwrap_or(1); + if variant_idx >= variants_num { + throw_ub!(BoundsCheckFailed { + len: variants_num as u64, + index: variant_idx as u64 + }); + } + + let fields_num = match ty.kind() { + ty::Adt(adt_def, _) => { + let variant_def = &adt_def.variants()[VariantIdx::from_usize(variant_idx)]; + variant_def.fields.len() + } + ty::Tuple(fields) => fields.len(), + _ => 0, // Other types have no fields + }; + + self.write_scalar(Scalar::from_target_usize(fields_num as u64, self), dest)?; + } + + sym::type_id_field_representing_type => { + let ty = self.read_type_id(&args[0])?; + let variant_idx = self.read_target_usize(&args[1])? as usize; + let field_idx = self.read_target_usize(&args[2])? as usize; + + let variants_num = + ty.ty_adt_def().map(|adt_def| adt_def.variants().len()).unwrap_or(1); + if variant_idx >= variants_num { + throw_ub!(BoundsCheckFailed { + len: variants_num as u64, + index: variant_idx as u64 + }); + } + + let fields_num = match ty.kind() { + ty::Adt(adt_def, _) => { + let variant_def = &adt_def.variants()[VariantIdx::from_usize(variant_idx)]; + variant_def.fields.len() + } + ty::Tuple(fields) => fields.len(), + _ => 0, // Other types have no fields + }; + if field_idx >= fields_num { + throw_ub!(BoundsCheckFailed { + len: fields_num as u64, + index: field_idx as u64 + }); + } + + let frt = Ty::new_field_representing_type( + *self.tcx, + ty, + VariantIdx::from_usize(variant_idx), + FieldIdx::from_usize(field_idx), + ); + self.write_type_id(frt, dest)?; + } + + sym::type_id_function_ptr => { + let ty = self.read_type_id(&args[0])?; + + self.write_option( + match ty.kind() { + ty::FnPtr(sig, fn_header) => Some((sig, fn_header)), + _ => None, + }, + dest, + |ecx, place, (sig, fn_header)| { + let sig = sig.skip_binder(); // FIXME: handle lifetime bounds + ecx.write_fn_ptr_type_info(place, &sig, fn_header) + }, + )? + } + + sym::type_id_dyn_trait => { + let ty: Ty<'tcx> = self.read_type_id(&args[0])?; + self.write_option( + match ty.kind() { + ty::Dynamic(p, r) => Some((p, r)), + _ => None, + }, + dest, + |ecx, place, (p, r)| ecx.write_dyn_trait_type_info(place, *p, *r), + )? + } + + sym::type_id_points_to => { + let ty = self.read_type_id(&args[0])?; + self.write_option( + match ty.kind() { + ty::RawPtr(pointee_ty, _) | ty::Ref(_, pointee_ty, _) => Some(pointee_ty), + _ => None, + }, + dest, + |ecx, place, pointee_ty| ecx.write_type_id(*pointee_ty, &place), + )? + } + + sym::type_id_variants => { + let ty = self.read_type_id(&args[0])?; + let variants_num = ty.ty_adt_def().map(|def| def.variants().len()).unwrap_or(1); + self.write_scalar(Scalar::from_target_usize(variants_num as u64, self), dest)?; + } + + sym::type_id_variant_name => { + let base = self.read_type_id(&args[0])?; + + let field_name = if let ty::Adt(def, _) = base.kind() { + let variant_idx = self.read_target_usize(&args[1])? as usize; + if variant_idx >= def.variants().len() { + throw_ub!(BoundsCheckFailed { + len: def.variants().len() as u64, + index: variant_idx as u64 + }); + } + let variant_idx = VariantIdx::from_usize(variant_idx); + def.variant(variant_idx).name + } else { + span_bug!(self.cur_span(), "expected enum type, got {base}") + }; + let ptr = self.allocate_bytes_dedup(field_name.as_str().as_bytes())?; + self.write_immediate( + Immediate::ScalarPair( + Scalar::from_pointer(ptr, self), + Scalar::from_target_usize(field_name.as_str().len() as u64, self), + ), + dest, + )?; + } + + sym::type_id_variant_reflected_attrs => { + let base = self.read_type_id(&args[0])?; + + if let ty::Adt(def, _) = base.kind() { + let variant_idx = self.read_target_usize(&args[1])? as usize; + if variant_idx >= def.variants().len() { + throw_ub!(BoundsCheckFailed { + len: def.variants().len() as u64, + index: variant_idx as u64 + }); + } + let variant_idx = VariantIdx::from_usize(variant_idx); + + self.write_reflect_attributes( + dest, + def.variant(variant_idx).def_id.get_attrs(&self.tcx), + )?; + } else { + span_bug!(self.cur_span(), "expected enum type, got {base}") + }; + } + + sym::type_id_variant_non_exhaustive => { + let base = self.read_type_id(&args[0])?; + + let non_exhaustive = if let ty::Adt(def, _) = base.kind() { + let variant_idx = self.read_target_usize(&args[1])? as usize; + if variant_idx >= def.variants().len() { + throw_ub!(BoundsCheckFailed { + len: def.variants().len() as u64, + index: variant_idx as u64 + }); + } + let variant_idx = VariantIdx::from_usize(variant_idx); + def.variant(variant_idx).is_field_list_non_exhaustive() + } else { + span_bug!(self.cur_span(), "expected enum type, got {base}") + }; + self.write_scalar(Scalar::from_bool(non_exhaustive), dest)?; + } + + sym::field_representing_type_name => { + let frt_ty = self.read_type_id(&args[0])?; + + let field_name = if let ty::Adt(def, args) = frt_ty.kind() + && let Some(FieldInfo { name, .. }) = + def.field_representing_type_info(self.tcx.tcx, *args) + { + name + } else { + span_bug!(self.cur_span(), "expected field representing type, got {frt_ty}") + }; + let ptr = self.allocate_bytes_dedup(field_name.as_str().as_bytes())?; + self.write_immediate( + Immediate::ScalarPair( + Scalar::from_pointer(ptr, self), + Scalar::from_target_usize(field_name.as_str().len() as u64, self), + ), + dest, + )?; + } + + sym::field_representing_type_offset => { + let frt_ty = self.read_type_id(&args[0])?; + + let (ty, variant, field) = if let ty::Adt(def, args) = frt_ty.kind() + && let Some(FieldInfo { base, variant_idx, field_idx, .. }) = + def.field_representing_type_info(self.tcx.tcx, *args) + { + (base, variant_idx, field_idx) + } else { + span_bug!(self.cur_span(), "expected field representing type, got {frt_ty}") + }; + let layout = self.layout_of(ty)?; + let cx = ty::layout::LayoutCx::new(self.tcx.tcx, self.typing_env()); + + let layout = layout.for_variant(&cx, variant); + let offset = layout.fields.offset(field.index()).bytes(); + + self.write_scalar(Scalar::from_target_usize(offset, self), dest)?; + } + + sym::field_representing_type_actual_type_id => { + let frt_ty = self.read_type_id(&args[0])?; + + let field_ty = if let ty::Adt(def, args) = frt_ty.kind() + && let Some(FieldInfo { ty, .. }) = + def.field_representing_type_info(self.tcx.tcx, *args) + { + self.tcx.erase_and_anonymize_regions(ty) + } else { + span_bug!(self.cur_span(), "expected field representing type, got {frt_ty}") + }; + self.write_type_id(field_ty, dest)?; + } + + sym::type_id_reflected_attrs => { + let ty = self.read_type_id(&args[0])?; + let attrs = match ty.kind() { + ty::Adt(def, args) + if let Some(FieldInfo { base, variant_idx, field_idx, .. }) = + def.field_representing_type_info(self.tcx(), *args) => + { + match base.kind() { + ty::Adt(base_def, _) => { + let field = &base_def.variants()[variant_idx].fields[field_idx]; + field.did.get_attrs(&self.tcx) + } + ty::Tuple(_) => &[], + _ => { + // only adts and tuples have fields + span_bug!(self.cur_span(), "expected adt or tuple type, got {ty}"); + } + } + } + ty::Adt(def, _) => def.did().get_attrs(&self.tcx), + _ => &[], + }; + + self.write_reflect_attributes(dest, attrs)?; + } + + sym::type_id_docs => { + let ty = self.read_type_id(&args[0])?; + let attrs = match ty.kind() { + ty::Adt(def, args) + if let Some(FieldInfo { base, variant_idx, field_idx, .. }) = + def.field_representing_type_info(self.tcx(), *args) => + { + match base.kind() { + ty::Adt(base_def, _) => { + let field = &base_def.variants()[variant_idx].fields[field_idx]; + Some(field.did) + } + ty::Tuple(_) => None, + _ => { + // only adts and tuples have fields + span_bug!(self.cur_span(), "expected adt or tuple type, got {ty}"); + } + } + } + ty::Adt(def, _) => Some(def.did()), + _ => None, + }; + + self.write_doc_attributes(dest, attrs)?; + } + + sym::type_id_variant_docs => { + let base = self.read_type_id(&args[0])?; + + if let ty::Adt(def, _) = base.kind() { + let variant_idx = self.read_target_usize(&args[1])? as usize; + if variant_idx >= def.variants().len() { + throw_ub!(BoundsCheckFailed { + len: def.variants().len() as u64, + index: variant_idx as u64 + }); + } + let var = def.variant(VariantIdx::from_usize(variant_idx)).def_id; + self.write_doc_attributes(dest, Some(var))?; + } else { + span_bug!(self.cur_span(), "expected enum type, got {base}") + }; + } + + sym::type_id_generics => { + let ty = self.read_type_id(&args[0])?; + self.write_type_id_generics(dest, ty)?; + } + + sym::type_id_non_exhaustive => { + let ty = self.read_type_id(&args[0])?; + + // FIXME(reflection): need a way to obtain non-exhaustiveness of a variant's fields. + let non_exhaustive = if let ty::Adt(def, _) = ty.kind() { + if def.is_enum() { + def.is_variant_list_non_exhaustive() + } else { + def.non_enum_variant().is_field_list_non_exhaustive() + } + } else { + false + }; + + self.write_scalar(Scalar::from_bool(non_exhaustive), dest)?; + } + _ => return interp_ok(false), + } + + self.return_to_block(target)?; + interp_ok(true) + } +} diff --git a/library/std/src/sys/pal/unix/stack_overflow/handler_cygwin.rs b/library/std/src/sys/pal/unix/stack_overflow/handler_cygwin.rs index 3289efe05b068..80cd34e9a8576 100644 --- a/library/std/src/sys/pal/unix/stack_overflow/handler_cygwin.rs +++ b/library/std/src/sys/pal/unix/stack_overflow/handler_cygwin.rs @@ -71,10 +71,8 @@ pub unsafe fn init() { reserve_stack(); } -pub fn make_handler(main_thread: bool) -> super::Handler { - if !main_thread { - reserve_stack(); - } +pub fn make_handler() -> super::Handler { + reserve_stack(); super::Handler::null() } diff --git a/library/std/src/sys/pal/unix/stack_overflow/handler_none.rs b/library/std/src/sys/pal/unix/stack_overflow/handler_none.rs index a0e2dfa941867..fd9d5fc7fa281 100644 --- a/library/std/src/sys/pal/unix/stack_overflow/handler_none.rs +++ b/library/std/src/sys/pal/unix/stack_overflow/handler_none.rs @@ -1,6 +1,6 @@ pub unsafe fn init() {} -pub fn make_handler(_main_thread: bool) -> super::Handler { +pub fn make_handler() -> super::Handler { super::Handler::null() } diff --git a/library/std/src/sys/pal/unix/stack_overflow/handler_signal.rs b/library/std/src/sys/pal/unix/stack_overflow/handler_signal.rs index ba81ca1e15bf9..fa8c588254fc2 100644 --- a/library/std/src/sys/pal/unix/stack_overflow/handler_signal.rs +++ b/library/std/src/sys/pal/unix/stack_overflow/handler_signal.rs @@ -126,7 +126,7 @@ pub unsafe fn init() { if !NEED_ALTSTACK.load(Ordering::Relaxed) { // haven't set up our sigaltstack yet NEED_ALTSTACK.store(true, Ordering::Release); - let handler = make_handler(true); + let handler = install_sigaltstack(); MAIN_ALTSTACK.store(handler.data, Ordering::Relaxed); mem::forget(handler); @@ -147,6 +147,18 @@ pub unsafe fn init() { } } +pub fn make_handler() -> Handler { + if cfg!(panic = "immediate-abort") || !NEED_ALTSTACK.load(Ordering::Acquire) { + return Handler::null(); + } + + if let Some(guard_page_range) = current_guard() { + set_current_info(guard_page_range); + } + + install_sigaltstack() +} + fn get_stack() -> libc::stack_t { // OpenBSD requires this flag for stack mapping // otherwise the said mapping will fail as a no-op on most systems @@ -189,17 +201,7 @@ fn get_stack() -> libc::stack_t { libc::stack_t { ss_sp: stackp, ss_flags: 0, ss_size: sigstack_size } } -pub fn make_handler(main_thread: bool) -> Handler { - if cfg!(panic = "immediate-abort") || !NEED_ALTSTACK.load(Ordering::Acquire) { - return Handler::null(); - } - - if !main_thread { - if let Some(guard_page_range) = current_guard() { - set_current_info(guard_page_range); - } - } - +fn install_sigaltstack() -> Handler { // Load the current alternate signal stack to see if we need to install // our own. // @@ -235,6 +237,12 @@ pub fn make_handler(main_thread: bool) -> Handler { /// Must only be called with a pointer returned by `make_handler`, and only /// once per `Handler`. pub unsafe fn drop_handler(data: *mut libc::c_void) { + if cfg!(panic = "immediate-abort") || !NEED_ALTSTACK.load(Ordering::Relaxed) { + debug_assert!(data.is_null()); + // Skip the thread-info-store access below. + return; + } + if !data.is_null() { let sigstack_size = sigstack_size(); let page_size = PAGE_SIZE.load(Ordering::Relaxed); @@ -266,6 +274,9 @@ pub unsafe fn drop_handler(data: *mut libc::c_void) { unsafe { munmap(data.sub(page_size), sigstack_size + page_size) }; } + // `make_handler` inserts the current thread's info into the store even if + // there is already a signal stack in place, so this cannot be conditional + // on `data`. delete_current_info(); } diff --git a/library/std/src/sys/pal/unix/stack_overflow/mod.rs b/library/std/src/sys/pal/unix/stack_overflow/mod.rs index dfd9e006353d2..50d6b7df4be2c 100644 --- a/library/std/src/sys/pal/unix/stack_overflow/mod.rs +++ b/library/std/src/sys/pal/unix/stack_overflow/mod.rs @@ -60,7 +60,7 @@ impl Handler { return Handler::null(); } - imp::make_handler(false) + imp::make_handler() } fn null() -> Handler { diff --git a/src/bootstrap/Cargo.lock b/src/bootstrap/Cargo.lock index 0b37202089cd6..b31d58887ebd3 100644 --- a/src/bootstrap/Cargo.lock +++ b/src/bootstrap/Cargo.lock @@ -48,6 +48,7 @@ dependencies = [ "clap", "clap_complete", "cmake", + "errno", "expect-test", "home", "ignore", diff --git a/src/bootstrap/Cargo.toml b/src/bootstrap/Cargo.toml index c7bef3a36eaeb..7d055bddf77c7 100644 --- a/src/bootstrap/Cargo.toml +++ b/src/bootstrap/Cargo.toml @@ -88,6 +88,10 @@ features = [ "Win32_System_Time", ] +# src/utils/job.rs +[target.'cfg(all(unix, not(any(target_os = "haiku", target_os = "hermit"))))'.dependencies] +errno = "0.3.14" + [dev-dependencies] expect-test = "1" diff --git a/src/bootstrap/defaults/bootstrap.dist.toml b/src/bootstrap/defaults/bootstrap.dist.toml index 03e012079b079..c7f551aa68d51 100644 --- a/src/bootstrap/defaults/bootstrap.dist.toml +++ b/src/bootstrap/defaults/bootstrap.dist.toml @@ -7,6 +7,9 @@ test-stage = 2 doc-stage = 2 # When compiling from source, you usually want all tools. extended = true +# Builds for distribution typically run beneath some other build +# system that is expected to perform its own priority lowering. +low-priority = false # Most users installing from source want to build all parts of the project from source. [llvm] diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 82728eebbdd16..c9b673edea236 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -1526,7 +1526,7 @@ NOTE: Please add `--stage 2` to your command line, or if you're sure you want to llvm_version_suffix, local_rebuild, locked_deps: build_locked_deps.unwrap_or(false), - low_priority: build_low_priority.unwrap_or(false), + low_priority: build_low_priority.unwrap_or(true), mandir: install_mandir.map(PathBuf::from), miri_info, musl_root: rust_musl_root.map(PathBuf::from), diff --git a/src/bootstrap/src/core/session.rs b/src/bootstrap/src/core/session.rs index 848b3e52de9f0..4a6cf789598b2 100644 --- a/src/bootstrap/src/core/session.rs +++ b/src/bootstrap/src/core/session.rs @@ -563,9 +563,7 @@ impl Session { #[cfg_attr(feature = "tracing", instrument(level = "debug", name = "Session::build", skip_all))] pub(crate) fn build(&mut self) { trace!("setting up job management"); - unsafe { - crate::utils::job::setup(self); - } + crate::utils::job::setup(self); // Handle hard-coded subcommands. { diff --git a/src/bootstrap/src/utils/change_tracker.rs b/src/bootstrap/src/utils/change_tracker.rs index 3db429b5f5124..78d0b22b0cbfc 100644 --- a/src/bootstrap/src/utils/change_tracker.rs +++ b/src/bootstrap/src/utils/change_tracker.rs @@ -686,4 +686,9 @@ pub const CONFIG_CHANGE_HISTORY: &[ChangeInfo] = &[ severity: ChangeSeverity::Info, summary: "A new option `llvm.tpde` has been added to control whether the TPDE pass plugin should be built as an experimental alternative LLVM backend.", }, + ChangeInfo { + change_id: 165707, + severity: ChangeSeverity::Info, + summary: "`low-priority` is now enabled by default aside from `bootstrap.dist.toml`, which is optimal for the overwhelming majority of situations.", + }, ]; diff --git a/src/bootstrap/src/utils/job.rs b/src/bootstrap/src/utils/job.rs index 45cff7c716ba9..b370bed36006b 100644 --- a/src/bootstrap/src/utils/job.rs +++ b/src/bootstrap/src/utils/job.rs @@ -1,15 +1,47 @@ +#[cfg(all(unix, not(any(target_os = "haiku", target_os = "hermit"))))] +pub(crate) use self::for_unix::setup; #[cfg(windows)] pub(crate) use self::for_windows::setup; use crate::core::session::Session; #[cfg(any(target_os = "haiku", target_os = "hermit", not(any(unix, windows))))] -pub(crate) unsafe fn setup(_sess: &Session) {} +pub(crate) fn setup(_sess: &Session) {} -#[cfg(all(unix, not(target_os = "haiku")))] -pub(crate) unsafe fn setup(sess: &Session) { - if sess.config.low_priority { - unsafe { - libc::setpriority(libc::PRIO_PGRP as _, 0, 10); +#[cfg(all(unix, not(any(target_os = "haiku", target_os = "hermit"))))] +mod for_unix { + use std::ffi::c_int; + use std::io; + + use libc::id_t; + + fn get_priority(which: c_int, who: id_t) -> io::Result { + // Genius design: `getpriority` can return -1 on success if the nice value is literally -1. + // Per `getpriority`'s docs, clear `errno` beforehand and check it afterward regardless of + // return value. + errno::set_errno(errno::Errno(0)); + // SAFETY: empty safety contract + let nice = unsafe { libc::getpriority(which as _, who) }; + let new_errno = errno::errno().0; + if new_errno == 0 { Ok(nice) } else { Err(io::Error::from_raw_os_error(new_errno)) } + } + fn set_priority(which: c_int, who: id_t, prio: c_int) -> io::Result<()> { + // SAFETY: empty safety contract + if unsafe { libc::setpriority(which as _, who, prio) != -1 } { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } + } + + pub(crate) fn setup(sess: &super::Session) { + const TARGET_NICE: c_int = 10; + // The processes that spawn the build are all descendants of the + // current thread. + let (which, who) = (libc::PRIO_PROCESS as _, 0); + // Unwrap both of those to alert users to ridiculous Seccomp-BPF setups messing up their + // performance. + if sess.config.low_priority && get_priority(which, who).unwrap() < TARGET_NICE { + set_priority(which, who, TARGET_NICE).unwrap(); } } } @@ -59,7 +91,7 @@ mod for_windows { use windows::Win32::System::Threading::{BELOW_NORMAL_PRIORITY_CLASS, GetCurrentProcess}; use windows::core::PCWSTR; - pub(crate) unsafe fn setup(sess: &super::Session) { + pub(crate) fn setup(sess: &super::Session) { // SAFETY: pretty much everything below is unsafe unsafe { // Enable the Windows Error Reporting dialog which msys disables, diff --git a/tests/run-make/compiler-lookup-paths/rmake.rs b/tests/run-make/compiler-lookup-paths/rmake.rs index 0e00f9b340019..edb3d69bbaba9 100644 --- a/tests/run-make/compiler-lookup-paths/rmake.rs +++ b/tests/run-make/compiler-lookup-paths/rmake.rs @@ -1,3 +1,6 @@ +// On `aarch64-unknown-linux-pauthtest`, rustc links static native libraries dynamically (with a +// warning), because the target requires dynamic linking. +//@ ignore-pauthtest //@ needs-target-std // // Since #19941, rustc can accept specifications on its library search paths. diff --git a/tests/run-make/invalid-staticlib/rmake.rs b/tests/run-make/invalid-staticlib/rmake.rs index 4844bff329aca..9dcbb7b43f160 100644 --- a/tests/run-make/invalid-staticlib/rmake.rs +++ b/tests/run-make/invalid-staticlib/rmake.rs @@ -1,3 +1,6 @@ +// On `aarch64-unknown-linux-pauthtest`, rustc links static native libraries dynamically (with a +// warning), because the target requires dynamic linking. +//@ ignore-pauthtest //@ needs-target-std // // If the static library provided is not valid (in this test, diff --git a/tests/run-make/native-link-modifier-verbatim-rustc/rmake.rs b/tests/run-make/native-link-modifier-verbatim-rustc/rmake.rs index d885df9e79eb4..15fdfa9f32b84 100644 --- a/tests/run-make/native-link-modifier-verbatim-rustc/rmake.rs +++ b/tests/run-make/native-link-modifier-verbatim-rustc/rmake.rs @@ -1,3 +1,6 @@ +// On `aarch64-unknown-linux-pauthtest`, rustc links static native libraries dynamically (with a +// warning), because the target requires dynamic linking. +//@ ignore-pauthtest //@ needs-target-std // // `verbatim` is a native link modifier that forces rustc to only accept libraries with diff --git a/tests/run-make/pass-linker-flags-from-dep/rmake.rs b/tests/run-make/pass-linker-flags-from-dep/rmake.rs index 1cd55468737dd..92dbdc0ffdfc9 100644 --- a/tests/run-make/pass-linker-flags-from-dep/rmake.rs +++ b/tests/run-make/pass-linker-flags-from-dep/rmake.rs @@ -1,3 +1,6 @@ +// On `aarch64-unknown-linux-pauthtest`, rustc links static native libraries dynamically (with a +// warning), because the target requires dynamic linking. +//@ ignore-pauthtest //@ needs-target-std // // A similar test to pass-linker-flags, testing that the `-l link-arg` flag