blob: 4900b7388840df7248a65219dd2df063cd90ea48 [file]
// Copyright 2026 The Fuchsia Authors
//
// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.
//! Refuse ambient compile-time function evaluation (CTFE) channels across
//! whole-crate, selected-unit, and monomorphized instantiation captures.
//!
//! Instead of predicting from HIR and `ty::Ty` which constants and trait
//! obligations `rustc` evaluates, this module combines two
//! compiler-authoritative mechanisms that share one [`CtfeMirScanner`] and one
//! post-compiler BFS:
//!
//! 1. **Dynamic CTFE interception (`override_queries`):** Hooks `rustc`'s own
//! CTFE entrypoints (`eval_to_allocation_raw`, `eval_to_const_value_raw`,
//! `eval_static_initializer` [local + extern], `mir_for_ctfe` [local +
//! extern], `promoted_mir` [local + extern], `mir_shims`, and
//! `providers.hooks.const_caller_location`). Hooks avoid recursive CTFE/MIR
//! queries that could trigger `E0391` cycles (calling only metadata and
//! attribute lookups such as `is_static`, `def_path_str`,
//! `codegen_fn_attrs`, `global_alloc`, and `type_of` on
//! `core::panic::Location` impls); they record evaluated roots, inspect
//! returned allocations/values, flag CTFE caller-location materialization
//! and CTFE static reads, and cache a compact [`CtfeBodySummary`] per MIR
//! body. Because `capture::run` lets `run_compiler` complete through
//! monomorphization and codegen before publishing `capture.json`, a
//! pure-Rust BFS in [`finalize_and_check`] covers 100% of CTFE executed
//! during analysis, capture, and codegen.
//! 2. **Whole-crate local constant & promoted MIR closure (`after_analysis`):**
//! Dynamic hooks alone miss ambient CTFE inside unmonomorphized generic
//! bodies (such as an uninstantiated generic `InlineConst` or
//! `generic_const_exprs` `AnonConst`). On normal crates,
//! [`audit_after_analysis`] seeds every crate-local `AnonConst`, `Const`,
//! `AssocConst`, `InlineConst`, and non-empty `promoted_mir` body (skipping
//! uncalled standalone `const fn`s) and forces their transitive `DefId`
//! summaries.
//!
//! Under `--stdlib-crate=core` (restricted to self-contained Profile v1
//! scalar-only `--select` roots without `Assert` or overflow checks), `core`
//! itself defines `TypeId::of`, `type_name`, `Field::OFFSET`, `guaranteed_eq`,
//! and immutable lookup `static`s. Whole-crate local-const seeding is skipped
//! there, and `capture::run` emits metadata only (`--emit=metadata`, skipping
//! codegen) with `audit_after_analysis` running after analysis and
//! selected-body extraction. Global dynamic CTFE interception still
//! unconditionally forbids `Location::caller()`, non-exempt `#[track_caller]`
//! items (exempting trusted `core` non-`Location`, non-forbidden-intrinsic
//! helpers whose CTFE MIR bodies remain transitively audited), `TypeId`,
//! `type_name`, `vtable_*`, `field_offset`, `const_allocate*`,
//! `const_eval_select`, `static` reads in any non-`DefKind::Static` body
//! (exempting `StaticRef` strictly on `DefKind::Static` initializer bodies and
//! their own promoted fragments—never on callable `const fn`, trait-impl,
//! `const Drop`, closure, or shim bodies, even when first evaluated under a
//! `static` initializer), and any `ptr_guaranteed_cmp` body dynamically loaded
//! during analysis, selected-body extraction, or uncached post-analysis CTFE
//! (including constants pre-folded before MIR extraction such as match
//! patterns, array lengths, and const-generic valtrees); every constant
//! referenced by a selected body is also audited strictly via
//! `selected_const_roots` BFS. Non-executed static `ptr_guaranteed_cmp` edges
//! reachable only from dead `core::ub_checks` branches (such as
//! `ptr::write_bytes::precondition_check` behind
//! `check_language_ub() == false`) remain exempted on non-selected roots when
//! capturing verbatim `core`.
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::sync::{Mutex, OnceLock};
use rustc_hir::def::DefKind;
use rustc_index::IndexVec;
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
use rustc_middle::mir::interpret::{
AllocId, ConstAllocation, EvalStaticInitializerRawResult, EvalToAllocationRawResult,
EvalToConstValueResult, GlobalAlloc, GlobalId, Scalar,
};
use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor as MirVisitor};
use rustc_middle::mir::{self, ConstValue};
use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt, TypingEnv};
use rustc_middle::util::Providers;
use rustc_span::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE, LocalDefId};
use rustc_span::{Span, Symbol, sym};
use crate::extract::Result;
use crate::{Failure, ir};
/// Deterministic map/set key identifying a `(DefId, Option<Promoted>)` body.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
struct BodyKey {
krate: u32,
index: u32,
promoted: Option<u32>,
}
impl BodyKey {
fn new(def_id: DefId, promoted: Option<u32>) -> Self {
Self { krate: def_id.krate.as_u32(), index: def_id.index.as_u32(), promoted }
}
fn def_id(self) -> DefId {
DefId { krate: CrateNum::from_u32(self.krate), index: DefIndex::from_u32(self.index) }
}
}
// RUSTC-WORKAROUND(#4365): fn-pointer query providers force a OnceLock hook.
// `rustc` query providers and hooks are plain function pointers, so hooks read
// their saved defaults and shared audit state from process-global cells
// initialized once per capture process (guarded by `CAPTURE_STARTED`).
struct OrigProviders {
eval_alloc: for<'tcx> fn(
TyCtxt<'tcx>,
ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>,
) -> EvalToAllocationRawResult<'tcx>,
eval_const_val: for<'tcx> fn(
TyCtxt<'tcx>,
ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>,
) -> EvalToConstValueResult<'tcx>,
eval_static_local:
for<'tcx> fn(TyCtxt<'tcx>, LocalDefId) -> EvalStaticInitializerRawResult<'tcx>,
eval_static_extern: for<'tcx> fn(TyCtxt<'tcx>, DefId) -> EvalStaticInitializerRawResult<'tcx>,
mir_for_ctfe_local: for<'tcx> fn(TyCtxt<'tcx>, LocalDefId) -> &'tcx mir::Body<'tcx>,
mir_for_ctfe_extern: for<'tcx> fn(TyCtxt<'tcx>, DefId) -> &'tcx mir::Body<'tcx>,
promoted_local:
for<'tcx> fn(TyCtxt<'tcx>, LocalDefId) -> &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>>,
promoted_extern:
for<'tcx> fn(TyCtxt<'tcx>, DefId) -> &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>>,
mir_shims: for<'tcx> fn(TyCtxt<'tcx>, ty::InstanceKind<'tcx>) -> mir::Body<'tcx>,
const_caller_loc: for<'tcx> fn(TyCtxt<'tcx>, Symbol, u32, u32) -> ConstValue,
}
static ORIG: OnceLock<OrigProviders> = OnceLock::new();
static STDLIB_CORE_SESSION: OnceLock<bool> = OnceLock::new();
#[derive(Clone, Copy, PartialEq, Eq)]
enum EvalKind {
Const,
Static,
}
thread_local! {
static EVAL_STACK: RefCell<Vec<EvalKind>> = const { RefCell::new(Vec::new()) };
}
struct EvalGuard;
impl EvalGuard {
fn enter(kind: EvalKind) -> Self {
EVAL_STACK.with(|s| s.borrow_mut().push(kind));
Self
}
}
impl Drop for EvalGuard {
fn drop(&mut self) {
EVAL_STACK.with(|s| {
let _ = s.borrow_mut().pop();
});
}
}
fn in_const_eval() -> bool {
EVAL_STACK.with(|s| s.borrow().last() == Some(&EvalKind::Const))
}
fn in_any_ctfe_eval() -> bool {
EVAL_STACK.with(|s| !s.borrow().is_empty())
}
fn is_stdlib_core_session() -> bool {
STDLIB_CORE_SESSION.get().copied().unwrap_or(false)
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
enum ViolationKind {
Ambient,
/// `GlobalAlloc::Static` or CTFE reading a `static`: refused for all
/// constants and all callable bodies (`const fn`, trait-impl, `const Drop`,
/// closure, and `mir_shims` bodies) on both normal crates and
/// `--stdlib-crate=core`; permitted strictly on `DefKind::Static`
/// initializer bodies and their own promoted fragments (static-to-static
/// pointers).
StaticRef,
/// `ptr_guaranteed_cmp` inside trusted `core`: refused on normal crates,
/// on selected bodies under `--stdlib-crate=core`, and on every body
/// dynamically loaded during analysis, selected-body extraction, or
/// uncached post-analysis CTFE (including pre-folded match patterns, array
/// lengths, and const-generic valtrees); exempted only on non-selected
/// static BFS edges (such as `ptr::write_bytes`'s dead
/// `if ub_checks::check_language_ub()` branch) when capturing verbatim
/// `core` (which emits metadata only and skips codegen).
CoreGuaranteedCmp,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
struct CtfeViolation {
kind: ViolationKind,
message: String,
}
impl CtfeViolation {
fn ambient(message: impl Into<String>) -> Self {
Self { kind: ViolationKind::Ambient, message: message.into() }
}
fn static_ref(message: impl Into<String>) -> Self {
Self { kind: ViolationKind::StaticRef, message: message.into() }
}
fn core_guaranteed_cmp(message: impl Into<String>) -> Self {
Self { kind: ViolationKind::CoreGuaranteedCmp, message: message.into() }
}
}
#[derive(Default)]
struct CtfeBodySummary {
/// True strictly when this summary belongs to a `DefKind::Static` item
/// (its top-level initializer or one of its own promoted fragments).
/// Callable `const fn`, trait-impl, `const Drop`, closure, shim, and
/// `const` bodies are always `false`.
is_static_initializer: bool,
violations: Vec<CtfeViolation>,
callees: Vec<BodyKey>,
}
#[derive(Default)]
struct CtfeAuditState {
eval_roots: BTreeSet<BodyKey>,
static_roots: BTreeSet<BodyKey>,
local_const_roots: BTreeSet<BodyKey>,
selected_const_roots: BTreeSet<BodyKey>,
dynamic_ctfe_bodies: BTreeSet<BodyKey>,
body_summaries: BTreeMap<BodyKey, CtfeBodySummary>,
hook_violations: BTreeSet<CtfeViolation>,
selected_violations: BTreeSet<String>,
local_consts_seeded: bool,
after_analysis_started: bool,
after_analysis_completed: bool,
}
static CTFE_STATE: Mutex<Option<CtfeAuditState>> = Mutex::new(None);
fn with_state<R, F: FnOnce(&mut CtfeAuditState) -> R>(f: F) -> R {
let mut guard = CTFE_STATE.lock().expect("CTFE audit mutex poisoned");
let state = guard.get_or_insert_with(CtfeAuditState::default);
f(state)
}
/// Record whether this capture process targets `--stdlib-crate=core` before
/// `rustc_driver::run_compiler` runs.
pub(crate) fn configure_session(
stdlib_crate: Option<ir::StdlibCrate>,
) -> std::result::Result<(), Failure> {
STDLIB_CORE_SESSION
.set(matches!(stdlib_crate, Some(ir::StdlibCrate::Core)))
.map_err(|_| Failure::tool("CTFE session configured more than once"))
}
/// Install CTFE query providers and `hooks.const_caller_location`.
///
/// Upstream `eval_to_allocation_raw` and `eval_to_const_value_raw` are single
/// queries (not `separate_provide_extern`) through which `const_eval_poly`,
/// `const_eval_resolve`, `const_eval_instance`, `const_eval_global_id`, and
/// `eval_to_valtree` funnel; `InterpCx::load_mir` loads bodies exclusively via
/// `promoted_mir`, `mir_for_ctfe`, or `mir_shims`; `sym::caller_location` calls
/// `providers.hooks.const_caller_location`.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/queries.rs#L1312-L1350
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/const_eval/eval_queries.rs#L326-L345
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/const_eval/valtrees.rs#L254-L265
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/interpret/eval_context.rs#L305-L325
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/interpret/intrinsics.rs#L290-L296
pub(crate) fn install_query_overrides(providers: &mut Providers) {
ORIG.set(OrigProviders {
eval_alloc: providers.queries.eval_to_allocation_raw,
eval_const_val: providers.queries.eval_to_const_value_raw,
eval_static_local: providers.queries.eval_static_initializer,
eval_static_extern: providers.extern_queries.eval_static_initializer,
mir_for_ctfe_local: providers.queries.mir_for_ctfe,
mir_for_ctfe_extern: providers.extern_queries.mir_for_ctfe,
promoted_local: providers.queries.promoted_mir,
promoted_extern: providers.extern_queries.promoted_mir,
mir_shims: providers.queries.mir_shims,
const_caller_loc: providers.hooks.const_caller_location,
})
.ok()
.expect("one compiler session per capture process");
providers.queries.eval_to_allocation_raw = hook_eval_alloc;
providers.queries.eval_to_const_value_raw = hook_eval_const_val;
providers.queries.eval_static_initializer = hook_eval_static_local;
providers.extern_queries.eval_static_initializer = hook_eval_static_extern;
providers.queries.mir_for_ctfe = hook_mir_for_ctfe_local;
providers.extern_queries.mir_for_ctfe = hook_mir_for_ctfe_extern;
providers.queries.promoted_mir = hook_promoted_local;
providers.extern_queries.promoted_mir = hook_promoted_extern;
providers.queries.mir_shims = hook_mir_shims;
providers.hooks.const_caller_location = hook_const_caller_location;
}
/// Refuse CTFE intrinsics whose result depends on build paths, source spans,
/// compiler crate/type identity hashes, diagnostic type formatting, or CTFE
/// heap/provenance non-determinism.
///
/// `remap_mir_for_const_eval_select` rewrites `Call` terminators to
/// `const_eval_select` in `mir_for_ctfe` into direct calls to the compile-time
/// arm, so only un-remapped `TailCall` or reified `FnDef` references reach the
/// `sym::const_eval_select` check below.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/interpret/intrinsics.rs#L187-L296
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/const_eval/machine.rs#L483-L720
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_mir_transform/src/lib.rs#L234-L304
fn is_forbidden_ctfe_intrinsic(name: Symbol) -> bool {
matches!(
name,
sym::caller_location
| sym::type_name
| sym::type_id
| sym::type_id_eq
| sym::type_id_vtable
| sym::type_of
| sym::size_of_type_id
| sym::type_id_fields
| sym::type_id_field_representing_type
| sym::type_id_variants
| sym::field_offset
| sym::field_representing_type_actual_type_id
| sym::vtable_size
| sym::vtable_align
| sym::const_allocate
| sym::const_deallocate
| sym::const_make_global
| sym::ptr_guaranteed_cmp
| sym::const_eval_select
)
}
/// Check whether `def_id` belongs to the authenticated sysroot `core` crate (or
/// the local crate only when compiling `--stdlib-crate=core` with no external
/// crates). Never trusts `--crate-name=core` on ordinary crates.
fn is_trusted_core_crate(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
if def_id.is_local() {
is_stdlib_core_session()
&& tcx.crate_name(LOCAL_CRATE) == sym::core
&& tcx.crates(()).is_empty()
} else {
Some(def_id.krate) == crate::extract::sysroot_core_crate(tcx)
}
}
/// Check whether `def_id` is `core::panic::Location` or an inherent associated
/// item of `core::panic::Location`. Checking `def_id.krate == loc_did.krate`
/// first avoids querying `type_of(impl_did)` on arbitrary local impls inside
/// query hooks.
fn is_panic_location_item(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
let Some(loc_did) = tcx.lang_items().panic_location() else {
return false;
};
if def_id == loc_did {
return true;
}
if def_id.krate != loc_did.krate {
return false;
}
if let Some(impl_did) = tcx.impl_of_assoc(def_id)
&& matches!(tcx.def_kind(impl_did), DefKind::Impl { of_trait: false })
&& let Some(adt) = tcx
.type_of(impl_did)
.instantiate_identity()
.skip_norm_wip()
.ty_adt_def()
{
return adt.did() == loc_did;
}
false
}
pub(crate) fn def_requires_caller_location(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
tcx.def_kind(def_id).has_codegen_attrs()
&& tcx
.codegen_fn_attrs(def_id)
.flags
.contains(CodegenFnAttrFlags::TRACK_CALLER)
}
/// Exempt only diverging `TerminatorKind::Call { target: None, .. }` calls to
/// `!`-returning abort hooks in trusted `core::panicking::*` /
/// `core::ub_checks::*` (such as untaken `const { assert!(...) }` panic paths).
/// Reaching a panic hook during CTFE aborts evaluation rather than returning a
/// `Location` value.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/const_eval/machine.rs#L230-L269
fn is_exempt_ctfe_diverging_panic_hook(
tcx: TyCtxt<'_>,
def_id: DefId,
is_diverging_call: bool,
) -> bool {
if !is_diverging_call || !is_trusted_core_crate(tcx, def_id) {
return false;
}
let path_ok = if def_id.is_local() {
let p = rustc_middle::ty::print::with_no_trimmed_paths!(
rustc_middle::ty::print::with_no_visible_paths!(tcx.def_path_str(def_id))
);
p.starts_with("panicking::") || p.starts_with("ub_checks::")
} else {
crate::extract::core_def_path(tcx, def_id).is_some_and(|p| {
p.starts_with("core::panicking::") || p.starts_with("core::ub_checks::")
})
};
path_ok && tcx.fn_sig(def_id).instantiate_identity().skip_binder().output().is_never()
}
/// Exempt non-`Location`, non-forbidden-intrinsic `#[track_caller]` helpers in
/// trusted `core` (such as `RangePattern::sub_one`,
/// `Layout::from_size_align_unchecked`, `Option::unwrap`,
/// `NonNull::new_unchecked`, and `core::intrinsics::unchecked_funnel_shl`,
/// whose `#[track_caller]` serves only `assert_unsafe_precondition!` UB aborts)
/// from the blanket `#[track_caller]` refusal; their `mir_for_ctfe` bodies are
/// still transitively audited and any dynamic `Location::caller()` call is
/// caught by `hook_const_caller_location`.
fn is_exempt_core_tracked_helper(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
is_trusted_core_crate(tcx, def_id)
&& !is_panic_location_item(tcx, def_id)
&& tcx.intrinsic(def_id).is_none_or(|intr| !is_forbidden_ctfe_intrinsic(intr.name))
&& matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn)
}
fn check_def_identity(
tcx: TyCtxt<'_>,
owner_def: DefId,
owner_path: &str,
target: DefId,
violations: &mut Vec<CtfeViolation>,
) {
if is_panic_location_item(tcx, target) {
violations.push(CtfeViolation::ambient(format!(
"CTFE reference to `core::panic::Location` (`{}`) in `{owner_path}` is \
unsupported because caller locations depend on build paths and source layout",
tcx.def_path_str(target),
)));
}
if let Some(intr) = tcx.intrinsic(target)
&& is_forbidden_ctfe_intrinsic(intr.name)
{
if intr.name == sym::caller_location {
violations.push(CtfeViolation::ambient(format!(
"CTFE intrinsic `caller_location` (`core::panic::Location`) in `{owner_path}` \
is unsupported because caller locations depend on build paths and source layout",
)));
} else {
let msg = format!(
"CTFE intrinsic `{}` in `{owner_path}` is unsupported because its output \
depends on ambient compiler/build context",
intr.name,
);
if intr.name == sym::ptr_guaranteed_cmp && is_trusted_core_crate(tcx, owner_def) {
violations.push(CtfeViolation::core_guaranteed_cmp(msg));
} else {
violations.push(CtfeViolation::ambient(msg));
}
}
}
if !is_exempt_core_tracked_helper(tcx, target) && def_requires_caller_location(tcx, target) {
violations.push(CtfeViolation::ambient(format!(
"CTFE reference to #[track_caller] item `{}` in `{owner_path}` is unsupported \
because caller locations depend on build paths and source layout",
tcx.def_path_str(target),
)));
}
}
fn scan_walk<'tcx>(
tcx: TyCtxt<'tcx>,
owner_def: DefId,
owner_path: &str,
iter: impl Iterator<Item = ty::GenericArg<'tcx>>,
summary: &mut CtfeBodySummary,
) {
for arg in iter {
if let Some(inner_ty) = arg.as_type() {
match *inner_ty.kind() {
ty::Adt(adt, _) if is_panic_location_item(tcx, adt.did()) => {
summary.violations.push(CtfeViolation::ambient(format!(
"CTFE references to `core::panic::Location` in `{owner_path}` are \
unsupported because caller locations depend on build paths and \
source layout",
)));
}
ty::FnDef(did, _) => {
check_def_identity(tcx, owner_def, owner_path, did, &mut summary.violations);
summary.callees.push(BodyKey::new(did, None));
}
ty::Closure(did, _) => summary.callees.push(BodyKey::new(did, None)),
_ => {}
}
} else if let Some(ct) = arg.as_const()
&& let ty::ConstKind::Unevaluated(uv) = ct.kind()
{
summary.callees.push(BodyKey::new(uv.def, None));
}
}
}
fn scan_ty<'tcx>(
tcx: TyCtxt<'tcx>,
owner_def: DefId,
owner_path: &str,
root_ty: ty::Ty<'tcx>,
summary: &mut CtfeBodySummary,
) {
scan_walk(tcx, owner_def, owner_path, root_ty.walk(), summary);
}
fn scan_generic_args<'tcx>(
tcx: TyCtxt<'tcx>,
owner_def: DefId,
owner_path: &str,
args: ty::GenericArgsRef<'tcx>,
summary: &mut CtfeBodySummary,
) {
for arg in args.iter() {
scan_walk(tcx, owner_def, owner_path, arg.walk(), summary);
}
}
fn scan_alloc_ids<'tcx>(
tcx: TyCtxt<'tcx>,
owner_def: DefId,
owner_path: &str,
mut stack: Vec<AllocId>,
allow_static_refs: bool,
summary: &mut CtfeBodySummary,
) {
let mut visited = BTreeSet::new();
while let Some(alloc_id) = stack.pop() {
if !visited.insert(alloc_id) {
continue;
}
match tcx.global_alloc(alloc_id) {
GlobalAlloc::Memory(mem) => {
stack.extend(mem.inner().provenance().ptrs().iter().map(|(_, p)| p.alloc_id()));
}
GlobalAlloc::Static(did) => {
if !allow_static_refs {
summary.violations.push(CtfeViolation::static_ref(format!(
"CTFE and constant references to static `{}` in `{owner_path}` are \
unsupported",
tcx.def_path_str(did),
)));
}
}
GlobalAlloc::TypeId { .. } => {
summary.violations.push(CtfeViolation::ambient(format!(
"type-id global allocations in `{owner_path}` are unsupported in constants",
)));
}
GlobalAlloc::VTable(..) => {
summary.violations.push(CtfeViolation::ambient(format!(
"vtable global allocations in `{owner_path}` are unsupported in constants",
)));
}
GlobalAlloc::Function { instance } => {
scan_generic_args(tcx, owner_def, owner_path, instance.args, summary);
let did = instance.def_id();
check_def_identity(tcx, owner_def, owner_path, did, &mut summary.violations);
if instance.def.requires_caller_location(tcx)
&& !is_exempt_core_tracked_helper(tcx, did)
{
summary.violations.push(CtfeViolation::ambient(format!(
"CTFE function pointer `{}` in `{owner_path}` carries #[track_caller], \
which is unsupported in constants",
tcx.def_path_str(did),
)));
}
summary.callees.push(BodyKey::new(did, None));
}
}
}
}
fn scan_const_val<'tcx>(
tcx: TyCtxt<'tcx>,
owner_def: DefId,
owner_path: &str,
val: ConstValue,
allow_static_refs: bool,
summary: &mut CtfeBodySummary,
) {
let stack = match val {
ConstValue::ZeroSized | ConstValue::Scalar(Scalar::Int(_)) => return,
ConstValue::Scalar(Scalar::Ptr(ptr, _)) => vec![ptr.prov_and_relative_offset().0.alloc_id()],
ConstValue::Indirect { alloc_id, .. } | ConstValue::Slice { alloc_id, .. } => {
vec![alloc_id]
}
};
scan_alloc_ids(tcx, owner_def, owner_path, stack, allow_static_refs, summary);
}
fn scan_const_allocation<'tcx>(
tcx: TyCtxt<'tcx>,
owner_def: DefId,
owner_path: &str,
alloc: ConstAllocation<'tcx>,
allow_static_refs: bool,
summary: &mut CtfeBodySummary,
) {
let stack: Vec<AllocId> =
alloc.inner().provenance().ptrs().iter().map(|(_, prov)| prov.alloc_id()).collect();
if !stack.is_empty() {
scan_alloc_ids(tcx, owner_def, owner_path, stack, allow_static_refs, summary);
}
}
struct CtfeMirScanner<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
owner_def: DefId,
owner_path: &'a str,
body: &'a mir::Body<'tcx>,
summary: CtfeBodySummary,
}
impl<'tcx> CtfeMirScanner<'_, 'tcx> {
fn scan_mir_const(&mut self, constant: mir::Const<'tcx>) {
scan_ty(self.tcx, self.owner_def, self.owner_path, constant.ty(), &mut self.summary);
match constant {
mir::Const::Val(cv, _) => scan_const_val(
self.tcx,
self.owner_def,
self.owner_path,
cv,
false,
&mut self.summary,
),
mir::Const::Unevaluated(uv, _) => {
scan_generic_args(
self.tcx,
self.owner_def,
self.owner_path,
uv.args,
&mut self.summary,
);
self.summary.callees.push(BodyKey::new(uv.def, uv.promoted.map(|p| p.as_u32())));
}
mir::Const::Ty(_, ct) => {
scan_walk(
self.tcx,
self.owner_def,
self.owner_path,
ct.walk(),
&mut self.summary,
);
}
}
}
}
impl<'tcx> MirVisitor<'tcx> for CtfeMirScanner<'_, 'tcx> {
fn visit_ty(&mut self, ty: ty::Ty<'tcx>, _ctx: mir::visit::TyContext) {
scan_ty(self.tcx, self.owner_def, self.owner_path, ty, &mut self.summary);
}
fn visit_const_operand(&mut self, constant: &mir::ConstOperand<'tcx>, _loc: mir::Location) {
self.scan_mir_const(constant.const_);
}
fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>, location: mir::Location) {
if let mir::Rvalue::ThreadLocalRef(did) = rvalue {
self.summary.violations.push(CtfeViolation::ambient(format!(
"thread-local references (`{}`) in CTFE (`{}`) are unsupported",
self.tcx.def_path_str(*did),
self.owner_path,
)));
}
self.super_rvalue(rvalue, location);
}
fn visit_terminator(&mut self, terminator: &mir::Terminator<'tcx>, location: mir::Location) {
match &terminator.kind {
mir::TerminatorKind::Call { func, args, destination, target, .. } => {
let is_diverging = target.is_none();
// Inspect `func.ty(body, tcx)` rather than matching only
// `Operand::Constant`: `remap_mir_for_const_eval_select` can
// lower a direct `FnDef` call through `Operand::Move(_tmp)`.
let func_ty = func.ty(self.body, self.tcx);
if let ty::FnDef(callee, callee_args) = *func_ty.kind() {
if is_exempt_ctfe_diverging_panic_hook(self.tcx, callee, is_diverging) {
scan_generic_args(
self.tcx,
self.owner_def,
self.owner_path,
callee_args,
&mut self.summary,
);
for arg in args {
self.visit_operand(&arg.node, location);
}
self.visit_place(
destination,
PlaceContext::MutatingUse(MutatingUseContext::Call),
location,
);
return;
}
if !is_trusted_core_crate(self.tcx, callee)
&& self
.tcx
.opt_associated_item(callee)
.is_some_and(|item| item.container == ty::AssocContainer::Trait)
{
self.summary.violations.push(CtfeViolation::ambient(format!(
"CTFE trait method call `{}` in `{}` is unsupported",
self.tcx.def_path_str(callee),
self.owner_path,
)));
}
check_def_identity(
self.tcx,
self.owner_def,
self.owner_path,
callee,
&mut self.summary.violations,
);
self.summary.callees.push(BodyKey::new(callee, None));
} else {
self.summary.violations.push(CtfeViolation::ambient(format!(
"indirect or closure calls in CTFE (`{}`) are unsupported \
(callee type `{func_ty}`)",
self.owner_path,
)));
}
self.super_terminator(terminator, location);
}
mir::TerminatorKind::TailCall { .. } => {
self.summary.violations.push(CtfeViolation::ambient(format!(
"CTFE tail calls in `{}` are unsupported",
self.owner_path,
)));
self.super_terminator(terminator, location);
}
mir::TerminatorKind::InlineAsm { .. }
| mir::TerminatorKind::Yield { .. }
| mir::TerminatorKind::CoroutineDrop => {
self.summary.violations.push(CtfeViolation::ambient(format!(
"unsupported CTFE terminator `{:?}` in `{}`",
terminator.kind, self.owner_path,
)));
self.super_terminator(terminator, location);
}
_ => self.super_terminator(terminator, location),
}
}
}
fn summarize_mir_body<'tcx>(
tcx: TyCtxt<'tcx>,
owner_def: DefId,
body: &mir::Body<'tcx>,
is_static_initializer: bool,
) -> CtfeBodySummary {
let owner_path = tcx.def_path_str(owner_def);
let mut summary = CtfeBodySummary { is_static_initializer, ..CtfeBodySummary::default() };
check_def_identity(tcx, owner_def, &owner_path, owner_def, &mut summary.violations);
let mut scanner = CtfeMirScanner { tcx, owner_def, owner_path: &owner_path, body, summary };
scanner.visit_body(body);
if let Some(required_consts) = body.required_consts.as_deref() {
for req in required_consts {
scanner.scan_mir_const(req.const_);
}
}
scanner.summary.callees.sort();
scanner.summary.callees.dedup();
scanner.summary.violations.sort();
scanner.summary.violations.dedup();
scanner.summary
}
// --- Query hooks (avoid recursive CTFE/MIR queries that could cycle) ---
fn orig_providers() -> &'static OrigProviders {
ORIG.get().expect("CTFE query hooks installed before queries")
}
fn record_hook_summary(summary: CtfeBodySummary, to_eval_roots: bool) {
if !summary.violations.is_empty() || !summary.callees.is_empty() {
with_state(|s| {
s.hook_violations.extend(summary.violations);
if to_eval_roots {
s.eval_roots.extend(summary.callees);
} else {
s.static_roots.extend(summary.callees);
}
});
}
}
fn hook_eval_alloc<'tcx>(
tcx: TyCtxt<'tcx>,
key: ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>,
) -> EvalToAllocationRawResult<'tcx> {
let def_id = key.value.instance.def_id();
let promoted = key.value.promoted.map(|p| p.as_u32());
// Promoteds owned by a `static` item (`tcx.is_static(def_id)`) are part of
// the static initializer and may reference or read other statics, matching
// `rustc_const_eval`'s `CanAccessMutGlobal::from(is_static)` check.
let is_static = tcx.is_static(def_id);
let read_from_const = is_static && in_const_eval();
let _guard = EvalGuard::enter(if is_static { EvalKind::Static } else { EvalKind::Const });
let owner_path = tcx.def_path_str(def_id);
with_state(|s| {
let bk = BodyKey::new(def_id, promoted);
s.dynamic_ctfe_bodies.insert(bk);
if is_static {
s.static_roots.insert(bk);
if read_from_const {
s.hook_violations.insert(CtfeViolation::ambient(format!(
"CTFE read of static `{owner_path}` is unsupported",
)));
}
} else {
s.eval_roots.insert(bk);
}
});
let mut arg_summary = CtfeBodySummary::default();
scan_generic_args(tcx, def_id, &owner_path, key.value.instance.args, &mut arg_summary);
record_hook_summary(arg_summary, !is_static);
let res = (orig_providers().eval_alloc)(tcx, key);
if let Ok(const_alloc) = &res {
let mut summary = CtfeBodySummary::default();
scan_alloc_ids(
tcx,
def_id,
&owner_path,
vec![const_alloc.alloc_id],
is_static,
&mut summary,
);
record_hook_summary(summary, !is_static);
}
res
}
fn hook_eval_const_val<'tcx>(
tcx: TyCtxt<'tcx>,
key: ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>,
) -> EvalToConstValueResult<'tcx> {
let def_id = key.value.instance.def_id();
let promoted = key.value.promoted.map(|p| p.as_u32());
let is_static = tcx.is_static(def_id);
let read_from_const = is_static && in_const_eval();
let _guard = EvalGuard::enter(if is_static { EvalKind::Static } else { EvalKind::Const });
let owner_path = tcx.def_path_str(def_id);
with_state(|s| {
let bk = BodyKey::new(def_id, promoted);
s.dynamic_ctfe_bodies.insert(bk);
if is_static {
s.static_roots.insert(bk);
if read_from_const {
s.hook_violations.insert(CtfeViolation::ambient(format!(
"CTFE read of static `{owner_path}` is unsupported",
)));
}
} else {
s.eval_roots.insert(bk);
}
});
let mut arg_summary = CtfeBodySummary::default();
scan_generic_args(tcx, def_id, &owner_path, key.value.instance.args, &mut arg_summary);
record_hook_summary(arg_summary, !is_static);
let res = (orig_providers().eval_const_val)(tcx, key);
if let Ok(cv) = &res {
let mut summary = CtfeBodySummary::default();
scan_const_val(tcx, def_id, &owner_path, *cv, is_static, &mut summary);
record_hook_summary(summary, !is_static);
}
res
}
fn hook_eval_static_local<'tcx>(
tcx: TyCtxt<'tcx>,
def_id: LocalDefId,
) -> EvalStaticInitializerRawResult<'tcx> {
let read_from_const = in_const_eval();
let _guard = EvalGuard::enter(EvalKind::Static);
let did = def_id.to_def_id();
with_state(|s| {
let bk = BodyKey::new(did, None);
s.static_roots.insert(bk);
s.dynamic_ctfe_bodies.insert(bk);
if read_from_const {
s.hook_violations.insert(CtfeViolation::ambient(format!(
"CTFE read of local static `{}` is unsupported",
tcx.def_path_str(did),
)));
}
});
let res = (orig_providers().eval_static_local)(tcx, def_id);
if let Ok(alloc) = &res {
let owner_path = tcx.def_path_str(did);
let mut summary = CtfeBodySummary::default();
scan_const_allocation(tcx, did, &owner_path, *alloc, true, &mut summary);
record_hook_summary(summary, false);
}
res
}
fn hook_eval_static_extern<'tcx>(
tcx: TyCtxt<'tcx>,
def_id: DefId,
) -> EvalStaticInitializerRawResult<'tcx> {
let read_from_const = in_const_eval();
let _guard = EvalGuard::enter(EvalKind::Static);
if read_from_const {
with_state(|s| {
s.hook_violations.insert(CtfeViolation::ambient(format!(
"CTFE read of external static `{}` is unsupported",
tcx.def_path_str(def_id),
)));
});
}
(orig_providers().eval_static_extern)(tcx, def_id)
}
fn record_mir_body_summary(key: BodyKey, summary: CtfeBodySummary) {
let active_eval = in_any_ctfe_eval();
let from_const = in_const_eval();
with_state(|s| {
s.body_summaries.insert(key, summary);
if active_eval || !s.after_analysis_started {
s.dynamic_ctfe_bodies.insert(key);
}
if active_eval {
if from_const {
s.eval_roots.insert(key);
} else {
s.static_roots.insert(key);
}
}
});
}
fn hook_mir_for_ctfe_local<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx mir::Body<'tcx> {
let body = (orig_providers().mir_for_ctfe_local)(tcx, def_id);
let did = def_id.to_def_id();
let summary = summarize_mir_body(tcx, did, body, tcx.is_static(did));
record_mir_body_summary(BodyKey::new(did, None), summary);
body
}
fn hook_mir_for_ctfe_extern<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &'tcx mir::Body<'tcx> {
let body = (orig_providers().mir_for_ctfe_extern)(tcx, def_id);
let summary = summarize_mir_body(tcx, def_id, body, tcx.is_static(def_id));
record_mir_body_summary(BodyKey::new(def_id, None), summary);
body
}
fn record_promoted_summaries<'tcx>(
tcx: TyCtxt<'tcx>,
did: DefId,
bodies: &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>>,
) {
if bodies.is_empty() {
return;
}
let active_eval = in_any_ctfe_eval();
let is_static_init = tcx.is_static(did);
let from_const = in_const_eval() && !is_static_init;
let summaries: Vec<(BodyKey, CtfeBodySummary)> = bodies
.iter_enumerated()
.map(|(p, b)| {
(BodyKey::new(did, Some(p.as_u32())), summarize_mir_body(tcx, did, b, is_static_init))
})
.collect();
with_state(|s| {
for (k, v) in summaries {
s.body_summaries.insert(k, v);
if active_eval || !s.after_analysis_started {
s.dynamic_ctfe_bodies.insert(k);
}
if active_eval {
if from_const {
s.eval_roots.insert(k);
} else {
s.static_roots.insert(k);
}
}
}
});
}
fn hook_promoted_local<'tcx>(
tcx: TyCtxt<'tcx>,
def_id: LocalDefId,
) -> &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>> {
let bodies = (orig_providers().promoted_local)(tcx, def_id);
record_promoted_summaries(tcx, def_id.to_def_id(), bodies);
bodies
}
fn hook_promoted_extern<'tcx>(
tcx: TyCtxt<'tcx>,
def_id: DefId,
) -> &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>> {
let bodies = (orig_providers().promoted_extern)(tcx, def_id);
record_promoted_summaries(tcx, def_id, bodies);
bodies
}
fn hook_mir_shims<'tcx>(tcx: TyCtxt<'tcx>, inst: ty::InstanceKind<'tcx>) -> mir::Body<'tcx> {
let body = (orig_providers().mir_shims)(tcx, inst);
if in_any_ctfe_eval() {
record_hook_summary(summarize_mir_body(tcx, inst.def_id(), &body, false), in_const_eval());
}
body
}
/// Intercept every `const_caller_location` materialization. During codegen
/// (`EVAL_STACK` empty), `rustc_codegen_ssa` calls `const_caller_location` to
/// materialize runtime `panic!()` / `assert!()` locations; only calls while a
/// CTFE or static-initializer evaluation frame is active (`in_any_ctfe_eval`)
/// indicate an ambient CTFE caller-location read.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_const_eval/src/interpret/intrinsics.rs#L290-L296
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_codegen_ssa/src/mir/block.rs#L1871-L1880
fn hook_const_caller_location<'tcx>(
tcx: TyCtxt<'tcx>,
file: Symbol,
line: u32,
col: u32,
) -> ConstValue {
if in_any_ctfe_eval() {
with_state(|s| {
s.hook_violations.insert(CtfeViolation::ambient(format!(
"CTFE invoked `core::panic::Location::caller()` at {file}:{line}:{col} \
(caller locations depend on build paths and source layout)",
)));
});
}
(orig_providers().const_caller_loc)(tcx, file, line, col)
}
// --- Post-analysis local constant closure & post-compiler check ---
/// Check whether `def_id` owns a `mir_for_ctfe` body (either locally or in
/// external crate metadata).
///
/// `TyCtxt::is_mir_available` queries `optimized_mir`, which
/// `rustc_metadata::rmeta::encoder::should_encode_mir` omits for CTFE-only
/// items such as external `InlineConst` (`core::any::TypeId::of::{constant#0}`)
/// and `AssocConst`. Calling `defaultness` on non-trait associated items or
/// `mir_for_ctfe` on `must_be_overridden` intrinsics panics.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_metadata/src/rmeta/encoder.rs#L1102-L1132
fn has_ctfe_mir(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
// RUSTC-WORKAROUND(#4503): is_mir_available omits CTFE-only items.
if tcx.is_type_const(def_id) || tcx.is_constructor(def_id) || tcx.is_foreign_item(def_id) {
return false;
}
if tcx.intrinsic(def_id).is_some_and(|intr| intr.must_be_overridden) {
return false;
}
match tcx.def_kind(def_id) {
DefKind::AssocConst { is_type_const: false } => {
if let Some(local) = def_id.as_local() {
tcx.hir_maybe_body_owned_by(local).is_some()
} else {
let item = tcx.associated_item(def_id);
item.container != ty::AssocContainer::Trait || item.defaultness(tcx).has_value()
}
}
DefKind::Const { is_type_const: false } | DefKind::AnonConst | DefKind::InlineConst => {
def_id.as_local().is_none_or(|local| tcx.hir_maybe_body_owned_by(local).is_some())
}
DefKind::Static { .. } => {
def_id.as_local().is_some_and(|local| tcx.hir_maybe_body_owned_by(local).is_some())
}
DefKind::Fn | DefKind::AssocFn | DefKind::Closure => {
if tcx.is_coroutine(def_id) || !tcx.is_const_fn(def_id) {
return false;
}
if let Some(local) = def_id.as_local() {
tcx.hir_maybe_body_owned_by(local).is_some()
&& tcx.hir_body_const_context(local).is_some()
} else {
if let Some(item) = tcx.opt_associated_item(def_id)
&& item.container == ty::AssocContainer::Trait
&& !item.defaultness(tcx).has_value()
{
return false;
}
true
}
}
_ => false,
}
}
/// Record a constant root directly referenced by a selected/extracted body so
/// `--stdlib-crate=core` audits it strictly alongside global dynamic CTFE
/// interception.
pub(crate) fn record_selected_const_root(def_id: DefId, promoted: Option<mir::Promoted>) {
with_state(|s| {
s.selected_const_roots.insert(BodyKey::new(def_id, promoted.map(|p| p.as_u32())));
});
}
/// Evaluate and strictly audit a MIR constant operand or `required_consts`
/// entry on a selected/extracted body.
///
/// Upstream `Const::eval` triggers `bug!` on `ty::ConstKind::Expr` and
/// `delayed_bug` on any other non-value `Const::Ty`; guard `Const::Ty` before
/// calling `eval`.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/mir/consts.rs#L268-L341
// RUSTC-WORKAROUND(#4369): `Const::eval` ICEs on non-value `Const::Ty`.
pub(crate) fn eval_mir_const_audited<'tcx>(
tcx: TyCtxt<'tcx>,
typing_env: TypingEnv<'tcx>,
constant: mir::Const<'tcx>,
span: Span,
) -> Result<ConstValue> {
if constant.has_non_region_param()
|| constant.has_non_region_infer()
|| constant.references_error()
{
return Err(format!("uninstantiated or erroneous constant: {constant:?}"));
}
let owner_def = LOCAL_CRATE.as_def_id();
let mut ty_summary = CtfeBodySummary::default();
scan_ty(tcx, owner_def, "MIR constant", constant.ty(), &mut ty_summary);
match constant {
mir::Const::Unevaluated(uv, _) => {
scan_generic_args(tcx, owner_def, "MIR constant", uv.args, &mut ty_summary);
}
mir::Const::Ty(_, ct) => {
scan_walk(tcx, owner_def, "MIR constant", ct.walk(), &mut ty_summary);
}
mir::Const::Val(..) => {}
}
if let Some(v) = ty_summary.violations.first() {
with_state(|s| s.selected_violations.insert(v.message.clone()));
return Err(v.message.clone());
}
if !ty_summary.callees.is_empty() {
with_state(|s| s.selected_const_roots.extend(ty_summary.callees));
}
let val = match constant {
mir::Const::Val(value, _) => value,
mir::Const::Unevaluated(uv, _) => {
record_selected_const_root(uv.def, uv.promoted);
constant
.eval(tcx, typing_env, span)
.map_err(|err| format!("unevaluated constant failed CTFE: {err:?}"))?
}
mir::Const::Ty(_, ct) if matches!(ct.kind(), ty::ConstKind::Value(_)) => constant
.eval(tcx, typing_env, span)
.map_err(|err| format!("type-level constant failed evaluation: {err:?}"))?,
mir::Const::Ty(..) => {
return Err(format!("unsupported non-value type-level constant: {constant:?}"));
}
};
let mut val_summary = CtfeBodySummary::default();
scan_const_val(tcx, owner_def, "MIR constant", val, false, &mut val_summary);
if let Some(v) = val_summary.violations.first() {
with_state(|s| s.selected_violations.insert(v.message.clone()));
return Err(v.message.clone());
}
if !val_summary.callees.is_empty() {
with_state(|s| s.selected_const_roots.extend(val_summary.callees));
}
Ok(val)
}
fn check_diverging_fndef<'tcx>(
tcx: TyCtxt<'tcx>,
typing_env: TypingEnv<'tcx>,
owner_def: DefId,
did: DefId,
fn_args: ty::GenericArgsRef<'tcx>,
) -> Result<()> {
let mut violations = Vec::new();
check_def_identity(tcx, owner_def, "diverging call", did, &mut violations);
if !fn_args.has_non_region_param()
&& !fn_args.has_non_region_infer()
&& !fn_args.has_escaping_bound_vars()
&& !fn_args.references_error()
&& let Ok(Some(inst)) = ty::Instance::try_resolve(tcx, typing_env, did, fn_args)
{
let resolved = inst.def_id();
if resolved != did {
check_def_identity(tcx, owner_def, "diverging call", resolved, &mut violations);
}
if inst.def.requires_caller_location(tcx) && !is_exempt_core_tracked_helper(tcx, resolved) {
violations.push(CtfeViolation::ambient(format!(
"diverging call references #[track_caller] item `{}` \
(caller locations depend on build paths and source layout)",
tcx.def_path_str(resolved),
)));
}
}
if let Some(v) = violations.into_iter().next() {
return Err(v.message);
}
Ok(())
}
fn check_diverging_ty<'tcx>(
tcx: TyCtxt<'tcx>,
typing_env: TypingEnv<'tcx>,
owner_def: DefId,
root_ty: ty::Ty<'tcx>,
) -> Result<()> {
for generic_arg in root_ty.walk() {
let Some(inner) = generic_arg.as_type() else {
continue;
};
match *inner.kind() {
ty::Adt(adt, _) if is_panic_location_item(tcx, adt.did()) => {
return Err(
"diverging call references `core::panic::Location` \
(caller locations depend on build paths and source layout)"
.into(),
);
}
ty::FnDef(did, fn_args) => {
check_diverging_fndef(tcx, typing_env, owner_def, did, fn_args)?;
}
ty::Closure(did, _) => {
let mut violations = Vec::new();
check_def_identity(tcx, owner_def, "diverging call", did, &mut violations);
if let Some(v) = violations.into_iter().next() {
return Err(v.message);
}
}
_ => {}
}
}
Ok(())
}
/// Refuse `core::panic::Location` types, `Location::caller` /
/// `core::intrinsics::caller_location` `FnDef`s, and non-exempt
/// `#[track_caller]` callees or arguments on a diverging runtime call lowered
/// to `ir::Terminator::Unsupported`.
pub(crate) fn check_diverging_call_no_location<'tcx>(
tcx: TyCtxt<'tcx>,
typing_env: TypingEnv<'tcx>,
body: &mir::Body<'tcx>,
func: &mir::Operand<'tcx>,
args: &[rustc_span::Spanned<mir::Operand<'tcx>>],
) -> Result<()> {
let owner_def = LOCAL_CRATE.as_def_id();
for op in core::iter::once(func).chain(args.iter().map(|spanned| &spanned.node)) {
check_diverging_ty(tcx, typing_env, owner_def, op.ty(body, tcx))?;
if let mir::Operand::Constant(const_op) = op {
match const_op.const_ {
mir::Const::Unevaluated(uv, _) => {
record_selected_const_root(uv.def, uv.promoted);
for a in uv.args.iter() {
if let Some(t) = a.as_type() {
check_diverging_ty(tcx, typing_env, owner_def, t)?;
}
}
}
mir::Const::Ty(_, ct) => {
for a in ct.walk() {
if let Some(t) = a.as_type() {
check_diverging_ty(tcx, typing_env, owner_def, t)?;
}
}
}
mir::Const::Val(..) => {}
}
}
}
Ok(())
}
/// Run the whole-crate local constant and promoted MIR closure on normal crates
/// and force transitive `DefId` summaries for all currently known roots while
/// `tcx` is alive inside `after_analysis`.
pub(crate) fn audit_after_analysis(tcx: TyCtxt<'_>, stdlib_crate: Option<ir::StdlibCrate>) {
with_state(|s| s.after_analysis_started = true);
let need_seed = stdlib_crate.is_none() && with_state(|s| !s.local_consts_seeded);
if need_seed {
let mut local_consts = Vec::new();
let mut local_statics = Vec::new();
let mut type_const_viols = Vec::new();
for def in tcx.iter_local_def_id() {
if matches!(
tcx.def_kind(def),
DefKind::Const { is_type_const: true }
| DefKind::AssocConst { is_type_const: true }
) {
type_const_viols.push(CtfeViolation::ambient(format!(
"CTFE type_const item `{}` is unsupported",
tcx.def_path_str(def.to_def_id()),
)));
}
}
for def in tcx.hir_body_owners() {
let did = def.to_def_id();
let kind = tcx.def_kind(def);
match kind {
DefKind::AnonConst
| DefKind::Const { is_type_const: false }
| DefKind::AssocConst { is_type_const: false }
| DefKind::InlineConst => local_consts.push(BodyKey::new(did, None)),
DefKind::Static { .. } if !tcx.is_foreign_item(did) => {
local_statics.push(BodyKey::new(did, None));
}
DefKind::AssocFn
if tcx.is_const_fn(did)
&& tcx.impl_of_assoc(did).is_some_and(|imp| {
matches!(tcx.def_kind(imp), DefKind::Impl { of_trait: true })
}) =>
{
local_consts.push(BodyKey::new(did, None));
}
_ => {}
}
if !tcx.is_trivial_const(did)
&& !tcx.is_type_const(did)
&& !matches!(kind, DefKind::GlobalAsm)
{
let target_roots = if matches!(kind, DefKind::Static { .. }) {
&mut local_statics
} else {
&mut local_consts
};
for p in tcx.promoted_mir(did).indices() {
target_roots.push(BodyKey::new(did, Some(p.as_u32())));
}
}
}
with_state(|s| {
s.local_const_roots.extend(local_consts);
s.static_roots.extend(local_statics);
s.hook_violations.extend(type_const_viols);
s.local_consts_seeded = true;
});
}
let mut worklist: VecDeque<BodyKey> = with_state(|s| {
s.eval_roots
.iter()
.chain(s.local_const_roots.iter())
.chain(s.static_roots.iter())
.chain(s.selected_const_roots.iter())
.copied()
.collect()
});
let mut visited = BTreeSet::new();
while let Some(key) = worklist.pop_front() {
if !visited.insert(key) {
continue;
}
let def_id = key.def_id();
let already = with_state(|s| s.body_summaries.contains_key(&key));
if !already {
if key.promoted.is_some() {
if !tcx.is_trivial_const(def_id) && !tcx.is_type_const(def_id) {
let _ = tcx.promoted_mir(def_id);
}
} else if has_ctfe_mir(tcx, def_id) {
if matches!(
tcx.def_kind(def_id),
DefKind::Const { .. }
| DefKind::AssocConst { .. }
| DefKind::AnonConst
| DefKind::InlineConst
) && let Some((triv_val, triv_ty)) = tcx.trivial_const(def_id)
{
// RUSTC-WORKAROUND(#4503): trivial_const omits CTFE MIR.
let owner_path = tcx.def_path_str(def_id);
let mut summary = CtfeBodySummary::default();
check_def_identity(tcx, def_id, &owner_path, def_id, &mut summary.violations);
scan_ty(
tcx,
def_id,
&owner_path,
tcx.type_of(def_id).instantiate_identity().skip_norm_wip(),
&mut summary,
);
scan_ty(tcx, def_id, &owner_path, triv_ty, &mut summary);
scan_const_val(tcx, def_id, &owner_path, triv_val, false, &mut summary);
with_state(|s| s.body_summaries.insert(key, summary));
} else {
let _ = tcx.mir_for_ctfe(def_id);
}
} else {
let owner_path = tcx.def_path_str(def_id);
let mut summary = CtfeBodySummary::default();
check_def_identity(tcx, def_id, &owner_path, def_id, &mut summary.violations);
if !summary.violations.is_empty() {
with_state(|s| s.body_summaries.insert(key, summary));
}
}
}
let callees: Vec<BodyKey> = with_state(|s| {
s.body_summaries.get(&key).map(|sum| sum.callees.clone()).unwrap_or_default()
});
for callee in callees {
if !visited.contains(&callee) {
worklist.push_back(callee);
}
}
}
with_state(|s| s.after_analysis_completed = true);
}
fn violation_matches(
kind: ViolationKind,
allow_static_ref: bool,
allow_core_guaranteed_cmp: bool,
) -> bool {
match kind {
ViolationKind::Ambient => true,
ViolationKind::StaticRef => !allow_static_ref,
ViolationKind::CoreGuaranteedCmp => !allow_core_guaranteed_cmp,
}
}
fn collect_bfs_violations(
state: &CtfeAuditState,
roots: impl IntoIterator<Item = BodyKey>,
allow_static_ref_on_static_bodies: bool,
allow_core_guaranteed_cmp: bool,
out: &mut BTreeSet<String>,
) {
let mut queue: VecDeque<BodyKey> = roots.into_iter().collect();
let mut visited = BTreeSet::new();
while let Some(key) = queue.pop_front() {
if !visited.insert(key) {
continue;
}
if let Some(summary) = state.body_summaries.get(&key) {
let allow_static_ref =
allow_static_ref_on_static_bodies && summary.is_static_initializer;
for v in &summary.violations {
if violation_matches(v.kind, allow_static_ref, allow_core_guaranteed_cmp) {
out.insert(v.message.clone());
}
}
for &callee in &summary.callees {
if !visited.contains(&callee) {
queue.push_back(callee);
}
}
}
}
}
/// Check all currently recorded CTFE violations (called both during
/// `after_analysis` on normal crates—before per-body extraction, matching
/// `check_no_ambient_builtin_macros`—and again after `run_compiler` finishes
/// via [`finalize_and_check`]).
pub(crate) fn check_current_violations(
stdlib_crate: Option<ir::StdlibCrate>,
) -> std::result::Result<(), Failure> {
if ORIG.get().is_none() {
return Err(Failure::tool("CTFE query hooks were not installed for this capture session"));
}
let is_core = matches!(stdlib_crate, Some(ir::StdlibCrate::Core));
let violations: BTreeSet<String> = with_state(|s| {
if !s.after_analysis_completed {
return Err(Failure::tool("CTFE post-analysis audit did not complete"));
}
let mut found: BTreeSet<String> = s.selected_violations.clone();
for v in &s.hook_violations {
if violation_matches(v.kind, false, false) {
found.insert(v.message.clone());
}
}
if is_core {
for key in &s.dynamic_ctfe_bodies {
if let Some(summary) = s.body_summaries.get(key) {
for v in &summary.violations {
if violation_matches(v.kind, summary.is_static_initializer, false) {
found.insert(v.message.clone());
}
}
}
}
collect_bfs_violations(s, s.eval_roots.iter().copied(), false, true, &mut found);
collect_bfs_violations(s, s.static_roots.iter().copied(), true, true, &mut found);
collect_bfs_violations(
s,
s.selected_const_roots.iter().copied(),
false,
false,
&mut found,
);
} else {
collect_bfs_violations(
s,
s.eval_roots
.iter()
.chain(s.local_const_roots.iter())
.chain(s.selected_const_roots.iter())
.copied(),
false,
false,
&mut found,
);
collect_bfs_violations(s, s.static_roots.iter().copied(), true, false, &mut found);
}
Ok(found)
})?;
if !violations.is_empty() {
let joined: Vec<&str> = violations.iter().map(String::as_str).take(6).collect();
return Err(Failure::unsupported(joined.join("; ")));
}
Ok(())
}
/// Pure-Rust post-compiler CTFE verification run after `run_compiler` finishes
/// (covering analysis, capture, monomorphization, and codegen) and before
/// `capture.json` is written.
pub(crate) fn finalize_and_check(
stdlib_crate: Option<ir::StdlibCrate>,
) -> std::result::Result<(), Failure> {
check_current_violations(stdlib_crate)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn eval_mir_const_audited_rejects_const_kind_expr_and_placeholder() {
struct ExprConstCallbacks {
ran: bool,
}
impl rustc_driver::Callbacks for ExprConstCallbacks {
fn after_analysis(
&mut self,
_compiler: &rustc_interface::interface::Compiler,
tcx: TyCtxt<'_>,
) -> rustc_driver::Compilation {
let typing_env = TypingEnv::fully_monomorphized();
let one = ty::Const::from_target_usize(tcx, 1);
let expr_ct = ty::Const::new_expr(
tcx,
ty::Expr::new_binop(
tcx,
mir::BinOp::Add,
tcx.types.usize,
tcx.types.usize,
one,
one,
),
);
let placeholder_ct = ty::Const::new_placeholder(
tcx,
ty::Placeholder::<TyCtxt<'_>, ty::BoundConst<'_>>::new_anon(
ty::UniverseIndex::ROOT,
ty::BoundVar::ZERO,
),
);
for bad_ct in [expr_ct, placeholder_ct] {
let mir_ct = mir::Const::Ty(tcx.types.usize, bad_ct);
let err =
eval_mir_const_audited(tcx, typing_env, mir_ct, rustc_span::DUMMY_SP)
.unwrap_err();
assert!(err.contains("unsupported non-value type-level constant"), "{err}");
}
self.ran = true;
rustc_driver::Compilation::Stop
}
}
let dir = tempfile::tempdir().unwrap();
let src_path = dir.path().join("no_core_probe.rs");
std::fs::write(
&src_path,
"#![allow(internal_features)]\n#![feature(no_core, lang_items)]\n#![no_core]\n\
#[lang = \"pointee_sized\"] pub trait PointeeSized {}\n\
#[lang = \"meta_sized\"] pub trait MetaSized: PointeeSized {}\n\
#[lang = \"sized\"] pub trait Sized: MetaSized {}\n\
#[lang = \"copy\"] pub trait Copy {}\n",
)
.unwrap();
let args = vec![
"rustc".to_string(),
src_path.to_str().unwrap().to_string(),
"--crate-type=lib".to_string(),
"--edition=2021".to_string(),
format!("--sysroot={}", dir.path().display()),
];
let mut callbacks = ExprConstCallbacks { ran: false };
rustc_driver::run_compiler(&args, &mut callbacks);
assert!(callbacks.ran, "after_analysis callback must run");
}
}