blob: 63125dde1df3c997e1f3c1fb5fac94ddd8a3fad6 [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.
//! Compiler observation, complete inventory, and exact input reads. The host
//! authenticates the compiler/sysroot distribution and stages declared inputs;
//! these checks do not defend against a compromised execution environment.
use std::{
collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque},
io,
path::{Path, PathBuf},
sync::{Arc, Mutex, OnceLock},
};
use std::ops::ControlFlow;
use rustc_abi::{Endian, ExternAbi, Size};
use rustc_ast::expand::allocator::AllocatorKind;
use rustc_ast::{Attribute, Crate, MetaItem, MetaItemInner, Mutability};
use rustc_data_structures::steal::Steal;
use rustc_driver::Compilation;
use rustc_feature::{
ACCEPTED_LANG_FEATURES, EnabledLangFeature, EnabledLibFeature, Features, UNSTABLE_LANG_FEATURES,
};
use rustc_hir as hir;
use rustc_hir::LangItem;
use rustc_hir::attrs::{AttributeKind, InlineAttr};
use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
use rustc_hir::intravisit;
use rustc_interface::interface;
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
use rustc_middle::mir;
use rustc_middle::mir::interpret::{AllocId, AllocRange, GlobalAlloc, Scalar};
use rustc_middle::mir::visit::Visitor as MirVisitor;
use rustc_middle::traits::ImplSource;
use rustc_middle::ty::adjustment::PointerCoercion;
use rustc_middle::ty::trait_def::{ImplRestrictionKind, TraitSpecializationKind};
use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt, TypingEnv, VtblEntry};
use rustc_middle::util::Providers;
use rustc_session::EarlyDiagCtxt;
use rustc_session::config::{CrateType, OptLevel, Options};
use rustc_span::def_id::{DefId, LOCAL_CRATE, LocalDefId};
use rustc_span::hygiene::{ExpnData, ExpnKind, LocalExpnId, MacroKind};
use rustc_span::source_map::{FileLoader, RealFileLoader};
use rustc_span::{DUMMY_SP, FileName, Symbol, kw, sym};
use rustc_target::spec::PanicStrategy as RustcPanicStrategy;
use crate::{Args, Failure, ctfe, extract, identity, ir, mono, tripwires};
// RUSTC-WORKAROUND(#4365): fn-pointer query providers force a OnceLock hook.
// rustc query providers are function pointers, so the hook cannot borrow a
// callback instance. These cells hold one process's session authority and owned
// snapshots. They are initialized once before queries and never reused for a
// second capture, avoiding stale bodies or selectors from another compilation.
type Provider = for<'tcx> fn(TyCtxt<'tcx>, LocalDefId) -> &'tcx Steal<mir::Body<'tcx>>;
static DEFAULT_PROVIDER: OnceLock<Provider> = OnceLock::new();
static CAPTURE_STARTED: OnceLock<()> = OnceLock::new();
static OBSERVED_HOOK: Mutex<BTreeSet<u32>> = Mutex::new(BTreeSet::new());
/// The query returns `Steal<Body>` and later codegen queries consume it. Call
/// the original provider, record that it ran for this callable `LocalDefId`,
/// and return the exact original result without running CTFE inside the active
/// query frame (evaluating a self-referential `const fn`'s `const { ... }`
/// inside the hook would trigger a `rustc` query cycle `E0391`). Extraction
/// runs immediately after the query returns in `collect`, before codegen can
/// steal the body; `mir_for_ctfe` clones `ConstFn` bodies without stealing.
/// The compiler explicitly supports overriding this query: "can be overridden
/// by custom rustc drivers".
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_mir_transform/src/lib.rs#L495-L503
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_mir_transform/src/lib.rs#L567-L598
///
/// Early hook observation does not decide coverage. The independent compiler
/// census is enumerated in full before selecting or assembling any output.
fn hook<'tcx>(tcx: TyCtxt<'tcx>, def: LocalDefId) -> &'tcx Steal<mir::Body<'tcx>> {
let provider = DEFAULT_PROVIDER.get().expect("provider installed before queries");
let original = provider(tcx, def);
if callable(tcx.def_kind(def)) {
OBSERVED_HOOK
.lock()
.expect("capture hook mutex poisoned")
.insert(def.local_def_index.as_u32());
}
original
}
fn override_queries(_: &rustc_session::Session, providers: &mut Providers) {
DEFAULT_PROVIDER
.set(providers.queries.mir_drops_elaborated_and_const_checked)
.expect("one compiler session per capture process");
providers.queries.mir_drops_elaborated_and_const_checked = hook;
ctfe::install_query_overrides(providers);
}
#[derive(Default)]
struct Reads {
files: BTreeMap<PathBuf, ir::SourceFile>,
refusals: Vec<String>,
tool_errors: Vec<String>,
}
struct RecordingLoader {
reads: Arc<Mutex<Reads>>,
allowed: BTreeSet<PathBuf>,
directories: BTreeSet<PathBuf>,
/// Absolute roots under which an undeclared text read is a diagnostic
/// snippet probe for an imported standard-library source (see
/// [`Self::is_snippet_probe`]), never an input of this compilation.
snippet_roots: Vec<PathBuf>,
}
impl RecordingLoader {
fn new(
reads: Arc<Mutex<Reads>>,
allowed: BTreeSet<PathBuf>,
snippet_roots: Vec<PathBuf>,
) -> Self {
// Directories are derived authority, not another ambient inventory.
// Requiring every original parent prefix preserves normal ../ lookup
// through declared ancestors without admitting missing/../file when an
// unrelated ambient directory happens to appear.
let directories = allowed
.iter()
.flat_map(|path| path.ancestors().skip(1).map(Path::to_path_buf))
.collect();
Self {
reads,
allowed,
directories,
snippet_roots,
}
}
// RUSTC-WORKAROUND(#4368): diagnostic snippet probes share the FileLoader.
/// Classify an undeclared text read as a diagnostic snippet probe.
///
/// To render a span in an imported crate, rustc's `SourceMap` re-reads
/// that crate's source because "The compiler produces better error
/// messages if the sources of dependencies are available", and it
/// discards any failure:
/// `self.file_loader.read_file(&local_path).ok()`. The file then stays
/// marked absent, the same state as a sysroot without the `rust-src`
/// component. The decoder names sysroot sources `/rustc/<commit>/...`
/// or, when `rust-src` is installed, paths under the session's
/// `real_rust_source_base_dir` (`<sysroot>/lib/rustlib/src/rust`).
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_span/src/source_map.rs#L1058-L1083
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_metadata/src/rmeta/decoder.rs#L1784-L1793
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_session/src/config.rs#L2678-L2697
///
/// Answering such a probe `NotFound` without a refusal lets a warning or
/// error that points into the sysroot render (or report its own compiler
/// failure) instead of failing as an undeclared read. No bytes are
/// returned or recorded, so the probe cannot change what rustc compiles
/// or enter the source binding. Every read that defines this crate's
/// contents (crate root, `#[path]` modules, `include!`, `include_str!`)
/// treats `NotFound` as a compiler error, so the probe roots cannot stand
/// in for an input. Binary reads, other prefixes, and lexical `..` escapes
/// out of a root stay hard refusals. So do relative paths: both decoder
/// names are absolute, and resolving a relative read against the working
/// directory would let ambient state decide the classification. The
/// roots themselves are absolute and lexically normalized by
/// [`snippet_roots`], so the component-wise prefix test compares like
/// with like.
fn is_snippet_probe(&self, path: &Path) -> bool {
if !path.is_absolute() {
return false;
}
let Ok(normalized) = path.normalize_lexically() else {
return false;
};
self.snippet_roots
.iter()
.any(|root| normalized.starts_with(root))
}
/// Resolve within the declared file-and-ancestor namespace. The standard
/// normalizer works "without traversing the filesystem" and warns that
/// lexical .. can differ when an intermediate component is a symlink.
/// Check every parent prefix against derived directories, then open only
/// the admitted normalized name. Neither missing prefixes nor undeclared
/// aliases may acquire authority from ambient filesystem state.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/library/std/src/path.rs#L3407-L3422
///
/// This is a configured source namespace, not evidence that undeclared
/// alternatives were absent in the original tree. The CLI stages regular
/// files; direct capture callers must keep declared canonical inputs and
/// their ancestors unchanged throughout the compiler session. These checks
/// do not make filesystem mutation by a compromised host atomic or safe.
fn lookup(&self, path: &Path) -> io::Result<PathBuf> {
let absolute = std::path::absolute(path)?;
for parent in absolute.ancestors().skip(1) {
let parent = parent.normalize_lexically().map_err(io::Error::other)?;
if !self.directories.contains(&parent) {
return Err(io::Error::other("undeclared source directory"));
}
}
let path = absolute.normalize_lexically().map_err(io::Error::other)?;
if !self.allowed.contains(&path) {
return Err(io::Error::other("undeclared source filename"));
}
// Membership must precede filesystem queries: even a symlink to an
// allowed target is invisible under an undeclared name. The canonical
// name itself must still denote the declared regular file.
if path.canonicalize()? != path || !path.is_file() {
return Err(io::Error::other("declared source is not a canonical regular file"));
}
Ok(path)
}
fn read_path(&self, path: &Path) -> io::Result<PathBuf> {
match self.lookup(path) {
Ok(path) => Ok(path),
Err(cause) => {
let error = format!("undeclared compiler read: {}: {cause}", path.display());
// Missing module candidates are normal negative probes. An
// actual denied read is different: compiler recovery must not
// publish a capture after handling this I/O error.
let mut reads =
self.reads.lock().map_err(|_| io::Error::other("input read mutex poisoned"))?;
reads.refusals.push(error.clone());
Err(io::Error::other(error))
}
}
}
fn record(&self, path: &Path, bytes: &[u8], read_kind: &'static str) -> io::Result<()> {
let path = path.canonicalize()?;
let mut reads =
self.reads.lock().map_err(|_| io::Error::other("input read mutex poisoned"))?;
// Membership, not an empty-list convention, authorizes the read. Keep
// refusals separately so a compiler recovery path cannot turn a denied
// input into success merely by handling the loader's I/O error.
if !self.allowed.contains(&path) {
let error = format!("undeclared compiler read: {}", path.display());
reads.refusals.push(error.clone());
return Err(io::Error::other(error));
}
let sha256 = identity::sha256_bytes(bytes);
if let Some(previous) = reads.files.get(&path) {
if previous.sha256 != sha256 {
let error = format!("input changed between compiler reads: {}", path.display());
reads.refusals.push(error.clone());
return Err(io::Error::other(error));
}
} else {
reads.files.insert(path.clone(), ir::SourceFile { path, sha256, read_kind });
}
Ok(())
}
}
/// Roots under which an undeclared text read is a sysroot snippet probe:
/// the compiler's virtual `/rustc/<commit>` prefix and, when the session
/// has one, `real_rust_source_base_dir`. rustc joins that directory onto
/// the sysroot and, if it is a symlink, will "Replace the symlink bootstrap
/// creates, with its destination" (`candidate = symlink_dest;`, the raw
/// `std::fs::read_link` result), so it may be relative or contain `.` and
/// `..` components.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_session/src/config.rs#L2678-L2697
///
/// A relative value is dropped rather than resolved against the working
/// directory. An absolute value is lexically normalized, as
/// `is_snippet_probe` normalizes the probed path, and dropped if
/// normalization fails. Dropping a root only turns its probes back into
/// hard refusals.
fn snippet_roots(real_rust_source_base_dir: Option<&Path>) -> Vec<PathBuf> {
let mut roots = vec![Path::new("/rustc").join(ir::COMPILER_COMMIT)];
if let Some(real) = real_rust_source_base_dir
&& real.is_absolute()
&& let Ok(real) = real.normalize_lexically()
{
roots.push(real);
}
roots
}
/// Hash the exact bytes returned to rustc, before SourceMap normalization.
/// `FileLoader::read_file` must "return a String because we normalize source
/// files"; binary inputs have a separate read method and are recorded too.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_span/src/source_map.rs#L81-L96
impl FileLoader for RecordingLoader {
fn file_exists(&self, path: &Path) -> bool {
// FileLoader asks to "Query the existence of a file." rustc probes
// both name.rs and name/mod.rs and rejects two visible candidates.
// Answer in the same closed namespace as reads: ambient alternatives
// must not change module choice or ambiguity without a declaration.
// A negative probe is not a refused read and needs no recorded input.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_span/src/source_map.rs#L81-L84
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_expand/src/module.rs#L246-L264
self.lookup(path).is_ok()
}
fn read_file(&self, path: &Path) -> io::Result<String> {
if self.lookup(path).is_err() && self.is_snippet_probe(path) {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"imported standard-library source is not a capture input",
));
}
let path = self.read_path(path)?;
let text = RealFileLoader.read_file(&path)?;
self.record(&path, text.as_bytes(), "text")?;
Ok(text)
}
fn read_binary_file(&self, path: &Path) -> io::Result<Arc<[u8]>> {
let path = self.read_path(path)?;
let bytes = RealFileLoader.read_binary_file(&path)?;
self.record(&path, &bytes, "binary")?;
Ok(bytes)
}
fn current_directory(&self) -> io::Result<PathBuf> {
RealFileLoader.current_directory()
}
}
fn callable(kind: DefKind) -> bool {
matches!(kind, DefKind::Fn | DefKind::AssocFn)
}
// Census policy is independent of successful body translation. Rust calls
// `hir_body_owners` an iterator over "all body-owners in this crate". Every
// such owner is required, including closures and anonymous/inline constants.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/hir/map.rs#L362-L367
//
// Functions (including declarations), statics, named constants, datatype and
// trait/impl owners, and global assembly also require explicit admission even
// without a HIR body. The initial adapter rejects unsupported owners instead
// of silently dropping their contracts or layout obligations.
//
// Other definitions describe names, parameters, or components of these owners;
// absent a body they add no separate obligation in this adapter. In particular,
// `Ctor` "Refers to the struct or enum variant's constructor", while the type
// owner is separately required. Unused `AnonConst` entries can be "unused and
// incomplete", with queries that "ICE when using this `DefId`". Use the body
// inventory rather than demanding a body query from every definition.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_hir/src/def.rs#L99-L205
//
// Keep this match exhaustive: a compiler upgrade must classify each new kind.
//
// `DefKind::ForeignMod` and `DefKind::ForeignTy` are unconditionally required
// even without child items or HIR bodies: an item-less
// `#[link(name = "...")] unsafe extern "C" {}` block embeds link-time
// native-library obligations into crate metadata, and foreign types introduce
// unmodeled FFI invariants.
//
// Externally visible `DefKind::Macro(..)` items (`#[macro_export]`,
// `pub macro`, or `pub use`-reexported macros) are required in whole-crate
// scope because they expand into downstream crates (where `rustc`'s
// `unsafe_code` lint exempts tokens originating from external macro spans).
// Crate-private helper `macro_rules!` remain non-required when bodyless
// because every crate-local expansion is already captured in caller MIR.
fn required(tcx: TyCtxt<'_>, def: LocalDefId, kind: DefKind, has_body: bool) -> bool {
match kind {
DefKind::Fn
| DefKind::AssocFn
| DefKind::Static { .. }
| DefKind::Const { .. }
| DefKind::AssocConst { .. }
| DefKind::Struct
| DefKind::Enum
| DefKind::Union
| DefKind::Trait
| DefKind::Impl { .. }
| DefKind::GlobalAsm
| DefKind::ForeignMod
| DefKind::ForeignTy => true,
DefKind::Macro(..) => {
has_body
|| tcx.effective_visibilities(()).is_exported(def)
|| tcx.visibility(def).is_public()
}
DefKind::Mod
| DefKind::Variant
| DefKind::TyAlias
| DefKind::TraitAlias
| DefKind::AssocTy
| DefKind::TyParam
| DefKind::ConstParam
| DefKind::Ctor(..)
| DefKind::ExternCrate
| DefKind::Use
| DefKind::AnonConst
| DefKind::InlineConst
| DefKind::OpaqueTy
| DefKind::Field
| DefKind::LifetimeParam
| DefKind::Closure
| DefKind::SyntheticCoroutineBody => has_body,
}
}
// Required does not mean supported. Whole-crate capture must admit every
// required owner, including owners with no runtime body:
// - Fieldless enums without explicit discriminant `AnonConst`s are admitted
// via the type adapter.
// - Pure array-length, repeat-count, and discriminant `AnonConst`s,
// non-generic pure-value `Const`/`AssocConst` items, safe `Trait`
// declarations (plus their bodyless safe Rust-ABI `AssocFn` and
// `AssocConst` items), and safe `Impl` blocks whose child items are
// checked separately are admitted fail-closed below with no fabricated body.
// - Required `Macro` items stay refused: no scan of an exported
// `macro_rules!` definition bounds its downstream expansions. Macro and
// item names in the definition (`inner!`, `crate::g!`) resolve at the
// call site, metavariables splice in caller tokens such as `unsafe` or a
// macro path, and a construct that ends in definition tokens takes the
// definition's span, for which the `unsafe_code` lint stays silent. When
// two spans' contexts differ, `Span::to` "consider[s] the combined span
// to be produced by the macro", and a lint whose span `in_external_macro`
// attributes to an imported bang macro is dropped unless the lint sets
// `report_in_external_macro`, which `UNSAFE_CODE` does not.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_span/src/lib.rs#L1142-L1165
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_span/src/hygiene.rs#L920-L938
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/lint.rs#L440-L475
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_lint/src/builtin.rs#L192-L230
// - `Struct` owners whose type `extract::ty` admits (non-generic crate-local
// structs without `Drop`, unsafe fields, interior mutability, unmodeled
// representations, or fields outside the Profile v2 data fragment), and
// their function-like constructors, are admitted with no fabricated body.
// - `InlineConst`, `Static`, `Union`, `ForeignMod`, `ForeignTy`,
// `GlobalAsm`, and bodyless free `Fn` items remain explicit refusals in
// whole-crate scope.
// - Callables with bodies are only candidates here: `collect` publishes one
// only if `extract::body` translates it, refusing intrinsics, generics,
// unsupported entry conditions, and unmodeled codegen attributes.
/// One attribute kind that a caller of [`check_non_callable_attrs`] has
/// validated (or shown to be inert) for its item, beyond the benign set that
/// every item admits.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ExtraAttr {
None,
/// `#[repr(..)]` on `Struct` constant types, whose `adt.repr()` options
/// the caller validates separately.
Repr,
/// `#[inline]` on a bodyless trait method declaration. rustc's inline
/// attribute parser lists that target as
/// `Warn(Target::Method(MethodKind::Trait { body: false }))`, accepting
/// the attribute there with a lint, while every body-bearing method
/// target is `Allow`. The declaration has no body to codegen, and an
/// implementing method inherits only `#[align]` and `#[track_caller]`
/// from it, not inlining. Only the modes [`extract::codegen_attrs`]
/// admits on bodies pass.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_attr_parsing/src/attributes/inline.rs#L15-L29
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_codegen_ssa/src/codegen_attrs.rs#L316-L317
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_codegen_ssa/src/codegen_attrs.rs#L355-L358
Inline,
}
/// Mirror the inlining modes that [`extract::codegen_attrs`] admits on
/// callables with bodies. The match is exhaustive so that a new mode fails to
/// compile here instead of being admitted silently.
fn inline_mode_admitted(inline: &InlineAttr) -> bool {
match inline {
InlineAttr::None | InlineAttr::Hint | InlineAttr::Always | InlineAttr::Never => true,
InlineAttr::Force { .. } => false,
}
}
/// Reject attributes on non-callable items whose semantic effect the scalar
/// model does not capture (`#[linkage]`, `#[no_mangle]`, `#[export_name]`,
/// `#[rustc_*]`, etc.). `extra` names one further attribute kind that the
/// caller has validated for this item (see [`ExtraAttr`]).
fn check_non_callable_attrs(
tcx: TyCtxt<'_>,
def: LocalDefId,
extra: ExtraAttr,
context: &str,
) -> extract::Result<()> {
for attr in tcx.hir_attrs(tcx.local_def_id_to_hir_id(def)) {
match attr {
hir::Attribute::Parsed(AttributeKind::Repr { .. }) if extra == ExtraAttr::Repr => {}
hir::Attribute::Parsed(AttributeKind::Inline(inline, _))
if extra == ExtraAttr::Inline && inline_mode_admitted(inline) => {}
hir::Attribute::Parsed(kind) => match kind {
AttributeKind::AutomaticallyDerived
| AttributeKind::CfgAttrTrace
| AttributeKind::CfgTrace(_)
| AttributeKind::Deprecated { .. }
| AttributeKind::Doc(_)
| AttributeKind::DocComment { .. }
| AttributeKind::DoNotRecommend
| AttributeKind::MustUse { .. }
| AttributeKind::OnConst { .. }
| AttributeKind::OnMove { .. }
| AttributeKind::OnUnimplemented { .. }
| AttributeKind::OnUnknown { .. }
| AttributeKind::OnUnmatchArgs { .. } => {}
other => {
return Err(format!("{context}: unmodeled attribute {other:?} is unsupported"));
}
},
hir::Attribute::Unparsed(item) => {
let segments = item.path.segments.as_ref();
let is_lint_attr = segments.len() == 1
&& matches!(
segments[0],
sym::allow | sym::warn | sym::deny | sym::forbid | sym::expect
);
let is_tool_attr =
segments.len() >= 2 && matches!(segments[0].as_str(), "clippy" | "rustfmt");
if !is_lint_attr && !is_tool_attr {
return Err(format!(
"{context}: unmodeled attribute `{}` is unsupported",
item.path
));
}
}
}
}
Ok(())
}
/// Admit only safe, ordinary Rust trait declarations (not `unsafe trait`,
/// `const trait`, `auto trait`, `#[marker]`, `#[fundamental]`, coinductive,
/// specialization, or `#[rustc_*]`-attributed traits).
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/ty/trait_def.rs#L19-L84
fn admit_safe_trait(tcx: TyCtxt<'_>, def: LocalDefId) -> extract::Result<()> {
let ty::TraitDef {
def_id: _,
impl_restriction,
safety,
constness,
paren_sugar,
has_auto_impl,
is_marker,
is_coinductive,
is_fundamental,
skip_array_during_method_dispatch,
skip_boxed_slice_during_method_dispatch,
specialization_kind,
must_implement_one_of,
force_dyn_incompatible,
deny_explicit_impl,
} = tcx.trait_def(def);
if *safety != hir::Safety::Safe {
return Err("whole-crate obligation is unsupported: Trait (unsafe trait)".into());
}
if *constness != hir::Constness::NotConst {
return Err("whole-crate obligation is unsupported: Trait (const trait)".into());
}
if *has_auto_impl {
return Err("whole-crate obligation is unsupported: Trait (auto trait)".into());
}
if *is_marker
|| *is_coinductive
|| *is_fundamental
|| *paren_sugar
|| *skip_array_during_method_dispatch
|| *skip_boxed_slice_during_method_dispatch
|| *deny_explicit_impl
|| must_implement_one_of.is_some()
|| force_dyn_incompatible.is_some()
|| !matches!(impl_restriction, ImplRestrictionKind::Unrestricted)
|| !matches!(specialization_kind, TraitSpecializationKind::None)
{
return Err(
"whole-crate obligation is unsupported: Trait (unmodeled trait modifier)".into()
);
}
check_non_callable_attrs(
tcx,
def,
ExtraAttr::None,
"whole-crate obligation is unsupported: Trait",
)
}
/// Admit safe inherent or trait `Impl` blocks whose associated items are
/// separately checked by `collect` / `whole_crate_item`. Reject `unsafe impl`
/// (except builtin `#[derive(Clone, Copy)]`'s `core::clone::TrivialClone`
/// marker impl, where `rustc` checks `self.is_automatically_derived(def_id)`
/// and `RustcBuiltinMacro` on the derive expansion), negative/reservation
/// impls (`ImplPolarity::{Negative, Reservation}`), `default impl`, `const
/// impl`, and unmodeled attributes.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/ty/mod.rs#L288-L294
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_type_ir/src/predicate.rs#L272-L284
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_builtin_macros/src/deriving/clone.rs#L71-L92
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/ty/mod.rs#L2047-L2060
fn admit_safe_impl(tcx: TyCtxt<'_>, def: LocalDefId, of_trait: bool) -> extract::Result<()> {
let impl_ = tcx.hir_expect_item(def).expect_impl();
if impl_.constness != hir::Constness::NotConst {
return Err(format!(
"whole-crate obligation is unsupported: Impl {{ of_trait: {of_trait} }} (const impl)"
));
}
if of_trait {
let Some(hir_header) = impl_.of_trait else {
return Err(
"whole-crate obligation is unsupported: Impl { of_trait: true } (missing header)"
.into(),
);
};
if !matches!(hir_header.defaultness, hir::Defaultness::Final) {
return Err(
"whole-crate obligation is unsupported: Impl { of_trait: true } (default impl)"
.into(),
);
}
let ty::ImplTraitHeader { trait_ref, polarity, safety, constness } =
tcx.impl_trait_header(def);
if constness != hir::Constness::NotConst {
return Err(
"whole-crate obligation is unsupported: Impl { of_trait: true } (const impl)"
.into(),
);
}
if !matches!(polarity, ty::ImplPolarity::Positive) {
return Err(format!(
"whole-crate obligation is unsupported: Impl {{ of_trait: true }} \
({polarity} polarity)"
));
}
if safety != hir::Safety::Safe {
let trait_def_id = trait_ref.instantiate_identity().skip_norm_wip().def_id;
let is_builtin_trivial_clone = !trait_def_id.is_local()
&& tcx.is_lang_item(trait_def_id, LangItem::TrivialClone)
&& tcx.is_builtin_derived(def.to_def_id());
if !is_builtin_trivial_clone {
return Err(
"whole-crate obligation is unsupported: Impl { of_trait: true } (unsafe impl)"
.into(),
);
}
}
}
check_non_callable_attrs(
tcx,
def,
ExtraAttr::None,
&format!("whole-crate obligation is unsupported: Impl {{ of_trait: {of_trait} }}"),
)
}
/// Check that a non-generic `Const`/`AssocConst` type contains only pure
/// immutable value data (scalars, `Ordering`, tuples, arrays, local plain
/// structs, non-`usize` pure-value `core::ops::{Range, RangeTo, RangeFrom}<I>`
/// lowered to synthetic structs, or local/`core::result::Result` enums without
/// `Drop`, `UnsafeCell`, unsafe fields, heap handles, or unmodeled
/// representations/attributes).
fn const_ty_is_pure_value<'tcx>(
tcx: TyCtxt<'tcx>,
ty: ty::Ty<'tcx>,
context: &str,
) -> extract::Result<()> {
match *ty.kind() {
ty::Bool | ty::Char | ty::Never | ty::Int(_) | ty::Uint(_) => Ok(()),
ty::Tuple(elems) => {
for elem in elems {
const_ty_is_pure_value(tcx, elem, context)?;
}
Ok(())
}
ty::Array(elem, _) => const_ty_is_pure_value(tcx, elem, context),
ty::Adt(adt, args)
if args.is_empty() && tcx.is_lang_item(adt.did(), LangItem::OrderingEnum) =>
{
Ok(())
}
ty::Adt(adt, args)
if adt.is_enum()
&& ((adt.did().is_local() && args.is_empty())
|| (args.len() == 2
&& extract::core_def_path(tcx, adt.did()).as_deref()
== Some("core::result::Result"))) =>
{
if adt.has_dtor(tcx) {
return Err(format!("{context}: Drop enum constant type {ty:?} is unsupported"));
}
let typing_env = TypingEnv::fully_monomorphized();
if ty.has_unsafe_fields() || !ty.is_freeze(tcx, typing_env) {
return Err(format!(
"{context}: interior-mutable or unsafe-field constant type {ty:?} is unsupported"
));
}
if let Some(local_def) = adt.did().as_local() {
check_non_callable_attrs(tcx, local_def, ExtraAttr::Repr, context)?;
}
for variant in adt.variants() {
for field in &variant.fields {
let field_ty = field.ty(tcx, args);
let normalized = tcx
.try_normalize_erasing_regions(typing_env, field_ty)
.map_err(|_| {
format!("{context}: unnormalizable field type {field_ty:?}")
})?;
if normalized.has_non_region_param()
|| normalized.has_non_region_infer()
|| normalized.references_error()
{
return Err(format!(
"{context}: generic or erroneous field type {normalized:?}"
));
}
const_ty_is_pure_value(tcx, normalized, context)?;
}
}
extract::ty(tcx, ty).map(|_| ())
}
ty::Adt(adt, args)
if adt.is_struct()
&& ((adt.did().is_local() && args.is_empty())
|| (args.len() == 1 && extract::is_core_range(tcx, adt.did()))) =>
{
if adt.has_dtor(tcx) {
return Err(format!("{context}: Drop struct constant type {ty:?} is unsupported"));
}
if ty.has_unsafe_fields() || !ty.is_freeze(tcx, TypingEnv::fully_monomorphized()) {
return Err(format!(
"{context}: interior-mutable or unsafe-field constant type {ty:?} is unsupported"
));
}
let repr = adt.repr();
if repr.simd() || repr.scalable() || repr.packed() {
return Err(format!("{context}: unmodeled repr on struct constant type {ty:?}"));
}
// Reject any `#[rustc_*]` or unmodeled attribute on crate-local
// structs (allowing benign attributes plus `#[repr(..)]`, whose
// fields are checked above).
if let Some(local_def) = adt.did().as_local() {
check_non_callable_attrs(tcx, local_def, ExtraAttr::Repr, context)?;
}
let typing_env = TypingEnv::fully_monomorphized();
for field in &adt.non_enum_variant().fields {
let field_ty = field.ty(tcx, args);
let normalized = tcx
.try_normalize_erasing_regions(typing_env, field_ty)
.map_err(|_| format!("{context}: unnormalizable field type {field_ty:?}"))?;
if normalized.has_non_region_param()
|| normalized.has_non_region_infer()
|| normalized.references_error()
{
return Err(format!(
"{context}: generic or erroneous field type {normalized:?}"
));
}
const_ty_is_pure_value(tcx, normalized, context)?;
}
if !adt.did().is_local() {
// Only non-`usize` ranges lowered to layout-verified synthetic
// structs are admitted as constants; `Range<usize>` stays on
// `MirTy.range*` and fails closed.
match extract::ty(tcx, ty)? {
ir::Ty::Struct(_) => {}
_ => return Err(format!("{context}: unsupported constant type {ty:?}")),
}
}
Ok(())
}
_ => Err(format!("{context}: unsupported constant type {ty:?}")),
}
}
fn check_const_value_pure<'tcx>(
tcx: TyCtxt<'tcx>,
ty: ty::Ty<'tcx>,
value: mir::ConstValue,
context: &str,
) -> extract::Result<()> {
let typing_env = TypingEnv::fully_monomorphized();
match value {
mir::ConstValue::ZeroSized => {
let layout = tcx
.layout_of(typing_env.as_query_input(ty))
.map_err(|err| format!("{context}: failed to compute layout for {ty:?}: {err}"))?;
if layout.is_zst() {
Ok(())
} else {
Err(format!(
"{context}: zero-sized constant value disagrees with non-ZST type {ty:?}"
))
}
}
mir::ConstValue::Scalar(scalar) => {
if scalar.try_to_scalar_int().is_ok() {
Ok(())
} else {
Err(format!("{context}: provenance-bearing scalar constant is unsupported"))
}
}
mir::ConstValue::Indirect { alloc_id, offset: _ } => match tcx.global_alloc(alloc_id) {
GlobalAlloc::Memory(const_alloc) => {
let alloc = const_alloc.inner();
if alloc.mutability != Mutability::Not {
return Err(format!(
"{context}: mutable global allocations are unsupported in constants"
));
}
let range = AllocRange { start: Size::ZERO, size: alloc.size() };
if !alloc.provenance().range_empty(range, &tcx) {
return Err(format!(
"{context}: provenance-bearing constant allocation is unsupported"
));
}
Ok(())
}
GlobalAlloc::Static(_)
| GlobalAlloc::Function { .. }
| GlobalAlloc::VTable(..)
| GlobalAlloc::TypeId { .. } => {
Err(format!("{context}: non-memory global allocation in constant is unsupported"))
}
},
mir::ConstValue::Slice { .. } => {
Err(format!("{context}: slice constant values are unsupported"))
}
}
}
struct ConstHirSafetyVisitor<'tcx> {
reject_calls_and_items: bool,
typeck: Option<&'tcx ty::TypeckResults<'tcx>>,
}
impl<'v, 'tcx> intravisit::Visitor<'v> for ConstHirSafetyVisitor<'tcx> {
type Result = ControlFlow<String>;
fn visit_block(&mut self, b: &'v hir::Block<'v>) -> Self::Result {
if matches!(b.rules, hir::BlockCheckMode::UnsafeBlock(_)) {
return ControlFlow::Break("unsafe blocks are unsupported in constants".into());
}
intravisit::walk_block(self, b)
}
fn visit_stmt(&mut self, s: &'v hir::Stmt<'v>) -> Self::Result {
if self.reject_calls_and_items && matches!(s.kind, hir::StmtKind::Item(_)) {
return ControlFlow::Break(
"nested items are unsupported in anonymous constants".into(),
);
}
intravisit::walk_stmt(self, s)
}
fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) -> Self::Result {
match ex.kind {
hir::ExprKind::InlineAsm(_) => {
return ControlFlow::Break("inline assembly is unsupported in constants".into());
}
hir::ExprKind::Call(..) | hir::ExprKind::MethodCall(..)
if self.reject_calls_and_items =>
{
return ControlFlow::Break(
"function and method calls are unsupported in anonymous constants".into(),
);
}
hir::ExprKind::ConstBlock(_)
| hir::ExprKind::Closure(_)
| hir::ExprKind::AddrOf(..)
if self.reject_calls_and_items =>
{
return ControlFlow::Break(
"const blocks, closures, and references are unsupported in anonymous constants"
.into(),
);
}
hir::ExprKind::Path(ref qpath) if self.reject_calls_and_items => {
if let Some(typeck) = self.typeck
&& let Res::Def(_, did) = typeck.qpath_res(qpath, ex.hir_id)
&& !did.is_local()
{
return ControlFlow::Break(
"external definitions are unsupported in anonymous constants".into(),
);
}
}
_ => {}
}
intravisit::walk_expr(self, ex)
}
fn visit_path(&mut self, path: &hir::Path<'v>, _id: hir::HirId) -> Self::Result {
if self.reject_calls_and_items
&& let Res::Def(_, did) = path.res
&& !did.is_local()
{
return ControlFlow::Break(
"external definitions are unsupported in anonymous constants".into(),
);
}
intravisit::walk_path(self, path)
}
}
fn check_const_hir_safety(
tcx: TyCtxt<'_>,
def: LocalDefId,
reject_calls_and_items: bool,
context: &str,
) -> extract::Result<()> {
let body = tcx.hir_body_owned_by(def);
let typeck = reject_calls_and_items.then(|| tcx.typeck(tcx.typeck_root_def_id_local(def)));
let mut visitor = ConstHirSafetyVisitor { reject_calls_and_items, typeck };
if let ControlFlow::Break(reason) = intravisit::Visitor::visit_body(&mut visitor, body) {
return Err(format!("{context}: {reason}"));
}
Ok(())
}
/// The most distinct instances of generic crate-local functions that capture
/// reaches through calls (transitive instantiation) before failing closed.
const MAX_CALLED_INSTANCES: usize = 512;
/// The deepest chain of calls of generic crate-local functions, each
/// instantiated by its caller, that capture follows before failing closed.
const MAX_INSTANTIATION_DEPTH: u32 = 32;
/// Resolved `--exclude-trait` state for `--scope crate` capture.
///
/// Holds both the resolved sysroot `core` trait `DefId`s and the full local
/// exclusion set (every admitted `Impl { of_trait: true }` for an excluded
/// trait plus every local definition nested beneath one via the parent chain).
#[derive(Default)]
struct ExclusionIndex {
excluded_traits: HashMap<DefId, ir::ExcludedTrait>,
excluded_defs: HashMap<LocalDefId, ir::ExcludedTrait>,
}
/// Resolve each allowlisted `--exclude-trait` entry to its `DefId` in the
/// authenticated sysroot `core` crate via `tcx.diagnostic_items(core_krate)`
/// ("Returns the diagnostic items defined in a crate.") rather than by string-
/// matching paths.
///
/// The three allowlisted traits carry pinned `#[rustc_diagnostic_item]`
/// attributes in sysroot `core` (intervening attributes elided):
/// - `#[rustc_diagnostic_item = "Debug"]` ... `pub trait Debug: PointeeSized`
/// - `#[rustc_diagnostic_item = "Display"]` ...
/// `pub trait Display: PointeeSized`
/// - `#[rustc_diagnostic_item = "Error"]` ...
/// `pub trait Error: Debug + Display`
///
/// Pinning the lookup to `extract::sysroot_core_crate(tcx)` (the external
/// sysroot `core` defining `LangItem::Sized`) ensures no local crate or
/// shadowed module can spoof a diagnostic item.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/library/core/src/fmt/mod.rs#L1051-L1053
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/library/core/src/fmt/mod.rs#L1185-L1187
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/library/core/src/error.rs#L56-L59
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/queries.rs#L2222-L2227
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_hir/src/diagnostic_items.rs#L8-L13
fn resolve_excluded_traits(
tcx: TyCtxt<'_>,
requested: &BTreeSet<ir::ExcludedTrait>,
) -> Result<HashMap<DefId, ir::ExcludedTrait>, Failure> {
if requested.is_empty() {
return Ok(HashMap::new());
}
let Some(core_krate) = extract::sysroot_core_crate(tcx) else {
return Err(Failure::unsupported(
"--exclude-trait requires the authenticated sysroot `core` crate",
));
};
let diag_items = tcx.diagnostic_items(core_krate);
let mut resolved = HashMap::new();
for &tr in requested {
let diag_sym = match tr {
ir::ExcludedTrait::Debug => sym::Debug,
ir::ExcludedTrait::Display => sym::Display,
ir::ExcludedTrait::Error => Symbol::intern("Error"),
};
let Some(&trait_did) = diag_items.name_to_id.get(&diag_sym) else {
return Err(Failure::unsupported(format!(
"excluded trait `{}` diagnostic item `{}` not found in sysroot core",
tr.as_str(),
diag_sym
)));
};
if trait_did.is_local()
|| trait_did.krate != core_krate
|| tcx.def_kind(trait_did) != DefKind::Trait
{
return Err(Failure::unsupported(format!(
"excluded trait `{}` resolved to unexpected definition `{}`",
tr.as_str(),
tcx.def_path_str(trait_did)
)));
}
resolved.insert(trait_did, tr);
}
Ok(resolved)
}
/// Walk the local `DefId` parent chain via `tcx.opt_local_parent`
/// ("self.opt_parent(id.to_def_id()).map(DefId::expect_local)") to classify
/// every definition nested inside an excluded trait impl: assoc fns/consts/tys,
/// closures, and anon/inline consts in their bodies.
///
/// Short-circuits to `None` as soon as any ancestor on the path up to (but not
/// including) the excluded impl satisfies [`is_unexcludable_nested_def`], so
/// methods or items nested inside a coherence-global inner `impl` (or `static`,
/// `extern`, or exported macro) can never inherit exclusion from an enclosing
/// excluded trait impl.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/ty/mod.rs#L365-L367
fn find_excluded_ancestor(
tcx: TyCtxt<'_>,
def: LocalDefId,
excluded_impls: &HashMap<LocalDefId, ir::ExcludedTrait>,
) -> Option<ir::ExcludedTrait> {
let mut cur = Some(def);
while let Some(id) = cur {
if let Some(&tr) = excluded_impls.get(&id) {
return Some(tr);
}
if is_unexcludable_nested_def(tcx, id, tcx.def_kind(id)) {
return None;
}
cur = tcx.opt_local_parent(id);
}
None
}
/// Reject crate-wide or link-time escape hatches nested inside an excluded
/// trait impl (`global_asm!`, `extern` blocks, nested `impl` blocks, `static`
/// items, exported macros, or
/// `#[no_mangle]`/`#[export_name]`/`#[link_section]`/`#[linkage]`), keeping
/// them and all of their descendants in the required census instead of silently
/// excluding them.
///
/// Excluded code is never extracted, so it must also be unable to act without
/// a call edge from verified code. An `unsafe fn`, or a body containing a
/// user-written `unsafe` block or inline assembly (which can, for example,
/// register an `.init_array` constructor that runs before `main`), is
/// therefore unexcludable as well (see [`body_has_user_unsafe_or_asm`]).
fn is_unexcludable_nested_def(tcx: TyCtxt<'_>, def: LocalDefId, kind: DefKind) -> bool {
match kind {
DefKind::GlobalAsm
| DefKind::ForeignMod
| DefKind::ForeignTy
| DefKind::Impl { .. }
| DefKind::Static { .. } => true,
DefKind::Macro(..) => {
tcx.effective_visibilities(()).is_exported(def) || tcx.visibility(def).is_public()
}
DefKind::Fn | DefKind::AssocFn => {
let attrs = tcx.codegen_fn_attrs(def);
attrs.symbol_name.is_some()
|| attrs.link_section.is_some()
|| attrs.linkage.is_some()
|| attrs.import_linkage.is_some()
|| !attrs.foreign_item_symbol_aliases.is_empty()
|| attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
|| tcx.fn_sig(def).instantiate_identity().skip_binder().safety().is_unsafe()
|| body_has_user_unsafe_or_asm(tcx, def)
}
DefKind::Closure
| DefKind::Const { .. }
| DefKind::AssocConst { .. }
| DefKind::AnonConst
| DefKind::InlineConst => body_has_user_unsafe_or_asm(tcx, def),
_ => false,
}
}
/// Finds a user-written `unsafe` block or inline assembly (`asm!` or
/// `naked_asm!`) in one HIR body. Nested closures and inline or anonymous
/// constants own separate bodies and are checked as their own definitions.
///
/// Compiler-generated `unsafe` blocks are allowed: `format_args!` lowering and
/// derives emit them (`UnsafeSource::CompilerGenerated`), and source code
/// cannot produce that variant.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_hir/src/hir.rs#L2257-L2266
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_ast_lowering/src/format.rs#L511-L516
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_builtin_macros/src/deriving/mod.rs#L101-L114
struct UserUnsafeOrAsmVisitor;
impl<'v> intravisit::Visitor<'v> for UserUnsafeOrAsmVisitor {
type Result = ControlFlow<()>;
fn visit_block(&mut self, b: &'v hir::Block<'v>) -> Self::Result {
if matches!(b.rules, hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided)) {
return ControlFlow::Break(());
}
intravisit::walk_block(self, b)
}
fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) -> Self::Result {
if matches!(ex.kind, hir::ExprKind::InlineAsm(_)) {
return ControlFlow::Break(());
}
intravisit::walk_expr(self, ex)
}
}
/// Whether `def` owns a HIR body containing a user-written `unsafe` block or
/// inline assembly ([`UserUnsafeOrAsmVisitor`]).
fn body_has_user_unsafe_or_asm(tcx: TyCtxt<'_>, def: LocalDefId) -> bool {
tcx.hir_maybe_body_owned_by(def).is_some_and(|body| {
intravisit::Visitor::visit_body(&mut UserUnsafeOrAsmVisitor, body).is_break()
})
}
/// Build the full exclusion index for `--scope crate`.
///
/// Every candidate `Impl { of_trait: true }` whose trait matches an excluded
/// diagnostic item must still pass [`admit_safe_impl`]; unsafe, negative,
/// default, or const impls and impls with unmodeled attributes stay outside the
/// exclusion set so whole-crate admission refuses them.
fn build_exclusion_index(
tcx: TyCtxt<'_>,
requested: &BTreeSet<ir::ExcludedTrait>,
) -> Result<ExclusionIndex, Failure> {
if requested.is_empty() {
return Ok(ExclusionIndex::default());
}
let excluded_traits = resolve_excluded_traits(tcx, requested)?;
let mut excluded_impls = HashMap::new();
for def in tcx.iter_local_def_id() {
if tcx.def_kind(def) != (DefKind::Impl { of_trait: true }) {
continue;
}
let trait_did =
tcx.impl_trait_header(def).trait_ref.instantiate_identity().skip_norm_wip().def_id;
if let Some(&tr) = excluded_traits.get(&trait_did)
&& admit_safe_impl(tcx, def, true).is_ok()
{
excluded_impls.insert(def, tr);
}
}
let mut excluded_defs = HashMap::new();
for def in tcx.iter_local_def_id() {
if let Some(tr) = find_excluded_ancestor(tcx, def, &excluded_impls) {
excluded_defs.insert(def, tr);
}
}
Ok(ExclusionIndex { excluded_traits, excluded_defs })
}
impl ExclusionIndex {
fn is_empty(&self) -> bool {
self.excluded_traits.is_empty()
}
fn excluded_for_local(&self, def: LocalDefId) -> Option<ir::ExcludedTrait> {
self.excluded_defs.get(&def).copied()
}
fn check_def_id(
&self,
tcx: TyCtxt<'_>,
def_id: DefId,
context: &str,
) -> extract::Result<()> {
if let Some(local) = def_id.as_local()
&& let Some(&tr) = self.excluded_defs.get(&local)
{
return Err(format!(
"{context} references excluded item `{}` (excluded by `{}`)",
tcx.def_path_str(def_id),
tr.as_str()
));
}
if let Some(&tr) = self.excluded_traits.get(&def_id) {
return Err(format!(
"{context} references excluded trait `{}`",
tr.as_str()
));
}
Ok(())
}
/// Check whether a trait `principal_did` is itself excluded or has an
/// excluded supertrait, using `rustc_trait_selection::traits::supertraits`
/// ("elaborate(cx, [trait_ref.upcast(cx)]).filter_only_self()
/// .filter_to_traits()").
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_type_ir/src/elaborate.rs#L346-L351
fn check_trait_or_supertraits<'tcx>(
&self,
tcx: TyCtxt<'tcx>,
principal_did: DefId,
context: &str,
) -> extract::Result<()> {
if let Some(&tr) = self.excluded_traits.get(&principal_did) {
return Err(format!(
"{context} references `dyn {}` (excluded trait)",
tr.as_str()
));
}
for super_ref in rustc_trait_selection::traits::supertraits(
tcx,
ty::Binder::dummy(ty::TraitRef::identity(tcx, principal_did)),
) {
let super_did = super_ref.def_id();
if let Some(&tr) = self.excluded_traits.get(&super_did) {
return Err(format!(
"{context} references `dyn {}`, whose supertrait `{}` is excluded",
tcx.def_path_str(principal_did),
tr.as_str()
));
}
}
Ok(())
}
/// Check a `ty::FnDef` or `ty::Closure` type against the exclusion set.
///
/// Resolves monomorphic trait/function items with `Instance::try_resolve`
/// (`"Ok(Some(instance))"` or `Ok(None)`/`Err(ErrorGuaranteed)`), inspects
/// `tcx.trait_of_assoc` ("If the given DefId is an associated item of a
/// trait, returns the DefId of the trait; otherwise, returns None."),
/// checks `tcx.codegen_select_candidate` so default methods inherited by an
/// empty excluded trait impl (such as `core::error::Error::source`) fail
/// closed when `Self` selects a local excluded impl, and for non-local
/// `FnDef`s elaborates `tcx.predicates_of(def_id).instantiate(tcx, args)`
/// via `rustc_trait_selection::traits::elaborate` so external callees with
/// excluded-trait bounds (or supertrait bounds, e.g. `Result::unwrap`) fail
/// closed before reaching excluded impls. The predicates of a non-local
/// resolved instance are elaborated too, so a blanket impl bounded on an
/// excluded trait fails closed.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/ty/instance.rs#L489-L505
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/ty/mod.rs#L1962-L1969
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/queries.rs#L423-L425
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/queries.rs#L1580-L1585
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_type_ir/src/elaborate.rs#L84-L87
fn check_fn_ty<'tcx>(
&self,
tcx: TyCtxt<'tcx>,
typing_env: TypingEnv<'tcx>,
fn_ty: ty::Ty<'tcx>,
context: &str,
) -> extract::Result<()> {
match *fn_ty.kind() {
ty::FnDef(def_id, args) => {
self.check_def_id(tcx, def_id, context)?;
let excluded_assoc_trait = tcx
.trait_of_assoc(def_id)
.and_then(|trait_did| self.excluded_traits.get(&trait_did).map(|&tr| (trait_did, tr)));
let is_concrete = !fn_ty.has_non_region_param()
&& !fn_ty.has_non_region_infer()
&& !fn_ty.references_error();
if is_concrete {
match ty::Instance::try_resolve(tcx, typing_env, def_id, args) {
Ok(Some(instance)) => {
self.check_def_id(tcx, instance.def_id(), context)?;
// A non-local trait method can resolve to a
// blanket impl whose bounds name an excluded
// trait that `def_id`'s own predicates do not
// (e.g. `<E as ToString>::to_string` resolves
// through the `ToString` blanket impl for
// every `T: Display`), so elaborate the
// resolved item's predicates too.
if let ty::InstanceKind::Item(item_did) = instance.def
&& item_did != def_id
&& !item_did.is_local()
{
self.check_nonlocal_predicates(
tcx,
item_did,
instance.args,
context,
)?;
}
}
Ok(None) | Err(_) => {
if let Some((_, tr)) = excluded_assoc_trait {
return Err(format!(
"{context} references unresolvable item `{}` of excluded trait `{}`",
tcx.def_path_str(def_id),
tr.as_str()
));
}
}
}
if let Some((trait_did, _)) = excluded_assoc_trait {
let trait_ref = ty::TraitRef::from_assoc(tcx, trait_did, args);
match tcx.codegen_select_candidate(typing_env.as_query_input(trait_ref)) {
Ok(ImplSource::UserDefined(data)) => {
self.check_def_id(tcx, data.impl_def_id, context)?;
}
Ok(_) => {}
Err(_) => {
return Err(format!(
"{context} failed to select impl for excluded trait item `{}`",
tcx.def_path_str(def_id)
));
}
}
}
} else if let Some((_, tr)) = excluded_assoc_trait {
return Err(format!(
"{context} references polymorphic item `{}` of excluded trait `{}`",
tcx.def_path_str(def_id),
tr.as_str()
));
}
if !def_id.is_local() {
self.check_nonlocal_predicates(tcx, def_id, args, context)?;
}
Ok(())
}
ty::Closure(def_id, _) => self.check_def_id(tcx, def_id, context),
_ => Ok(()),
}
}
/// Elaborate `tcx.predicates_of(def_id).instantiate(tcx, args)` (which
/// includes the predicates of `def_id`'s parent impl or trait) for a
/// non-local item and check every trait bound, and its supertraits,
/// against the exclusion set.
fn check_nonlocal_predicates<'tcx>(
&self,
tcx: TyCtxt<'tcx>,
def_id: DefId,
args: ty::GenericArgsRef<'tcx>,
context: &str,
) -> extract::Result<()> {
let instantiated = tcx.predicates_of(def_id).instantiate(tcx, args);
let clauses = instantiated
.predicates
.into_iter()
.map(|pred| pred.skip_norm_wip());
for clause in rustc_trait_selection::traits::elaborate(tcx, clauses) {
if let ty::ClauseKind::Trait(trait_pred) = clause.kind().skip_binder() {
self.check_trait_or_supertraits(
tcx,
trait_pred.def_id(),
&format!(
"{context} (non-local callee `{}` trait bound)",
tcx.def_path_str(def_id)
),
)?;
}
}
Ok(())
}
/// Check all types nested in `ty` (via `ty.walk()`) for direct references
/// to excluded `FnDef`s, `Closure`s, local ADTs nested in excluded impls,
/// or `dyn <ExcludedTrait>` trait objects.
fn check_ty_mentions<'tcx>(
&self,
tcx: TyCtxt<'tcx>,
typing_env: TypingEnv<'tcx>,
ty: ty::Ty<'tcx>,
context: &str,
) -> extract::Result<()> {
for arg in ty.walk() {
let Some(nested) = arg.as_type() else {
continue;
};
match *nested.kind() {
ty::FnDef(..) | ty::Closure(..) => {
self.check_fn_ty(tcx, typing_env, nested, context)?;
}
ty::Adt(adt, _) => {
self.check_def_id(tcx, adt.did(), context)?;
}
ty::Dynamic(preds, ..) => {
if let Some(principal_did) = preds.principal_def_id() {
self.check_trait_or_supertraits(tcx, principal_did, context)?;
}
}
_ => {}
}
}
Ok(())
}
/// Check a `PointerCoercion::Unsize` coercion (`source_ty -> target_ty`)
/// for any `dyn` target naming an excluded trait (or a subtrait of one),
/// and for any vtable method entry (`VtblEntry::Method(instance)`) in
/// `tcx.vtable_entries` that resolves into `excluded_defs`.
///
/// Upstream `vtable_entries` returns `&'tcx [VtblEntry<'tcx>]` covering
/// "all methods of the trait, including those of its supertraits".
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/queries.rs#L1559-L1562
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/ty/vtable.rs#L13-L25
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_monomorphize/src/collector.rs#L1220-L1245
fn check_unsize_cast<'tcx>(
&self,
tcx: TyCtxt<'tcx>,
typing_env: TypingEnv<'tcx>,
source_ty: ty::Ty<'tcx>,
target_ty: ty::Ty<'tcx>,
context: &str,
) -> extract::Result<()> {
self.check_ty_mentions(tcx, typing_env, source_ty, context)?;
self.check_ty_mentions(tcx, typing_env, target_ty, context)?;
if source_ty.has_non_region_param()
|| target_ty.has_non_region_param()
|| source_ty.has_non_region_infer()
|| target_ty.has_non_region_infer()
|| source_ty.references_error()
|| target_ty.references_error()
{
return Ok(());
}
let (src_tail, dst_tail) = match (source_ty.kind(), target_ty.kind()) {
(
&ty::Ref(_, src_pt, _),
&ty::Ref(_, dst_pt, _) | &ty::RawPtr(dst_pt, _),
)
| (&ty::RawPtr(src_pt, _), &ty::RawPtr(dst_pt, _)) => {
tcx.struct_lockstep_tails_for_codegen(src_pt, dst_pt, typing_env)
}
_ => (source_ty, target_ty),
};
if let ty::Dynamic(preds, ..) = *dst_tail.kind()
&& !src_tail.is_trait()
&& let Some(principal) = preds.principal()
{
self.check_trait_or_supertraits(tcx, principal.def_id(), context)?;
let trait_ref =
tcx.instantiate_bound_regions_with_erased(principal.with_self_ty(tcx, src_tail));
for entry in tcx.vtable_entries(trait_ref) {
if let VtblEntry::Method(instance) = *entry {
self.check_def_id(tcx, instance.def_id(), context)?;
}
}
}
Ok(())
}
fn check_drop_ty<'tcx>(
&self,
tcx: TyCtxt<'tcx>,
typing_env: TypingEnv<'tcx>,
drop_ty: ty::Ty<'tcx>,
context: &str,
) -> extract::Result<()> {
self.check_ty_mentions(tcx, typing_env, drop_ty, context)?;
for arg in drop_ty.walk() {
if let Some(nested) = arg.as_type()
&& let ty::Adt(adt, _) = *nested.kind()
&& let Some(dtor) = adt.destructor(tcx)
{
self.check_def_id(tcx, dtor.did, context)?;
}
}
Ok(())
}
fn check_const_alloc<'tcx>(
&self,
tcx: TyCtxt<'tcx>,
alloc_id: AllocId,
seen: &mut BTreeSet<AllocId>,
context: &str,
) -> extract::Result<()> {
if !seen.insert(alloc_id) {
return Ok(());
}
match tcx.global_alloc(alloc_id) {
GlobalAlloc::Static(def_id) => self.check_def_id(tcx, def_id, context),
GlobalAlloc::Function { instance, .. } => {
self.check_def_id(tcx, instance.def_id(), context)
}
GlobalAlloc::VTable(vtable_ty, dyn_ty) => {
if let Some(principal_did) = dyn_ty.principal_def_id() {
self.check_trait_or_supertraits(tcx, principal_did, context)?;
}
if let Some(principal) = dyn_ty.principal() {
let trait_ref = tcx.instantiate_bound_regions_with_erased(
principal.with_self_ty(tcx, vtable_ty),
);
for entry in tcx.vtable_entries(trait_ref) {
if let VtblEntry::Method(instance) = *entry {
self.check_def_id(tcx, instance.def_id(), context)?;
}
}
}
Ok(())
}
GlobalAlloc::Memory(alloc) => {
for &prov in alloc.inner().provenance().ptrs().values() {
self.check_const_alloc(tcx, prov.alloc_id(), seen, context)?;
}
Ok(())
}
GlobalAlloc::TypeId { .. } => Ok(()),
}
}
/// Check a MIR constant operand, including any promoted MIR body referenced
/// by `Const::Unevaluated { promoted: Some(p), .. }` via `tcx.promoted_mir`
/// ("This function returns all promoteds in the specified body.").
/// `promoted_mir` steals only `tcx.mir_promoted(def).1`, never the main
/// `Runtime(PostCleanup)` body.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/queries.rs#L741-L750
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_mir_transform/src/lib.rs#L821-L838
fn check_mir_const<'tcx>(
&self,
tcx: TyCtxt<'tcx>,
typing_env: TypingEnv<'tcx>,
constant: mir::Const<'tcx>,
seen_promoted: &mut HashSet<(DefId, mir::Promoted)>,
context: &str,
) -> extract::Result<()> {
self.check_ty_mentions(tcx, typing_env, constant.ty(), context)?;
match constant {
mir::Const::Unevaluated(uv, _) => {
self.check_def_id(tcx, uv.def, context)?;
if let Some(promoted) = uv.promoted
&& seen_promoted.insert((uv.def, promoted))
{
let promoteds = tcx.promoted_mir(uv.def);
let Some(promoted_body) = promoteds.get(promoted) else {
return Err(format!(
"{context} references missing promoted `{promoted:?}` in `{}`",
tcx.def_path_str(uv.def)
));
};
self.check_body_disjoint_inner(
tcx,
typing_env,
promoted_body,
seen_promoted,
)
.map_err(|reason| {
format!(
"{context} (promoted `{promoted:?}` of `{}`): {reason}",
tcx.def_path_str(uv.def)
)
})?;
}
}
mir::Const::Val(val, _) => {
let mut seen = BTreeSet::new();
match val {
mir::ConstValue::Scalar(Scalar::Ptr(ptr, _)) => {
self.check_const_alloc(tcx, ptr.provenance.alloc_id(), &mut seen, context)?;
}
mir::ConstValue::Indirect { alloc_id, .. }
| mir::ConstValue::Slice { alloc_id, .. } => {
self.check_const_alloc(tcx, alloc_id, &mut seen, context)?;
}
mir::ConstValue::ZeroSized | mir::ConstValue::Scalar(Scalar::Int(_)) => {}
}
}
mir::Const::Ty(..) => {}
}
Ok(())
}
/// Inspect a `Runtime(PostCleanup)` or CTFE MIR body for any reference to
/// an excluded trait or excluded local definition (direct calls, fn-item
/// constants, `ReifyFnPointer`/`ClosureFnPointer`/`Unsize` coercions,
/// `required_consts`, promoted bodies, local/constant types, and global
/// allocations).
fn check_body_disjoint<'tcx>(
&self,
tcx: TyCtxt<'tcx>,
typing_env: TypingEnv<'tcx>,
body: &mir::Body<'tcx>,
) -> extract::Result<()> {
if self.excluded_traits.is_empty() {
return Ok(());
}
let mut seen_promoted = HashSet::new();
self.check_body_disjoint_inner(tcx, typing_env, body, &mut seen_promoted)
}
fn check_body_disjoint_inner<'tcx>(
&self,
tcx: TyCtxt<'tcx>,
typing_env: TypingEnv<'tcx>,
body: &mir::Body<'tcx>,
seen_promoted: &mut HashSet<(DefId, mir::Promoted)>,
) -> extract::Result<()> {
for decl in body.local_decls.iter() {
self.check_ty_mentions(tcx, typing_env, decl.ty, "MIR local declaration")?;
}
if let Some(req_consts) = body.required_consts.as_deref() {
for const_op in req_consts {
self.check_mir_const(
tcx,
typing_env,
const_op.const_,
seen_promoted,
"MIR required_consts",
)?;
}
}
struct DisjointVisitor<'a, 'tcx> {
index: &'a ExclusionIndex,
tcx: TyCtxt<'tcx>,
typing_env: TypingEnv<'tcx>,
body: &'a mir::Body<'tcx>,
seen_promoted: &'a mut HashSet<(DefId, mir::Promoted)>,
violation: Option<String>,
}
impl<'tcx> DisjointVisitor<'_, 'tcx> {
fn record(&mut self, res: extract::Result<()>) {
if self.violation.is_none()
&& let Err(msg) = res
{
self.violation = Some(msg);
}
}
}
impl<'tcx> MirVisitor<'tcx> for DisjointVisitor<'_, 'tcx> {
fn visit_terminator(
&mut self,
terminator: &mir::Terminator<'tcx>,
location: mir::Location,
) {
if self.violation.is_some() {
return;
}
match &terminator.kind {
mir::TerminatorKind::Call { func, .. }
| mir::TerminatorKind::TailCall { func, .. } => {
let fn_ty = func.ty(self.body, self.tcx);
let res = self.index.check_fn_ty(
self.tcx,
self.typing_env,
fn_ty,
"direct call",
);
self.record(res);
}
mir::TerminatorKind::Drop { place, .. } => {
let drop_ty = place.ty(self.body, self.tcx).ty;
let res = self.index.check_drop_ty(
self.tcx,
self.typing_env,
drop_ty,
"drop terminator",
);
self.record(res);
}
mir::TerminatorKind::InlineAsm { operands, .. } => {
for op in operands {
if let mir::InlineAsmOperand::SymFn { value } = op {
let res = self.index.check_fn_ty(
self.tcx,
self.typing_env,
value.const_.ty(),
"inline asm sym fn",
);
self.record(res);
}
}
}
_ => {}
}
self.super_terminator(terminator, location);
}
fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>, location: mir::Location) {
if self.violation.is_some() {
return;
}
match rvalue {
mir::Rvalue::Cast(
mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _),
operand,
target_ty,
) => {
let source_ty = operand.ty(self.body, self.tcx);
let res = self.index.check_unsize_cast(
self.tcx,
self.typing_env,
source_ty,
*target_ty,
"Unsize coercion",
);
self.record(res);
}
mir::Rvalue::Cast(
mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer(_), _),
operand,
_,
) => {
let fn_ty = operand.ty(self.body, self.tcx);
let res = self.index.check_fn_ty(
self.tcx,
self.typing_env,
fn_ty,
"reify-to-fn-ptr cast",
);
self.record(res);
}
mir::Rvalue::Cast(
mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _),
operand,
_,
) => {
let closure_ty = operand.ty(self.body, self.tcx);
let res = self.index.check_fn_ty(
self.tcx,
self.typing_env,
closure_ty,
"closure-to-fn-ptr cast",
);
self.record(res);
}
_ => {}
}
self.super_rvalue(rvalue, location);
}
fn visit_const_operand(
&mut self,
constant: &mir::ConstOperand<'tcx>,
location: mir::Location,
) {
if self.violation.is_some() {
return;
}
let res = self.index.check_mir_const(
self.tcx,
self.typing_env,
constant.const_,
self.seen_promoted,
"MIR constant",
);
self.record(res);
self.super_const_operand(constant, location);
}
}
let mut visitor = DisjointVisitor {
index: self,
tcx,
typing_env,
body,
seen_promoted,
violation: None,
};
visitor.visit_body(body);
if let Some(msg) = visitor.violation {
return Err(msg);
}
Ok(())
}
/// Inspect `tcx.optimized_mir(def).mentioned_items` after all
/// `Runtime(PostCleanup)` bodies have been extracted so `optimized_mir`
/// never steals a body prematurely.
///
/// `rustc_mir_transform::mentioned_items::MentionedItems` runs inside
/// `inner_optimized_mir` ("Before doing anything, remember which items are
/// being mentioned so that the set of items visited does not depend on the
/// optimization level") and populates `Body::mentioned_items` with
/// `MentionedItem::{Fn, Drop, UnsizeCast, Closure}`. Keep the match
/// exhaustive and fail closed if `mentioned_items` is `None`.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/mir/mod.rs#L189-L202
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/mir/mod.rs#L273-L285
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_mir_transform/src/lib.rs#L802-L805
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_mir_transform/src/mentioned_items.rs#L35-L120
///
/// For an `instance` of a generic `def`, each mentioned item is first
/// instantiated with the instance's arguments, as `rustc`'s
/// monomorphization collector does with `mentioned_items`, so the checks
/// see the concrete types the instance runs with.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_monomorphize/src/collector.rs#L1355-L1362
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_monomorphize/src/collector.rs#L691-L702
fn check_mentioned_items<'tcx>(
&self,
tcx: TyCtxt<'tcx>,
def: LocalDefId,
instance: Option<ty::Instance<'tcx>>,
typing_env: TypingEnv<'tcx>,
) -> extract::Result<()> {
if self.excluded_traits.is_empty() {
return Ok(());
}
let opt_body = tcx.optimized_mir(def.to_def_id());
let Some(mentioned) = opt_body.mentioned_items.as_deref() else {
return Err("MIR mentioned_items unavailable for exclusion disjointness check".into());
};
let concrete = |t: ty::Ty<'tcx>| -> extract::Result<ty::Ty<'tcx>> {
match instance {
None => Ok(t),
Some(instance) => instance
.try_instantiate_mir_and_normalize_erasing_regions(
tcx,
typing_env,
ty::EarlyBinder::bind(t),
)
.map_err(|_| {
format!(
"failed to instantiate MIR mentioned item `{t}` for `{}`",
tcx.def_path_str_with_args(instance.def_id(), instance.args)
)
}),
}
};
for item in mentioned {
match item.node {
mir::MentionedItem::Fn(fn_ty) => {
self.check_fn_ty(tcx, typing_env, concrete(fn_ty)?, "MIR mentioned_items::Fn")?;
}
mir::MentionedItem::Drop(drop_ty) => {
self.check_drop_ty(
tcx,
typing_env,
concrete(drop_ty)?,
"MIR mentioned_items::Drop",
)?;
}
mir::MentionedItem::UnsizeCast { source_ty, target_ty } => {
self.check_unsize_cast(
tcx,
typing_env,
concrete(source_ty)?,
concrete(target_ty)?,
"MIR mentioned_items::UnsizeCast",
)?;
}
mir::MentionedItem::Closure(closure_ty) => {
self.check_fn_ty(
tcx,
typing_env,
concrete(closure_ty)?,
"MIR mentioned_items::Closure",
)?;
}
}
}
Ok(())
}
}
fn admit_const_item(
tcx: TyCtxt<'_>,
def: LocalDefId,
is_assoc: bool,
is_type_const: bool,
has_body: bool,
exclusion_index: &ExclusionIndex,
crate_facts: &tripwires::CrateFacts<'_>,
) -> extract::Result<()> {
let kind_label = if is_assoc { "AssocConst" } else { "Const" };
let context = format!(
"whole-crate obligation is unsupported: {kind_label} {{ is_type_const: {is_type_const} }}"
);
if is_type_const {
return Err(context);
}
check_non_callable_attrs(tcx, def, ExtraAttr::None, &context)?;
if !has_body {
if is_assoc && tcx.def_kind(tcx.local_parent(def)) == DefKind::Trait {
return admit_safe_trait(tcx, tcx.local_parent(def));
}
return Err(format!("{context} (missing constant body)"));
}
if tcx.generics_of(def).count() != 0 {
return Err(format!(
"{context} (generic constants require quantified instantiation obligations)"
));
}
let raw_ty = tcx.type_of(def).instantiate_identity();
let ty = tcx
.try_normalize_erasing_regions(TypingEnv::fully_monomorphized(), raw_ty)
.map_err(|_| format!("{context}: failed to normalize constant type"))?;
if ty.has_non_region_param() || ty.has_non_region_infer() || ty.references_error() {
return Err(format!("{context}: generic or erroneous constant type {ty:?}"));
}
const_ty_is_pure_value(tcx, ty, &context)?;
check_const_hir_safety(tcx, def, false, &context)?;
let ctfe_mir = tcx.mir_for_ctfe(def.to_def_id());
if ctfe_mir.tainted_by_errors.is_some() {
return Err(format!("{context}: constant MIR tainted by compiler errors"));
}
let def_path = extract::canonical_def_path(tcx, def);
tripwires::check_mir_body(crate_facts, &def_path, ctfe_mir)?;
exclusion_index
.check_body_disjoint(tcx, TypingEnv::fully_monomorphized(), ctfe_mir)
.map_err(|reason| format!("{context}: {reason}"))?;
let val = tcx
.const_eval_poly(def.to_def_id())
.map_err(|err| format!("{context}: constant failed CTFE: {err:?}"))?;
check_const_value_pure(tcx, ty, val, &context)
}
/// Admit pure scalar `AnonConst` items (literal/arithmetic array lengths,
/// repeat counts, and explicit enum discriminants) while rejecting `GCE`/`GCA`
/// const-generics, `unsafe` blocks, calls, nested items, external references,
/// and generic-dependent constants.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_hir_analysis/src/collect/generics_of.rs#L97-L104
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/mir/interpret/queries.rs#L15-L29
fn admit_anon_const(
tcx: TyCtxt<'_>,
def: LocalDefId,
has_body: bool,
exclusion_index: &ExclusionIndex,
crate_facts: &tripwires::CrateFacts<'_>,
) -> extract::Result<()> {
let context = "whole-crate obligation is unsupported: AnonConst";
if !has_body {
return Err(format!("{context} (missing body)"));
}
if matches!(
tcx.anon_const_kind(def.to_def_id()),
ty::AnonConstKind::GCE | ty::AnonConstKind::GCA
) {
return Err(format!("{context} (generic const expr/arg)"));
}
check_non_callable_attrs(tcx, def, ExtraAttr::None, context)?;
check_const_hir_safety(tcx, def, true, context)?;
let raw_ty = tcx.type_of(def).instantiate_identity();
let ty = tcx
.try_normalize_erasing_regions(TypingEnv::fully_monomorphized(), raw_ty)
.map_err(|_| format!("{context}: failed to normalize type"))?;
if !matches!(ty.kind(), ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char) {
return Err(format!("{context}: unsupported scalar type {ty:?}"));
}
let ctfe_mir = tcx.mir_for_ctfe(def.to_def_id());
if ctfe_mir.tainted_by_errors.is_some() {
return Err(format!("{context}: MIR tainted by compiler errors"));
}
let def_path = extract::canonical_def_path(tcx, def);
tripwires::check_mir_body(crate_facts, &def_path, ctfe_mir)?;
exclusion_index
.check_body_disjoint(tcx, TypingEnv::fully_monomorphized(), ctfe_mir)
.map_err(|reason| format!("{context}: {reason}"))?;
for block in ctfe_mir.basic_blocks.iter() {
let Some(term) = &block.terminator else {
return Err(format!("{context}: missing terminator in CTFE MIR"));
};
if matches!(
term.kind,
mir::TerminatorKind::Call { .. }
| mir::TerminatorKind::TailCall { .. }
| mir::TerminatorKind::Drop { .. }
| mir::TerminatorKind::InlineAsm { .. }
| mir::TerminatorKind::Yield { .. }
| mir::TerminatorKind::CoroutineDrop
) {
return Err(format!("{context}: unsupported CTFE MIR terminator {:?}", term.kind));
}
}
let val = tcx
.const_eval_poly(def.to_def_id())
.map_err(|err| format!("{context}: failed CTFE: {err:?}"))?;
if val.try_to_scalar_int().is_none() {
return Err(format!("{context}: expected concrete scalar integer constant"));
}
Ok(())
}
/// Return `true` when `item` is an `#[anneal::assume_stub(...)]` tool
/// attribute.
fn is_anneal_assume_stub_attr(item: &hir::AttrItem) -> bool {
let segments = item.path.segments.as_ref();
segments.len() == 2
&& segments[0].as_str() == "anneal"
&& segments[1].as_str() == "assume_stub"
}
/// Resolve `def` to its `HirId` without panicking on synthetic
/// `MaybeOwner::Phantom` definitions (such as RPIT opaque-type lifetime
/// parameters `{opaque#0}::'a`), mirroring `rustc_middle/src/hir/map.rs`
/// lines 107-113 and `rustc_middle/src/hir/mod.rs` lines 489-500
/// (`rust-lang/rust` `f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1`).
fn opt_local_hir_id(tcx: TyCtxt<'_>, def: LocalDefId) -> Option<hir::HirId> {
match tcx.hir_crate(()).owner(tcx, def) {
hir::MaybeOwner::Owner(_) => Some(hir::HirId::make_owner(def)),
hir::MaybeOwner::NonOwner(hir_id) => Some(hir_id),
hir::MaybeOwner::Phantom => None,
}
}
/// Parse and validate any `#[anneal::assume_stub(reason = "...")]` HIR tool
/// attribute attached to `def`.
///
/// Fails closed on duplicate attributes, missing or non-parenthesized
/// arguments, wrong or extra keys, non-string values, or empty/whitespace-only
/// reasons.
fn parse_assume_stub_attr(tcx: TyCtxt<'_>, def: LocalDefId) -> extract::Result<Option<String>> {
let Some(hir_id) = opt_local_hir_id(tcx, def) else {
return Ok(None);
};
let mut found: Option<String> = None;
for attr in tcx.hir_attrs(hir_id) {
let hir::Attribute::Unparsed(item) = attr else {
continue;
};
if !is_anneal_assume_stub_attr(item) {
continue;
}
if found.is_some() {
return Err("duplicate `#[anneal::assume_stub(...)]` attribute is unsupported".into());
}
let hir::AttrArgs::Delimited(delim) = &item.args else {
return Err(
"`#[anneal::assume_stub]` requires a non-empty `reason = \"...\"` argument".into(),
);
};
if delim.delim != rustc_ast::token::Delimiter::Parenthesis {
return Err(
"`#[anneal::assume_stub]` requires parenthesized `reason = \"...\"`".into(),
);
}
let Some(items) = attr.meta_item_list() else {
return Err(
"`#[anneal::assume_stub]` requires a non-empty `reason = \"...\"` argument".into(),
);
};
if items.len() != 1 {
return Err(
"`#[anneal::assume_stub]` expects exactly one `reason = \"...\"` argument".into(),
);
}
let Some(meta) = items[0].meta_item() else {
return Err(
"`#[anneal::assume_stub]` requires a non-empty `reason = \"...\"` argument".into(),
);
};
let is_reason_key = meta.path.segments.len() == 1
&& meta.path.segments[0].ident.name.as_str() == "reason";
if !is_reason_key {
return Err(
"`#[anneal::assume_stub]` requires a `reason = \"...\"` key-value argument".into(),
);
}
let Some(reason_sym) = meta.value_str() else {
return Err(
"`#[anneal::assume_stub]` requires a string literal `reason = \"...\"`".into(),
);
};
let reason = reason_sym.as_str();
if reason.trim().is_empty() {
return Err(
"`#[anneal::assume_stub]` requires a non-empty `reason = \"...\"`".into(),
);
}
if reason.chars().any(|c| {
c.is_control()
|| matches!(
c,
'\u{AD}'
| '\u{61C}'
| '\u{180E}'
| '\u{200B}'..='\u{200F}'
| '\u{2028}'..='\u{202E}'
| '\u{2060}'..='\u{206F}'
| '\u{FEFF}'
)
}) {
return Err(
"`#[anneal::assume_stub]` reason must not contain control or formatting characters"
.into(),
);
}
found = Some(reason.to_owned());
}
Ok(found)
}
/// Validate HIR attributes on an explicitly stubbed `Fn`, `AssocFn`, or
/// `ForeignMod` `extern` function item.
///
/// Admits `#[anneal::assume_stub(reason = "...")]`, `#[target_feature(...)]`,
/// admitted `#[inline]` modes, `#[cold]`, `#[optimize(...)]`, and benign
/// doc/lint/clippy/rustfmt attributes; fails closed on any other unmodeled
/// attribute.
fn check_stub_hir_attrs(tcx: TyCtxt<'_>, def: LocalDefId) -> extract::Result<()> {
let Some(hir_id) = opt_local_hir_id(tcx, def) else {
return Err("stubbed item has no HIR node".into());
};
for attr in tcx.hir_attrs(hir_id) {
match attr {
hir::Attribute::Parsed(AttributeKind::Inline(inline, _))
if inline_mode_admitted(inline) => {}
hir::Attribute::Parsed(kind) => match kind {
AttributeKind::AutomaticallyDerived
| AttributeKind::CfgAttrTrace
| AttributeKind::CfgTrace(_)
| AttributeKind::Cold
| AttributeKind::Deprecated { .. }
| AttributeKind::Doc(_)
| AttributeKind::DocComment { .. }
| AttributeKind::DoNotRecommend
| AttributeKind::MustUse { .. }
| AttributeKind::OnConst { .. }
| AttributeKind::OnMove { .. }
| AttributeKind::OnUnimplemented { .. }
| AttributeKind::OnUnknown { .. }
| AttributeKind::OnUnmatchArgs { .. }
| AttributeKind::Optimize(_, _)
| AttributeKind::TargetFeature { .. } => {}
other => {
return Err(format!(
"stubbed item: unmodeled attribute {other:?} is unsupported"
));
}
},
hir::Attribute::Unparsed(item) => {
if is_anneal_assume_stub_attr(item) {
continue;
}
let segments = item.path.segments.as_ref();
let is_lint_attr = segments.len() == 1
&& matches!(
segments[0],
sym::allow | sym::warn | sym::deny | sym::forbid | sym::expect
);
let is_tool_attr =
segments.len() >= 2 && matches!(segments[0].as_str(), "clippy" | "rustfmt");
if !is_lint_attr && !is_tool_attr {
return Err(format!(
"stubbed item: unmodeled attribute `{}` is unsupported",
item.path
));
}
}
}
}
Ok(())
}
/// Whether `def` is eligible to be stubbed as an external declaration:
/// a local `Fn` or `AssocFn` with a body, or a `ForeignMod` `extern` `Fn`
/// declaration (bodyless `Fn` whose parent is `DefKind::ForeignMod`).
fn is_stubbable_item(tcx: TyCtxt<'_>, def: LocalDefId, kind: DefKind, has_body: bool) -> bool {
match kind {
DefKind::Fn | DefKind::AssocFn if has_body => true,
DefKind::Fn if !has_body => {
tcx.opt_local_parent(def).is_some_and(|parent| tcx.def_kind(parent) == DefKind::ForeignMod)
}
_ => false,
}
}
/// Index of all explicitly stubbed local items (via `#[anneal::assume_stub]` or
/// `--assume-stub <def_path>`).
#[derive(Default)]
struct StubIndex {
reasons: HashMap<LocalDefId, String>,
matched_paths: HashMap<LocalDefId, String>,
}
impl StubIndex {
fn is_stubbed(&self, def: LocalDefId) -> bool {
self.reasons.contains_key(&def)
}
fn reason(&self, def: LocalDefId) -> Option<&str> {
self.reasons.get(&def).map(String::as_str)
}
fn explicit_cli_path(&self, def: LocalDefId) -> Option<&str> {
self.matched_paths.get(&def).map(String::as_str)
}
/// Return the path recorded in `configuration.assumed_stubs` and
/// `manifest.census` for a stubbed item: the exact matched CLI
/// `--assume-stub` selector (preserving unambiguous untrimmed visible-path
/// parity with `cargo-anneal` and `anneal-spec-obligations`), the untrimmed
/// visible path when an attribute-only `AssocFn` stub shares an `Impl` or
/// `Trait` owner in `visible_owners`, or `extract::canonical_def_path`.
fn emitted_path_with_visible_owners(
&self,
tcx: TyCtxt<'_>,
def: LocalDefId,
visible_owners: &HashSet<LocalDefId>,
) -> String {
if let Some(matched) = self.matched_paths.get(&def) {
return matched.clone();
}
if matches!(tcx.def_kind(def), DefKind::AssocFn)
&& tcx.opt_local_parent(def).is_some_and(|p| visible_owners.contains(&p))
{
return extract::untrimmed_visible_def_path(tcx, def);
}
extract::canonical_def_path(tcx, def)
}
/// Return all stubbed item paths (sorted and deduplicated), covering both
/// `--assume-stub` CLI arguments and
/// `#[anneal::assume_stub(reason = "...")]` attributes.
fn sorted_paths_with_visible_owners(
&self,
tcx: TyCtxt<'_>,
visible_owners: &HashSet<LocalDefId>,
) -> Vec<String> {
let paths: BTreeSet<String> = self
.reasons
.keys()
.map(|&def| self.emitted_path_with_visible_owners(tcx, def, visible_owners))
.collect();
paths.into_iter().collect()
}
/// Return `true` when `def` is a body-internal compiler-synthesized child
/// (`Closure`, `AnonConst`, or `InlineConst`) nested strictly inside a
/// stubbed function's skipped `hir::Body` expression (NOT in the function's
/// signature, such as array-length `AnonConst`s in parameter/return types),
/// without crossing any crate-wide or link-time escape hatch (`GlobalAsm`,
/// `ForeignMod`, `ForeignTy`, `Impl`, `Static`, `Trait`, `Macro`, or
/// another `Fn`/`AssocFn`).
fn is_body_internal_child(&self, tcx: TyCtxt<'_>, def: LocalDefId, kind: DefKind) -> bool {
if !matches!(kind, DefKind::Closure | DefKind::AnonConst | DefKind::InlineConst) {
return false;
}
let Some(def_hir_id) = opt_local_hir_id(tcx, def) else {
return false;
};
let mut stub_parent = None;
let mut cur = tcx.opt_local_parent(def);
while let Some(parent) = cur {
if self.is_stubbed(parent) {
stub_parent = Some(parent);
break;
}
match tcx.def_kind(parent) {
DefKind::Closure | DefKind::AnonConst | DefKind::InlineConst => {
cur = tcx.opt_local_parent(parent);
}
_ => return false,
}
}
let Some(parent) = stub_parent else {
return false;
};
let Some(parent_hir_id) = opt_local_hir_id(tcx, parent) else {
return false;
};
let Some(body_id) = tcx.hir_node(parent_hir_id).body_id() else {
return false;
};
let body_val_id = tcx.hir_body(body_id).value.hir_id;
let mut cur_hir = def_hir_id;
while cur_hir != parent_hir_id {
if cur_hir == body_val_id {
return true;
}
let next = tcx.parent_hir_id(cur_hir);
if next == cur_hir {
return false;
}
cur_hir = next;
}
false
}
}
fn build_stub_index(
tcx: TyCtxt<'_>,
body_owners: &BTreeSet<u32>,
cli_stubs: &BTreeSet<String>,
exclusion_index: &ExclusionIndex,
) -> Result<StubIndex, Failure> {
for stub in cli_stubs {
if let Some(ext) = extract::shadowed_external_crate_prefix(tcx, stub) {
return Err(Failure::unsupported(format!(
"--assume-stub path `{stub}` is ambiguous: leading segment `{ext}` names an \
external crate"
)));
}
}
let mut index = StubIndex::default();
let mut matched_cli = BTreeSet::new();
let mut cli_ineligible: BTreeMap<String, Vec<(u32, DefKind)>> = BTreeMap::new();
let mut collisions = CallableCollisionIndex::default();
for stub in cli_stubs {
collisions.mark_selector_checked(stub);
}
let mut errors = Vec::new();
for def in tcx.iter_local_def_id() {
let kind = tcx.def_kind(def);
if kind == (DefKind::Impl { of_trait: true }) {
collisions.record_trait_impl(tcx, def);
}
let canon = extract::canonical_def_path(tcx, def);
let visible = extract::untrimmed_visible_def_path(tcx, def);
if callable(kind) {
collisions.record_def_with_paths(tcx, def, &canon, &visible);
}
let has_body = body_owners.contains(&def.local_def_index.as_u32());
let eligible = is_stubbable_item(tcx, def, kind, has_body);
let attr_reason = match parse_assume_stub_attr(tcx, def) {
Ok(reason) => reason,
Err(reason) => {
errors.push(ir::Unsupported {
def_id: def.local_def_index.as_u32(),
path: canon,
reason,
});
continue;
}
};
let matched_canon = cli_stubs.contains(&canon) && !matches!(kind, DefKind::Field);
let matched_visible =
visible != canon && cli_stubs.contains(&visible) && !matches!(kind, DefKind::Field);
if matched_canon && matched_visible {
return Err(Failure::unsupported(format!(
"duplicate --assume-stub selector: `{canon}` and `{visible}` name the same \
definition"
)));
}
let cli_matched_path = if matched_canon {
Some(canon.as_str())
} else if matched_visible {
Some(visible.as_str())
} else {
None
};
if attr_reason.is_none() && cli_matched_path.is_none() {
continue;
}
if !eligible {
if attr_reason.is_some() {
errors.push(ir::Unsupported {
def_id: def.local_def_index.as_u32(),
path: canon,
reason: format!(
"#[anneal::assume_stub] is supported only on `Fn`, `AssocFn` \
(with a body), and `ForeignMod` `extern` function items, not {kind:?}"
),
});
} else if let Some(matched_path) = cli_matched_path {
// Defer CLI mismatch errors until after the full local scan so
// a type- or module-namespace sibling (`struct`, `enum`, `mod`)
// sharing a canonical path with a value-namespace `fn` does
// not block stubbing the function.
cli_ineligible
.entry(matched_path.to_owned())
.or_default()
.push((def.local_def_index.as_u32(), kind));
}
continue;
}
if let Some(matched_path) = cli_matched_path {
matched_cli.insert(matched_path.to_owned());
index.matched_paths.insert(def, matched_path.to_owned());
}
collisions.mark_def_checked_with_paths(tcx, def, &canon, &visible, true);
if let Some(tr) = exclusion_index.excluded_for_local(def) {
errors.push(ir::Unsupported {
def_id: def.local_def_index.as_u32(),
path: canon,
reason: format!(
"item cannot be both stubbed and excluded by --exclude-trait `{}`",
tr.as_str()
),
});
continue;
}
let reason = attr_reason.unwrap_or_else(|| "--assume-stub".to_owned());
index.reasons.insert(def, reason);
}
collisions.check()?;
collisions.check_shadowed_external_crates(tcx)?;
for (path, entries) in cli_ineligible {
if matched_cli.contains(&path) {
continue;
}
for (def_id, kind) in entries {
errors.push(ir::Unsupported {
def_id,
path: path.clone(),
reason: format!(
"--assume-stub is supported only on `Fn`, `AssocFn` (with a body), \
and `ForeignMod` `extern` function items, not {kind:?}"
),
});
}
}
if !errors.is_empty() {
return Err(Failure::unsupported_items(errors));
}
if &matched_cli != cli_stubs {
let missing: Vec<&String> = cli_stubs.difference(&matched_cli).collect();
return Err(Failure::unsupported(format!(
"--assume-stub paths matched zero stubbable items: {missing:?}"
)));
}
Ok(index)
}
fn whole_crate_item(
tcx: TyCtxt<'_>,
def: LocalDefId,
has_body: bool,
exclusion_index: &ExclusionIndex,
stub_index: &StubIndex,
crate_facts: &tripwires::CrateFacts<'_>,
) -> extract::Result<()> {
let kind = tcx.def_kind(def);
if stub_index.is_stubbed(def) {
return check_stub_hir_attrs(tcx, def);
}
if stub_index.is_body_internal_child(tcx, def, kind) {
return Ok(());
}
match kind {
DefKind::Fn | DefKind::AssocFn if has_body => Ok(()),
DefKind::ForeignMod => {
check_non_callable_attrs(
tcx,
def,
ExtraAttr::None,
"whole-crate obligation is unsupported: ForeignMod",
)?;
let hir::ItemKind::ForeignMod { items, .. } = tcx.hir_expect_item(def).kind else {
return Err("whole-crate obligation is unsupported: ForeignMod".into());
};
if items.is_empty() {
return Err("empty ForeignMod block is unsupported".into());
}
for item_ref in items {
let child = item_ref.owner_id.def_id;
if tcx.def_kind(child) != DefKind::Fn {
return Err(format!(
"ForeignMod item `{}` of kind {:?} is unsupported",
extract::canonical_def_path(tcx, child),
tcx.def_kind(child)
));
}
if !stub_index.is_stubbed(child) {
return Err(format!(
"unstubbed ForeignMod extern function `{}` is unsupported \
(use #[anneal::assume_stub(reason = \"...\")] or --assume-stub)",
extract::canonical_def_path(tcx, child)
));
}
}
Ok(())
}
DefKind::AssocFn => {
let parent = tcx.local_parent(def);
if tcx.def_kind(parent) != DefKind::Trait {
return Err("whole-crate obligation is unsupported: AssocFn".into());
}
admit_safe_trait(tcx, parent)?;
if let Some(intrinsic) = tcx.intrinsic(def) {
return Err(format!(
"intrinsic `{}` is unsupported in trait declaration",
intrinsic.name
));
}
let sig = tcx.fn_sig(def).instantiate_identity().skip_binder();
if sig.safety().is_unsafe() {
return Err("unsafe trait method declarations are unsupported".into());
}
if sig.abi() != ExternAbi::Rust || sig.c_variadic() {
return Err("only non-variadic Rust ABI functions are admitted".into());
}
extract::codegen_attrs(tcx, def)?;
check_non_callable_attrs(
tcx,
def,
ExtraAttr::Inline,
"whole-crate obligation is unsupported: AssocFn",
)
}
DefKind::Trait => admit_safe_trait(tcx, def),
DefKind::Impl { of_trait } => admit_safe_impl(tcx, def, of_trait),
DefKind::Const { is_type_const } => {
admit_const_item(tcx, def, false, is_type_const, has_body, exclusion_index, crate_facts)
}
DefKind::AssocConst { is_type_const } => {
admit_const_item(tcx, def, true, is_type_const, has_body, exclusion_index, crate_facts)
}
DefKind::AnonConst => admit_anon_const(tcx, def, has_body, exclusion_index, crate_facts),
// `instantiate_identity` "Makes the identity replacement
// `T0 => T0, ..., TN => TN`", so a generic enum keeps its own
// parameters and `extract::ty` refuses it. The enum's own type has no
// projection for normalization to resolve.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_type_ir/src/binder.rs#L665-L673
DefKind::Enum => {
extract::ty(tcx, tcx.type_of(def).instantiate_identity().skip_norm_wip()).map(|_| ())
}
// As for `Enum`, `instantiate_identity` keeps a generic struct's own
// parameters, so `extract::ty` refuses it, as it refuses structs
// with `Drop`, unsafe or interior-mutable fields, unmodeled
// representations, and unsupported (including recursive) fields.
DefKind::Struct => {
check_non_callable_attrs(
tcx,
def,
ExtraAttr::Repr,
"whole-crate obligation is unsupported: Struct",
)?;
extract::ty(tcx, tcx.type_of(def).instantiate_identity().skip_norm_wip()).map(|_| ())
}
// `Ctor` "Refers to the struct or enum variant's constructor"; a
// function-like struct constructor builds exactly the struct's
// aggregate, so it is admitted with its struct.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_hir/src/def.rs#L99-L205
DefKind::Ctor(CtorOf::Struct, CtorKind::Fn) => {
let parent = tcx.local_parent(def);
if tcx.def_kind(parent) != DefKind::Struct {
return Err("whole-crate obligation is unsupported: Ctor".into());
}
whole_crate_item(tcx, parent, false, exclusion_index, stub_index, crate_facts)
}
other => Err(format!("whole-crate obligation is unsupported: {other:?}")),
}
}
pub(crate) struct CaptureArtifacts {
pub(crate) manifest: ir::Manifest,
pub(crate) ffi_exports: Option<crate::ffi_exports::FfiExportsManifest>,
}
struct Callbacks<'a> {
args: &'a Args,
declared_env: &'a BTreeMap<String, String>,
verified_sysroot: &'a Path,
verified_compiler: &'a identity::VerifiedCompiler,
scope: &'a ir::Scope,
reads: Arc<Mutex<Reads>>,
result: Option<Result<CaptureArtifacts, Failure>>,
}
impl rustc_driver::Callbacks for Callbacks<'_> {
fn config(&mut self, config: &mut interface::Config) {
crate::driver::configure(config);
// Pin both explicit and default sysroot unconditionally to the
// pre-verified logical sysroot so `rustc_session::filesearch` can
// never fall back to `AT_FDCWD` `./lib/rustlib`.
config.opts.sysroot.explicit = Some(self.verified_sysroot.to_path_buf());
config.opts.sysroot.default = self.verified_sysroot.to_path_buf();
if let Err(reason) = validate_compiler_options(
&config.opts,
self.args.crate_type.into(),
self.args.panic.into(),
self.args.overflow_checks,
FeaturePolicy::of(self.args),
) {
if let Ok(mut reads) = self.reads.lock() {
reads.tool_errors.push(reason.clone());
}
EarlyDiagCtxt::new(config.opts.error_format).early_fatal(reason);
}
// Populate `rustc`'s logical compile-time environment directly instead
// of mutating process environment variables or passing `--env-set`
// through argv. `lookup_env` checks `cx.sess.opts.logical_env.get(var)`
// before falling back to `std::env::var(var)`, so explicit `--env`
// bindings override ambient values without exposing them to the
// compiler process environment or response-file expansion.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_builtin_macros/src/env.rs#L21-L29
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_session/src/config.rs#L1436
for (key, value) in self.declared_env {
config.opts.logical_env.insert(key.clone(), value.clone());
}
config.override_queries = Some(override_queries);
// Imported sysroot sources appear under the compiler's virtual
// `/rustc/<commit>` prefix or, with `rust-src` installed, under the
// session's own `real_rust_source_base_dir`, which rustc derives from
// the sysroot pinned above (following one symlink). Use the session
// value rather than recomputing it so the roots match the decoder's
// names. See `snippet_roots` and `RecordingLoader::is_snippet_probe`.
config.file_loader = Some(Box::new(RecordingLoader::new(
self.reads.clone(),
self.args.source_file.iter().cloned().collect(),
snippet_roots(config.opts.real_rust_source_base_dir.as_deref()),
)));
}
fn after_crate_root_parsing(
&mut self,
compiler: &interface::Compiler,
krate: &mut Crate,
) -> Compilation {
// Refuse operator-allowed features in the hard-ban floor first, so a
// misconfigured allowlist is reported as such whatever the crate
// enables.
let policy = FeaturePolicy::of(self.args);
if let FeaturePolicy::Normal(operator) = policy
&& let Err(reason) = check_operator_features(operator)
{
if let Ok(mut reads) = self.reads.lock() {
reads.refusals.push(reason);
}
return Compilation::Stop;
}
// Reject `#![crate_type]` (other than a top-level restatement of
// `--crate-type=lib`; see `crate_type_attr_matches`) and
// `#![feature(rustc_private)]` (including under `#![cfg_attr]`) before
// macro expansion so sysroot `rustc-dev` proc-macro dylibs can never
// load or execute.
if let Err(reason) = validate_crate_root_attrs(&krate.attrs, self.args.crate_type.into()) {
if let Ok(mut reads) = self.reads.lock() {
reads.refusals.push(reason);
}
return Compilation::Stop;
}
// Refuse `cfg(miri)` before macro expansion so Miri-only `#[cfg(miri)]`
// branches or `#[cfg_attr(miri, ...)]` attributes cannot alter what is
// compiled or captured.
if let Err(reason) =
check_no_cfg_miri(compiler.sess.config.iter().map(|(name, _)| name.as_str()))
{
if let Ok(mut reads) = self.reads.lock() {
reads.refusals.push(reason);
}
return Compilation::Stop;
}
// Refuse any active `#![feature(...)]` outside the closed positive
// allowlist before macro expansion, while leaving inactive
// `#![cfg_attr(..., feature(...))]` lines (such as
// `zerocopy/src/lib.rs` under default cfgs) untouched.
if let Err(reason) = validate_active_crate_features(&compiler.sess, &krate.attrs, policy) {
if let Ok(mut reads) = self.reads.lock() {
reads.refusals.push(reason);
}
return Compilation::Stop;
}
Compilation::Continue
}
fn after_analysis<'tcx>(&mut self, _: &interface::Compiler, tcx: TyCtxt<'tcx>) -> Compilation {
self.result = Some(collect(
tcx,
self.args,
self.declared_env,
self.verified_sysroot,
self.verified_compiler,
self.scope,
&self.reads,
));
// Continue through metadata/object emission and rustc's final check.
// A candidate manifest is published only after the session returns
// successfully, so errors after this callback still prohibit capture.
// `run_compiler` finishes with "sess.dcx().abort_if_errors()".
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_interface/src/interface.rs#L491-L509
Compilation::Continue
}
}
/// Whether a top-level `#![crate_type = "..."]` restates the requested crate
/// type. Only `lib` and `rlib` on a `--crate-type=lib` capture qualify: both
/// parse to `CrateType::Rlib`, the default crate type, which capture already
/// passes on the command line. rustc reads the attribute only when the
/// command line names no crate type (`if base.is_empty()`), and
/// `validate_compiler_options` requires exactly the requested one there, so a
/// matching attribute selects nothing. Every other value, a non-literal
/// form, and any `crate_type` under `#![cfg_attr]` (which rustc itself
/// rejects when the predicate holds) stay refused before expansion.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_interface/src/passes.rs#L1429-L1449
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_hir/src/attrs/data_structures.rs#L640-L677
fn crate_type_attr_matches(meta: &MetaItem, expected: ir::CrateType) -> bool {
expected == ir::CrateType::Lib
&& meta.path == sym::crate_type
&& matches!(meta.value_str(), Some(sym::lib | sym::rlib))
}
fn validate_crate_root_meta(
meta: &MetaItem,
expected: ir::CrateType,
top_level: bool,
) -> Result<(), String> {
let last_ident = meta.path.segments.last().map(|seg| seg.ident.name);
let admitted = top_level && crate_type_attr_matches(meta, expected);
if last_ident == Some(sym::crate_type) && !admitted {
return Err("crate-level #![crate_type] attributes are unsupported during capture".into());
}
if last_ident == Some(sym::feature)
&& let Some(items) = meta.meta_item_list()
{
for item in items {
if item.has_name(sym::rustc_private) {
return Err("#![feature(rustc_private)] is unsupported during capture".into());
}
}
}
if last_ident == Some(sym::cfg_attr)
&& let Some(items) = meta.meta_item_list()
{
for item in items.iter().skip(1) {
if let MetaItemInner::MetaItem(nested) = item {
validate_crate_root_meta(nested, expected, false)?;
}
}
}
// Inside a `cfg_attr`, `Attribute::meta` parses `unsafe(feature(..))` as
// a meta item named `unsafe`, while `cfg_attr` expansion parses it as an
// unsafe-wrapped `feature(..)` attribute, so check what it wraps.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_parse/src/parser/attr.rs#L321-L334
if last_ident == Some(kw::Unsafe)
&& let Some(items) = meta.meta_item_list()
{
for item in items {
if let MetaItemInner::MetaItem(nested) = item {
validate_crate_root_meta(nested, expected, false)?;
}
}
}
Ok(())
}
/// `Attribute::meta` parses only parenthesized lists of meta items with
/// literal values, so it returns `None` for a whole `#![cfg_attr(..)]` if
/// any item uses a non-literal value such as `doc = concat!(..)`, while
/// rustc's own `cfg_attr` expansion accepts it. Refuse such `cfg_attr`,
/// `feature`, and `crate_type` attributes instead of skipping them, or a
/// `feature(rustc_private)` or `crate_type` item inside would go unchecked.
/// This also refuses harmless forms such as
/// `#![cfg_attr(not(doctest), doc = include_str!(..))]`.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_ast/src/attr/mod.rs#L288-L293
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_expand/src/config.rs#L248-L306
fn validate_crate_root_attrs(attrs: &[Attribute], expected: ir::CrateType) -> Result<(), String> {
for attr in attrs {
if let Some(meta) = attr.meta() {
validate_crate_root_meta(&meta, expected, true)?;
} else if attr.has_name(sym::crate_type) {
return Err(
"crate-level #![crate_type] attributes are unsupported during capture".into()
);
} else if attr.has_name(sym::cfg_attr) || attr.has_name(sym::feature) {
return Err("crate-level #![cfg_attr] or #![feature] attributes with \
unparsed (such as non-literal) arguments are unsupported during capture"
.into());
}
}
Ok(())
}
/// Version-pinned positive allowlist of crate-level `#![feature(...)]` gates
/// permitted under `--stdlib-crate core`.
///
/// Matches the exact set of `#![feature(...)]` declarations in the pinned
/// standard library crate root (`library/core/src/lib.rs`, sorted
/// lexicographically). Explicitly excludes post-capture-divergent and
/// host-loading gates such as `ergonomic_clones`, `rustc_private`, and
/// `custom_mir`.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/library/core/src/lib.rs#L97-L194
const STDLIB_CORE_ALLOWED_FEATURES: &[&str] = &[
"aarch64_unstable_target_feature",
"abi_unadjusted",
"adt_const_params",
"allow_internal_unsafe",
"allow_internal_unstable",
"arm_target_feature",
"asm_experimental_arch",
"auto_traits",
"avx10_target_feature",
"bstr_internals",
"cfg_sanitize",
"cfg_target_has_atomic",
"cfg_target_has_reliable_f16_f128",
"cfg_ub_checks",
"const_carrying_mul_add",
"const_closures",
"const_cmp",
"const_destruct",
"const_eval_select",
"const_precise_live_drops",
"const_select_unpredictable",
"const_trait_impl",
"core_intrinsics",
"coverage_attribute",
"decl_macro",
"deprecated_suggestion",
"derive_const",
"diagnostic_on_const",
"diagnostic_on_unmatch_args",
"disjoint_bitor",
"doc_cfg",
"doc_notable_trait",
"extern_types",
"f128",
"f16",
"field_projections",
"freeze_impls",
"fundamental",
"funnel_shifts",
"hexagon_target_feature",
"intra_doc_pointers",
"intrinsics",
"lang_items",
"link_cfg",
"link_llvm_intrinsics",
"loongarch_target_feature",
"macro_metavar_expr",
"macro_metavar_expr_concat",
"marker_trait_attr",
"min_specialization",
"mips_target_feature",
"movrs_target_feature",
"multiple_supertrait_upcastable",
"must_not_suspend",
"negative_impls",
"never_type",
"no_core",
"nvptx_target_feature",
"offset_of_enum",
"optimize_attribute",
"panic_internals",
"pattern_type_macro",
"pattern_types",
"pin_macro_internals",
"powerpc_target_feature",
"prelude_import",
"repr_simd",
"riscv_target_feature",
"rtm_target_feature",
"rustc_attrs",
"rustdoc_internals",
"s390x_target_feature",
"sealed",
"simd_ffi",
"staged_api",
"stmt_expr_attributes",
"strict_provenance_lints",
"trait_alias",
"transparent_unions",
"try_blocks",
"ub_checks",
"uint_carryless_mul",
"unboxed_closures",
"unsized_fn_params",
"wasm_target_feature",
"with_negative_coherence",
"x86_amx_intrinsics",
];
/// Feature gates that stay refused on normal crates even when the operator
/// names them via `--allow-unstable-feature`, in addition to every enabled
/// feature that `rustc_feature` itself classifies as internal
/// (`Features::internal`: internal language features, `core_intrinsics`, and
/// library features ending in `_internal` or `_internals`).
///
/// `rustc_private` is an unstable language feature that `Features::internal`
/// does not classify as internal, yet it loads compiler dylibs into the
/// capture process. `ergonomic_clones` lets post-capture `optimize_use_clone`
/// diverge from captured MIR (see `collect`).
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_feature/src/unstable.rs#L187-L207
// RUSTC-WORKAROUND(#4364): codegen rewrites `Use` calls after capture.
// RUSTC-WORKAROUND(#4361): `rustc` exposes no internal-feature table, and
// its `Features::internal` misses `rustc_private`, so this list supplements
// it explicitly.
const HARD_BANNED_FEATURES: &[&str] = &["ergonomic_clones", "rustc_private"];
/// The `#![feature(...)]` gates one capture may activate.
///
/// Normal crates admit no unstable feature by default. Enforcing a closed
/// positive allowlist (backed by expansion-time `-Zallow-features=` and
/// post-analysis `tcx.features()` inspection) prevents unmodeled nightly
/// features such as `ergonomic_clones`, `custom_mir`, `specialization`,
/// `const_eval_select`, `rustc_attrs`, `intrinsics`, `core_intrinsics`,
/// `generic_const_exprs`, and `adt_const_params` from altering lowering,
/// trait resolution, or post-capture codegen unless the operator names them.
/// Inactive `#![cfg_attr(..., feature(...))]` attributes (for example
/// `zerocopy/src/lib.rs` under default cfgs) remain admitted when their
/// configuration predicate evaluates to false.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_expand/src/config.rs#L50-L128
#[derive(Clone, Copy, Debug)]
pub(crate) enum FeaturePolicy<'a> {
/// A normal crate admits exactly the unstable features named by
/// `--allow-unstable-feature` (sorted and duplicate-free; empty by
/// default). `cargo anneal verify` taints every receipt produced under a
/// non-empty list, whether or not the crate enables those features.
Normal(&'a [String]),
/// `--stdlib-crate` admits its version-pinned feature set.
Stdlib(ir::StdlibCrate),
}
impl<'a> FeaturePolicy<'a> {
pub(crate) fn of(args: &'a Args) -> Self {
match args.stdlib_crate {
Some(krate) => Self::Stdlib(krate.into()),
None => Self::Normal(&args.allow_unstable_feature),
}
}
/// The exact `-Zallow-features` list, sorted as `rustc` stores it.
fn allowlist(self) -> Vec<&'a str> {
match self {
Self::Normal(operator) => operator.iter().map(String::as_str).collect(),
Self::Stdlib(ir::StdlibCrate::Core) => STDLIB_CORE_ALLOWED_FEATURES.to_vec(),
}
}
fn allows(self, feature: &str) -> bool {
match self {
Self::Normal(operator) => {
operator.binary_search_by(|allowed| allowed.as_str().cmp(feature)).is_ok()
}
Self::Stdlib(ir::StdlibCrate::Core) => {
STDLIB_CORE_ALLOWED_FEATURES.binary_search(&feature).is_ok()
}
}
}
/// Whether this policy admits `#![feature(...)]` attributes naming
/// language features that the pinned compiler has already stabilized
/// (`ACCEPTED_LANG_FEATURES`, recorded with `stable_since: Some(_)`).
///
/// Such an attribute activates no unstable behavior:
/// `rustc_expand::config::features` records it before consulting
/// `-Zallow-features`, and `check_unused_or_stable_features` only warns
/// (`stable_features`). Normal crates admit it without taint (`collect`
/// records it in `configuration.stabilized_features_present`), so a crate
/// that keeps the attribute for older compilers still verifies here.
/// `--stdlib-crate` keeps its exact pinned list. Stabilized library
/// features get no such exemption from `rustc`, so they stay subject to
/// the allowlist.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_expand/src/config.rs#L77-L98
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_passes/src/stability.rs#L958-L975
// RUSTC-WORKAROUND(#4360): `-Zallow-features` exempts stabilized language
// features but not stabilized library features; the lang-only exemption
// here mirrors that asymmetry.
fn admits_stabilized_lang_features(self) -> bool {
matches!(self, Self::Normal(_))
}
}
/// Check every enabled crate feature against the closed positive allowlist of
/// `policy`.
///
/// Disallowed features are collected into a `BTreeSet` so diagnostics remain
/// deterministic across source order and repeated attributes.
fn check_feature_allowlist<'a>(
enabled: impl IntoIterator<Item = &'a str>,
policy: FeaturePolicy<'_>,
) -> Result<(), String> {
let disallowed: BTreeSet<&str> =
enabled.into_iter().filter(|feat| !policy.allows(feat)).collect();
if disallowed.is_empty() {
return Ok(());
}
let scope_note = match policy {
FeaturePolicy::Normal(_) => {
"feature is not in the positive allowlist (see --allow-unstable-feature)"
}
FeaturePolicy::Stdlib(ir::StdlibCrate::Core) => {
"feature is not in the pinned --stdlib-crate core allowlist"
}
};
let extra = if disallowed.contains("ergonomic_clones") {
" (post-capture optimize_use_clone can diverge from captured MIR)"
} else {
""
};
let names: Vec<&str> = disallowed.into_iter().collect();
if names.len() == 1 {
Err(format!("#![feature({})] is unsupported during capture: {scope_note}{extra}", names[0]))
} else {
Err(format!(
"#![feature({})] are unsupported during capture: {scope_note}{extra}",
names.join(", ")
))
}
}
/// Whether `name` belongs to the non-overridable hard-ban floor. `features`
/// must enable `name`: `Features::internal` panics on a name that is neither
/// enabled nor declared as a language feature.
// RUSTC-WORKAROUND(#4361): `Features::internal` panics on undeclared,
// unenabled names, so callers classify only enabled names (see
// `enabled_probe`).
fn is_hard_banned(features: &Features, name: Symbol) -> bool {
HARD_BANNED_FEATURES.contains(&name.as_str()) || features.internal(name)
}
fn hard_ban_error(names: BTreeSet<&str>) -> Result<(), String> {
if names.is_empty() {
return Ok(());
}
let names: Vec<&str> = names.into_iter().collect();
Err(format!(
"#![feature({})] cannot be allowed during capture: compiler-internal and \
capture-divergent features stay refused even under --allow-unstable-feature",
names.join(", ")
))
}
/// Build a `Features` table enabling each of `names` the way
/// `rustc_expand::config::features` would if a crate enabled it: as an
/// unstable language feature when declared as one, and otherwise as a library
/// feature. Classifying with `rustc`'s own `Features::{internal, incomplete}`
/// keeps the hard-ban floor in step with the pinned compiler.
fn enabled_probe(names: &[String]) -> (Features, Vec<Symbol>) {
let mut probe = Features::default();
let names: Vec<Symbol> = names.iter().map(|name| Symbol::intern(name)).collect();
for &name in &names {
if UNSTABLE_LANG_FEATURES.iter().any(|feat| feat.name == name) {
probe.set_enabled_lang_feature(EnabledLangFeature {
gate_name: name,
attr_sp: DUMMY_SP,
stable_since: None,
});
} else {
probe.set_enabled_lib_feature(EnabledLibFeature { gate_name: name, attr_sp: DUMMY_SP });
}
}
(probe, names)
}
/// Refuse operator-named features in the hard-ban floor before compilation
/// proceeds.
fn check_operator_features(operator: &[String]) -> Result<(), String> {
let (probe, names) = enabled_probe(operator);
hard_ban_error(
operator
.iter()
.zip(&names)
.filter(|&(_, &name)| is_hard_banned(&probe, name))
.map(|(name, _)| name.as_str())
.collect(),
)
}
/// `#![feature(...)]` gates classified from `tcx.features()`.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct ObservedFeatures {
/// All enabled gated unstable features (sorted), populated across both
/// normal and `--stdlib-crate` captures for Phase-0 tripwire predicates.
pub(crate) tripwire_unstable: Vec<String>,
/// Enabled unstable language and library features recorded in normal-crate
/// manifests (sorted; empty on `--stdlib-crate` captures).
pub(crate) manifest_unstable: Vec<String>,
/// The subset of `manifest_unstable` that `rustc_feature` marks incomplete
/// (empty on `--stdlib-crate` captures).
pub(crate) manifest_incomplete: Vec<String>,
/// Enabled language features that the pinned compiler has stabilized
/// (empty on `--stdlib-crate` captures).
pub(crate) manifest_stabilized: Vec<String>,
}
/// Verify that every feature recorded in `tcx.features()` is admitted by
/// `policy`, reporting all enabled gated unstable features for Phase-0
/// tripwires and normal-crate manifest taint fields.
///
/// `rustc_expand::config::features` populates `enabled_lang_features` (both
/// unstable features and already-accepted `ACCEPTED_LANG_FEATURES` with
/// `stable_since: Some(_)`) and `enabled_lib_features`, and mirrors their union
/// in `enabled_features`. Because `-Zallow-features` skips
/// `ACCEPTED_LANG_FEATURES`, this check classifies them explicitly (see
/// `FeaturePolicy::admits_stabilized_lang_features`) and holds every other
/// feature to the allowlist and, on normal crates, to the hard-ban floor.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_expand/src/config.rs#L77-L115
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_feature/src/unstable.rs#L46-L111
pub(crate) fn check_allowed_features(
tcx: TyCtxt<'_>,
policy: FeaturePolicy<'_>,
) -> Result<ObservedFeatures, String> {
check_allowed_features_table(tcx.features(), policy)
}
fn check_allowed_features_table(
features: &Features,
policy: FeaturePolicy<'_>,
) -> Result<ObservedFeatures, String> {
// RUSTC-WORKAROUND(#4362): `tcx.features()` is crate-global with no record
// of which items a feature affected, so observations (and the receipt
// taint they back) are crate-level rather than per selected unit.
let mut gated: BTreeSet<Symbol> = BTreeSet::new();
let mut stabilized: BTreeSet<String> = BTreeSet::new();
for feat in features.enabled_lang_features() {
if feat.stable_since.is_some() && policy.admits_stabilized_lang_features() {
stabilized.insert(feat.gate_name.as_str().to_owned());
} else {
gated.insert(feat.gate_name);
}
}
gated.extend(features.enabled_lib_features().iter().map(|feat| feat.gate_name));
// `enabled_features` should be exactly the union classified above; a
// member outside it would otherwise escape both checks.
for name in features.enabled_features() {
if !gated.contains(name) && !stabilized.contains(name.as_str()) {
return Err(format!("#![feature({name})] escaped feature classification"));
}
}
if matches!(policy, FeaturePolicy::Normal(_)) {
hard_ban_error(
gated
.iter()
.filter(|&&name| is_hard_banned(features, name))
.map(|name| name.as_str())
.collect(),
)?;
}
check_feature_allowlist(gated.iter().map(|name| name.as_str()), policy)?;
let unstable: Vec<String> = gated
.iter()
.map(|name| name.as_str().to_owned())
.collect::<BTreeSet<_>>()
.into_iter()
.collect();
if !matches!(policy, FeaturePolicy::Normal(_)) {
return Ok(ObservedFeatures { tripwire_unstable: unstable, ..ObservedFeatures::default() });
}
let incomplete: BTreeSet<String> = gated
.iter()
.filter(|&&name| features.incomplete(name))
.map(|name| name.as_str().to_owned())
.collect();
Ok(ObservedFeatures {
tripwire_unstable: unstable.clone(),
manifest_unstable: unstable,
manifest_incomplete: incomplete.into_iter().collect(),
manifest_stabilized: stabilized.into_iter().collect(),
})
}
fn meta_mentions_feature(meta: &MetaItem) -> bool {
let last_ident = meta.path.segments.last().map(|seg| seg.ident.name);
if last_ident == Some(sym::feature) {
return true;
}
if last_ident == Some(sym::cfg_attr)
&& let Some(items) = meta.meta_item_list()
{
return items.iter().skip(1).any(|item| match item {
MetaItemInner::MetaItem(nested) => meta_mentions_feature(nested),
MetaItemInner::Lit(_) => false,
});
}
if last_ident == Some(kw::Unsafe)
&& let Some(items) = meta.meta_item_list()
{
return items.iter().any(|item| match item {
MetaItemInner::MetaItem(nested) => meta_mentions_feature(nested),
MetaItemInner::Lit(_) => false,
});
}
false
}
/// Evaluate only feature-bearing crate-root attributes through `rustc`'s own
/// `pre_configure_attrs` (`StripUnconfigured`) and check every active
/// `#![feature(...)]` against the closed positive allowlist before macro
/// expansion.
///
/// Limiting pre-configuration to attributes that mention `feature` avoids
/// duplicating lints on unrelated `#[cfg_attr]` attributes while matching
/// `rustc_interface::passes::create_and_enter_global_ctxt` on active vs.
/// inactive `#![cfg_attr(..., feature(...))]` predicates. If
/// `pre_configure_attrs` itself records compiler errors (such as a malformed
/// `cfg_attr` predicate), this function returns `Ok(())` so `rustc` reports
/// the compilation failure cleanly rather than masking it as an unsupported
/// refusal.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_interface/src/passes.rs#L925
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_expand/src/config.rs#L130-L144
fn validate_active_crate_features(
sess: &rustc_session::Session,
attrs: &[Attribute],
policy: FeaturePolicy<'_>,
) -> Result<(), String> {
if sess.dcx().has_errors().is_some() {
return Ok(());
}
let feature_attrs: Vec<Attribute> = attrs
.iter()
.filter(|attr| attr.meta().is_some_and(|meta| meta_mentions_feature(&meta)))
.cloned()
.collect();
if feature_attrs.is_empty() {
return Ok(());
}
let pre_configured = rustc_expand::config::pre_configure_attrs(sess, &feature_attrs);
if sess.dcx().has_errors().is_some() {
return Ok(());
}
let mut active_names = Vec::new();
for attr in &pre_configured {
if !attr.has_name(sym::feature) {
continue;
}
let Some(meta) = attr.meta() else {
return Err("crate-level #![feature] attribute with unparsed arguments is \
unsupported during capture"
.into());
};
let Some(items) = meta.meta_item_list() else {
return Err(
"crate-level #![feature] attribute must list feature identifiers during capture"
.into(),
);
};
for item in items {
if !item.is_word() {
return Err(
"crate-level #![feature] attribute must list feature identifiers during capture"
.into(),
);
}
let Some(ident) = item.ident() else {
return Err(
"crate-level #![feature] attribute must list feature identifiers during capture"
.into(),
);
};
active_names.push(ident.name);
}
}
let admits_stabilized = policy.admits_stabilized_lang_features();
check_feature_allowlist(
active_names
.iter()
.filter(|&&name| {
!(admits_stabilized && ACCEPTED_LANG_FEATURES.iter().any(|feat| feat.name == name))
})
.map(|name| name.as_str()),
policy,
)
}
/// Verify that `-Zallow-features` matches the exact closed positive allowlist
/// of `policy`.
///
/// `rustc`'s `parse_opt_comma_list` parses `Some(s)` via
/// `s.split(',').map(|s| s.to_string()).collect()` and sorts the result, so an
/// empty `-Zallow-features=` parses to `Some(vec![""])` (which matches no
/// feature identifier in `rustc_expand::config::features`). Accept either
/// `Some([])` or `Some([""])` for an empty allowlist, and require an exact
/// element-for-element match for non-empty allowlists.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_session/src/options.rs#L1059-L1069
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_expand/src/config.rs#L87-L98
fn validate_allow_features_option(opts: &Options, policy: FeaturePolicy<'_>) -> Result<(), String> {
let expected = policy.allowlist();
// RUSTC-WORKAROUND(#4360): `rustc` parses `-Zallow-features=` as
// `Some([""])` rather than `Some([])`, so both spell the empty allowlist.
let Some(actual) = opts.unstable_opts.allow_features.as_deref() else {
return Err("-Zallow-features must be explicitly configured during capture".into());
};
let matches = if expected.is_empty() {
actual.is_empty() || (actual.len() == 1 && actual[0].is_empty())
} else {
actual.len() == expected.len()
&& actual.iter().zip(&expected).all(|(got, want)| got == want)
};
if !matches {
return Err(format!(
"-Zallow-features disagreed with the capture allowlist (got {actual:?})"
));
}
Ok(())
}
/// Refuse `cfg(miri)` on every capture (both normal crates and
/// `--stdlib-crate`).
///
/// In the pinned standard library, `core::ub_checks::check_language_ub`
/// evaluates `!cfg!(miri) && intrinsics::ub_checks()` ("Disable UB checks in
/// Miri"), and real crates (such as `zerocopy/src/util/mod.rs` and
/// `zerocopy/src/pointer/ptr.rs`) branch on `#[cfg(miri)]` to substitute
/// Miri-only bodies or bypass checks that execute in non-Miri builds. Checking
/// the cfg name alone rejects both bare `--cfg miri` and key-value
/// `--cfg miri="..."`.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/library/core/src/ub_checks.rs#L96-L108
fn check_no_cfg_miri<'a>(cfgs: impl IntoIterator<Item = &'a str>) -> Result<(), String> {
if cfgs.into_iter().any(|name| name == "miri") {
return Err(
"cfg(miri) is forbidden during capture: it disables UB checks and selects Miri-only \
branches"
.into(),
);
}
Ok(())
}
fn validate_compiler_args(compiler_args: &[String]) -> Result<(), Failure> {
for arg in compiler_args {
if arg.starts_with('@') {
return Err(Failure::tool("response-file arguments are forbidden during capture"));
}
if arg == "--extern" || arg.starts_with("--extern=") || arg == "-L" || arg.starts_with("-L")
{
return Err(Failure::tool(format!(
"external crate and library search arguments are forbidden: {arg}"
)));
}
if arg == "--env-set" || arg.starts_with("--env-set=") {
return Err(Failure::tool(format!(
"raw compiler --env-set arguments are forbidden: {arg}"
)));
}
if arg == "--crate-type"
|| (arg.starts_with("--crate-type=")
&& !matches!(
arg.as_str(),
"--crate-type=lib" | "--crate-type=rlib" | "--crate-type=bin"
))
{
return Err(Failure::tool(format!("unsupported crate type during capture: {arg}")));
}
if arg == "-C"
|| arg == "-Cpanic"
|| (arg.starts_with("-Cpanic=")
&& !matches!(arg.as_str(), "-Cpanic=unwind" | "-Cpanic=abort"))
{
return Err(Failure::tool(format!(
"unsupported panic or split -C compiler option during capture: {arg}"
)));
}
}
Ok(())
}
fn rustc_crate_type(crate_type: ir::CrateType) -> CrateType {
match crate_type {
ir::CrateType::Lib => CrateType::Rlib,
ir::CrateType::Bin => CrateType::Executable,
}
}
/// Validate the captured compilation's optimization level (`-Copt-level=0`),
/// `-Zmir-opt-level=0`, debug-assertion, overflow-check, and UB-preservation
/// flags, returning the numeric optimization level encoded in
/// `ir::Configuration`.
///
/// `rustc` defines `OptLevel::No` as `"-Copt-level=0"`, computes
/// `"let debug_assertions = cg.debug_assertions.unwrap_or(opt_level ==`
/// `OptLevel::No);"`, and computes `Session::overflow_checks` as
/// `"self.opts.cg.overflow_checks.unwrap_or(self.opts.debug_assertions)"`.
/// Require explicit `-Coverflow-checks=no` (`Some(false)`) here so missing
/// flags cannot pass silently by defaulting through `debug_assertions`.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_session/src/config.rs#L91-L105
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_session/src/config.rs#L2629-L2634
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_session/src/session.rs#L724-L726
fn validate_profile_options(opts: &Options, expected_overflow_checks: bool) -> Result<u8, String> {
let opt_level = match opts.optimize {
OptLevel::No => 0,
other @ (OptLevel::Less
| OptLevel::More
| OptLevel::Aggressive
| OptLevel::Size
| OptLevel::SizeMin) => {
return Err(format!("-Copt-level=0 is required during capture (got {other:?})"));
}
};
if opts.debug_assertions {
return Err("-Cdebug-assertions=no is required during capture".into());
}
if opts.cg.overflow_checks != Some(expected_overflow_checks) {
let expected_flag = if expected_overflow_checks {
"-Coverflow-checks=yes"
} else {
"-Coverflow-checks=no"
};
return Err(format!(
"{expected_flag} is required during capture (got {:?})",
opts.cg.overflow_checks
));
}
// RUSTC-WORKAROUND(#4365): MIR UB checks survive only under this flag.
if !opts.unstable_opts.mir_preserve_ub {
return Err("-Zmir-preserve-ub must be enabled during capture".into());
}
if opts.unstable_opts.mir_opt_level != Some(0) {
return Err(format!(
"-Zmir-opt-level=0 is required during capture (got {:?})",
opts.unstable_opts.mir_opt_level
));
}
Ok(opt_level)
}
fn validate_compiler_options(
opts: &Options,
expected_crate_type: ir::CrateType,
expected_panic: ir::PanicStrategy,
expected_overflow_checks: bool,
features: FeaturePolicy<'_>,
) -> Result<(), String> {
if opts.sysroot.explicit.is_none() {
return Err("explicit --sysroot is required during capture".into());
}
if opts.externs.iter().next().is_some() {
return Err("external crate flags (--extern) are forbidden during capture".into());
}
if !opts.search_paths.is_empty() {
return Err("library search path flags (-L) are forbidden during capture".into());
}
let expected_rustc_ct = rustc_crate_type(expected_crate_type);
if opts.crate_types.as_slice() != [expected_rustc_ct] {
return Err(format!(
"unsupported or mismatched crate types during capture: {:?}",
opts.crate_types
));
}
let panic_ok = match expected_panic {
ir::PanicStrategy::Unwind => {
matches!(opts.cg.panic, None | Some(RustcPanicStrategy::Unwind))
}
ir::PanicStrategy::Abort => matches!(opts.cg.panic, Some(RustcPanicStrategy::Abort)),
};
if !panic_ok {
return Err(format!(
"panic strategy {:?} disagreed with configured strategy `{}`",
opts.cg.panic,
expected_panic.as_str()
));
}
let _ = validate_profile_options(opts, expected_overflow_checks)?;
validate_allow_features_option(opts, features)?;
if !opts.logical_env.is_empty() {
return Err("raw compiler --env-set flags are forbidden during capture".into());
}
Ok(())
}
fn collect_sysroot_lib_identities(
sysroot: &Path,
target: &str,
) -> Result<BTreeSet<(u64, u64)>, Failure> {
let target_lib = sysroot.join("lib/rustlib").join(target).join("lib");
if !target_lib.is_dir() {
return Err(Failure::tool(format!(
"target sysroot library directory missing: {}",
target_lib.display()
)));
}
let mut allowed = BTreeSet::new();
let entries = std::fs::read_dir(&target_lib).map_err(Failure::io)?;
for entry in entries {
let entry = entry.map_err(Failure::io)?;
if let Ok(dev_ino) = identity::regular_file_dev_ino(&entry.path()) {
allowed.insert(dev_ino);
}
}
if allowed.is_empty() {
return Err(Failure::tool(format!(
"no target libraries found in sysroot {}",
target_lib.display()
)));
}
Ok(allowed)
}
struct ExternalCrate<'a> {
name: &'a str,
macros_only: bool,
has_rlib: bool,
has_dylib: bool,
has_sdylib: bool,
paths: &'a [&'a Path],
}
/// When `allow_dual_rlib_dylib` is true (specifically `CrateType::Bin`, where
/// `rustc_metadata::locator::Context::needs_crate_flavor` probes all flavors and
/// sysroot `std` carries both `.rlib` and `.so`), a sysroot crate with both
/// `rlib` and `dylib` artifacts is admitted provided every resolved artifact
/// resides inside `allowed_sysroot_ids`. Pure dynamic/proc-macro crates
/// (`!has_rlib`) and `CrateType::Lib` dylibs remain refused.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_metadata/src/locator.rs#L550-L561
fn admit_external_crate<F>(
krate: &ExternalCrate<'_>,
allow_dual_rlib_dylib: bool,
allowed_sysroot_ids: &BTreeSet<(u64, u64)>,
stat_dev_ino: F,
) -> Result<(), Failure>
where
F: Fn(&Path) -> io::Result<(u64, u64)>,
{
if krate.macros_only || krate.name == "proc_macro" {
return Err(Failure::unsupported(format!(
"proc-macro or macro-only crate is unsupported: {}",
krate.name
)));
}
if krate.has_dylib && !(allow_dual_rlib_dylib && krate.has_rlib) {
return Err(Failure::unsupported(format!(
"dynamic library or proc-macro crate is unsupported: {}",
krate.name
)));
}
if krate.has_sdylib {
return Err(Failure::unsupported(format!(
"sdylib interface crate is unsupported: {}",
krate.name
)));
}
if krate.paths.is_empty() {
return Err(Failure::unsupported(format!(
"external crate lacks a resolved artifact path: {}",
krate.name
)));
}
for path in krate.paths {
let dev_ino = stat_dev_ino(path).map_err(|error| {
Failure::tool(format!(
"cannot stat artifact for crate {} at {}: {error}",
krate.name,
path.display()
))
})?;
if !allowed_sysroot_ids.contains(&dev_ino) {
return Err(Failure::unsupported(format!(
"external crate {} resolved outside target sysroot: {}",
krate.name,
path.display()
)));
}
}
Ok(())
}
/// Whether a parsed `#![crate_type]` attribute that survived expansion is
/// admitted: it must name `Rlib` alone, and `Rlib` must be the requested
/// (and, checked by the caller, the session's only) crate type.
fn parsed_crate_type_attr_admitted(types: &[CrateType], expected: CrateType) -> bool {
expected == CrateType::Rlib
&& !types.is_empty()
&& types.iter().all(|ty| *ty == CrateType::Rlib)
}
/// Defense-in-depth sysroot-only and no-proc-macro gate run in
/// `after_analysis`.
fn verify_sysroot_only_crates(
tcx: TyCtxt<'_>,
sysroot: &Path,
target: &str,
expected_crate_type: ir::CrateType,
) -> Result<(), Failure> {
let crate_types = tcx.crate_types();
let expected_rustc_ct = rustc_crate_type(expected_crate_type);
if crate_types != [expected_rustc_ct] {
return Err(Failure::unsupported(format!(
"unsupported or mismatched crate types during capture: {crate_types:?}"
)));
}
// Defense in depth for the pre-expansion `validate_crate_root_attrs`.
if tcx.hir_krate_attrs().iter().any(|attr| match attr {
rustc_hir::Attribute::Parsed(rustc_hir::attrs::AttributeKind::CrateType(types)) => {
!parsed_crate_type_attr_admitted(types, expected_rustc_ct)
}
other => other.has_name(rustc_span::sym::crate_type),
}) {
return Err(Failure::unsupported(
"crate-level #![crate_type] attributes are unsupported during capture",
));
}
if tcx.proc_macro_decls_static(()).is_some() {
return Err(Failure::unsupported("proc-macro declarations are unsupported during capture"));
}
if tcx.sess.opts.externs.iter().next().is_some() || !tcx.sess.opts.search_paths.is_empty() {
return Err(Failure::tool(
"external crate flags and search paths are forbidden during capture",
));
}
let allowed_ids = collect_sysroot_lib_identities(sysroot, target)?;
for &cnum in tcx.crates(()) {
let crate_name = tcx.crate_name(cnum);
let dep_kind = tcx.crate_dep_kind(cnum);
let source = tcx.used_crate_source(cnum);
let extern_paths = tcx.crate_extern_paths(cnum);
let mut paths: Vec<&Path> = source.paths().map(PathBuf::as_path).collect();
for path in extern_paths {
if !paths.contains(&path.as_path()) {
paths.push(path.as_path());
}
}
admit_external_crate(
&ExternalCrate {
name: crate_name.as_str(),
macros_only: dep_kind.macros_only(),
has_rlib: source.rlib.is_some(),
has_dylib: source.dylib.is_some(),
has_sdylib: source.sdylib_interface.is_some(),
paths: &paths,
},
expected_crate_type == ir::CrateType::Bin,
&allowed_ids,
identity::regular_file_dev_ino,
)?;
}
Ok(())
}
/// Verify that the active compiler session's logical sysroot matches the
/// pre-verified logical path and still resolves to the directory `(st_dev,
/// st_ino)` recorded before `identity::verify_compiler` ran.
fn verify_session_sysroot(
session_sysroot: &Path,
verified_sysroot: &Path,
verified_sysroot_id: identity::DevIno,
) -> Result<PathBuf, Failure> {
let sysroot = identity::normalize_logical_sysroot(session_sysroot)?;
let session_sysroot_id = identity::dir_dev_ino(&sysroot).map_err(Failure::io)?;
if sysroot != verified_sysroot || session_sysroot_id != verified_sysroot_id {
return Err(Failure::tool("compiler session sysroot diverged from verified sysroot"));
}
Ok(sysroot)
}
/// Verify that every compile-time environment variable read recorded in
/// `tcx.sess.env_depinfo` matches an explicitly declared `--env KEY=VALUE`
/// binding.
///
/// `rustc` records `(var, value.as_ref().ok().copied())` for both `env!` and
/// `option_env!`, including absent variables (`None`). Requiring every
/// observed key to exist in `declared` with an exact `Some(expected)` match
/// keeps undeclared reads—whether present or absent in the ambient
/// environment—fail-closed while permitting explicitly bound values.
fn check_env_depinfo<'a>(
declared: &BTreeMap<String, String>,
observed: impl IntoIterator<Item = (&'a str, Option<&'a str>)>,
) -> Result<(), Failure> {
let mut entries: Vec<(&'a str, Option<&'a str>)> = observed.into_iter().collect();
entries.sort_unstable();
for (name, value) in entries {
let Some(expected) = declared.get(name) else {
return Err(Failure::unsupported(format!(
"environment-dependent source inputs are unsupported: undeclared variable {name}"
)));
};
if value != Some(expected.as_str()) {
return Err(Failure::unsupported(format!(
"environment-dependent source inputs are unsupported: observed value for {name} \
disagreed with declared --env binding"
)));
}
}
Ok(())
}
/// Verify that every emitted or whole-crate-admitted nominal `kind` id
/// (`EnumTy.id` or `StructLayout.id`) maps to a unique local definition of
/// that kind in the compiled crate.
fn check_admitted_nominal_collisions(
tcx: TyCtxt<'_>,
kind: &str,
all_local_defs: &BTreeMap<u32, Vec<LocalDefId>>,
admitted_ids: &BTreeSet<u32>,
) -> Result<(), Failure> {
for &id in admitted_ids {
let Some(defs) = all_local_defs.get(&id) else {
return Err(Failure::tool(format!(
"captured {kind} id {id} has no matching local {kind} definition"
)));
};
if defs.len() > 1 {
return Err(Failure::unsupported(format!(
"{kind} identity collision: {} and {} share id {id}",
tcx.def_path_str(defs[0]),
tcx.def_path_str(defs[1]),
)));
}
}
Ok(())
}
/// Return all implemented trait `DefId`s for local trait `impl` blocks
/// enclosing `def` at any ancestor depth (covering both direct `AssocFn`
/// methods and nested `DefKind::Fn` helpers defined inside impl methods).
fn enclosing_impl_traits(tcx: TyCtxt<'_>, def: LocalDefId) -> Vec<DefId> {
let mut traits = Vec::new();
let mut cur = Some(def);
while let Some(anc) = cur {
if tcx.def_kind(anc) == (DefKind::Impl { of_trait: true }) {
let trait_did =
tcx.impl_trait_header(anc).trait_ref.instantiate_identity().skip_norm_wip().def_id;
traits.push(trait_did);
}
cur = tcx.opt_local_parent(anc);
}
traits
}
/// Fail closed whenever any checked canonical path maps to more than one
/// distinct local callable definition (`DefKind::Fn` or `DefKind::AssocFn`).
// FIXME: Interim band-aid guarding against canonical path-printing collisions
// (for example, crate-local modules shadowing an external sysroot trait path
// once visible-reexport aliasing is disabled, or alpha-renamed generic and
// lifetime impl parameters) until capture migrates to crate-qualified
// structural `DefId` identities.
fn check_callable_path_collisions(
all_callable_paths: &BTreeMap<String, BTreeSet<u32>>,
checked_paths: &BTreeSet<String>,
) -> Result<(), Failure> {
for path in checked_paths {
if let Some(defs) = all_callable_paths.get(path)
&& defs.len() > 1
{
let ids: Vec<u32> = defs.iter().copied().collect();
return Err(Failure::unsupported(format!(
"canonical path collision: distinct local callable definitions {ids:?} share \
canonical path `{path}`"
)));
}
}
Ok(())
}
/// Fail closed whenever any checked trait-impl callable implements a trait
/// whose canonical path collides with a distinct trait implemented elsewhere
/// in the crate (for example `::core::cmp::PartialEq` vs local
/// `crate::core::cmp::PartialEq`, even when one impl is generic and the other
/// is concrete).
// FIXME: Interim band-aid guarding against distinct traits sharing a canonical
// path across generic and concrete local impls until capture migrates to
// crate-qualified structural `DefId` identities.
fn check_trait_path_collisions(
all_trait_paths: &BTreeMap<String, BTreeSet<(u32, u32)>>,
checked_trait_paths: &BTreeSet<String>,
) -> Result<(), Failure> {
for path in checked_trait_paths {
if let Some(traits) = all_trait_paths.get(path)
&& traits.len() > 1
{
return Err(Failure::unsupported(format!(
"canonical path collision: distinct traits share canonical path `{path}`"
)));
}
}
Ok(())
}
#[derive(Default)]
struct CallableCollisionIndex {
callable_paths: BTreeMap<String, BTreeSet<u32>>,
alpha_callable_paths: BTreeMap<String, BTreeSet<u32>>,
impl_trait_paths: BTreeMap<String, BTreeSet<(u32, u32)>>,
checked_paths: BTreeSet<String>,
checked_alpha_paths: BTreeSet<String>,
checked_trait_paths: BTreeSet<String>,
checked_explicit_defs: BTreeMap<u32, LocalDefId>,
checked_impl_header_defs: BTreeMap<u32, LocalDefId>,
}
impl CallableCollisionIndex {
fn mark_selector_checked(&mut self, selector: &str) {
self.checked_paths.insert(selector.to_owned());
}
fn record_trait_did(&mut self, tcx: TyCtxt<'_>, trait_did: DefId) {
let key = (trait_did.krate.as_u32(), trait_did.index.as_u32());
let canon = extract::canonical_def_path(tcx, trait_did);
let visible = extract::untrimmed_visible_def_path(tcx, trait_did);
self.impl_trait_paths.entry(canon.clone()).or_default().insert(key);
if visible != canon {
self.impl_trait_paths.entry(visible).or_default().insert(key);
}
}
fn record_trait_impl(&mut self, tcx: TyCtxt<'_>, impl_def: LocalDefId) {
if tcx.def_kind(impl_def) == (DefKind::Impl { of_trait: true }) {
let trait_did = tcx
.impl_trait_header(impl_def)
.trait_ref
.instantiate_identity()
.skip_norm_wip()
.def_id;
self.record_trait_did(tcx, trait_did);
}
}
fn record_def_with_paths(
&mut self,
tcx: TyCtxt<'_>,
def: LocalDefId,
canon: &str,
visible: &str,
) {
let key = def.local_def_index.as_u32();
self.callable_paths.entry(canon.to_owned()).or_default().insert(key);
if visible != canon {
self.callable_paths.entry(visible.to_owned()).or_default().insert(key);
}
let (alpha_canon, alpha_visible) = extract::alpha_normalized_def_paths(tcx, def);
self.alpha_callable_paths.entry(alpha_canon.clone()).or_default().insert(key);
if alpha_visible != alpha_canon {
self.alpha_callable_paths.entry(alpha_visible).or_default().insert(key);
}
for trait_did in enclosing_impl_traits(tcx, def) {
self.record_trait_did(tcx, trait_did);
}
}
fn mark_def_checked_with_paths(
&mut self,
tcx: TyCtxt<'_>,
def: LocalDefId,
canon: &str,
visible: &str,
is_explicit_target: bool,
) {
self.checked_paths.insert(canon.to_owned());
if visible != canon {
self.checked_paths.insert(visible.to_owned());
}
let (alpha_canon, alpha_visible) = extract::alpha_normalized_def_paths(tcx, def);
self.checked_alpha_paths.insert(alpha_canon.clone());
if alpha_visible != alpha_canon {
self.checked_alpha_paths.insert(alpha_visible);
}
for trait_did in enclosing_impl_traits(tcx, def) {
let trait_canon = extract::canonical_def_path(tcx, trait_did);
let trait_visible = extract::untrimmed_visible_def_path(tcx, trait_did);
self.checked_trait_paths.insert(trait_canon.clone());
if trait_visible != trait_canon {
self.checked_trait_paths.insert(trait_visible);
}
}
let key = def.local_def_index.as_u32();
if is_explicit_target {
self.checked_explicit_defs.insert(key, def);
}
self.checked_impl_header_defs.insert(key, def);
}
fn mark_impl_checked(&mut self, tcx: TyCtxt<'_>, impl_def: LocalDefId) {
if let DefKind::Impl { of_trait } = tcx.def_kind(impl_def) {
if of_trait {
let trait_did = tcx
.impl_trait_header(impl_def)
.trait_ref
.instantiate_identity()
.skip_norm_wip()
.def_id;
let trait_canon = extract::canonical_def_path(tcx, trait_did);
let trait_visible = extract::untrimmed_visible_def_path(tcx, trait_did);
self.checked_trait_paths.insert(trait_canon.clone());
if trait_visible != trait_canon {
self.checked_trait_paths.insert(trait_visible);
}
}
self.checked_impl_header_defs.insert(impl_def.local_def_index.as_u32(), impl_def);
}
}
fn record_and_mark_callee(&mut self, tcx: TyCtxt<'_>, def: LocalDefId) {
let canon = extract::canonical_def_path(tcx, def);
let visible = extract::untrimmed_visible_def_path(tcx, def);
let kind = tcx.def_kind(def);
if callable(kind) {
self.record_def_with_paths(tcx, def, &canon, &visible);
}
self.mark_def_checked_with_paths(tcx, def, &canon, &visible, true);
}
fn record_and_mark_instance(&mut self, tcx: TyCtxt<'_>, def: LocalDefId, inst_path: &str) {
let canon = extract::canonical_def_path(tcx, def);
let visible = extract::untrimmed_visible_def_path(tcx, def);
if callable(tcx.def_kind(def)) {
self.record_def_with_paths(tcx, def, &canon, &visible);
}
self.mark_def_checked_with_paths(tcx, def, &canon, &visible, true);
let key = def.local_def_index.as_u32();
self.callable_paths.entry(inst_path.to_owned()).or_default().insert(key);
self.checked_paths.insert(inst_path.to_owned());
// Match concrete and lifetime-erased local impls (`impl_fn::...`) and
// same-owner callables against the monomorphized `inst_path`, without
// collapsing trait declarations with blanket impls.
let owner_tag = extract::alpha_callable_owner_tag(tcx, def);
let own_key = format!("{owner_tag}::{inst_path}");
self.alpha_callable_paths.entry(own_key.clone()).or_default().insert(key);
self.checked_alpha_paths.insert(own_key);
if inst_path.starts_with('<') && owner_tag != "impl_fn" {
let impl_key = format!("impl_fn::{inst_path}");
self.alpha_callable_paths.entry(impl_key.clone()).or_default().insert(key);
self.checked_alpha_paths.insert(impl_key);
}
}
fn check(&self) -> Result<(), Failure> {
check_callable_path_collisions(&self.callable_paths, &self.checked_paths)?;
check_callable_path_collisions(&self.alpha_callable_paths, &self.checked_alpha_paths)?;
check_trait_path_collisions(&self.impl_trait_paths, &self.checked_trait_paths)
}
fn check_shadowed_external_crates(&self, tcx: TyCtxt<'_>) -> Result<(), Failure> {
for &def in self.checked_explicit_defs.values() {
if let Some(ext) = extract::local_def_shadowed_external_crate(tcx, def) {
return Err(Failure::unsupported(format!(
"external crate shadowing: local callable `{}` resides under crate-local \
item or module `{ext}` shadowing an external crate",
extract::canonical_def_path(tcx, def)
)));
}
}
for &def in self.checked_impl_header_defs.values() {
if let Some((ext, shadowed)) = extract::find_shadowed_impl_header_component(tcx, def) {
return Err(Failure::unsupported(format!(
"external crate shadowing: impl item `{}` references crate-local \
`{shadowed}` shadowing external crate `{ext}`",
extract::canonical_def_path(tcx, def)
)));
}
}
Ok(())
}
}
struct CheckedProfileConfig {
opt_level: u8,
debug_assertions: bool,
overflow_checks: bool,
mir_preserve_ub: bool,
pointer_bits: u64,
endian: &'static str,
}
fn checked_target_profile(
pointer_bits: u64,
endian: Endian,
) -> Result<(u64, &'static str), Failure> {
match endian {
Endian::Little if pointer_bits == 64 => Ok((pointer_bits, "little")),
Endian::Little | Endian::Big => {
Err(Failure::unsupported("only 64-bit little-endian targets are modeled"))
}
}
}
/// The target ABI alignments, in bytes, that `Trusted.MirSemantics.Layout`
/// hard-codes, as `(data-layout field, required alignment)`.
///
/// `intLayout` gives `i8`..`i128` their natural alignments and `isize` the
/// `i64` alignment (the pointer-sized integer on the checked 64-bit target).
/// `rustc` takes integer alignment from these fields ("I8 => dl.i8_align, ...
/// I128 => dl.i128_align,"); `bool` and `char` are `I8` and `I32` scalars.
/// `layoutOfTyV2` gives thin and wide pointers alignment 8, the
/// `pointer_align()` of the default address space. `overflowPairLayout` and
/// the `RangeTo<usize>`/`RangeFrom<usize>` layouts assume `aggregate_align`
/// raises no alignment (univariant layouts start from "let mut align = if
/// pack.is_some() { dl.i8_align } else { dl.aggregate_align };", and
/// `scalar_pair` applies `.max(dl.aggregate_align)`).
///
/// Profile v2 observes these alignments: reads and writes check them, and
/// entry arguments are assumed to satisfy them. So capture refuses any target
/// whose data layout differs rather than modeling it with the wrong values.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_abi/src/lib.rs#L262-L271
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_abi/src/lib.rs#L714-L719
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_abi/src/lib.rs#L1240-L1250
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_abi/src/layout.rs#L1108
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_abi/src/layout/simple.rs#L94
const MODELED_TARGET_ALIGNMENTS: [(&str, u64); 7] = [
("i8_align", 1),
("i16_align", 2),
("i32_align", 4),
("i64_align", 8),
("i128_align", 16),
("pointer_align", 8),
("aggregate_align", 1),
];
/// Check the target's ABI alignments, in [`MODELED_TARGET_ALIGNMENTS`] order,
/// against the alignments the semantics hard-codes.
fn checked_target_alignments(actual: [u64; 7]) -> Result<(), Failure> {
for ((field, required), got) in MODELED_TARGET_ALIGNMENTS.iter().zip(actual) {
if got != *required {
return Err(Failure::unsupported(format!(
"target data layout {field} is {got} bytes; only {required}-byte \
alignment is modeled"
)));
}
}
Ok(())
}
/// Validate and derive the captured target and compiler-flag profile from
/// the active `TyCtxt` rather than hardcoding literals in `ir::Configuration`.
///
/// Check `tcx.sess.overflow_checks()` directly alongside `tcx.sess.opts`
/// because MIR building (`"check_overflow |= tcx.sess.overflow_checks();"`)
/// and `cfg(overflow_checks)` read that resolved session predicate.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_mir_build/src/builder/mod.rs#L759-L760
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_session/src/config/cfg.rs#L194-L214
fn verified_profile_config(
tcx: TyCtxt<'_>,
expected_overflow_checks: bool,
) -> Result<CheckedProfileConfig, Failure> {
// `pointer_size` is the compiler's "pointer size in the default data
// address space". `endian` is the "Endianness of the target, which must
// match cfg(target-endian)", set to `Endian::Little` by the data-layout
// specification `"e"`. The owned syntax fixes both that width and
// endianness; neither a host-width guess nor a target-name heuristic
// supplies them.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_abi/src/lib.rs#L674-L678
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_abi/src/lib.rs#L259-L260
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_abi/src/lib.rs#L444
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_abi/src/lib.rs#L752-L756
let (pointer_bits, endian) =
checked_target_profile(tcx.data_layout.pointer_size().bits(), tcx.data_layout.endian)?;
let dl = &tcx.data_layout;
checked_target_alignments([
dl.i8_align.bytes(),
dl.i16_align.bytes(),
dl.i32_align.bytes(),
dl.i64_align.bytes(),
dl.i128_align.bytes(),
dl.pointer_align().abi.bytes(),
dl.aggregate_align.bytes(),
])?;
let opt_level =
validate_profile_options(&tcx.sess.opts, expected_overflow_checks).map_err(Failure::tool)?;
let debug_assertions = tcx.sess.opts.debug_assertions;
let overflow_checks = tcx.sess.overflow_checks();
if overflow_checks != expected_overflow_checks {
let expected_flag = if expected_overflow_checks {
"-Coverflow-checks=yes"
} else {
"-Coverflow-checks=no"
};
return Err(Failure::tool(format!(
"{expected_flag} is required during capture"
)));
}
let mir_preserve_ub = tcx.sess.opts.unstable_opts.mir_preserve_ub;
Ok(CheckedProfileConfig {
opt_level,
debug_assertions,
overflow_checks,
mir_preserve_ub,
pointer_bits,
endian,
})
}
/// Admit the explicit `--stdlib-crate` capability only for the exact crate it
/// names, compiled in the configuration whose language items the extractor
/// can trust.
///
/// Ordinary crates must not define language items: a crate-local `#[lang]`
/// item would change what compiler-generated MIR means. A standard-library
/// crate legitimately defines them, so the capability admits them only when
/// all of the following hold:
///
/// - The local crate is the named crate (`core`), compiled as a library from
/// selected roots (whole-crate scope is unmodeled for it).
/// - No other crate is loaded (`tcx.crates(())` is empty), so every language
/// item the compilation uses is a definition in the captured sources.
/// `core` is `#![no_core]` and links nothing.
/// - `cfg(miri)` is not set. `core::ub_checks::check_language_ub` computes
/// its runtime answer as `!cfg!(miri) && intrinsics::ub_checks()` ("Disable
/// UB checks in Miri"), so `cfg(miri)` would remove the
/// `assert_unsafe_precondition!` checks that standard-library verification
/// relies on, even though the manifest would record the cfg.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/library/core/src/ub_checks.rs#L96-L108
/// - Every language item the extractor gives special meaning has the shape
/// that meaning assumes ([`check_local_ordering`]). Other language items
/// reach the captured program only through compiler-generated MIR, which
/// capture translates 1:1 like any other MIR.
///
/// The last condition holds only because the extractor's admitted subset is
/// narrow: it refuses returning calls, `Drop`, `Assert`, references, and
/// boxes. Before the extractor admits a construct whose meaning depends on a
/// language item (for example the `panic_*` items behind `Assert`,
/// `drop_in_place`, `UnsafeCell`/`Freeze` for retags, or `owned_box`), add a
/// structural check of the local definition here, as for `Ordering`;
/// otherwise a crate named `core` could supply a forged definition.
fn check_stdlib_capability(
tcx: TyCtxt<'_>,
stdlib_crate: ir::StdlibCrate,
crate_type: ir::CrateType,
scope: &ir::Scope,
) -> Result<(), Failure> {
let crate_name = tcx.crate_name(LOCAL_CRATE);
if crate_name.as_str() != stdlib_crate.crate_name() {
return Err(Failure::unsupported(format!(
"--stdlib-crate {} does not match crate name {crate_name}",
stdlib_crate.crate_name()
)));
}
if crate_type != ir::CrateType::Lib || !matches!(scope, ir::Scope::SelectedUnit { .. }) {
return Err(Failure::unsupported(
"--stdlib-crate requires a library crate and selected roots",
));
}
if !tcx.crates(()).is_empty() {
return Err(Failure::unsupported(
"--stdlib-crate core requires a compilation that loads no other crate",
));
}
check_no_cfg_miri(tcx.sess.config.iter().map(|(name, _)| name.as_str()))
.map_err(Failure::unsupported)?;
check_local_ordering(tcx)
}
/// `extract::ty` maps the `Ordering` language item to
/// `Trusted.MirAst.MirTy.ordering`, whose values are exactly `Less`,
/// `Equal`, and `Greater` at `-1_i8`, `0_i8`, and `1_i8`. A dependency's
/// `Ordering` comes from the authenticated sysroot; a crate-local one is
/// checked against that shape here instead of being trusted by name. The
/// pinned definition reads: "This is a lang item only so that `BinOp::Cmp` in
/// MIR can return it. It has no special behavior, but does require that the
/// three variants `Less`/`Equal`/`Greater` remain `-1_i8`/`0_i8`/`+1_i8`
/// respectively."
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/library/core/src/cmp.rs#L400-L415
fn check_local_ordering(tcx: TyCtxt<'_>) -> Result<(), Failure> {
let Some(def) = tcx.lang_items().get(LangItem::OrderingEnum) else {
return Ok(());
};
if !def.is_local() {
return Ok(());
}
let adt = tcx.adt_def(def);
let variants: Vec<(String, u128, bool)> = if adt.is_enum() {
adt.discriminants(tcx)
.map(|(index, discr)| {
let variant = adt.variant(index);
let fieldless = variant.fields.is_empty()
&& variant.ctor_kind() == Some(rustc_hir::def::CtorKind::Const);
(variant.name.to_string(), discr.val, fieldless)
})
.collect()
} else {
Vec::new()
};
// Only a plain `#[repr(i8)]` is modeled; `align`, `packed`, `C`,
// `transparent`, or `simd` would change the layout `MirTy.ordering`
// assumes.
let repr = adt.repr();
let repr_i8 = repr.int == Some(rustc_abi::IntegerType::Fixed(rustc_abi::Integer::I8, true))
&& repr.align.is_none()
&& repr.pack.is_none()
&& !repr.c()
&& !repr.transparent()
&& !repr.simd();
if ordering_shape_matches(tcx.generics_of(def).count(), repr_i8, &variants) {
Ok(())
} else {
Err(Failure::unsupported(format!(
"crate-local Ordering language item {} does not have the modeled shape",
tcx.def_path_str(def)
)))
}
}
/// `Discr::val` is the "Bit representation of the discriminant (e.g.,
/// `-1i8` is `0xFF_u128`)", so `Less = -1` under `repr(i8)` is `0xff`.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/ty/util.rs#L35-L37
fn ordering_shape_matches(
generic_count: usize,
repr_i8: bool,
variants: &[(String, u128, bool)],
) -> bool {
const EXPECTED: [(&str, u128); 3] = [("Less", 0xff), ("Equal", 0), ("Greater", 1)];
generic_count == 0
&& repr_i8
&& variants.len() == EXPECTED.len()
&& variants.iter().zip(EXPECTED).all(
|((name, value, fieldless), (expected_name, expected_value))| {
*fieldless && name == expected_name && *value == expected_value
},
)
}
fn builtin_macro_symbol(tcx: TyCtxt<'_>, macro_def_id: DefId) -> Option<Symbol> {
rustc_hir::find_attr!(
tcx,
macro_def_id,
RustcBuiltinMacro { builtin_name, .. } => builtin_name.unwrap_or_else(|| tcx.item_name(macro_def_id))
)
}
// RUSTC-WORKAROUND(#4502): HygieneData::local_expn_data is private.
/// Refuse crate-local expansions of built-in source-location and module-path
/// macros (`file!`, `line!`, `column!`, `module_path!`).
///
/// `expand_file`, `expand_line`, and `expand_column` attach the outermost
/// root-context `topmost` span to the emitted literal, and `concat!(file!())`
/// folds the literal eagerly during macro expansion, so HIR spans alone do not
/// retain the built-in macro mark; meanwhile `use core::file as alias;` with
/// `alias!()` records `ExpnKind::Macro(Bang, "alias")` while preserving
/// `expn_data.macro_def_id = Some(core_file_def_id)`. Scanning every crate-
/// local `LocalExpnId` in `HygieneData` and resolving `macro_def_id`'s
/// `#[rustc_builtin_macro]` attribute catches direct, `macro_rules!`-nested,
/// `concat!`-folded, and `use`-aliased invocations without rejecting ordinary
/// user-defined `macro_rules!` of the same name.
///
/// `HygieneData::local_expn_data` is private in `rustc_span`, so after macro
/// expansion and analysis have completed (`after_analysis` in non-incremental
/// capture), allocate one `ExpnKind::Root` sentinel ID to bound
/// `1..sentinel.as_u32()`. `LocalExpnId::fresh_empty` pushes
/// `(None, ExpnHash(Fingerprint::ZERO))` in lockstep with `local_expn_data`,
/// whereas `HygieneData::new` reserves `ExpnHash(Fingerprint::ZERO)`
/// (`is_root()`) exclusively for `LocalExpnId::ROOT` (`0`) and `fresh` /
/// `set_expn_data` assign unique non-root `ExpnHash` values. Checking
/// `expn_hash().is_root()` first rejects any unfilled `fresh_empty()` slot
/// with `Failure::unsupported` without triggering `expn_data()`'s `expect`
/// panic or `rustc`'s ICE hook.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_builtin_macros/src/source_util.rs#L30-L101
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_resolve/src/macros.rs#L321-L334
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_expand/src/base.rs#L940-L951
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_span/src/hygiene.rs#L151-L154
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_span/src/hygiene.rs#L203-L248
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_span/src/hygiene.rs#L371-L400
fn check_no_ambient_builtin_macros(tcx: TyCtxt<'_>) -> Result<(), Failure> {
let sentinel = tcx.with_stable_hashing_context(|hcx| {
LocalExpnId::fresh(
ExpnData::default(ExpnKind::Root, DUMMY_SP, tcx.sess.edition(), None, None),
hcx,
)
});
for raw in 1..sentinel.as_u32() {
let local_id = LocalExpnId::from_u32(raw);
if local_id.to_expn_id().expn_hash().is_root() {
return Err(Failure::unsupported(
"unfilled macro expansion slot in compiler hygiene table",
));
}
let expn_data = local_id.expn_data();
let builtin = match expn_data.macro_def_id {
Some(def_id) => builtin_macro_symbol(tcx, def_id),
None => match expn_data.kind {
ExpnKind::Macro(MacroKind::Bang, name) => Some(name),
_ => None,
},
};
if let Some(name) = builtin
&& matches!(name, sym::file | sym::line | sym::column | sym::module_path)
{
return Err(Failure::unsupported(format!(
"built-in `{name}!()` macro is unsupported during capture: \
source-location and module-path macros depend on build paths \
and source layout"
)));
}
}
Ok(())
}
#[derive(Clone, Copy)]
struct ExternalAllocatorCrate<'a> {
name: &'a str,
has_global_allocator: bool,
has_alloc_error_handler: bool,
}
struct AllocatorHooks<'a> {
local_has_global_allocator: bool,
local_has_alloc_error_handler: bool,
external_crates: &'a [ExternalAllocatorCrate<'a>],
allocator_kind: Option<AllocatorKind>,
alloc_error_handler_kind: Option<AllocatorKind>,
}
/// Pure policy check for [`check_no_custom_allocator`].
///
/// Precondition: `hooks.external_crates` comes from a compilation that has
/// already passed [`verify_sysroot_only_crates`], so an external crate named
/// `"std"` is the verified target sysroot `std`.
fn validate_allocator_hooks(hooks: &AllocatorHooks<'_>) -> Result<(), String> {
if hooks.local_has_global_allocator {
return Err("crate-local #[global_allocator] is unsupported during capture".into());
}
if hooks.local_has_alloc_error_handler {
return Err("crate-local #[alloc_error_handler] is unsupported during capture".into());
}
let mut std_provides_alloc_error_handler = false;
for dep in hooks.external_crates {
if dep.has_global_allocator {
return Err(format!(
"custom #[global_allocator] in external crate `{}` is unsupported during capture",
dep.name
));
}
if dep.has_alloc_error_handler {
if dep.name == "std" {
std_provides_alloc_error_handler = true;
} else {
return Err(format!(
"custom #[alloc_error_handler] in external crate `{}` is unsupported \
during capture",
dep.name
));
}
}
}
match hooks.allocator_kind {
None | Some(AllocatorKind::Default) => {}
Some(AllocatorKind::Global) => {
return Err("custom #[global_allocator] is unsupported during capture".into());
}
}
match hooks.alloc_error_handler_kind {
None | Some(AllocatorKind::Default) => {}
Some(AllocatorKind::Global) if std_provides_alloc_error_handler => {}
Some(AllocatorKind::Global) => {
return Err("custom #[alloc_error_handler] is unsupported during capture".into());
}
}
Ok(())
}
fn is_forbidden_allocator_hir_attr(attr: &hir::Attribute, forbid_internal_symbol: bool) -> bool {
matches!(
attr,
hir::Attribute::Parsed(
AttributeKind::DefaultLibAllocator
| AttributeKind::NeedsAllocator
| AttributeKind::RustcAllocator
| AttributeKind::RustcAllocatorZeroed
| AttributeKind::RustcAllocatorZeroedVariant { .. }
| AttributeKind::RustcDeallocator
| AttributeKind::RustcReallocator
)
) || (forbid_internal_symbol
&& matches!(attr, hir::Attribute::Parsed(AttributeKind::RustcStdInternalSymbol)))
}
/// Reject custom `#[global_allocator]` and `#[alloc_error_handler]` hooks
/// across all crate types and capture scopes.
///
/// Anneal's Profile v2 heap contracts (`Trusted.MirSemantics.AllocContracts`)
/// assume the standard library's default allocator contract
/// (`alloc::alloc::Global` backed by the default system allocator). Neither
/// `#[global_allocator]` nor `#[alloc_error_handler]` is a `LangItem`: both
/// expand as built-in attribute macros into anonymous `const _: ()` items
/// containing `#[rustc_std_internal_symbol]` functions (`__rust_alloc` and
/// `__rust_alloc_error_handler`). `CStore::inject_allocator_crate` records
/// `has_global_allocator` and `has_alloc_error_handler` before returning early
/// on `rlib` crates or crates without `#![needs_allocator]`, catching custom
/// hooks on both `lib` and `bin` crates under both `Crate` and `SelectedUnit`
/// scopes. Because `libstd` itself defines `#[alloc_error_handler]`
/// (`rust_oom`), `alloc_error_handler_kind(())` reports
/// `Some(AllocatorKind::Global)` for normal `std` binaries; only verified
/// sysroot `std` is permitted to supply it.
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_ast/src/expand/allocator.rs#L4-L10
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_builtin_macros/src/global_allocator.rs#L15-L66
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_builtin_macros/src/alloc_error_handler.rs#L12-L56
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_metadata/src/creader.rs#L1080-L1178
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_metadata/src/creader.rs#L1390-L1410
/// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/library/std/src/alloc.rs#L419-L455
fn check_no_custom_allocator(
tcx: TyCtxt<'_>,
stdlib_crate: Option<ir::StdlibCrate>,
) -> Result<(), Failure> {
let external_names: Vec<Symbol> =
tcx.crates(()).iter().map(|&cnum| tcx.crate_name(cnum)).collect();
let external_crates: Vec<ExternalAllocatorCrate<'_>> = tcx
.crates(())
.iter()
.zip(&external_names)
.map(|(&cnum, name)| ExternalAllocatorCrate {
name: name.as_str(),
has_global_allocator: tcx.has_global_allocator(cnum),
has_alloc_error_handler: tcx.has_alloc_error_handler(cnum),
})
.collect();
validate_allocator_hooks(&AllocatorHooks {
local_has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
local_has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
external_crates: &external_crates,
allocator_kind: tcx.allocator_kind(()),
alloc_error_handler_kind: tcx.alloc_error_handler_kind(()),
})
.map_err(Failure::unsupported)?;
// Defense in depth over post-expansion HIR attributes on the crate root
// and every local owner (including nested items inside `const _: ()` and
// function blocks).
let forbid_internal_symbol = stdlib_crate.is_none();
if tcx
.hir_krate_attrs()
.iter()
.any(|attr| is_forbidden_allocator_hir_attr(attr, forbid_internal_symbol))
{
return Err(Failure::unsupported(
"crate-local allocator hook attributes are unsupported during capture",
));
}
for owner in tcx.hir_crate_items(()).owners() {
let hir_id = hir::HirId::make_owner(owner.def_id);
if tcx
.hir_attrs(hir_id)
.iter()
.any(|attr| is_forbidden_allocator_hir_attr(attr, forbid_internal_symbol))
{
return Err(Failure::unsupported(
"crate-local allocator hook attributes are unsupported during capture",
));
}
}
Ok(())
}
fn collect(
tcx: TyCtxt<'_>,
args: &Args,
declared_env: &BTreeMap<String, String>,
verified_sysroot: &Path,
verified_compiler: &identity::VerifiedCompiler,
scope: &ir::Scope,
reads: &Arc<Mutex<Reads>>,
) -> Result<CaptureArtifacts, Failure> {
// `has_errors` "excludes delayed bugs". `run_compiler` flushes those after
// the callbacks return and panics if any exist without an emitted error;
// `catch_fatal_errors` resumes that non-fatal unwind, so `run_capture`
// reports a failed capture.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_errors/src/lib.rs#L723-L726
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_interface/src/interface.rs#L511-L515
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_errors/src/lib.rs#L1477-L1478
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_span/src/fatal_error.rs#L33-L41
if tcx.dcx().has_errors().is_some() {
return Err(Failure::compiler("compiler diagnostics prohibit capture"));
}
let profile = verified_profile_config(tcx, args.overflow_checks)?;
let sysroot = verify_session_sysroot(
tcx.sess.opts.sysroot.path(),
verified_sysroot,
verified_compiler.sysroot_id,
)?;
let requested_crate_type: ir::CrateType = args.crate_type.into();
let requested_panic: ir::PanicStrategy = args.panic.into();
if (requested_panic == ir::PanicStrategy::Abort)
!= (tcx.sess.panic_strategy() == RustcPanicStrategy::Abort)
{
return Err(Failure::unsupported(format!(
"session panic strategy {:?} disagreed with configured strategy `{}`",
tcx.sess.panic_strategy(),
requested_panic.as_str()
)));
}
verify_sysroot_only_crates(tcx, verified_sysroot, &args.target, requested_crate_type)?;
let stdlib_crate = args.stdlib_crate.map(ir::StdlibCrate::from);
let feature_policy = FeaturePolicy::of(args);
validate_allow_features_option(&tcx.sess.opts, feature_policy).map_err(Failure::tool)?;
check_no_cfg_miri(tcx.sess.config.iter().map(|(name, _)| name.as_str()))
.map_err(Failure::unsupported)?;
if let Some(stdlib_crate) = stdlib_crate {
check_stdlib_capability(tcx, stdlib_crate, requested_crate_type, scope)?;
}
// "Defined lang items can come from the current crate or its dependencies."
// Admit crate-local `#[panic_handler]` (`LangItem::PanicImpl`) only in
// `SelectedUnit` scope on binary crates (`CrateType::Executable`); every
// other crate-local lang item (and any `PanicImpl` in `Scope::Crate` or
// `CrateType::Lib`) stays refused unless the `--stdlib-crate` capability
// has passed `check_stdlib_capability` above.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_hir/src/lang_items.rs#L24-L67
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_hir/src/lang_items.rs#L289
if stdlib_crate.is_none()
&& let Some((lang_item, _)) = tcx.lang_items().iter().find(|(lang_item, def)| {
def.is_local()
&& !(requested_crate_type == ir::CrateType::Bin
&& matches!(scope, ir::Scope::SelectedUnit { .. })
&& matches!(lang_item, LangItem::PanicImpl))
})
{
return Err(Failure::unsupported(format!(
"crate-local language item {lang_item:?} is unsupported"
)));
}
let has_local_panic_handler = tcx
.lang_items()
.iter()
.any(|(lang_item, def)| def.is_local() && matches!(lang_item, LangItem::PanicImpl));
check_no_custom_allocator(tcx, stdlib_crate)?;
// RUSTC-WORKAROUND(#4364): codegen rewrites `Use` calls after capture.
// Enforce the closed positive `#![feature(...)]` allowlist over
// `tcx.features()` (both language and library features, including
// `ACCEPTED_LANG_FEATURES` that `-Zallow-features` skips). Normal crates
// admit only operator-allowed unstable features outside the hard-ban floor
// (plus already-stabilized language features); `--stdlib-crate core`
// admits only its version-pinned set (excluding `ergonomic_clones`, where
// post-capture `optimize_use_clone` in `rustc_codegen_ssa` can diverge from
// captured MIR, `rustc_private`, and `custom_mir`). Enforcing this at crate
// level guarantees bodyless `--scope=crate` captures fail closed before
// per-body extraction.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_codegen_ssa/src/mir/mod.rs#L217-L224
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_codegen_ssa/src/mir/mod.rs#L350-L407
let observed_features =
check_allowed_features(tcx, feature_policy).map_err(Failure::unsupported)?;
let crate_facts = tripwires::CrateFacts {
crate_name: &args.crate_name,
crate_type: requested_crate_type,
panic: requested_panic,
overflow_checks: profile.overflow_checks,
observed_unstable_features: &observed_features.tripwire_unstable,
declared_env,
};
if let Err(reason) = tripwires::check_crate(&crate_facts) {
return Err(Failure::unsupported(reason));
}
check_no_ambient_builtin_macros(tcx)?;
if stdlib_crate.is_none() {
ctfe::audit_after_analysis(tcx, None);
ctfe::check_current_violations(None)?;
}
// `iter_local_def_id` finishes analysis and visits all definitions,
// including definitions created during enumeration: "Recompute the number
// of definitions each time, because our caller may be creating new ones."
// `hir_body_owners` independently identifies bodies, including uncalled and
// unsupported ones. Neither list comes from walking successfully translated
// selected bodies.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/ty/context.rs#L1353-L1371
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/hir/map.rs
let exclusion_index = match scope {
ir::Scope::Crate { excluded_traits } => build_exclusion_index(tcx, excluded_traits)?,
ir::Scope::SelectedUnit { .. } => ExclusionIndex::default(),
};
let body_owners: BTreeSet<_> =
tcx.hir_body_owners().map(|def| def.local_def_index.as_u32()).collect();
let cli_stubs = args.resolved_assume_stubs()?;
let stub_index = build_stub_index(tcx, &body_owners, &cli_stubs, &exclusion_index)?;
let mut found = BTreeSet::new();
let mut census = Vec::new();
let mut selected_defs = Vec::new();
let mut unsupported = Vec::new();
// `extract::ty` admits only crate-local enums and keys each one by
// `extract::enum_id`, so every emitted `EnumTy.id` belongs to a definition
// visited here. Record all local enum definitions by key, then after
// admission refuse any emitted (or whole-crate-admitted) key shared by two
// local definitions. That preserves global uniqueness for every key that
// enters `ir::Program` without letting unreferenced colliding enums (such
// as macro-expanded `const _: () = { enum ... }` blocks) abort unrelated
// selected-unit captures.
// Struct keys from `extract::struct_id` follow the same discipline.
let mut enum_ids: BTreeMap<u32, Vec<LocalDefId>> = BTreeMap::new();
let mut admitted_enum_ids = BTreeSet::new();
let mut struct_ids: BTreeMap<u32, Vec<LocalDefId>> = BTreeMap::new();
let mut admitted_struct_ids = BTreeSet::new();
// FIXME: Interim band-aid tracking canonical, untrimmed visible,
// alpha-normalized, and trait-impl paths across all local callables so
// shadowed or ambiguous paths fail closed until capture migrates to
// crate-qualified structural `DefId` identities.
let mut collisions = CallableCollisionIndex::default();
let mut inst_paths: BTreeSet<&str> = BTreeSet::new();
if let ir::Scope::SelectedUnit { roots, instantiations } = scope {
for root in roots {
if let Some(ext) = extract::shadowed_external_crate_prefix(tcx, root) {
return Err(Failure::unsupported(format!(
"selected root `{root}` is ambiguous: leading segment `{ext}` names an \
external crate"
)));
}
collisions.mark_selector_checked(root);
}
for inst in instantiations {
inst_paths.insert(inst.path.as_str());
}
}
// FIXME: Interim band-aid keeping `DefKind::TyParam` / `ConstParam` and
// sibling `AssocFn` census owner paths synchronized with any explicit
// untrimmed visible re-export selector (via `--select`, `--assume-stub`,
// or `--instantiate`) so downstream receipt validation never loses generic-
// owner tracking until capture migrates to structural `DefId` identities.
let mut visible_param_owners: HashSet<LocalDefId> = HashSet::new();
let mut canon_param_owners: HashSet<LocalDefId> = HashSet::new();
for def in tcx.iter_local_def_id() {
let kind = tcx.def_kind(def);
if !callable(kind) {
continue;
}
let canon = extract::canonical_def_path(tcx, def);
let visible = extract::untrimmed_visible_def_path(tcx, def);
if visible == canon {
continue;
}
let stub_cli = stub_index.explicit_cli_path(def);
let (uses_visible, uses_canon) = match scope {
ir::Scope::Crate { .. } => {
(stub_cli == Some(visible.as_str()), stub_cli == Some(canon.as_str()))
}
ir::Scope::SelectedUnit { roots, .. } => {
let vis = roots.contains(&visible)
|| stub_cli == Some(visible.as_str())
|| inst_paths.contains(visible.as_str());
let can = roots.contains(&canon)
|| stub_cli == Some(canon.as_str())
|| inst_paths.contains(canon.as_str());
(vis, can)
}
};
if uses_visible && uses_canon {
// Defer to the main loop's per-definition duplicate/conflict
// diagnostic (`duplicate root selector`, etc.).
continue;
}
if uses_visible {
visible_param_owners.insert(def);
if let Some(parent) = tcx.opt_local_parent(def)
&& matches!(tcx.def_kind(parent), DefKind::Impl { .. } | DefKind::Trait)
{
visible_param_owners.insert(parent);
}
}
if uses_canon {
canon_param_owners.insert(def);
if let Some(parent) = tcx.opt_local_parent(def)
&& matches!(tcx.def_kind(parent), DefKind::Impl { .. } | DefKind::Trait)
{
canon_param_owners.insert(parent);
}
}
}
for owner in tcx.iter_local_def_id() {
if visible_param_owners.contains(&owner)
&& canon_param_owners.contains(&owner)
&& matches!(tcx.def_kind(owner), DefKind::Impl { .. } | DefKind::Trait)
{
return Err(Failure::unsupported(format!(
"conflicting canonical and visible selectors on the same owner `{}`",
extract::canonical_def_path(tcx, owner)
)));
}
}
for def in tcx.iter_local_def_id() {
let canon = extract::canonical_def_path(tcx, def);
let visible = extract::untrimmed_visible_def_path(tcx, def);
let kind = tcx.def_kind(def);
if kind == (DefKind::Impl { of_trait: true }) {
collisions.record_trait_impl(tcx, def);
}
if callable(kind) {
collisions.record_def_with_paths(tcx, def, &canon, &visible);
}
let enum_key = if matches!(kind, DefKind::Enum) {
let id = extract::enum_id(tcx, def.to_def_id());
enum_ids.entry(id).or_default().push(def);
Some(id)
} else {
None
};
let struct_key = if matches!(kind, DefKind::Struct) {
let id = extract::struct_id(tcx, def.to_def_id());
struct_ids.entry(id).or_default().push(def);
Some(id)
} else {
None
};
let has_body = body_owners.contains(&def.local_def_index.as_u32());
let is_required = required(tcx, def, kind, has_body);
let excluded_by = exclusion_index.excluded_for_local(def);
let is_stubbed = stub_index.is_stubbed(def);
let is_stub_child = stub_index.is_body_internal_child(tcx, def, kind);
let is_visible_assoc_sibling = matches!(kind, DefKind::AssocFn)
&& visible != canon
&& tcx.opt_local_parent(def).is_some_and(|p| visible_param_owners.contains(&p));
let is_visible_param = matches!(kind, DefKind::TyParam | DefKind::ConstParam)
&& visible != canon
&& tcx.opt_local_parent(def).is_some_and(|p| {
visible_param_owners.contains(&p)
|| (matches!(tcx.def_kind(p), DefKind::AssocFn)
&& tcx
.opt_local_parent(p)
.is_some_and(|gp| visible_param_owners.contains(&gp)))
});
// Selected-unit claims cover only the requested callable bodies. Keep
// every other item visible in the census without pretending to verify
// it. Whole-crate mode instead requires admission of every required
// item outside the `--exclude-trait` exclusion set, so an unsupported
// owner cannot disappear with its body.
let (selected, emitted_path) = match scope {
ir::Scope::Crate { .. } => {
let path = if is_stubbed {
stub_index.emitted_path_with_visible_owners(tcx, def, &visible_param_owners)
} else if is_visible_param || is_visible_assoc_sibling {
visible.clone()
} else {
canon.clone()
};
(is_required && excluded_by.is_none(), path)
}
ir::Scope::SelectedUnit { roots, .. } => {
// A struct field shares its path with a same-named method
// (`MemoryId::id` names both), and a field is never a
// callable root, so it never matches a selection.
let matched_canon = roots.contains(&canon) && !matches!(kind, DefKind::Field);
let matched_visible =
visible != canon && roots.contains(&visible) && !matches!(kind, DefKind::Field);
if matched_canon && matched_visible {
return Err(Failure::unsupported(format!(
"duplicate root selector: `{canon}` and `{visible}` name the same \
definition"
)));
}
if matched_canon {
if visible != canon && inst_paths.contains(visible.as_str()) {
return Err(Failure::unsupported(format!(
"conflicting canonical and visible selectors: `{canon}` and \
`{visible}` name the same definition"
)));
}
found.insert(canon.clone());
(true, canon.clone())
} else if matched_visible {
if inst_paths.contains(canon.as_str()) {
return Err(Failure::unsupported(format!(
"conflicting canonical and visible selectors: `{canon}` and \
`{visible}` name the same definition"
)));
}
found.insert(visible.clone());
(true, visible.clone())
} else if is_stubbed {
if visible != canon {
let stub_cli = stub_index.explicit_cli_path(def);
if (stub_cli == Some(canon.as_str()) && inst_paths.contains(visible.as_str()))
|| (stub_cli == Some(visible.as_str())
&& inst_paths.contains(canon.as_str()))
{
return Err(Failure::unsupported(format!(
"conflicting canonical and visible selectors: `{canon}` and \
`{visible}` name the same definition"
)));
}
}
(
false,
stub_index.emitted_path_with_visible_owners(
tcx,
def,
&visible_param_owners,
),
)
} else if callable(kind)
&& visible != canon
&& inst_paths.contains(visible.as_str())
{
if inst_paths.contains(canon.as_str()) {
return Err(Failure::unsupported(format!(
"duplicate instantiation target selector: `{canon}` and `{visible}` \
name the same definition"
)));
}
// FIXME: Interim band-aid preserving visible-reexport
// `census[].path` parity with `scope.instantiations` so
// downstream receipt validation binds legacy selectors
// until selectors migrate to structural `DefId`s.
(false, visible.clone())
} else if is_visible_param || is_visible_assoc_sibling {
// FIXME: Interim band-aid keeping owning `TyParam`/
// `ConstParam` and sibling `AssocFn` census paths aligned
// with an explicit visible-reexport selector on the same
// `Impl` or `Trait` until selectors migrate to structural
// `DefId`s.
(false, visible.clone())
} else {
(false, canon.clone())
}
}
};
// Stubbed items and their skipped body-internal children are not
// verified bodies: emit `selected: false` in `manifest.census` so
// receipt coverage accounting counts them as unverified required items
// (`[SCOPED]`, never `[OK]`), while still running `whole_crate_item`
// admission and signature-only stub extraction below.
let census_selected = selected && !is_stubbed && !is_stub_child;
census.push(ir::CensusItem {
def_id: def.local_def_index.as_u32(),
path: emitted_path.clone(),
kind: format!("{kind:?}"),
has_body,
selected: census_selected,
required: is_required,
excluded_by,
assumed_stub_reason: stub_index.reason(def).map(str::to_owned),
});
if !selected {
continue;
}
let admission = match scope {
ir::Scope::Crate { .. } => whole_crate_item(
tcx,
def,
has_body,
&exclusion_index,
&stub_index,
&crate_facts,
),
ir::Scope::SelectedUnit { .. } if is_stubbed => {
Err("stubbed items cannot be selected as verified roots".into())
}
ir::Scope::SelectedUnit { .. } if callable(kind) && has_body => Ok(()),
ir::Scope::SelectedUnit { .. } => {
Err("selected roots must be callable definitions with bodies".into())
}
};
match admission {
Ok(()) if (callable(kind) && has_body) || is_stubbed => {
collisions.mark_def_checked_with_paths(tcx, def, &canon, &visible, true);
selected_defs.push((def, emitted_path));
}
Ok(()) => {
if matches!(kind, DefKind::Impl { .. }) {
collisions.mark_impl_checked(tcx, def);
}
if let Some(id) = enum_key {
admitted_enum_ids.insert(id);
}
if let Some(id) = struct_key {
admitted_struct_ids.insert(id);
}
}
Err(reason) => unsupported.push(ir::Unsupported {
def_id: def.local_def_index.as_u32(),
path: emitted_path,
reason,
}),
}
}
collisions.check()?;
if matches!(scope, ir::Scope::SelectedUnit { .. }) {
collisions.check_shadowed_external_crates(tcx)?;
}
if let ir::Scope::SelectedUnit { roots, .. } = scope
&& &found != roots
{
return Err(Failure::unsupported(format!(
"selected definitions not found: {:?}",
roots.difference(&found).collect::<Vec<_>>()
)));
}
// A provider is only called when a query is demanded. Force every selected
// body (and any intra-crate callees reached from them) before code
// generation, with no incremental cache or fallback to optimized MIR.
// Confirm the provider hook fired and the body is unstolen, then extract
// outside the query frame so CTFE cannot cycle on self-calls.
// The query is declared `no_hash` without `cache_on_disk_if`, and capture
// passes no `-Cincremental`, so no stored result can stand in for the
// provider call.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_middle/src/queries.rs#L638-L641
struct LocalCaptureState<'a, 'tcx> {
features: FeaturePolicy<'a>,
allow_foreign_exports: bool,
exclusion_index: &'a ExclusionIndex,
stub_index: &'a StubIndex,
crate_facts: &'a tripwires::CrateFacts<'a>,
raw_bodies: Vec<(LocalDefId, String, extract::ExtractedBody<'tcx>)>,
/// The instance of each entry of `raw_bodies` that is an
/// instantiation of a generic function, whose definition's MIR is
/// polymorphic in the instance's arguments.
raw_instances: Vec<Option<ty::Instance<'tcx>>>,
body_indices: BTreeMap<u32, usize>,
/// The body index of each captured instance of a generic function.
instance_indices: HashMap<ty::Instance<'tcx>, usize>,
seen_instances: HashSet<ty::Instance<'tcx>>,
visited_called_instances: HashSet<ty::Instance<'tcx>>,
callee_queue: VecDeque<LocalDefId>,
/// Instances of generic functions called by captured bodies, with
/// their instantiation depth, still to capture.
instance_queue: VecDeque<(ty::Instance<'tcx>, u32)>,
selected: Vec<ir::SelectedBody>,
unsupported: Vec<ir::Unsupported>,
}
impl<'tcx> LocalCaptureState<'_, 'tcx> {
// Only operator-requested roots enter `selected`; transitive
// callees appear solely in `program.bodies`.
fn record_local_body(
&mut self,
tcx: TyCtxt<'tcx>,
target: LocalDefId,
path: String,
is_root: bool,
) -> Result<(), Failure> {
let key = target.local_def_index.as_u32();
let steal = tcx.mir_drops_elaborated_and_const_checked(target);
let observed = OBSERVED_HOOK
.lock()
.map_err(|_| Failure::tool("capture hook mutex poisoned"))?
.contains(&key);
let result = if !observed {
Err("compiler did not provide Runtime(PostCleanup) MIR".into())
} else if steal.is_stolen() {
Err("Runtime(PostCleanup) MIR was already stolen before capture".into())
} else {
let body_ref = steal.borrow();
let canon_path = extract::canonical_def_path(tcx, target);
if let Err(reason) =
tripwires::check_mir_body(self.crate_facts, &canon_path, &body_ref)
{
Err(reason)
} else if let Err(reason) = self.exclusion_index.check_body_disjoint(
tcx,
TypingEnv::fully_monomorphized(),
&body_ref,
) {
Err(reason)
} else {
extract::extract_body(
tcx,
target,
&body_ref,
self.features,
self.allow_foreign_exports,
)
}
};
match result {
Ok(extracted) => {
self.seen_instances.insert(ty::Instance::mono(tcx, target.to_def_id()));
let body_index = self.raw_bodies.len();
self.body_indices.insert(key, body_index);
if is_root {
self.selected.push(ir::SelectedBody {
def_id: key,
path: path.clone(),
body_index,
});
}
for &next_callee in extracted.local_callees() {
self.callee_queue.push_back(next_callee);
}
self.push_raw_body(target, path, extracted, 0, None);
}
Err(reason) => self.unsupported.push(ir::Unsupported { def_id: key, path, reason }),
}
Ok(())
}
fn record_stub_body(
&mut self,
tcx: TyCtxt<'tcx>,
target: LocalDefId,
path: String,
) {
let key = target.local_def_index.as_u32();
let result = check_stub_hir_attrs(tcx, target)
.and_then(|()| extract::extract_stub_body(tcx, target, self.features));
match result {
Ok(extracted) => {
let body_index = self.raw_bodies.len();
self.body_indices.insert(key, body_index);
self.push_raw_body(target, path, extracted, 0, None);
}
Err(reason) => self.unsupported.push(ir::Unsupported { def_id: key, path, reason }),
}
}
/// Capture `instance`, a monomorphic instance of a generic crate-local
/// function that a captured body calls, at instantiation depth
/// `depth`, unless it was already captured.
///
/// It is captured exactly as an explicit `--instantiate` request is
/// ([`mono::instantiate_resolved`],
/// [`extract::extract_instantiated_body`]).
/// It must not be excluded by `--exclude-trait`, and its body must be
/// disjoint from the excluded items, as for a non-generic callee.
/// `rustc`'s recursion limit rejects unbounded polymorphic recursion
/// (`f::<T>` calling `f::<Option<T>>`), but capture bounds its own
/// work independently: the number of distinct instances and the
/// instantiation depth are bounded, and exceeding either fails closed.
fn capture_called_instance(
&mut self,
tcx: TyCtxt<'tcx>,
instance: ty::Instance<'tcx>,
depth: u32,
collisions: &mut CallableCollisionIndex,
seen_instance_paths: &mut BTreeSet<String>,
) -> Result<(), Failure> {
if self.instance_indices.contains_key(&instance)
|| !self.visited_called_instances.insert(instance)
{
return Ok(());
}
let path = extract::instance_path(tcx, instance);
let Some(resolved_local) = instance.def_id().as_local() else {
self.unsupported.push(ir::Unsupported {
def_id: 0,
path: path.clone(),
reason: format!("instance `{path}` resolves outside the local crate"),
});
return Ok(());
};
let key = resolved_local.local_def_index.as_u32();
let refuse = |reason: String| ir::Unsupported { def_id: key, path: path.clone(), reason };
if depth > MAX_INSTANTIATION_DEPTH {
self.unsupported.push(refuse(format!(
"instantiation depth exceeds {MAX_INSTANTIATION_DEPTH}"
)));
return Ok(());
}
if self.instance_indices.len() >= MAX_CALLED_INSTANCES {
self.unsupported.push(refuse(format!(
"more than {MAX_CALLED_INSTANCES} generic-function instances"
)));
return Ok(());
}
collisions.record_and_mark_instance(tcx, resolved_local, &path);
collisions.check()?;
collisions.check_shadowed_external_crates(tcx)?;
if self.seen_instances.insert(instance) && !seen_instance_paths.insert(path.clone()) {
return Err(Failure::unsupported(format!(
"canonical path collision: distinct monomorphic instances share \
canonical path `{path}`"
)));
}
if let Some((ext, shadowed)) =
extract::find_shadowed_local_def_in_args(tcx, instance.args)
{
return Err(Failure::unsupported(format!(
"external crate shadowing: instantiation `{path}` references \
crate-local `{shadowed}` shadowing external crate `{ext}`"
)));
}
if let Some(tr) = self.exclusion_index.excluded_for_local(resolved_local) {
self.unsupported.push(refuse(format!(
"instance of an excluded item (excluded by `{}`)",
tr.as_str()
)));
return Ok(());
}
if self.stub_index.is_stubbed(resolved_local) {
self.unsupported.push(refuse(
"calls to generic or instantiated stubbed items are unsupported".into(),
));
return Ok(());
}
let extracted = mono::instantiate_resolved(tcx, instance).and_then(|resolved| {
let observed = OBSERVED_HOOK
.lock()
.map_err(|_| "capture hook mutex poisoned".to_string())?
.contains(&key);
if !observed {
return Err("compiler did not provide Runtime(PostCleanup) MIR".into());
}
tripwires::check_mir_body(self.crate_facts, &path, &resolved.body)?;
self.exclusion_index.check_body_disjoint(
tcx,
TypingEnv::fully_monomorphized(),
&resolved.body,
)?;
extract::extract_instantiated_body(
tcx,
&resolved,
self.features,
self.allow_foreign_exports,
)
});
match extracted {
Ok(extracted) => {
self.instance_indices.insert(instance, self.raw_bodies.len());
for &next_callee in extracted.local_callees() {
self.callee_queue.push_back(next_callee);
}
self.push_raw_body(resolved_local, path, extracted, depth, Some(instance));
}
Err(reason) => self.unsupported.push(refuse(reason)),
}
Ok(())
}
/// Record an extracted body at instantiation depth `depth` and queue
/// the generic-function instances it calls one level deeper.
fn push_raw_body(
&mut self,
def: LocalDefId,
path: String,
extracted: extract::ExtractedBody<'tcx>,
depth: u32,
instance: Option<ty::Instance<'tcx>>,
) {
for &called in extracted.instances() {
self.instance_queue.push_back((called, depth + 1));
}
self.raw_bodies.push((def, path, extracted));
self.raw_instances.push(instance);
}
}
let mut state = LocalCaptureState {
features: feature_policy,
allow_foreign_exports: args.allow_foreign_exports,
exclusion_index: &exclusion_index,
stub_index: &stub_index,
crate_facts: &crate_facts,
raw_bodies: Vec::new(),
raw_instances: Vec::new(),
body_indices: BTreeMap::new(),
instance_indices: HashMap::new(),
seen_instances: HashSet::new(),
visited_called_instances: HashSet::new(),
callee_queue: VecDeque::new(),
instance_queue: VecDeque::new(),
selected: Vec::new(),
unsupported,
};
let mut visited_callees: BTreeSet<u32> = BTreeSet::new();
for (def, path) in selected_defs {
visited_callees.insert(def.local_def_index.as_u32());
if stub_index.is_stubbed(def) {
state.record_stub_body(tcx, def, path);
} else {
state.record_local_body(tcx, def, path, true)?;
}
}
let mut seen_instance_paths: BTreeSet<String> = BTreeSet::new();
if let ir::Scope::SelectedUnit { instantiations, .. } = scope {
for inst in instantiations {
match mono::instantiate_body(tcx, &inst.path, &inst.args) {
Ok(resolved) => {
if !state.seen_instances.insert(resolved.instance) {
continue;
}
let inst_path = extract::instance_path(tcx, resolved.instance);
let key = resolved.resolved_local.local_def_index.as_u32();
collisions.record_and_mark_instance(tcx, resolved.resolved_local, &inst_path);
collisions.check()?;
collisions.check_shadowed_external_crates(tcx)?;
if !seen_instance_paths.insert(inst_path.clone()) {
return Err(Failure::unsupported(format!(
"canonical path collision: distinct monomorphic instances share \
canonical path `{inst_path}`"
)));
}
if let Some((ext, shadowed)) =
extract::find_shadowed_local_def_in_args(tcx, resolved.instance.args)
{
return Err(Failure::unsupported(format!(
"external crate shadowing: instantiation `{inst_path}` references \
crate-local `{shadowed}` shadowing external crate `{ext}`"
)));
}
if stub_index.is_stubbed(resolved.resolved_local) {
state.unsupported.push(ir::Unsupported {
def_id: key,
path: inst_path,
reason: "stubbed items cannot be instantiated as verified roots".into(),
});
continue;
}
let observed = OBSERVED_HOOK
.lock()
.map_err(|_| Failure::tool("capture hook mutex poisoned"))?
.contains(&key);
let extracted = if !observed {
Err("compiler did not provide Runtime(PostCleanup) MIR".into())
} else if let Err(reason) =
tripwires::check_mir_body(&crate_facts, &inst_path, &resolved.body)
{
Err(reason)
} else {
extract::extract_instantiated_body(
tcx,
&resolved,
feature_policy,
args.allow_foreign_exports,
)
};
match extracted {
Ok(extracted) => {
let body_index = state.raw_bodies.len();
// `LocalCall` admits only callees without
// non-lifetime generics or bounds
// (`is_uninstantiated_callable`) and `resolve`
// keys them by definition, so such an
// instantiation is the same body a queued call
// would reach. Register it so a call (or
// self-recursion) reuses this index instead of
// extracting a duplicate identity.
if extract::is_uninstantiated_callable(
tcx,
resolved.resolved_local.to_def_id(),
) {
visited_callees.insert(key);
state.body_indices.insert(key, body_index);
} else {
state.instance_indices.insert(resolved.instance, body_index);
}
state.selected.push(ir::SelectedBody {
def_id: key,
path: inst_path.clone(),
body_index,
});
for &next_callee in extracted.local_callees() {
state.callee_queue.push_back(next_callee);
}
state.push_raw_body(
resolved.resolved_local,
inst_path,
extracted,
0,
Some(resolved.instance),
);
}
Err(reason) => state.unsupported.push(ir::Unsupported {
def_id: key,
path: inst_path,
reason,
}),
}
}
Err(reason) => state.unsupported.push(ir::Unsupported {
def_id: 0,
path: format!("{}<{}>", inst.path, inst.args.join(", ")),
reason,
}),
}
}
}
loop {
while let Some(callee) = state.callee_queue.pop_front() {
let key = callee.local_def_index.as_u32();
if !visited_callees.insert(key) {
continue;
}
let kind = tcx.def_kind(callee);
let path = extract::canonical_def_path(tcx, callee);
collisions.record_and_mark_callee(tcx, callee);
if let Some(tr) = exclusion_index.excluded_for_local(callee) {
state.unsupported.push(ir::Unsupported {
def_id: key,
path,
reason: format!(
"callee-queue hit on excluded item (excluded by `{}`)",
tr.as_str()
),
});
continue;
}
if stub_index.is_stubbed(callee) {
state.record_stub_body(tcx, callee, path);
continue;
}
if !callable(kind) || !body_owners.contains(&key) {
state.unsupported.push(ir::Unsupported {
def_id: key,
path,
reason: format!(
"called local item of kind {kind:?} lacks an extractable callable MIR body"
),
});
continue;
}
state.record_local_body(tcx, callee, path, false)?;
}
// Capture the next instance of a generic function that a captured body
// calls (transitive instantiation), then drain the callees it adds.
let Some((instance, depth)) = state.instance_queue.pop_front() else {
break;
};
state.capture_called_instance(
tcx,
instance,
depth,
&mut collisions,
&mut seen_instance_paths,
)?;
}
if !exclusion_index.is_empty() {
for ((def, path, extracted), instance) in
state.raw_bodies.iter().zip(&state.raw_instances)
{
if extracted.is_external() {
continue;
}
if let Err(reason) = exclusion_index.check_mentioned_items(
tcx,
*def,
*instance,
TypingEnv::fully_monomorphized(),
) {
state.unsupported.push(ir::Unsupported {
def_id: def.local_def_index.as_u32(),
path: path.clone(),
reason,
});
}
}
}
if tcx.dcx().has_errors().is_some() {
return Err(Failure::compiler("late compiler diagnostics prohibit capture"));
}
if !state.unsupported.is_empty() {
return Err(Failure::unsupported_items(state.unsupported));
}
ctfe::audit_after_analysis(tcx, stdlib_crate);
let body_indices = state.body_indices;
let selected = state.selected;
let unsupported = state.unsupported;
let mut bodies = Vec::with_capacity(state.raw_bodies.len());
let mut extracted_ffi_exports = Vec::new();
for (def, path, extracted) in state.raw_bodies {
let instance_indices = extracted
.instances()
.iter()
.map(|instance| {
state.instance_indices.get(instance).copied().ok_or_else(|| {
format!(
"resolved body index missing for instance callee `{}`",
extract::instance_path(tcx, *instance)
)
})
})
.collect::<Result<Vec<_>, String>>();
let (body, ffi_export) = instance_indices
.and_then(|indices| extracted.resolve(&body_indices, &indices))
.map_err(|reason| {
Failure::unsupported_items(vec![ir::Unsupported {
def_id: def.local_def_index.as_u32(),
path,
reason,
}])
})?;
bodies.push(body);
if let Some(export) = ffi_export {
extracted_ffi_exports.push(export);
}
}
// Belt-and-suspenders guard complementing `DefKind::ForeignMod`: refuse
// any crate carrying native-library link directives in crate metadata
// (such as item-less `#[link(name = ...)]` blocks or `-l` flags), since
// link-time native-library obligations are unmodeled in the scalar profile.
if !tcx.native_libraries(LOCAL_CRATE).is_empty() {
return Err(Failure::unsupported("crate-local native libraries are unsupported"));
}
for body in &bodies {
body.collect_enum_ids(&mut admitted_enum_ids);
body.collect_struct_ids(&mut admitted_struct_ids);
}
check_admitted_nominal_collisions(tcx, "enum", &enum_ids, &admitted_enum_ids)?;
check_admitted_nominal_collisions(tcx, "struct", &struct_ids, &admitted_struct_ids)?;
collisions.check()?;
collisions.check_shadowed_external_crates(tcx)?;
// Synthetic structs (tuples and monomorphized sysroot structs such as
// non-`usize` ranges lowered to structs) are not crate-local definitions;
// refuse any key they share with another distinct synthetic struct or with
// any local struct or enum definition.
let mut synthetic_structs = Vec::new();
for body in &bodies {
body.collect_synthetic_structs(&mut synthetic_structs);
}
ir::check_synthetic_struct_ids(
&synthetic_structs,
&struct_ids.keys().copied().collect(),
&enum_ids.keys().copied().collect(),
)
.map_err(Failure::unsupported)?;
// Defense in depth: confirm `rustc`'s logical environment still matches the
// explicit `--env` map installed in `Callbacks::config`.
if tcx.sess.opts.logical_env.len() != declared_env.len()
|| !declared_env.iter().all(|(k, v)| tcx.sess.opts.logical_env.get(k) == Some(v))
{
return Err(Failure::tool(
"compiler logical environment diverged from declared --env bindings",
));
}
// The manifest binds file bytes, explicit flags, and explicitly declared
// `--env KEY=VALUE` bindings, never ambient environment values. rustc
// records "Environment variables accessed during the build and their values
// when they exist"; `env!` and `option_env!` both insert
// `(var, value.as_ref().ok().copied())`, so undeclared variables—present or
// absent—are refused here while declared bindings are checked against the
// exact value rustc observed.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_session/src/session.rs#L155-L159
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_builtin_macros/src/env.rs#L54-L55
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_builtin_macros/src/env.rs#L133-L134
{
let env_depinfo = tcx.sess.env_depinfo.borrow();
check_env_depinfo(
declared_env,
env_depinfo
.iter()
.map(|(var, value)| (var.as_str(), value.as_ref().map(rustc_span::Symbol::as_str))),
)?;
}
let reads = reads.lock().map_err(|_| Failure::tool("input read mutex poisoned"))?;
// Cross-check rustc's input inventories against the loader instead of
// assuming that installing a loader intercepted every source dependency.
// Imported source-map entries describe precompiled dependency source;
// authenticating that distribution belongs to the host, while local source
// reads must all have records here. `is_imported` is
// `self.src.is_none()`, and external crates "will have a `None` value as
// `self.src`". `FileName` "Differentiates between real files and common
// virtual files"; `local_path` returns "the path suitable for reading from
// the file system on the local host, if this information exists."
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_span/src/lib.rs#L2358-L2361
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_span/src/lib.rs#L1934-L1936
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_span/src/lib.rs#L505-L508
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_span/src/lib.rs#L387-L394
for file in tcx.sess.source_map().files().iter() {
if file.is_imported() {
continue;
}
let FileName::Real(real) = &file.name else {
return Err(Failure::unsupported("non-file compiler source input is unsupported"));
};
let path = real
.local_path()
.ok_or_else(|| Failure::unsupported("source input lacks a local path"))?
.canonicalize()
.map_err(Failure::io)?;
if !reads.files.contains_key(&path) {
return Err(Failure::unsupported(format!(
"source input bypassed read recording: {}",
path.display()
)));
}
}
// SourceMap alone is insufficient: rustc also records "File paths accessed
// during the build". Binary include inputs must have the same byte binding
// as textual source, even when they have no source-map entry.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_session/src/session.rs#L158-L159
for file in tcx.sess.file_depinfo.borrow().iter() {
let path = Path::new(file.as_str()).canonicalize().map_err(Failure::io)?;
if !reads.files.contains_key(&path) {
return Err(Failure::unsupported(format!(
"dependency input bypassed read recording: {}",
path.display()
)));
}
}
check_current_inputs(&reads)?;
let source_root = args.source_root.as_deref();
let crate_root = crate::manifest_path(&args.crate_root, source_root)?;
let mut declared_source_files: Vec<PathBuf> = args
.source_file
.iter()
.map(|path| crate::manifest_path(path, source_root))
.collect::<Result<_, _>>()?;
declared_source_files.sort();
let source_files = manifest_source_files(&reads, source_root)?;
let program = ir::Program::try_new_with_options(
scope.clone(),
profile.overflow_checks,
requested_panic,
has_local_panic_handler,
bodies,
)
.map_err(Failure::unsupported)?;
// Profile v2 admits `Assert` and `CoreCall` terminators, and Profile v1
// admits primitive `Assert` terminators. Under `--stdlib-crate` the
// captured crate defines the language items (the `panic_*` family among
// them) that give `Assert` and `CoreCall` their behavior, so
// `check_stdlib_capability` only covers `Assert`-free Profile v1 bodies
// without runtime overflow checks.
let has_assert = program.bodies().iter().any(|body| {
body.blocks()
.iter()
.any(|block| matches!(block.terminator, ir::Terminator::Assert { .. }))
});
if stdlib_crate.is_some()
&& (program.mir_profile_version() != 1 || profile.overflow_checks || has_assert)
{
return Err(Failure::unsupported(
"--stdlib-crate admits only Profile v1 bodies without \
overflow checks or Assert terminators",
));
}
let ffi_exports = crate::ffi_exports::assemble_manifest(
tcx,
&args.target,
profile.pointer_bits,
extracted_ffi_exports,
)
.map_err(Failure::unsupported)?;
Ok(CaptureArtifacts {
manifest: ir::Manifest {
schema_version: ir::SCHEMA_VERSION,
compiler: ir::Compiler {
commit: ir::COMPILER_COMMIT,
version: ir::COMPILER_VERSION,
sysroot,
rustc_sha256: verified_compiler.rustc_sha256.clone(),
driver: verified_compiler.driver.clone(),
},
configuration: ir::Configuration {
crate_root,
crate_name: args.crate_name.clone(),
crate_type: requested_crate_type,
panic: requested_panic,
edition: args.edition.clone(),
target: args.target.clone(),
cfg: args.cfg.clone(),
env: declared_env.clone(),
opt_level: profile.opt_level,
debug_assertions: profile.debug_assertions,
overflow_checks: profile.overflow_checks,
mir_preserve_ub: profile.mir_preserve_ub,
pointer_bits: profile.pointer_bits,
endian: profile.endian,
declared_source_files,
stdlib_crate,
allowed_unstable_features: args.allow_unstable_feature.clone(),
observed_unstable_features: observed_features.manifest_unstable,
incomplete_observed_unstable_features: observed_features.manifest_incomplete,
stabilized_features_present: observed_features.manifest_stabilized,
assumed_stubs: stub_index.sorted_paths_with_visible_owners(
tcx,
&visible_param_owners,
),
allow_foreign_exports: args.allow_foreign_exports,
},
source_files,
census,
selected,
unsupported,
program,
},
ffi_exports,
})
}
fn manifest_source_files(
reads: &Reads,
source_root: Option<&Path>,
) -> Result<Vec<ir::SourceFile>, Failure> {
let mut files: Vec<ir::SourceFile> = reads
.files
.values()
.map(|file| {
Ok(ir::SourceFile {
path: crate::manifest_path(&file.path, source_root)?,
sha256: file.sha256.clone(),
read_kind: file.read_kind,
})
})
.collect::<Result<_, Failure>>()?;
files.sort_by(|a, b| a.path.cmp(&b.path));
Ok(files)
}
// The compiler continues through object emission after analysis. Recheck the
// observed bytes after that work as well as when constructing the manifest.
fn check_current_inputs(reads: &Reads) -> Result<(), Failure> {
for file in reads.files.values() {
let current = std::fs::read(&file.path).map_err(Failure::io)?;
if identity::sha256_bytes(&current) != file.sha256 {
return Err(Failure::unsupported(format!(
"compiler input changed after reading: {}",
file.path.display()
)));
}
}
Ok(())
}
pub(crate) fn run(
args: &Args,
declared_env: &BTreeMap<String, String>,
verified_sysroot: &Path,
verified_compiler: &identity::VerifiedCompiler,
) -> Result<CaptureArtifacts, Failure> {
let scope = args.resolved_scope()?;
CAPTURE_STARTED
.set(())
.map_err(|_| Failure::tool("one capture invocation per process is required"))?;
ctfe::configure_session(args.stdlib_crate.map(Into::into))?;
let requested_crate_type: ir::CrateType = args.crate_type.into();
let requested_panic: ir::PanicStrategy = args.panic.into();
let emit = if args.stdlib_crate.is_some() {
"--emit=metadata"
} else {
"--emit=metadata,obj"
};
let mut compiler_args = vec![
"anneal-rustc-capture".into(),
compiler_path(&args.crate_root)?.to_string(),
format!("--crate-type={}", requested_crate_type.as_str()),
format!("--crate-name={}", args.crate_name),
format!("--edition={}", args.edition),
format!("--target={}", args.target),
format!("-Cpanic={}", requested_panic.as_str()),
// RUSTC-WORKAROUND(#4365): only `obj` output monomorphizes generics.
// Metadata alone skips monomorphization and can miss a failing generic
// inline constant. rustc skips crate items when `should_codegen` is
// false: "Skip crate items and just output metadata in -Z no-codegen
// mode." Request object output to reach normal code generation without
// a linker; these outputs stay in the private publication staging area.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_interface/src/passes.rs#L1308-L1318
//
// The collector says: "Always visit all `required_consts`, so that we
// evaluate them and abort compilation if any of them errors."
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_monomorphize/src/collector.rs#L1347-L1353
//
// Under `--stdlib-crate`, request metadata only. Object emission would
// run code generation over every monomorphic item of the whole
// standard-library crate, not just the selection. The collector's
// guarantee still holds for everything that enters the captured
// program: `extract::body` evaluates every `required_consts` entry of
// each selected or instantiated body and refuses returning calls, so
// no other body's constants can reach it, and a diverging call lowers
// to `TerminatorKind.unsupported`. Adding returning calls must extend
// this evaluation to the callee closure before the capability admits
// them.
emit.into(),
// This explicit profile belongs to the captured configuration, rather
// than inheriting Cargo or host defaults. rustc says debug-assertions
// controls "cfg(debug_assertions)" and overflow-checks controls
// "runtime integer overflow". This subject disables debug assertions
// and enables overflow checks only under `--overflow-checks`; explicit
// MIR checks are still translated or refused, never silently removed.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/src/doc/rustc/src/codegen-options/index.md#L65-L76
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/src/doc/rustc/src/codegen-options/index.md#L463-L474
"-Copt-level=0".into(),
"-Cdebug-assertions=no".into(),
format!(
"-Coverflow-checks={}",
if args.overflow_checks { "yes" } else { "no" }
),
// RUSTC-WORKAROUND(#4365): MIR UB checks survive only under this flag.
// Preserve `StatementKind::PlaceMention` (`RemovePlaceMention` checks
// `!sess.opts.unstable_opts.mir_preserve_ub`) and `SwitchInt` reads
// (`SimplifyCfg` checks
// `|| tcx.sess.opts.unstable_opts.mir_preserve_ub`), matching Miri's
// UB-preservation flag. Note that despite `options.rs`'s help text
// ("implies -Zmir-opt-level=0"), `Session::mir_opt_level` inspects
// only `mir_opt_level` and `optimize`, so `-Zmir-preserve-ub` does not
// force `-Zmir-opt-level=0` (Miri passes both flags separately; pass
// `-Zmir-opt-level=0` explicitly alongside `-Zmir-preserve-ub`):
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_mir_transform/src/remove_place_mention.rs#L10-L12
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_mir_transform/src/simplify.rs#L128-L130
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_mir_transform/src/simplify.rs#L304-L312
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_session/src/session.rs#L617-L622
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/src/tools/miri/src/lib.rs#L183-L188
"-Zmir-preserve-ub".into(),
"-Zmir-opt-level=0".into(),
// Enforce the closed positive feature allowlist inside `rustc`'s own
// expansion-time feature collector as defense in depth alongside
// `validate_active_crate_features` and `check_allowed_features`. For
// normal crates this passes the operator's validated, sorted
// `--allow-unstable-feature` identifiers (which contain no comma), or
// `-Zallow-features=` by default (parsed by `parse_opt_comma_list` to
// `Some(vec![""])`, matching no unstable feature).
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_expand/src/config.rs#L87-L98
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_session/src/options.rs#L1059-L1069
format!("-Zallow-features={}", FeaturePolicy::of(args).allowlist().join(",")),
format!("--out-dir={}", compiler_path(&args.out_dir)?),
];
compiler_args.push(format!("--sysroot={}", compiler_path(verified_sysroot)?));
// The pinned driver expands argument files before parsing compiler options:
// "Replaces any `@file` arguments with the contents of `file`, with each
// line of `file` as a separate argument." Keep cfg text attached to its
// option so a leading @ stays literal instead of reading unauthenticated
// bytes or introducing compiler flags. Expander::arg checks the argv
// prefix; rustc itself parses the complete cfg grammar.
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_driver_impl/src/lib.rs#L171-L187
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_driver_impl/src/args.rs#L14-L32
// https://github.com/rust-lang/rust/blob/f8a08b688cbe60acc386ed1fbd1b7cbaaf5576b1/compiler/rustc_driver_impl/src/args.rs#L94-L108
for cfg in &args.cfg {
compiler_args.push(format!("--cfg={cfg}"));
}
validate_compiler_args(&compiler_args)?;
let reads = Arc::new(Mutex::new(Reads::default()));
let mut callbacks = Callbacks {
args,
declared_env,
verified_sysroot,
verified_compiler,
scope: &scope,
reads: reads.clone(),
result: None,
};
let compiler_result = rustc_driver::catch_fatal_errors(|| {
crate::driver::install_ice_hook();
rustc_driver::run_compiler(&compiler_args, &mut callbacks);
});
let reads = reads.lock().map_err(|_| Failure::tool("input read mutex poisoned"))?;
if !reads.tool_errors.is_empty() {
return Err(Failure::tool(reads.tool_errors.join("; ")));
}
if !reads.refusals.is_empty() {
return Err(Failure::unsupported(reads.refusals.join("; ")));
}
if compiler_result.is_err() {
return Err(Failure::compiler("rustc rejected the compilation; see stderr diagnostics"));
}
let artifacts = callbacks
.result
.unwrap_or_else(|| Err(Failure::compiler("rustc did not reach after_analysis")))?;
// Continuing after analysis must not leave later compiler reads out of
// the source binding. Reject a changed read set rather than completing
// an earlier snapshot with inputs that its compiler census never checked.
let final_source_files = manifest_source_files(&reads, args.source_root.as_deref())?;
if artifacts.manifest.source_files.len() != final_source_files.len()
|| !artifacts.manifest.source_files.iter().zip(&final_source_files).all(
|(captured, final_read)| {
captured.path == final_read.path
&& captured.sha256 == final_read.sha256
&& captured.read_kind == final_read.read_kind
},
)
{
return Err(Failure::unsupported("compiler inputs changed after the analysis snapshot"));
}
check_current_inputs(&reads)?;
ctfe::finalize_and_check(args.stdlib_crate.map(Into::into))?;
let _ =
verify_session_sysroot(verified_sysroot, verified_sysroot, verified_compiler.sysroot_id)?;
Ok(artifacts)
}
fn compiler_path(path: &Path) -> Result<&str, Failure> {
path.to_str().ok_or_else(|| {
Failure::unsupported("non-UTF-8 paths cannot be passed to the compiler driver")
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn compiler_args_gate_rejects_extern_search_paths_response_files_and_proc_macro() {
let valid = vec![
"anneal-rustc-capture".to_owned(),
"lib.rs".to_owned(),
"--crate-type=lib".to_owned(),
"--crate-type=bin".to_owned(),
"-Cpanic=unwind".to_owned(),
"-Cpanic=abort".to_owned(),
"--crate-name=demo".to_owned(),
];
assert!(validate_compiler_args(&valid).is_ok());
for bad in [
vec!["@args.rsp".to_owned()],
vec!["--extern".to_owned(), "foo=libfoo.rlib".to_owned()],
vec!["--extern=foo=libfoo.rlib".to_owned()],
vec!["-L".to_owned(), "/tmp/deps".to_owned()],
vec!["-L/tmp/deps".to_owned()],
vec!["--env-set".to_owned(), "FOO=bar".to_owned()],
vec!["--env-set=FOO=bar".to_owned()],
vec!["--crate-type=proc-macro".to_owned()],
vec!["--crate-type=dylib".to_owned()],
vec!["--crate-type".to_owned(), "proc-macro".to_owned()],
vec!["-Cpanic=immediate-abort".to_owned()],
vec!["-Cpanic".to_owned(), "abort".to_owned()],
vec!["-C".to_owned(), "panic=abort".to_owned()],
] {
assert!(validate_compiler_args(&bad).is_err(), "expected {bad:?} to fail");
}
}
fn valid_capture_options(crate_type: CrateType) -> Options {
let mut opts = Options { crate_types: vec![crate_type], ..Options::default() };
opts.sysroot.explicit = Some(PathBuf::from("/sysroot"));
opts.optimize = OptLevel::No;
opts.debug_assertions = false;
opts.cg.overflow_checks = Some(false);
opts.unstable_opts.mir_preserve_ub = true;
opts.unstable_opts.mir_opt_level = Some(0);
opts.unstable_opts.allow_features = Some(vec![String::new()]);
opts
}
#[test]
fn compiler_options_gate_requires_mir_preserve_ub_and_matching_crate_type_and_panic() {
let mut opts = valid_capture_options(CrateType::Rlib);
opts.unstable_opts.mir_preserve_ub = false;
let err = validate_compiler_options(
&opts,
ir::CrateType::Lib,
ir::PanicStrategy::Unwind,
false,
FeaturePolicy::Normal(&[]),
)
.unwrap_err();
assert!(err.contains("-Zmir-preserve-ub"), "{err}");
opts.unstable_opts.mir_preserve_ub = true;
assert!(
validate_compiler_options(
&opts,
ir::CrateType::Lib,
ir::PanicStrategy::Unwind,
false,
FeaturePolicy::Normal(&[]),
)
.is_ok()
);
assert!(
validate_compiler_options(
&opts,
ir::CrateType::Bin,
ir::PanicStrategy::Unwind,
false,
FeaturePolicy::Normal(&[]),
)
.is_err()
);
let mut bin_opts = valid_capture_options(CrateType::Executable);
bin_opts.cg.panic = Some(RustcPanicStrategy::Abort);
assert!(
validate_compiler_options(
&bin_opts,
ir::CrateType::Bin,
ir::PanicStrategy::Abort,
false,
FeaturePolicy::Normal(&[]),
)
.is_ok()
);
assert!(
validate_compiler_options(
&bin_opts,
ir::CrateType::Bin,
ir::PanicStrategy::Unwind,
false,
FeaturePolicy::Normal(&[]),
)
.is_err()
);
opts.logical_env.insert("FOO".to_owned(), "bar".to_owned());
let err = validate_compiler_options(
&opts,
ir::CrateType::Lib,
ir::PanicStrategy::Unwind,
false,
FeaturePolicy::Normal(&[]),
)
.unwrap_err();
assert!(err.contains("--env-set"), "{err}");
}
#[test]
fn compiler_options_gate_enforces_opt_level_debug_assertions_and_overflow_checks() {
let base = valid_capture_options(CrateType::Rlib);
assert_eq!(validate_profile_options(&base, false).unwrap(), 0);
assert!(
validate_compiler_options(
&base,
ir::CrateType::Lib,
ir::PanicStrategy::Unwind,
false,
FeaturePolicy::Normal(&[]),
)
.is_ok()
);
for level in [
OptLevel::Less,
OptLevel::More,
OptLevel::Aggressive,
OptLevel::Size,
OptLevel::SizeMin,
] {
let mut opts = valid_capture_options(CrateType::Rlib);
opts.optimize = level;
let err = validate_compiler_options(
&opts,
ir::CrateType::Lib,
ir::PanicStrategy::Unwind,
false,
FeaturePolicy::Normal(&[]),
)
.unwrap_err();
assert!(err.contains("-Copt-level=0"), "{level:?}: {err}");
}
let mut debug_opts = valid_capture_options(CrateType::Rlib);
debug_opts.debug_assertions = true;
let err = validate_compiler_options(
&debug_opts,
ir::CrateType::Lib,
ir::PanicStrategy::Unwind,
false,
FeaturePolicy::Normal(&[]),
)
.unwrap_err();
assert!(err.contains("-Cdebug-assertions=no"), "{err}");
for overflow in [None, Some(true)] {
let mut overflow_opts = valid_capture_options(CrateType::Rlib);
overflow_opts.cg.overflow_checks = overflow;
let err = validate_compiler_options(
&overflow_opts,
ir::CrateType::Lib,
ir::PanicStrategy::Unwind,
false,
FeaturePolicy::Normal(&[]),
)
.unwrap_err();
assert!(err.contains("-Coverflow-checks=no"), "{overflow:?}: {err}");
}
let mut overflow_on_opts = valid_capture_options(CrateType::Rlib);
overflow_on_opts.cg.overflow_checks = Some(true);
assert!(
validate_compiler_options(
&overflow_on_opts,
ir::CrateType::Lib,
ir::PanicStrategy::Unwind,
true,
FeaturePolicy::Normal(&[]),
)
.is_ok()
);
for overflow in [None, Some(false)] {
let mut mismatch_opts = valid_capture_options(CrateType::Rlib);
mismatch_opts.cg.overflow_checks = overflow;
let err = validate_compiler_options(
&mismatch_opts,
ir::CrateType::Lib,
ir::PanicStrategy::Unwind,
true,
FeaturePolicy::Normal(&[]),
)
.unwrap_err();
assert!(err.contains("-Coverflow-checks=yes"), "{overflow:?}: {err}");
}
for mir_opt in [None, Some(1), Some(2)] {
let mut mir_opts = valid_capture_options(CrateType::Rlib);
mir_opts.unstable_opts.mir_opt_level = mir_opt;
let err = validate_compiler_options(
&mir_opts,
ir::CrateType::Lib,
ir::PanicStrategy::Unwind,
false,
FeaturePolicy::Normal(&[]),
)
.unwrap_err();
assert!(err.contains("-Zmir-opt-level=0"), "{mir_opt:?}: {err}");
}
}
#[test]
fn target_profile_gate_requires_64_bit_little_endian() {
assert_eq!(checked_target_profile(64, Endian::Little).unwrap(), (64, "little"));
for (bits, endian) in [(32, Endian::Little), (64, Endian::Big), (32, Endian::Big)] {
let err = checked_target_profile(bits, endian).unwrap_err();
assert_eq!(err.status, "unsupported");
assert!(
err.diagnostics[0].contains("64-bit little-endian"),
"{bits}, {endian:?}: {err:?}"
);
}
}
#[test]
fn target_alignment_gate_requires_exactly_the_modeled_alignments() {
let modeled = MODELED_TARGET_ALIGNMENTS.map(|(_, align)| align);
assert_eq!(modeled, [1, 2, 4, 8, 16, 8, 1]);
checked_target_alignments(modeled).unwrap();
for i in 0..modeled.len() {
for wrong in [modeled[i] / 2, modeled[i] * 2] {
if wrong == 0 {
continue;
}
let mut actual = modeled;
actual[i] = wrong;
let err = checked_target_alignments(actual).unwrap_err();
assert_eq!(err.status, "unsupported");
let field = MODELED_TARGET_ALIGNMENTS[i].0;
assert!(err.diagnostics[0].contains(field), "{field}: {err:?}");
}
}
}
#[test]
fn env_depinfo_gate_requires_exact_declared_bindings() {
let empty = BTreeMap::new();
assert!(check_env_depinfo(&empty, []).is_ok());
let declared = BTreeMap::from([
("CARGO_PKG_VERSION".to_owned(), "0.8.64".to_owned()),
("UNUSED".to_owned(), "val".to_owned()),
]);
assert!(check_env_depinfo(&declared, []).is_ok());
assert!(check_env_depinfo(&declared, [("CARGO_PKG_VERSION", Some("0.8.64"))]).is_ok());
let undeclared_present =
check_env_depinfo(&declared, [("AMBIENT", Some("secret"))]).unwrap_err();
assert_eq!(undeclared_present.status, "unsupported");
assert!(
undeclared_present.diagnostics[0]
.contains("environment-dependent source inputs are unsupported")
&& undeclared_present.diagnostics[0].contains("AMBIENT"),
"{undeclared_present:?}"
);
let undeclared_absent = check_env_depinfo(&declared, [("MISSING", None)]).unwrap_err();
assert_eq!(undeclared_absent.status, "unsupported");
assert!(
undeclared_absent.diagnostics[0]
.contains("environment-dependent source inputs are unsupported")
&& undeclared_absent.diagnostics[0].contains("MISSING"),
"{undeclared_absent:?}"
);
let mismatched =
check_env_depinfo(&declared, [("CARGO_PKG_VERSION", Some("0.8.65"))]).unwrap_err();
assert_eq!(mismatched.status, "unsupported");
assert!(
mismatched.diagnostics[0].contains("disagreed with declared --env binding"),
"{mismatched:?}"
);
let observed_none =
check_env_depinfo(&declared, [("CARGO_PKG_VERSION", None)]).unwrap_err();
assert_eq!(observed_none.status, "unsupported");
assert!(
observed_none.diagnostics[0].contains("disagreed with declared --env binding"),
"{observed_none:?}"
);
}
#[cfg(unix)]
#[test]
fn sysroot_only_crate_admission_enforces_sysroot_dev_ino_and_no_proc_macro() {
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir().unwrap();
let sysroot = dir.path().join("sysroot");
let target_lib = sysroot.join("lib/rustlib/x86_64-unknown-linux-gnu/lib");
let host_lib = sysroot.join("lib");
let cas = dir.path().join("cas");
let outside = dir.path().join("outside");
std::fs::create_dir_all(&target_lib).unwrap();
std::fs::create_dir_all(&host_lib).unwrap();
std::fs::create_dir_all(&cas).unwrap();
std::fs::create_dir_all(&outside).unwrap();
let core_real = cas.join("libcore-123.rmeta");
std::fs::write(&core_real, b"core").unwrap();
let core_link = target_lib.join("libcore-123.rmeta");
symlink(&core_real, &core_link).unwrap();
let host_only = host_lib.join("libhost_only.rlib");
std::fs::write(&host_only, b"host").unwrap();
let outside_rlib = outside.join("libevil.rlib");
std::fs::write(&outside_rlib, b"evil").unwrap();
let allowed = collect_sysroot_lib_identities(&sysroot, "x86_64-unknown-linux-gnu").unwrap();
assert!(
admit_external_crate(
&ExternalCrate {
name: "core",
macros_only: false,
has_rlib: true,
has_dylib: false,
has_sdylib: false,
paths: &[core_link.as_path()],
},
false,
&allowed,
identity::regular_file_dev_ino,
)
.is_ok()
);
assert!(
admit_external_crate(
&ExternalCrate {
name: "host_only",
macros_only: false,
has_rlib: true,
has_dylib: false,
has_sdylib: false,
paths: &[host_only.as_path()],
},
false,
&allowed,
identity::regular_file_dev_ino,
)
.is_err()
);
assert!(
admit_external_crate(
&ExternalCrate {
name: "evil",
macros_only: false,
has_rlib: true,
has_dylib: false,
has_sdylib: false,
paths: &[outside_rlib.as_path()],
},
false,
&allowed,
identity::regular_file_dev_ino,
)
.is_err()
);
assert!(
admit_external_crate(
&ExternalCrate {
name: "my_macro",
macros_only: true,
has_rlib: false,
has_dylib: false,
has_sdylib: false,
paths: &[core_link.as_path()],
},
false,
&allowed,
identity::regular_file_dev_ino,
)
.is_err()
);
assert!(
admit_external_crate(
&ExternalCrate {
name: "my_macro",
macros_only: false,
has_rlib: false,
has_dylib: true,
has_sdylib: false,
paths: &[core_link.as_path()],
},
true,
&allowed,
identity::regular_file_dev_ino,
)
.is_err()
);
assert!(
admit_external_crate(
&ExternalCrate {
name: "std",
macros_only: false,
has_rlib: true,
has_dylib: true,
has_sdylib: false,
paths: &[core_link.as_path()],
},
false,
&allowed,
identity::regular_file_dev_ino,
)
.is_err()
);
assert!(
admit_external_crate(
&ExternalCrate {
name: "std",
macros_only: false,
has_rlib: true,
has_dylib: true,
has_sdylib: false,
paths: &[core_link.as_path()],
},
true,
&allowed,
identity::regular_file_dev_ino,
)
.is_ok()
);
assert!(
admit_external_crate(
&ExternalCrate {
name: "proc_macro",
macros_only: false,
has_rlib: true,
has_dylib: false,
has_sdylib: false,
paths: &[core_link.as_path()],
},
true,
&allowed,
identity::regular_file_dev_ino,
)
.is_err()
);
assert!(
admit_external_crate(
&ExternalCrate {
name: "core",
macros_only: false,
has_rlib: true,
has_dylib: false,
has_sdylib: false,
paths: &[],
},
false,
&allowed,
identity::regular_file_dev_ino,
)
.is_err()
);
}
#[cfg(unix)]
#[test]
fn session_sysroot_check_detects_symlink_retargeting_toctou() {
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir().unwrap();
let sysroot_a = dir.path().join("sysroot-a");
let sysroot_b = dir.path().join("sysroot-b");
std::fs::create_dir_all(&sysroot_a).unwrap();
std::fs::create_dir_all(&sysroot_b).unwrap();
let logical_link = dir.path().join("logical-sysroot");
symlink(&sysroot_a, &logical_link).unwrap();
let verified_logical = identity::normalize_logical_sysroot(&logical_link).unwrap();
let pinned_id = identity::dir_dev_ino(&verified_logical).unwrap();
assert_eq!(
verify_session_sysroot(&logical_link, &verified_logical, pinned_id).unwrap(),
verified_logical
);
// Retarget the symlink to a different directory inode while preserving
// the logical path: checking against `pinned_id` must fail closed.
std::fs::remove_file(&logical_link).unwrap();
symlink(&sysroot_b, &logical_link).unwrap();
let err = verify_session_sysroot(&logical_link, &verified_logical, pinned_id).unwrap_err();
assert!(
err.diagnostics[0].contains("compiler session sysroot diverged from verified sysroot"),
"{err:?}"
);
}
#[test]
fn snippet_probes_under_sysroot_roots_are_not_found_without_refusal() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let declared = root.join("crate/lib.rs");
std::fs::create_dir_all(declared.parent().unwrap()).unwrap();
std::fs::write(&declared, "pub fn f() {}\n").unwrap();
let rust_src = root.join("sysroot/lib/rustlib/src/rust");
let rust_src_file = rust_src.join("library/core/src/lib.rs");
std::fs::create_dir_all(rust_src_file.parent().unwrap()).unwrap();
std::fs::write(&rust_src_file, "// sysroot source\n").unwrap();
let undeclared = root.join("crate/other.rs");
std::fs::write(&undeclared, "pub fn g() {}\n").unwrap();
let virtual_root = Path::new("/rustc").join(ir::COMPILER_COMMIT);
let reads = Arc::new(Mutex::new(Reads::default()));
let loader = RecordingLoader::new(
reads.clone(),
BTreeSet::from([declared.clone()]),
vec![virtual_root.clone(), rust_src.clone()],
);
// Text probes under either root: `NotFound`, no refusal, no record.
for probe in [
virtual_root.join("library/core/src/mem/mod.rs"),
rust_src_file.clone(),
] {
let error = loader.read_file(&probe).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::NotFound, "{probe:?}");
}
{
let reads = reads.lock().unwrap();
assert!(reads.refusals.is_empty(), "{:?}", reads.refusals);
assert!(reads.files.is_empty());
}
// Declared inputs are still read and recorded.
assert_eq!(loader.read_file(&declared).unwrap(), "pub fn f() {}\n");
// Binary reads, other compiler commits, `..` escapes out of a root,
// and ordinary undeclared files all remain hard refusals.
assert!(loader.read_binary_file(&rust_src_file).is_err());
let refused = [
Path::new("/rustc/0000000000000000000000000000000000000000/library/core/src/lib.rs")
.to_path_buf(),
virtual_root.join("../../etc/passwd"),
rust_src.join("../../../../../crate/other.rs"),
undeclared.clone(),
];
for path in &refused {
let error = loader.read_file(path).unwrap_err();
assert_ne!(error.kind(), io::ErrorKind::NotFound, "{path:?}");
}
let reads = reads.lock().unwrap();
assert_eq!(
reads.refusals.len(),
refused.len() + 1,
"{:?}",
reads.refusals
);
assert_eq!(reads.files.keys().collect::<Vec<_>>(), vec![&declared]);
}
#[test]
fn snippet_roots_are_absolute_and_lexically_normalized() {
let virtual_root = Path::new("/rustc").join(ir::COMPILER_COMMIT);
assert_eq!(snippet_roots(None), vec![virtual_root.clone()]);
// Relative values are dropped, never resolved against the working
// directory; so are absolute values that escape the filesystem root.
for dropped in ["lib/rustlib/src/rust", "../src/rust", "/..", "/a/../.."] {
assert_eq!(
snippet_roots(Some(Path::new(dropped))),
vec![virtual_root.clone()],
"{dropped:?}"
);
}
assert_eq!(
snippet_roots(Some(Path::new("/opt/rust/lib/./rustlib/x/../src/rust"))),
vec![virtual_root.clone(), PathBuf::from("/opt/rust/lib/rustlib/src/rust")]
);
// A probe under an unnormalized `real_rust_source_base_dir` (for
// example, a `read_link` target with `..`) is still classified.
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let rust_src_file = root.join("sysroot/lib/rustlib/src/rust/library/core/src/lib.rs");
std::fs::create_dir_all(rust_src_file.parent().unwrap()).unwrap();
std::fs::write(&rust_src_file, "// sysroot source\n").unwrap();
let unnormalized = root.join("sysroot/lib/rustlib/x/../src/./rust");
let reads = Arc::new(Mutex::new(Reads::default()));
let loader = RecordingLoader::new(
reads.clone(),
BTreeSet::new(),
snippet_roots(Some(&unnormalized)),
);
for probe in [
rust_src_file.clone(),
unnormalized.join("library/core/src/lib.rs"),
] {
let error = loader.read_file(&probe).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::NotFound, "{probe:?}");
}
let reads = reads.lock().unwrap();
assert!(reads.refusals.is_empty(), "{:?}", reads.refusals);
assert!(reads.files.is_empty());
}
#[test]
fn relative_reads_are_never_snippet_probes() {
// Even with the working directory itself as a root, a relative read
// stays an undeclared-read refusal rather than a silent `NotFound`.
let cwd = std::env::current_dir().unwrap().canonicalize().unwrap();
let reads = Arc::new(Mutex::new(Reads::default()));
let loader = RecordingLoader::new(reads.clone(), BTreeSet::new(), vec![cwd.clone()]);
assert!(loader.is_snippet_probe(&cwd.join("Cargo.toml")));
for relative in ["Cargo.toml", "./Cargo.toml", "src/../Cargo.toml"] {
assert!(!loader.is_snippet_probe(Path::new(relative)), "{relative:?}");
let error = loader.read_file(Path::new(relative)).unwrap_err();
assert_ne!(error.kind(), io::ErrorKind::NotFound, "{relative:?}");
}
let reads = reads.lock().unwrap();
assert_eq!(reads.refusals.len(), 3, "{:?}", reads.refusals);
assert!(reads.files.is_empty());
}
#[test]
fn local_ordering_shape_must_match_the_modeled_lang_item() {
let shape = |entries: &[(&str, u128, bool)]| -> Vec<(String, u128, bool)> {
entries
.iter()
.map(|&(name, value, fieldless)| (name.to_owned(), value, fieldless))
.collect()
};
let pinned = shape(&[
("Less", 0xff, true),
("Equal", 0, true),
("Greater", 1, true),
]);
assert!(ordering_shape_matches(0, true, &pinned));
assert!(!ordering_shape_matches(1, true, &pinned), "generic");
assert!(!ordering_shape_matches(0, false, &pinned), "not repr(i8)");
for forged in [
shape(&[("Less", 0, true), ("Equal", 1, true), ("Greater", 2, true)]),
shape(&[
("Greater", 1, true),
("Equal", 0, true),
("Less", 0xff, true),
]),
shape(&[
("Less", 0xff, true),
("Equal", 0, false),
("Greater", 1, true),
]),
shape(&[("Less", 0xff, true), ("Equal", 0, true)]),
shape(&[
("Less", 0xff, true),
("Equal", 0, true),
("Greater", 1, true),
("Other", 2, true),
]),
Vec::new(),
] {
assert!(!ordering_shape_matches(0, true, &forged), "{forged:?}");
}
}
#[test]
fn parsed_crate_type_attr_admits_only_rlib_on_rlib_captures() {
assert!(parsed_crate_type_attr_admitted(&[CrateType::Rlib], CrateType::Rlib));
assert!(parsed_crate_type_attr_admitted(
&[CrateType::Rlib, CrateType::Rlib],
CrateType::Rlib
));
assert!(!parsed_crate_type_attr_admitted(&[], CrateType::Rlib));
assert!(!parsed_crate_type_attr_admitted(&[CrateType::Rlib], CrateType::Executable));
for other in [
CrateType::Executable,
CrateType::Dylib,
CrateType::Cdylib,
CrateType::StaticLib,
CrateType::ProcMacro,
CrateType::Sdylib,
] {
assert!(!parsed_crate_type_attr_admitted(&[other], CrateType::Rlib), "{other:?}");
assert!(
!parsed_crate_type_attr_admitted(&[CrateType::Rlib, other], CrateType::Rlib),
"{other:?}"
);
}
}
#[test]
fn inline_modes_on_trait_declarations_mirror_codegen_attrs() {
for admitted in [InlineAttr::None, InlineAttr::Hint, InlineAttr::Always, InlineAttr::Never]
{
assert!(inline_mode_admitted(&admitted), "{admitted:?}");
}
let forced = InlineAttr::Force { attr_span: rustc_span::DUMMY_SP, reason: None };
assert!(!inline_mode_admitted(&forced));
}
fn owned(names: &[&str]) -> Vec<String> {
names.iter().map(|name| (*name).to_owned()).collect()
}
#[test]
fn feature_allowlist_admits_operator_features_and_pinned_stdlib_core() {
// The pinned list must be strictly sorted and free of duplicates so
// binary search and `-Zallow-features` comparisons stay sound.
assert!(!STDLIB_CORE_ALLOWED_FEATURES.is_empty());
for pair in STDLIB_CORE_ALLOWED_FEATURES.windows(2) {
assert!(
pair[0] < pair[1],
"STDLIB_CORE_ALLOWED_FEATURES not strictly sorted: {pair:?}"
);
}
for banned_everywhere in [
"ergonomic_clones",
"rustc_private",
"custom_mir",
"specialization",
"generic_const_exprs",
"c_variadic",
"linkage",
"ptr_metadata",
"trivial_clone",
"unsafe_binders",
] {
assert!(
STDLIB_CORE_ALLOWED_FEATURES.binary_search(&banned_everywhere).is_err(),
"{banned_everywhere} must stay outside STDLIB_CORE_ALLOWED_FEATURES"
);
}
// By default, normal crates admit zero features through the
// allowlist itself (already-stabilized language features are
// filtered out before this check; see
// `stabilized_language_features_are_admitted_only_on_normal_crates`).
let default = FeaturePolicy::Normal(&[]);
assert!(default.allowlist().is_empty());
assert!(check_feature_allowlist(std::iter::empty::<&str>(), default).is_ok());
for rejected in [
"doc_cfg",
"ergonomic_clones",
"rustc_private",
"core_intrinsics",
"ptr_metadata",
"specialization",
"generic_const_exprs",
"adt_const_params",
"const_eval_select",
"rustc_attrs",
"intrinsics",
"custom_mir",
] {
let err = check_feature_allowlist([rejected], default).unwrap_err();
assert!(err.contains(rejected), "{rejected}: {err}");
assert!(err.contains("positive allowlist"), "{rejected}: {err}");
assert!(err.contains("--allow-unstable-feature"), "{rejected}: {err}");
}
let ergonomic_err = check_feature_allowlist(["ergonomic_clones"], default).unwrap_err();
assert!(ergonomic_err.contains("optimize_use_clone"), "{ergonomic_err}");
// Multiple disallowed features are reported deterministically sorted.
let multi_err =
check_feature_allowlist(["specialization", "core_intrinsics", "doc_cfg"], default)
.unwrap_err();
assert!(
multi_err.contains("#![feature(core_intrinsics, doc_cfg, specialization)]"),
"{multi_err}"
);
// Operator-allowed features are admitted exactly; nothing else is.
let operator = owned(&["allocator_api", "doc_cfg"]);
let allowed = FeaturePolicy::Normal(&operator);
assert_eq!(allowed.allowlist(), ["allocator_api", "doc_cfg"]);
assert!(check_feature_allowlist(["doc_cfg", "allocator_api", "doc_cfg"], allowed).is_ok());
let err = check_feature_allowlist(["doc_cfg", "specialization"], allowed).unwrap_err();
assert!(err.contains("#![feature(specialization)] is unsupported"), "{err}");
// `--stdlib-crate core` admits its exact pinned set and refuses all
// others (including `ergonomic_clones` and `custom_mir`).
let core = FeaturePolicy::Stdlib(ir::StdlibCrate::Core);
assert_eq!(core.allowlist(), STDLIB_CORE_ALLOWED_FEATURES);
assert!(
check_feature_allowlist(STDLIB_CORE_ALLOWED_FEATURES.iter().copied(), core).is_ok()
);
for rejected in ["ergonomic_clones", "rustc_private", "custom_mir", "doc_alias"] {
let err = check_feature_allowlist([rejected], core).unwrap_err();
assert!(err.contains(rejected), "{rejected}: {err}");
assert!(err.contains("--stdlib-crate core"), "{rejected}: {err}");
}
}
#[test]
fn stabilized_language_features_are_admitted_only_on_normal_crates() {
let operator = owned(&["doc_cfg"]);
assert!(FeaturePolicy::Normal(&[]).admits_stabilized_lang_features());
assert!(FeaturePolicy::Normal(&operator).admits_stabilized_lang_features());
assert!(!FeaturePolicy::Stdlib(ir::StdlibCrate::Core).admits_stabilized_lang_features());
}
#[test]
fn hard_ban_floor_tracks_rustc_internal_features() {
rustc_span::create_default_session_globals_then(|| {
for banned in [
// Not classified as internal by `rustc`; banned explicitly.
"rustc_private",
"ergonomic_clones",
// Internal language features.
"abi_unadjusted",
"allow_internal_unsafe",
"allow_internal_unstable",
"custom_mir",
"intrinsics",
"lang_items",
"link_llvm_intrinsics",
"prelude_import",
"rustc_attrs",
"staged_api",
"unsized_fn_params",
// Internal library features (`core_intrinsics` and the
// `_internal`/`_internals` suffixes).
"core_intrinsics",
"fmt_internals",
"panic_internals",
] {
let err = check_operator_features(&owned(&["doc_cfg", banned])).unwrap_err();
assert!(err.contains(&format!("#![feature({banned})]")), "{banned}: {err}");
assert!(err.contains("--allow-unstable-feature"), "{banned}: {err}");
}
let err =
check_operator_features(&owned(&["rustc_attrs", "rustc_private"])).unwrap_err();
assert!(err.contains("#![feature(rustc_attrs, rustc_private)]"), "{err}");
// Ordinary, incomplete, already-stabilized, and unknown names stay
// available to the operator; `rustc` rejects unknown ones later.
let admitted = owned(&[
"allocator_api",
"arbitrary_self_types",
"doc_alias",
"doc_cfg",
"generic_const_exprs",
"min_specialization",
"not_a_real_feature",
"specialization",
]);
assert!(check_operator_features(&admitted).is_ok());
// `incomplete_observed` relies on `rustc`'s own classification.
let (probe, names) = enabled_probe(&admitted);
let incomplete: Vec<&str> = names
.iter()
.filter(|&&name| probe.incomplete(name))
.map(|name| name.as_str())
.collect();
assert_eq!(incomplete, ["generic_const_exprs", "specialization"]);
});
}
#[test]
fn operator_feature_names_are_strict_identifiers() {
for valid in ["doc_cfg", "f16", "a", "x86_amx_intrinsics"] {
assert_eq!(crate::parse_feature_name(valid).unwrap(), valid);
}
for invalid in
["", "*", "all*", "Doc_cfg", "_doc", "1abc", "doc-cfg", "doc cfg", "a,b", "a=b", "a\0"]
{
assert!(crate::parse_feature_name(invalid).is_err(), "{invalid:?}");
}
}
#[test]
fn allow_features_option_gate_enforces_exact_allowlist() {
let default = FeaturePolicy::Normal(&[]);
let core = FeaturePolicy::Stdlib(ir::StdlibCrate::Core);
let mut opts = valid_capture_options(CrateType::Rlib);
opts.unstable_opts.allow_features = None;
let err = validate_allow_features_option(&opts, default).unwrap_err();
assert!(err.contains("-Zallow-features"), "{err}");
// `-Zallow-features=` parses to `Some(vec![""])`; `Some(vec![])` is
// also an empty allowlist. Any non-empty feature entry is rejected.
opts.unstable_opts.allow_features = Some(vec![String::new()]);
assert!(validate_allow_features_option(&opts, default).is_ok());
assert!(validate_allow_features_option(&opts, core).is_err());
opts.unstable_opts.allow_features = Some(Vec::new());
assert!(validate_allow_features_option(&opts, default).is_ok());
opts.unstable_opts.allow_features = Some(vec!["doc_cfg".to_owned()]);
assert!(validate_allow_features_option(&opts, default).is_err());
// Operator allowlists must match element for element.
let operator = owned(&["allocator_api", "doc_cfg"]);
let allowed = FeaturePolicy::Normal(&operator);
assert!(validate_allow_features_option(&opts, allowed).is_err());
opts.unstable_opts.allow_features = Some(operator.clone());
assert!(validate_allow_features_option(&opts, allowed).is_ok());
assert!(validate_allow_features_option(&opts, default).is_err());
opts.unstable_opts.allow_features = Some(owned(&["allocator_api", "doc_cfg", "f16"]));
assert!(validate_allow_features_option(&opts, allowed).is_err());
opts.unstable_opts.allow_features = Some(vec![String::new()]);
assert!(validate_allow_features_option(&opts, allowed).is_err());
let core_list: Vec<String> =
STDLIB_CORE_ALLOWED_FEATURES.iter().map(|s| (*s).to_owned()).collect();
opts.unstable_opts.allow_features = Some(core_list.clone());
assert!(validate_allow_features_option(&opts, core).is_ok());
assert!(validate_allow_features_option(&opts, default).is_err());
let mut widened = core_list;
widened.push("ergonomic_clones".to_owned());
widened.sort_unstable();
opts.unstable_opts.allow_features = Some(widened);
assert!(validate_allow_features_option(&opts, core).is_err());
}
#[test]
fn cfg_miri_gate_refuses_miri_on_all_captures() {
assert!(check_no_cfg_miri(std::iter::empty::<&str>()).is_ok());
assert!(check_no_cfg_miri(["no_zerocopy_allocator_api_1_100_0", "doc_cfg"]).is_ok());
for cfgs in [vec!["miri"], vec!["doc_cfg", "miri"]] {
let err = check_no_cfg_miri(cfgs).unwrap_err();
assert!(err.contains("cfg(miri)"), "{err}");
}
}
#[test]
fn stdlib_core_features_populate_tripwire_facts_without_manifest_taint() {
fn has_adt_const_params(facts: &tripwires::CrateFacts<'_>) -> bool {
facts.observed_unstable_features.iter().any(|feat| feat == "adt_const_params")
}
fn has_const_closures(facts: &tripwires::CrateFacts<'_>) -> bool {
facts.observed_unstable_features.iter().any(|feat| feat == "const_closures")
}
fn has_specialization(facts: &tripwires::CrateFacts<'_>) -> bool {
facts.observed_unstable_features.iter().any(|feat| feat == "specialization")
}
fn has_doc_alias(facts: &tripwires::CrateFacts<'_>) -> bool {
facts.observed_unstable_features.iter().any(|feat| feat == "doc_alias")
}
rustc_span::create_default_session_globals_then(|| {
// Under `--stdlib-crate core`, all enabled gated features populate
// `tripwire_unstable` (sorted) while manifest taint fields remain
// empty.
let stdlib_names = owned(&["no_core", "lang_items", "f16", "adt_const_params"]);
let (stdlib_probe, _) = enabled_probe(&stdlib_names);
let stdlib_observed = check_allowed_features_table(
&stdlib_probe,
FeaturePolicy::Stdlib(ir::StdlibCrate::Core),
)
.expect("pinned core features admitted");
assert_eq!(
stdlib_observed.tripwire_unstable,
owned(&["adt_const_params", "f16", "lang_items", "no_core"])
);
assert!(stdlib_observed.manifest_unstable.is_empty());
assert!(stdlib_observed.manifest_incomplete.is_empty());
assert!(stdlib_observed.manifest_stabilized.is_empty());
let empty_env = BTreeMap::new();
let stdlib_facts = tripwires::CrateFacts {
crate_name: "core",
crate_type: ir::CrateType::Lib,
panic: ir::PanicStrategy::Unwind,
overflow_checks: false,
observed_unstable_features: &stdlib_observed.tripwire_unstable,
declared_env: &empty_env,
};
let matching_rule = tripwires::Phase0Tripwire {
bug_id: "DIFF-STDLIB-0123456789ab",
issue: "https://github.com/google/zerocopy/issues/4415",
owner: "anneal-maintainers",
added_date: "2026-11-27",
scope: "Refuse adt_const_params across normal and stdlib captures",
rationale: "Regression check for stdlib CrateFacts unstable features",
regression_test: "anneal/tests/rustc-capture/tests/phase0_tripwires.rs::stdlib_core_crate_tripwire_observes_unstable_features_without_manifest_taint",
activation: tripwires::TripwireActivation::Always,
predicate: tripwires::TripwirePredicate::Crate(has_adt_const_params),
};
let err =
tripwires::evaluate_crate_tripwires(&stdlib_facts, &[matching_rule]).unwrap_err();
assert!(err.contains("[PHASE0_TRIPWIRE:DIFF-STDLIB-0123456789ab]"), "{err}");
let non_matching_rule = tripwires::Phase0Tripwire {
predicate: tripwires::TripwirePredicate::Crate(has_const_closures),
..matching_rule
};
assert!(
tripwires::evaluate_crate_tripwires(&stdlib_facts, &[non_matching_rule]).is_ok()
);
// Under normal crates, `tripwire_unstable` mirrors
// `manifest_unstable` while stabilized language features stay out
// of both unstable lists.
let operator = owned(&["doc_cfg", "specialization"]);
let (mut normal_probe, _) = enabled_probe(&owned(&["specialization", "doc_cfg"]));
let doc_alias = ACCEPTED_LANG_FEATURES
.iter()
.find(|feat| feat.name.as_str() == "doc_alias")
.expect("doc_alias is an accepted lang feature");
normal_probe.set_enabled_lang_feature(EnabledLangFeature {
gate_name: doc_alias.name,
attr_sp: DUMMY_SP,
stable_since: Some(Symbol::intern(doc_alias.since)),
});
let normal_observed =
check_allowed_features_table(&normal_probe, FeaturePolicy::Normal(&operator))
.expect("operator-allowed normal features admitted");
assert_eq!(normal_observed.tripwire_unstable, owned(&["doc_cfg", "specialization"]));
assert_eq!(normal_observed.manifest_unstable, owned(&["doc_cfg", "specialization"]));
assert_eq!(normal_observed.manifest_incomplete, owned(&["specialization"]));
assert_eq!(normal_observed.manifest_stabilized, owned(&["doc_alias"]));
let normal_facts = tripwires::CrateFacts {
crate_name: "demo",
observed_unstable_features: &normal_observed.tripwire_unstable,
..stdlib_facts
};
let spec_rule = tripwires::Phase0Tripwire {
predicate: tripwires::TripwirePredicate::Crate(has_specialization),
..matching_rule
};
assert!(tripwires::evaluate_crate_tripwires(&normal_facts, &[spec_rule]).is_err());
let stabilized_rule = tripwires::Phase0Tripwire {
predicate: tripwires::TripwirePredicate::Crate(has_doc_alias),
..matching_rule
};
assert!(tripwires::evaluate_crate_tripwires(&normal_facts, &[stabilized_rule]).is_ok());
});
}
#[test]
fn body_tripwire_predicate_matches_mir_body_def_path_and_returns_refusal() {
fn has_two_or_more_args(
_facts: &tripwires::CrateFacts<'_>,
def_path: &str,
body: &mir::Body<'_>,
) -> bool {
def_path.ends_with("tripped_pair") && body.arg_count >= 2
}
static USING_INTERNAL_FEATURES: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
let mut opts = Options {
unstable_features: rustc_feature::UnstableFeatures::Allow,
..Options::default()
};
opts.unstable_opts.allow_features =
Some(vec!["no_core".to_owned(), "lang_items".to_owned()]);
let config = rustc_interface::Config {
opts,
crate_cfg: Vec::new(),
crate_check_cfg: Vec::new(),
input: rustc_session::config::Input::Str {
name: FileName::Custom("body_tripwire_test.rs".into()),
input: concat!(
"#![feature(no_core, lang_items)]\n",
"#![allow(internal_features)]\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",
"pub fn tripped_pair(_a: (), _b: ()) {}\n",
"pub fn clean_single(_a: ()) {}\n",
)
.to_owned(),
},
output_dir: None,
output_file: None,
ice_file: None,
file_loader: None,
lint_caps: Default::default(),
psess_created: None,
track_state: None,
register_lints: None,
override_queries: None,
extra_symbols: Vec::new(),
make_codegen_backend: None,
using_internal_features: &USING_INTERNAL_FEATURES,
};
rustc_interface::run_compiler(config, |compiler| {
let krate = rustc_interface::passes::parse(&compiler.sess);
rustc_interface::passes::create_and_enter_global_ctxt(compiler, krate, |tcx| {
let empty_env = BTreeMap::new();
let features = Vec::new();
let facts = tripwires::CrateFacts {
crate_name: "demo",
crate_type: ir::CrateType::Lib,
panic: ir::PanicStrategy::Unwind,
overflow_checks: false,
observed_unstable_features: &features,
declared_env: &empty_env,
};
let multi_env = BTreeMap::from([(
tripwires::SYNTHETIC_DEMO_ENV_KEY.to_owned(),
tripwires::SYNTHETIC_DEMO_ENV_VALUE.to_owned(),
)]);
let multi_facts = tripwires::CrateFacts {
crate_name: "demo",
crate_type: ir::CrateType::Lib,
panic: ir::PanicStrategy::Unwind,
overflow_checks: false,
observed_unstable_features: &features,
declared_env: &multi_env,
};
let rule = tripwires::Phase0Tripwire {
bug_id: "ITREE-BODY_TEST-0123456789ab",
issue: "https://github.com/google/zerocopy/issues/4415",
owner: "anneal-maintainers",
added_date: "2026-11-28",
scope: "Refuse matching body signature",
rationale: "Exercise TripwirePredicate::Body dispatch against MIR",
regression_test: "anneal/tests/rustc-capture/tests/phase0_tripwires.rs::synthetic_demo_tripwire_refuses_only_when_explicitly_enabled",
activation: tripwires::TripwireActivation::Always,
predicate: tripwires::TripwirePredicate::Body(has_two_or_more_args),
};
let mut seen = BTreeSet::new();
for def in tcx.hir_body_owners() {
let path = tcx.def_path_str(def);
if !matches!(path.as_str(), "tripped_pair" | "clean_single") {
continue;
}
seen.insert(path.clone());
let body = tcx.mir_drops_elaborated_and_const_checked(def).borrow();
let res = tripwires::evaluate_body_tripwires(
&facts,
&path,
&body,
std::slice::from_ref(&rule),
);
if path == "tripped_pair" {
let err = res.expect_err("tripped_pair must match Body predicate");
assert!(err.contains("[PHASE0_TRIPWIRE:ITREE-BODY_TEST-0123456789ab]"));
let multi_err = tripwires::evaluate_body_tripwires(
&multi_facts,
&path,
&body,
&[rule, tripwires::SYNTHETIC_DEMO_TRIPWIRE],
)
.expect_err("overlapping Body and AnyBody rules must both refuse");
assert!(
multi_err.contains("[PHASE0_TRIPWIRE:ITREE-BODY_TEST-0123456789ab]")
);
assert!(
multi_err.contains("[PHASE0_TRIPWIRE:ITREE-DEMO-000000000001]"),
"{multi_err}"
);
} else {
assert!(res.is_ok(), "clean_single must pass: {res:?}");
}
}
assert_eq!(seen.len(), 2, "expected both functions in MIR census: {seen:?}");
});
});
}
#[test]
fn allocator_hooks_gate_refuses_custom_local_and_external_hooks_and_admits_defaults() {
let std_dep = ExternalAllocatorCrate {
name: "std",
has_global_allocator: false,
has_alloc_error_handler: true,
};
let core_dep = ExternalAllocatorCrate {
name: "core",
has_global_allocator: false,
has_alloc_error_handler: false,
};
let alloc_dep = ExternalAllocatorCrate {
name: "alloc",
has_global_allocator: false,
has_alloc_error_handler: false,
};
// Positive controls: default `std` lib/bin and `#![no_std]` crates.
assert!(
validate_allocator_hooks(&AllocatorHooks {
local_has_global_allocator: false,
local_has_alloc_error_handler: false,
external_crates: &[core_dep, alloc_dep, std_dep],
allocator_kind: None,
alloc_error_handler_kind: None,
})
.is_ok()
);
assert!(
validate_allocator_hooks(&AllocatorHooks {
local_has_global_allocator: false,
local_has_alloc_error_handler: false,
external_crates: &[core_dep, alloc_dep, std_dep],
allocator_kind: Some(AllocatorKind::Default),
alloc_error_handler_kind: Some(AllocatorKind::Global),
})
.is_ok()
);
assert!(
validate_allocator_hooks(&AllocatorHooks {
local_has_global_allocator: false,
local_has_alloc_error_handler: false,
external_crates: &[core_dep, alloc_dep],
allocator_kind: Some(AllocatorKind::Default),
alloc_error_handler_kind: Some(AllocatorKind::Default),
})
.is_ok()
);
assert!(
validate_allocator_hooks(&AllocatorHooks {
local_has_global_allocator: false,
local_has_alloc_error_handler: false,
external_crates: &[core_dep],
allocator_kind: None,
alloc_error_handler_kind: None,
})
.is_ok()
);
// Local `#[global_allocator]` refused even on `rlib` (`None` kind).
let local_global = validate_allocator_hooks(&AllocatorHooks {
local_has_global_allocator: true,
local_has_alloc_error_handler: false,
external_crates: &[core_dep, alloc_dep, std_dep],
allocator_kind: None,
alloc_error_handler_kind: None,
})
.expect_err("local #[global_allocator] must be refused");
assert!(local_global.contains("#[global_allocator]"), "{local_global}");
// Local `#[alloc_error_handler]` refused even when `std` is loaded.
let local_oom = validate_allocator_hooks(&AllocatorHooks {
local_has_global_allocator: false,
local_has_alloc_error_handler: true,
external_crates: &[core_dep, alloc_dep, std_dep],
allocator_kind: Some(AllocatorKind::Default),
alloc_error_handler_kind: Some(AllocatorKind::Global),
})
.expect_err("local #[alloc_error_handler] must be refused");
assert!(local_oom.contains("#[alloc_error_handler]"), "{local_oom}");
// External dependency defining `#[global_allocator]` stays refused
// even on `rlib`.
let ext_global_dep = ExternalAllocatorCrate {
name: "custom_alloc_dep",
has_global_allocator: true,
has_alloc_error_handler: false,
};
let ext_global = validate_allocator_hooks(&AllocatorHooks {
local_has_global_allocator: false,
local_has_alloc_error_handler: false,
external_crates: &[core_dep, ext_global_dep],
allocator_kind: None,
alloc_error_handler_kind: None,
})
.expect_err("external #[global_allocator] must be refused");
assert!(ext_global.contains("custom_alloc_dep"), "{ext_global}");
assert!(ext_global.contains("#[global_allocator]"), "{ext_global}");
// Non-`std` external crate defining `#[alloc_error_handler]` refused.
let ext_oom_dep = ExternalAllocatorCrate {
name: "custom_oom_dep",
has_global_allocator: false,
has_alloc_error_handler: true,
};
let ext_oom = validate_allocator_hooks(&AllocatorHooks {
local_has_global_allocator: false,
local_has_alloc_error_handler: false,
external_crates: &[core_dep, std_dep, ext_oom_dep],
allocator_kind: Some(AllocatorKind::Default),
alloc_error_handler_kind: Some(AllocatorKind::Global),
})
.expect_err("non-std external #[alloc_error_handler] must be refused");
assert!(ext_oom.contains("custom_oom_dep"), "{ext_oom}");
assert!(ext_oom.contains("#[alloc_error_handler]"), "{ext_oom}");
// Resolved `AllocatorKind::Global` refused even without `has_*` flags.
let kind_global = validate_allocator_hooks(&AllocatorHooks {
local_has_global_allocator: false,
local_has_alloc_error_handler: false,
external_crates: &[core_dep],
allocator_kind: Some(AllocatorKind::Global),
alloc_error_handler_kind: None,
})
.expect_err("AllocatorKind::Global must be refused");
assert!(kind_global.contains("#[global_allocator]"), "{kind_global}");
// Resolved `alloc_error_handler_kind == Global` refused without `std`.
let kind_oom = validate_allocator_hooks(&AllocatorHooks {
local_has_global_allocator: false,
local_has_alloc_error_handler: false,
external_crates: &[core_dep, alloc_dep],
allocator_kind: Some(AllocatorKind::Default),
alloc_error_handler_kind: Some(AllocatorKind::Global),
})
.expect_err("non-std Global alloc_error_handler_kind must be refused");
assert!(kind_oom.contains("#[alloc_error_handler]"), "{kind_oom}");
}
#[test]
fn allocator_hir_attr_gate_flags_allocator_and_internal_symbol_attributes() {
let always_forbidden = [
AttributeKind::DefaultLibAllocator,
AttributeKind::NeedsAllocator,
AttributeKind::RustcAllocator,
AttributeKind::RustcAllocatorZeroed,
AttributeKind::RustcAllocatorZeroedVariant { name: sym::alloc },
AttributeKind::RustcDeallocator,
AttributeKind::RustcReallocator,
];
for kind in always_forbidden {
let attr = hir::Attribute::Parsed(kind);
assert!(is_forbidden_allocator_hir_attr(&attr, true));
assert!(is_forbidden_allocator_hir_attr(&attr, false));
}
let internal_sym = hir::Attribute::Parsed(AttributeKind::RustcStdInternalSymbol);
assert!(is_forbidden_allocator_hir_attr(&internal_sym, true));
assert!(!is_forbidden_allocator_hir_attr(&internal_sym, false));
let benign = hir::Attribute::Parsed(AttributeKind::Cold);
assert!(!is_forbidden_allocator_hir_attr(&benign, true));
assert!(!is_forbidden_allocator_hir_attr(&benign, false));
}
#[test]
fn callable_path_collision_check_refuses_distinct_defs_and_allows_unreferenced_collisions() {
let mut all_paths: BTreeMap<String, BTreeSet<u32>> = BTreeMap::new();
all_paths.insert("clean_fn".to_owned(), BTreeSet::from([1]));
all_paths.insert("_::macro_helper".to_owned(), BTreeSet::from([2, 3]));
all_paths.insert("<Foo as core::cmp::PartialEq>::eq".to_owned(), BTreeSet::from([4, 5]));
all_paths.insert("tri_dup".to_owned(), BTreeSet::from([6, 7, 8]));
// Positive control: unique checked path passes even when unrelated
// local callables elsewhere in the crate collide.
assert!(
check_callable_path_collisions(&all_paths, &BTreeSet::from(["clean_fn".to_owned()]))
.is_ok()
);
// Unknown checked path is not a collision (reported separately as not
// found).
assert!(
check_callable_path_collisions(&all_paths, &BTreeSet::from(["missing".to_owned()]))
.is_ok()
);
// Negative controls: two-way and three-way colliding checked paths fail
// closed.
let err = check_callable_path_collisions(
&all_paths,
&BTreeSet::from(["<Foo as core::cmp::PartialEq>::eq".to_owned()]),
)
.expect_err("two distinct local defs sharing a canonical path must fail closed");
let val = serde_json::to_value(&err).unwrap();
assert_eq!(val["status"], "unsupported", "{val}");
let msg = val.to_string();
assert!(msg.contains("canonical path collision"), "{msg}");
assert!(msg.contains("[4, 5]"), "{msg}");
assert!(msg.contains("<Foo as core::cmp::PartialEq>::eq"), "{msg}");
let tri_err =
check_callable_path_collisions(&all_paths, &BTreeSet::from(["tri_dup".to_owned()]))
.expect_err("three distinct local defs sharing a canonical path must fail closed");
let tri_val = serde_json::to_value(&tri_err).unwrap();
assert_eq!(tri_val["status"], "unsupported", "{tri_val}");
let tri_msg = tri_val.to_string();
assert!(tri_msg.contains("canonical path collision"), "{tri_msg}");
assert!(tri_msg.contains("[6, 7, 8]"), "{tri_msg}");
// Distinct trait DefIds sharing a canonical path fail closed only when
// checked.
let mut trait_paths: BTreeMap<String, BTreeSet<(u32, u32)>> = BTreeMap::new();
trait_paths.insert("MyTrait".to_owned(), BTreeSet::from([(0, 10)]));
trait_paths
.insert("core::cmp::PartialEq".to_owned(), BTreeSet::from([(0, 20), (1, 30)]));
assert!(
check_trait_path_collisions(&trait_paths, &BTreeSet::from(["MyTrait".to_owned()]))
.is_ok()
);
let trait_err = check_trait_path_collisions(
&trait_paths,
&BTreeSet::from(["core::cmp::PartialEq".to_owned()]),
)
.expect_err("distinct traits sharing a canonical path must fail closed");
let trait_val = serde_json::to_value(&trait_err).unwrap();
assert_eq!(trait_val["status"], "unsupported", "{trait_val}");
assert!(
trait_val.to_string().contains("distinct traits share canonical path"),
"{trait_val}"
);
}
}