Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions compiler/rustc_attr_ir/src/lang_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,9 +303,7 @@ language_item_table! {
ConstPanicFmt, sym::const_panic_fmt, const_panic_fmt, Target::Fn, GenericRequirement::None;
PanicBoundsCheck, sym::panic_bounds_check, panic_bounds_check_fn, Target::Fn, GenericRequirement::Exact(0);
PanicMisalignedPointerDereference, sym::panic_misaligned_pointer_dereference, panic_misaligned_pointer_dereference_fn, Target::Fn, GenericRequirement::Exact(0);
PanicInfo, sym::panic_info, panic_info, Target::Struct, GenericRequirement::None;
PanicLocation, sym::panic_location, panic_location, Target::Struct, GenericRequirement::None;
PanicImpl, sym::panic_impl, panic_impl, Target::ForeignFn, GenericRequirement::None;
PanicCannotUnwind, sym::panic_cannot_unwind, panic_cannot_unwind, Target::Fn, GenericRequirement::Exact(0);
PanicInCleanup, sym::panic_in_cleanup, panic_in_cleanup, Target::Fn, GenericRequirement::Exact(0);
/// Constant panic messages, used for codegen of MIR asserts.
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_attr_ir/src/weak_lang_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,5 @@ macro_rules! weak_lang_items {
}

weak_lang_items! {
PanicImpl, rust_begin_unwind;
EhPersonality, rust_eh_personality;
}
10 changes: 3 additions & 7 deletions compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -612,13 +612,9 @@ impl CombineAttributeParser for TargetFeatureParser {
// `#[target_feature]` is incompatible with lang item functions,
// except on WASM where calling target-feature functions is safe (see #84988).
if !cx.sess().target.is_like_wasm && !cx.sess().opts.actually_rustdoc {
// `#[panic_handler]` is checked first so it takes priority in the diagnostic.
let lang_kind = cx
.all_attrs
.iter()
.find_map(|a| [sym::panic_handler, sym::lang].into_iter().find(|&s| a.word_is(s)));
if let Some(kind) = lang_kind {
cx.emit_err(TargetFeatureOnLangItem { attr_span, kind, item_span: cx.target_span });
let is_lang_item = cx.all_attrs.iter().any(|a| a.word_is(sym::lang));
if is_lang_item {
cx.emit_err(TargetFeatureOnLangItem { attr_span, item_span: cx.target_span });
}
}
}
Expand Down
9 changes: 0 additions & 9 deletions compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -584,15 +584,6 @@ impl NoArgsAttributeParser for RustcHasIncoherentInherentImplsParser {
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcHasIncoherentInherentImpls;
}

pub(crate) struct PanicHandlerParser;

impl NoArgsAttributeParser for PanicHandlerParser {
const PATH: &[Symbol] = &[sym::panic_handler];
const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowList(&[Allow(Target::Fn)]);
const STABILITY: AttributeStability = AttributeStability::Stable;
const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::Lang(LangItem::PanicImpl);
}

pub(crate) struct RustcNounwindParser;

impl NoArgsAttributeParser for RustcNounwindParser {
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_attr_parsing/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,6 @@ attribute_parsers!(
Single<WithoutArgs<NoMangleParser>>,
Single<WithoutArgs<NoStdParser>>,
Single<WithoutArgs<NonExhaustiveParser>>,
Single<WithoutArgs<PanicHandlerParser>>,
Single<WithoutArgs<PanicRuntimeParser>>,
Single<WithoutArgs<PinV2Parser>>,
Single<WithoutArgs<PreludeImportParser>>,
Expand Down
15 changes: 2 additions & 13 deletions compiler/rustc_attr_parsing/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1094,22 +1094,11 @@ pub(crate) struct DocAttrNotTraitLevel {
}

#[derive(Diagnostic)]
#[diag(
"`#[target_feature]` cannot be applied to a {$kind ->
[panic_handler] `#[panic_handler]`
*[other] lang item
} function"
)]
#[diag("`#[target_feature]` cannot be applied to a lang item function")]
pub(crate) struct TargetFeatureOnLangItem {
#[primary_span]
pub attr_span: Span,
pub kind: Symbol,
#[label(
"{$kind ->
[panic_handler] `#[panic_handler]`
*[other] lang item
} function is not allowed to have `#[target_feature]`"
)]
#[label("lang item function is not allowed to have `#[target_feature]`")]
pub item_span: Span,
}

Expand Down
7 changes: 7 additions & 0 deletions compiler/rustc_builtin_macros/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,13 @@ pub(crate) struct AllocErrorMustBeFn {
pub(crate) span: Span,
}

#[derive(Diagnostic)]
#[diag("panic_handler must be a function")]
pub(crate) struct PanicHandlerMustBeFn {
#[primary_span]
pub(crate) span: Span,
}

#[derive(Diagnostic)]
#[diag("macro requires a boolean expression as an argument")]
pub(crate) struct AssertRequiresBoolean {
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_builtin_macros/src/eii.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,9 @@ fn split_attrs(
Some(sym::track_caller) => {
foreign_item_attributes.push(attr);
}
Some(sym::rustc_diagnostic_item) => {
macro_attributes.push(attr.clone());
}
Some(sym::eii) => unreachable!("should already be filtered out"),
_ => {
ecx.dcx().emit_err(EiiAttributeNotSupported { span, attr_span: attr.span });
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_builtin_macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ mod global_allocator;
mod iter;
mod log_syntax;
mod offload;
mod panic_handler;
mod pattern_type;
mod rustdoc_skip_body;
mod source_util;
Expand Down Expand Up @@ -126,6 +127,7 @@ pub fn register_builtin_macros(resolver: &mut dyn ResolverExpand) {
eii_shared_macro: eii::eii_shared_macro,
global_allocator: global_allocator::expand,
offload_kernel: offload::expand_kernel,
panic_handler: panic_handler::expand,
rustdoc_skip_body: rustdoc_skip_body::expand,
test: test::expand_test,
test_case: test::expand_test_case,
Expand Down
43 changes: 43 additions & 0 deletions compiler/rustc_builtin_macros/src/panic_handler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use rustc_ast::{self as ast, AttrArgs, AttrItem, AttrStyle, Safety, StmtKind, attr};
use rustc_expand::base::{Annotatable, ExtCtxt};
use rustc_span::{Span, sym};

use crate::diagnostics;
use crate::util::check_builtin_macro_attribute;

pub(crate) fn expand(
ecx: &mut ExtCtxt<'_>,
span: Span,
meta_item: &ast::MetaItem,
mut item: Annotatable,
) -> Vec<Annotatable> {
check_builtin_macro_attribute(ecx, meta_item, sym::global_allocator);

// Allow using `#[panic_handler]` on an item statement
// FIXME - if we get deref patterns, use them to reduce duplication here
let attrs = if let Annotatable::Item(item) = &mut item {
&mut item.attrs
} else if let Annotatable::Stmt(stmt) = &mut item
&& let StmtKind::Item(item) = &mut stmt.kind
{
&mut item.attrs
} else {
ecx.dcx().emit_err(diagnostics::PanicHandlerMustBeFn { span: item.span() });
return vec![item];
};

attrs.push(attr::mk_attr_from_item(
&ecx.sess.psess.attr_id_generator,
AttrItem {
unsafety: Safety::Default,
path: ecx.std_path(span, &[sym::panicking, sym::panic_handler]),
args: AttrArgs::Empty,
span,
},
None,
AttrStyle::Outer,
span,
));

vec![item]
}
14 changes: 14 additions & 0 deletions compiler/rustc_codegen_cranelift/example/mini_core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -835,6 +835,20 @@ struct PanicLocation {
column: u32,
}

#[track_caller]
#[lang = "panic_misaligned_pointer_dereference"] // needed by codegen for panic on misaligned pointer deref
#[rustc_nounwind] // `CheckAlignment` MIR pass requires this function to never unwind
fn panic_misaligned_pointer_dereference(_required: usize, _found: usize) -> ! {
loop {}
}

#[track_caller]
#[lang = "panic_null_pointer_dereference"] // needed by codegen for panic on null pointer deref
#[rustc_nounwind] // `CheckNull` MIR pass requires this function to never unwind
fn panic_null_pointer_dereference() -> ! {
loop {}
}

#[unsafe(no_mangle)]
#[cfg(not(all(windows, target_env = "gnu")))]
pub fn get_tls() -> u8 {
Expand Down
5 changes: 0 additions & 5 deletions compiler/rustc_codegen_gcc/example/alloc_example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,6 @@ extern "C" {
fn puts(s: *const u8) -> i32;
}

#[panic_handler]
fn panic_handler(_: &core::panic::PanicInfo<'_>) -> ! {
core::intrinsics::abort_immediate();
}

#[alloc_error_handler]
fn alloc_error_handler(_: alloc::alloc::Layout) -> ! {
core::intrinsics::abort_immediate();
Expand Down
15 changes: 15 additions & 0 deletions compiler/rustc_codegen_gcc/example/mini_core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
extern_types,
decl_macro,
rustc_attrs,
rustc_private,
transparent_unions,
auto_traits,
freeze_impls,
Expand Down Expand Up @@ -573,6 +574,20 @@ fn panic_bounds_check(index: usize, len: usize) -> ! {
}
}

#[track_caller]
#[lang = "panic_misaligned_pointer_dereference"] // needed by codegen for panic on misaligned pointer deref
#[rustc_nounwind] // `CheckAlignment` MIR pass requires this function to never unwind
fn panic_misaligned_pointer_dereference(_required: usize, _found: usize) -> ! {
loop {}
}

#[track_caller]
#[lang = "panic_null_pointer_dereference"] // needed by codegen for panic on null pointer deref
#[rustc_nounwind] // `CheckNull` MIR pass requires this function to never unwind
fn panic_null_pointer_dereference() -> ! {
loop {}
}

#[lang = "eh_personality"]
fn eh_personality() -> ! {
loop {}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_error_codes/src/error_codes/E0264.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ A list of available external lang items is available in
#![allow(internal_features)]

extern "C" {
#[lang = "panic_impl"] // ok!
#[lang = "eh_personality"] // ok!
fn cake();
}
```
1 change: 0 additions & 1 deletion compiler/rustc_feature/src/builtin_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,6 @@ pub static BUILTIN_ATTRIBUTES: &[Symbol] = &[

// Runtime
sym::windows_subsystem,
sym::panic_handler, // RFC 2070

// Code generation:
sym::inline,
Expand Down
80 changes: 0 additions & 80 deletions compiler/rustc_hir_typeck/src/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,16 @@ use std::cell::RefCell;

use rustc_attr_ir::lang_items::LangItem;
use rustc_hir as hir;
use rustc_hir::def::DefKind;
use rustc_hir_analysis::check::check_function_signature;
use rustc_infer::infer::RegionVariableOrigin;
use rustc_infer::traits::WellFormedLoc;
use rustc_lint_defs::builtin::UNSAFE_PANIC_HANDLERS;
use rustc_middle::ty::{self, Binder, Ty, TyCtxt};
use rustc_span::def_id::LocalDefId;
use rustc_span::sym;
use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode};
use tracing::{debug, instrument};

use crate::coercion::CoerceMany;
use crate::diagnostics::UnsafePanicHandlers;
use crate::gather_locals::GatherLocalsVisitor;
use crate::{CoroutineTypes, Diverges, FnCtxt};

Expand Down Expand Up @@ -150,90 +147,13 @@ pub(super) fn check_fn<'a, 'tcx>(
// we have a recursive call site and do the sadly stabilized fallback to `()`.
fcx.demand_suptype(span, ret_ty, actual_return_ty);

// Check that a function marked as `#[panic_handler]` has signature `fn(&PanicInfo) -> !`
if tcx.is_lang_item(fn_def_id.to_def_id(), LangItem::PanicImpl) {
check_panic_info_fn(tcx, fn_def_id, fn_sig);
}

if tcx.is_lang_item(fn_def_id.to_def_id(), LangItem::Start) {
check_lang_start_fn(tcx, fn_sig, fn_def_id);
}

fcx.coroutine_types
}

fn check_panic_info_fn(tcx: TyCtxt<'_>, fn_id: LocalDefId, fn_sig: ty::FnSig<'_>) {
let span = tcx.def_span(fn_id);

let DefKind::Fn = tcx.def_kind(fn_id) else {
tcx.dcx().span_err(span, "should be a function");
return;
};

let generic_counts = tcx.generics_of(fn_id).own_counts();
if generic_counts.types != 0 {
tcx.dcx().span_err(span, "should have no type parameters");
}
if generic_counts.consts != 0 {
tcx.dcx().span_err(span, "should have no const parameters");
}

if fn_sig.safety().is_unsafe() {
let hir_id = tcx.local_def_id_to_hir_id(fn_id);
let span = tcx.def_span(fn_id);
// If the function is implicitly "unsafe" because it has a `#[target_feature]` attribute,
// then we should already have emitted an error. Don't also emit a warning.
// See `tests/ui/panic-handler/panic-handler-with-target-feature.rs`
if let Some(hir_fn_sig) = tcx.hir_fn_sig_by_hir_id(hir_id)
&& hir_fn_sig.header.safety == hir::HeaderSafety::SafeTargetFeatures
{
tcx.dcx().span_delayed_bug(span, "`unsafe_panic_handlers` lint suppressed because there should already be an error for `#[target_feature]`");
} else {
tcx.emit_node_span_lint(UNSAFE_PANIC_HANDLERS, hir_id, span, UnsafePanicHandlers);
}
}

let panic_info_did = tcx.require_lang_item(LangItem::PanicInfo, span);

// build type `for<'a, 'b> fn(&'a PanicInfo<'b>) -> !`
let panic_info_ty = tcx
.type_of(panic_info_did)
.instantiate(
tcx,
&[ty::GenericArg::from(ty::Region::new_bound(
tcx,
ty::INNERMOST,
ty::BoundRegion { var: ty::BoundVar::from_u32(1), kind: ty::BoundRegionKind::Anon },
))],
)
.skip_norm_wip();
let panic_info_ref_ty = Ty::new_imm_ref(
tcx,
ty::Region::new_bound(
tcx,
ty::INNERMOST,
ty::BoundRegion { var: ty::BoundVar::ZERO, kind: ty::BoundRegionKind::Anon },
),
panic_info_ty,
);

let bounds = tcx.mk_bound_variable_kinds(&[
ty::BoundVariableKind::Region(ty::BoundRegionKind::Anon),
ty::BoundVariableKind::Region(ty::BoundRegionKind::Anon),
]);
let expected_sig = ty::Binder::bind_with_vars(
tcx.mk_fn_sig_rust_abi([panic_info_ref_ty], tcx.types.never, fn_sig.safety()),
bounds,
);

let _ = check_function_signature(
tcx,
ObligationCause::new(span, fn_id, ObligationCauseCode::LangFunctionType(sym::panic_impl)),
fn_id.into(),
expected_sig,
);
}

fn check_lang_start_fn<'tcx>(tcx: TyCtxt<'tcx>, fn_sig: ty::FnSig<'tcx>, def_id: LocalDefId) {
// build type `fn(main: fn() -> T, argc: isize, argv: *const *const u8, sigpipe: u8)`

Expand Down
4 changes: 0 additions & 4 deletions compiler/rustc_hir_typeck/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1370,10 +1370,6 @@ impl ExprParenthesesNeeded {
}
}

#[derive(Diagnostic)]
#[diag("`#[panic_handler]` functions can't be `unsafe`")]
pub(crate) struct UnsafePanicHandlers;

#[derive(Diagnostic)]
#[diag("comptime functions can only be called at compile time")]
pub(crate) struct ComptimeFnCalledOutsideConstContext {
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_metadata/src/rmeta/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -812,10 +812,9 @@ impl MetadataBlob {
)?;
writeln!(
out,
"has_global_allocator {} has_alloc_error_handler {} has_panic_handler {} has_default_lib_allocator {}",
"has_global_allocator {} has_alloc_error_handler {} has_default_lib_allocator {}",
root.has_global_allocator,
root.has_alloc_error_handler,
root.has_panic_handler,
root.has_default_lib_allocator
)?;
writeln!(
Expand Down
2 changes: 0 additions & 2 deletions compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,8 +341,6 @@ provide! { tcx, def_id, other, cdata,
has_global_allocator => { cdata.root.has_global_allocator }
// FIXME: to be replaced with externally_implementable_items below
has_alloc_error_handler => { cdata.root.has_alloc_error_handler }
// FIXME: to be replaced with externally_implementable_items below
has_panic_handler => { cdata.root.has_panic_handler }

externally_implementable_items => {
cdata.get_externally_implementable_items(tcx)
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_metadata/src/rmeta/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -787,7 +787,6 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
edition: tcx.sess.edition(),
has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
has_default_lib_allocator: find_attr!(attrs, DefaultLibAllocator),
externally_implementable_items,
proc_macro_data,
Expand Down
Loading
Loading