Skip to content

Commit 3fa6cc1

Browse files
committed
Implement the #[sanitize(..)] attribute
This change implements the #[sanitize(..)] attribute, which opts to replace the currently unstable #[no_sanitize]. Essentially the new attribute works similar as #[no_sanitize], just with more flexible options regarding where it is applied. E.g. it is possible to turn a certain sanitizer either on or off: `#[sanitize(address = "on|off")]` This attribute now also applies to more places, e.g. it is possible to turn off a sanitizer for an entire module or impl block: ```rust \#[sanitize(address = "off")] mod foo { fn unsanitized(..) {} #[sanitize(address = "on")] fn sanitized(..) {} } \#[sanitize(thread = "off")] impl MyTrait for () { ... } ``` This attribute is enabled behind the unstable `sanitize` feature.
1 parent 07b7dc9 commit 3fa6cc1

File tree

21 files changed

+742
-6
lines changed

21 files changed

+742
-6
lines changed

compiler/rustc_codegen_ssa/messages.ftl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,9 @@ codegen_ssa_invalid_monomorphization_unsupported_symbol_of_size = invalid monomo
172172
codegen_ssa_invalid_no_sanitize = invalid argument for `no_sanitize`
173173
.note = expected one of: `address`, `cfi`, `hwaddress`, `kcfi`, `memory`, `memtag`, `shadow-call-stack`, or `thread`
174174
175+
codegen_ssa_invalid_sanitize = invalid argument for `sanitize`
176+
.note = expected one of: `address`, `cfi`, `hwaddress`, `kcfi`, `memory`, `memtag`, `shadow-call-stack`, or `thread`
177+
175178
codegen_ssa_invalid_windows_subsystem = invalid windows subsystem `{$subsystem}`, only `windows` and `console` are allowed
176179
177180
codegen_ssa_ld64_unimplemented_modifier = `as-needed` modifier not implemented yet for ld64

compiler/rustc_codegen_ssa/src/codegen_attrs.rs

Lines changed: 99 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,7 @@ fn parse_patchable_function_entry(
195195
struct InterestingAttributeDiagnosticSpans {
196196
link_ordinal: Option<Span>,
197197
no_sanitize: Option<Span>,
198+
sanitize: Option<Span>,
198199
inline: Option<Span>,
199200
no_mangle: Option<Span>,
200201
}
@@ -376,6 +377,7 @@ fn process_builtin_attrs(
376377
codegen_fn_attrs.no_sanitize |=
377378
parse_no_sanitize_attr(tcx, attr).unwrap_or_default();
378379
}
380+
sym::sanitize => interesting_spans.sanitize = Some(attr.span()),
379381
sym::instruction_set => {
380382
codegen_fn_attrs.instruction_set = parse_instruction_set_attr(tcx, attr)
381383
}
@@ -399,6 +401,8 @@ fn apply_overrides(tcx: TyCtxt<'_>, did: LocalDefId, codegen_fn_attrs: &mut Code
399401
codegen_fn_attrs.alignment =
400402
Ord::max(codegen_fn_attrs.alignment, tcx.sess.opts.unstable_opts.min_function_alignment);
401403

404+
// Compute the disabled sanitizers.
405+
codegen_fn_attrs.no_sanitize |= tcx.disabled_sanitizers_for(did);
402406
// On trait methods, inherit the `#[align]` of the trait's method prototype.
403407
codegen_fn_attrs.alignment = Ord::max(codegen_fn_attrs.alignment, tcx.inherited_align(did));
404408

@@ -483,6 +487,16 @@ fn check_result(
483487
lint.span_note(inline_span, "inlining requested here");
484488
})
485489
}
490+
if !codegen_fn_attrs.no_sanitize.is_empty()
491+
&& codegen_fn_attrs.inline.always()
492+
&& let (Some(sanitize_span), Some(inline_span)) = (interesting_spans.sanitize, interesting_spans.inline)
493+
{
494+
let hir_id = tcx.local_def_id_to_hir_id(did);
495+
tcx.node_span_lint(lint::builtin::INLINE_NO_SANITIZE, hir_id, sanitize_span, |lint| {
496+
lint.primary_message("setting `sanitize` off will have no effect after inlining");
497+
lint.span_note(inline_span, "inlining requested here");
498+
})
499+
}
486500

487501
// error when specifying link_name together with link_ordinal
488502
if let Some(_) = codegen_fn_attrs.link_name
@@ -605,6 +619,84 @@ fn opt_trait_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
605619
}
606620
}
607621

622+
/// For an attr that has the `sanitize` attribute, read the list of
623+
/// disabled sanitizers.
624+
fn parse_sanitize_attr(tcx: TyCtxt<'_>, attr: &Attribute) -> SanitizerSet {
625+
let mut result = SanitizerSet::empty();
626+
if let Some(list) = attr.meta_item_list() {
627+
for item in list.iter() {
628+
let MetaItemInner::MetaItem(set) = item else {
629+
tcx.dcx().emit_err(errors::InvalidSanitize { span: attr.span() });
630+
break;
631+
};
632+
let segments = set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
633+
match segments.as_slice() {
634+
[sym::address] if set.value_str() == Some(sym::off) => {
635+
result |= SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS
636+
}
637+
[sym::address] if set.value_str() == Some(sym::on) => {
638+
result &= !SanitizerSet::ADDRESS;
639+
result &= !SanitizerSet::KERNELADDRESS;
640+
}
641+
[sym::cfi] if set.value_str() == Some(sym::off) => result |= SanitizerSet::CFI,
642+
[sym::cfi] if set.value_str() == Some(sym::on) => result &= !SanitizerSet::CFI,
643+
[sym::kcfi] if set.value_str() == Some(sym::off) => result |= SanitizerSet::KCFI,
644+
[sym::kcfi] if set.value_str() == Some(sym::on) => result &= !SanitizerSet::KCFI,
645+
[sym::memory] if set.value_str() == Some(sym::off) => {
646+
result |= SanitizerSet::MEMORY
647+
}
648+
[sym::memory] if set.value_str() == Some(sym::on) => {
649+
result &= !SanitizerSet::MEMORY
650+
}
651+
[sym::memtag] if set.value_str() == Some(sym::off) => {
652+
result |= SanitizerSet::MEMTAG
653+
}
654+
[sym::memtag] if set.value_str() == Some(sym::on) => {
655+
result &= !SanitizerSet::MEMTAG
656+
}
657+
[sym::shadow_call_stack] if set.value_str() == Some(sym::off) => {
658+
result |= SanitizerSet::SHADOWCALLSTACK
659+
}
660+
[sym::shadow_call_stack] if set.value_str() == Some(sym::on) => {
661+
result &= !SanitizerSet::SHADOWCALLSTACK
662+
}
663+
[sym::thread] if set.value_str() == Some(sym::off) => {
664+
result |= SanitizerSet::THREAD
665+
}
666+
[sym::thread] if set.value_str() == Some(sym::on) => {
667+
result &= !SanitizerSet::THREAD
668+
}
669+
[sym::hwaddress] if set.value_str() == Some(sym::off) => {
670+
result |= SanitizerSet::HWADDRESS
671+
}
672+
[sym::hwaddress] if set.value_str() == Some(sym::on) => {
673+
result &= !SanitizerSet::HWADDRESS
674+
}
675+
_ => {
676+
tcx.dcx().emit_err(errors::InvalidSanitize { span: attr.span() });
677+
}
678+
}
679+
}
680+
}
681+
result
682+
}
683+
684+
fn disabled_sanitizers_for(tcx: TyCtxt<'_>, did: LocalDefId) -> SanitizerSet {
685+
// Check for a sanitize annotation directly on this def.
686+
if let Some(attr) = tcx.get_attr(did, sym::sanitize) {
687+
return parse_sanitize_attr(tcx, attr);
688+
}
689+
690+
// Otherwise backtrack.
691+
match tcx.opt_local_parent(did) {
692+
// Check the parent (recursively).
693+
Some(parent) => tcx.disabled_sanitizers_for(parent),
694+
// We reached the crate root without seeing an attribute, so
695+
// there is no sanitizers to exclude.
696+
None => SanitizerSet::empty(),
697+
}
698+
}
699+
608700
/// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
609701
/// applied to the method prototype.
610702
fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
@@ -729,6 +821,11 @@ fn autodiff_attrs(tcx: TyCtxt<'_>, id: DefId) -> Option<AutoDiffAttrs> {
729821
}
730822

731823
pub(crate) fn provide(providers: &mut Providers) {
732-
*providers =
733-
Providers { codegen_fn_attrs, should_inherit_track_caller, inherited_align, ..*providers };
824+
*providers = Providers {
825+
codegen_fn_attrs,
826+
should_inherit_track_caller,
827+
inherited_align,
828+
disabled_sanitizers_for,
829+
..*providers
830+
};
734831
}

compiler/rustc_codegen_ssa/src/errors.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1108,6 +1108,14 @@ pub(crate) struct InvalidNoSanitize {
11081108
pub span: Span,
11091109
}
11101110

1111+
#[derive(Diagnostic)]
1112+
#[diag(codegen_ssa_invalid_sanitize)]
1113+
#[note]
1114+
pub(crate) struct InvalidSanitize {
1115+
#[primary_span]
1116+
pub span: Span,
1117+
}
1118+
11111119
#[derive(Diagnostic)]
11121120
#[diag(codegen_ssa_target_feature_safe_trait)]
11131121
pub(crate) struct TargetFeatureSafeTrait {

compiler/rustc_feature/src/builtin_attrs.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -545,6 +545,10 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
545545
template!(List: "address, kcfi, memory, thread"), DuplicatesOk,
546546
EncodeCrossCrate::No, experimental!(no_sanitize)
547547
),
548+
gated!(
549+
sanitize, Normal, template!(List: r#"address = "on|off", cfi = "on|off""#), ErrorPreceding,
550+
EncodeCrossCrate::No, sanitize, experimental!(sanitize),
551+
),
548552
gated!(
549553
coverage, Normal, template!(OneOf: &[sym::off, sym::on]),
550554
ErrorPreceding, EncodeCrossCrate::No,

compiler/rustc_feature/src/unstable.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -623,6 +623,8 @@ declare_features! (
623623
(unstable, return_type_notation, "1.70.0", Some(109417)),
624624
/// Allows `extern "rust-cold"`.
625625
(unstable, rust_cold_cc, "1.63.0", Some(97544)),
626+
/// Allows the use of the `sanitize` attribute.
627+
(unstable, sanitize, "CURRENT_RUSTC_VERSION", Some(39699)),
626628
/// Allows the use of SIMD types in functions declared in `extern` blocks.
627629
(unstable, simd_ffi, "1.0.0", Some(27731)),
628630
/// Allows specialization of implementations (RFC 1210).

compiler/rustc_middle/src/query/erase.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,7 @@ trivial! {
343343
rustc_span::Symbol,
344344
rustc_span::Ident,
345345
rustc_target::spec::PanicStrategy,
346+
rustc_target::spec::SanitizerSet,
346347
rustc_type_ir::Variance,
347348
u32,
348349
usize,

compiler/rustc_middle/src/query/mod.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ use rustc_session::lint::LintExpectationId;
100100
use rustc_span::def_id::LOCAL_CRATE;
101101
use rustc_span::source_map::Spanned;
102102
use rustc_span::{DUMMY_SP, Span, Symbol};
103-
use rustc_target::spec::PanicStrategy;
103+
use rustc_target::spec::{PanicStrategy, SanitizerSet};
104104
use {rustc_abi as abi, rustc_ast as ast, rustc_hir as hir};
105105

106106
use crate::infer::canonical::{self, Canonical};
@@ -2681,6 +2681,16 @@ rustc_queries! {
26812681
desc { |tcx| "looking up anon const kind of `{}`", tcx.def_path_str(def_id) }
26822682
separate_provide_extern
26832683
}
2684+
2685+
/// Checks for the nearest `#[sanitize(xyz = "off")]` or
2686+
/// `#[sanitize(xyz = "on")]` on this def and any enclosing defs, up to the
2687+
/// crate root.
2688+
///
2689+
/// Returns the set of sanitizers that is explicitly disabled for this def.
2690+
query disabled_sanitizers_for(key: LocalDefId) -> SanitizerSet {
2691+
desc { |tcx| "checking what set of sanitizers are enabled on `{}`", tcx.def_path_str(key) }
2692+
feedable
2693+
}
26842694
}
26852695

26862696
rustc_with_all_queries! { define_callbacks! }

compiler/rustc_passes/messages.ftl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -672,6 +672,12 @@ passes_rustc_unstable_feature_bound =
672672
attribute should be applied to `impl` or free function outside of any `impl` or trait
673673
.label = not an `impl` or free function
674674
675+
passes_sanitize_attribute_not_allowed =
676+
sanitize attribute not allowed here
677+
.not_fn_impl_mod = not a function, impl block, or module
678+
.no_body = function has no body
679+
.help = sanitize attribute can be applied to a function (with body), impl block, or module
680+
675681
passes_should_be_applied_to_fn =
676682
attribute should be applied to a function definition
677683
.label = {$on_crate ->

compiler/rustc_passes/src/check_attr.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
336336
[sym::no_sanitize, ..] => {
337337
self.check_no_sanitize(attr, span, target)
338338
}
339+
[sym::sanitize, ..] => {
340+
self.check_sanitize(attr, span, target)
341+
}
339342
[sym::thread_local, ..] => self.check_thread_local(attr, span, target),
340343
[sym::doc, ..] => self.check_doc_attrs(
341344
attr,
@@ -694,6 +697,46 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
694697
}
695698
}
696699

700+
/// Checks that the `#[sanitize(..)]` attribute is applied to a
701+
/// function/closure/method, or to an impl block or module.
702+
fn check_sanitize(&self, attr: &Attribute, target_span: Span, target: Target) {
703+
let mut not_fn_impl_mod = None;
704+
let mut no_body = None;
705+
706+
if let Some(list) = attr.meta_item_list() {
707+
for item in list.iter() {
708+
let MetaItemInner::MetaItem(set) = item else {
709+
return;
710+
};
711+
let segments = set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
712+
match target {
713+
Target::Fn
714+
| Target::Closure
715+
| Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent)
716+
| Target::Impl { .. }
717+
| Target::Mod => return,
718+
Target::Static if matches!(segments.as_slice(), [sym::address]) => return,
719+
720+
// These are "functions", but they aren't allowed because they don't
721+
// have a body, so the usual explanation would be confusing.
722+
Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
723+
no_body = Some(target_span);
724+
}
725+
726+
_ => {
727+
not_fn_impl_mod = Some(target_span);
728+
}
729+
}
730+
}
731+
self.dcx().emit_err(errors::SanitizeAttributeNotAllowed {
732+
attr_span: attr.span(),
733+
not_fn_impl_mod,
734+
no_body,
735+
help: (),
736+
});
737+
}
738+
}
739+
697740
/// FIXME: Remove when all attributes are ported to the new parser
698741
fn check_generic_attr_unparsed(
699742
&self,

compiler/rustc_passes/src/errors.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1770,6 +1770,23 @@ pub(crate) struct NoSanitize<'a> {
17701770
pub attr_str: &'a str,
17711771
}
17721772

1773+
/// "sanitize attribute not allowed here"
1774+
#[derive(Diagnostic)]
1775+
#[diag(passes_sanitize_attribute_not_allowed)]
1776+
pub(crate) struct SanitizeAttributeNotAllowed {
1777+
#[primary_span]
1778+
pub attr_span: Span,
1779+
/// "not a function, impl block, or module"
1780+
#[label(passes_not_fn_impl_mod)]
1781+
pub not_fn_impl_mod: Option<Span>,
1782+
/// "function has no body"
1783+
#[label(passes_no_body)]
1784+
pub no_body: Option<Span>,
1785+
/// "sanitize attribute can be applied to a function (with body), impl block, or module"
1786+
#[help]
1787+
pub help: (),
1788+
}
1789+
17731790
// FIXME(jdonszelmann): move back to rustc_attr
17741791
#[derive(Diagnostic)]
17751792
#[diag(passes_rustc_const_stable_indirect_pairing)]

0 commit comments

Comments
 (0)