Skip to content

Commit 401884e

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 30017c3 commit 401884e

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
@@ -174,6 +174,9 @@ codegen_ssa_invalid_monomorphization_unsupported_symbol_of_size = invalid monomo
174174
codegen_ssa_invalid_no_sanitize = invalid argument for `no_sanitize`
175175
.note = expected one of: `address`, `cfi`, `hwaddress`, `kcfi`, `memory`, `memtag`, `shadow-call-stack`, or `thread`
176176
177+
codegen_ssa_invalid_sanitize = invalid argument for `sanitize`
178+
.note = expected one of: `address`, `cfi`, `hwaddress`, `kcfi`, `memory`, `memtag`, `shadow-call-stack`, or `thread`
179+
177180
codegen_ssa_invalid_windows_subsystem = invalid windows subsystem `{$subsystem}`, only `windows` and `console` are allowed
178181
179182
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
@@ -162,6 +162,7 @@ fn parse_patchable_function_entry(
162162
struct InterestingAttributeDiagnosticSpans {
163163
link_ordinal: Option<Span>,
164164
no_sanitize: Option<Span>,
165+
sanitize: Option<Span>,
165166
inline: Option<Span>,
166167
no_mangle: Option<Span>,
167168
}
@@ -343,6 +344,7 @@ fn process_builtin_attrs(
343344
codegen_fn_attrs.no_sanitize |=
344345
parse_no_sanitize_attr(tcx, attr).unwrap_or_default();
345346
}
347+
sym::sanitize => interesting_spans.sanitize = Some(attr.span()),
346348
sym::instruction_set => {
347349
codegen_fn_attrs.instruction_set = parse_instruction_set_attr(tcx, attr)
348350
}
@@ -366,6 +368,8 @@ fn apply_overrides(tcx: TyCtxt<'_>, did: LocalDefId, codegen_fn_attrs: &mut Code
366368
codegen_fn_attrs.alignment =
367369
Ord::max(codegen_fn_attrs.alignment, tcx.sess.opts.unstable_opts.min_function_alignment);
368370

371+
// Compute the disabled sanitizers.
372+
codegen_fn_attrs.no_sanitize |= tcx.disabled_sanitizers_for(did);
369373
// On trait methods, inherit the `#[align]` of the trait's method prototype.
370374
codegen_fn_attrs.alignment = Ord::max(codegen_fn_attrs.alignment, tcx.inherited_align(did));
371375

@@ -471,6 +475,16 @@ fn check_result(
471475
lint.span_note(inline_span, "inlining requested here");
472476
})
473477
}
478+
if !codegen_fn_attrs.no_sanitize.is_empty()
479+
&& codegen_fn_attrs.inline.always()
480+
&& let (Some(sanitize_span), Some(inline_span)) = (interesting_spans.sanitize, interesting_spans.inline)
481+
{
482+
let hir_id = tcx.local_def_id_to_hir_id(did);
483+
tcx.node_span_lint(lint::builtin::INLINE_NO_SANITIZE, hir_id, sanitize_span, |lint| {
484+
lint.primary_message("setting `sanitize` off will have no effect after inlining");
485+
lint.span_note(inline_span, "inlining requested here");
486+
})
487+
}
474488

475489
// error when specifying link_name together with link_ordinal
476490
if let Some(_) = codegen_fn_attrs.link_name
@@ -593,6 +607,84 @@ fn opt_trait_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
593607
}
594608
}
595609

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

719811
pub(crate) fn provide(providers: &mut Providers) {
720-
*providers =
721-
Providers { codegen_fn_attrs, should_inherit_track_caller, inherited_align, ..*providers };
812+
*providers = Providers {
813+
codegen_fn_attrs,
814+
should_inherit_track_caller,
815+
inherited_align,
816+
disabled_sanitizers_for,
817+
..*providers
818+
};
722819
}

compiler/rustc_codegen_ssa/src/errors.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1128,6 +1128,14 @@ pub(crate) struct InvalidNoSanitize {
11281128
pub span: Span,
11291129
}
11301130

1131+
#[derive(Diagnostic)]
1132+
#[diag(codegen_ssa_invalid_sanitize)]
1133+
#[note]
1134+
pub(crate) struct InvalidSanitize {
1135+
#[primary_span]
1136+
pub span: Span,
1137+
}
1138+
11311139
#[derive(Diagnostic)]
11321140
#[diag(codegen_ssa_target_feature_safe_trait)]
11331141
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
@@ -745,6 +745,10 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
745745
template!(List: &["address, kcfi, memory, thread"]), DuplicatesOk,
746746
EncodeCrossCrate::No, experimental!(no_sanitize)
747747
),
748+
gated!(
749+
sanitize, Normal, template!(List: r#"address = "on|off", cfi = "on|off""#), ErrorPreceding,
750+
EncodeCrossCrate::No, sanitize, experimental!(sanitize),
751+
),
748752
gated!(
749753
coverage, Normal, template!(OneOf: &[sym::off, sym::on]),
750754
ErrorPreceding, EncodeCrossCrate::No,

compiler/rustc_feature/src/unstable.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -626,6 +626,8 @@ declare_features! (
626626
(unstable, return_type_notation, "1.70.0", Some(109417)),
627627
/// Allows `extern "rust-cold"`.
628628
(unstable, rust_cold_cc, "1.63.0", Some(97544)),
629+
/// Allows the use of the `sanitize` attribute.
630+
(unstable, sanitize, "CURRENT_RUSTC_VERSION", Some(39699)),
629631
/// Allows the use of SIMD types in functions declared in `extern` blocks.
630632
(unstable, simd_ffi, "1.0.0", Some(27731)),
631633
/// 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};
@@ -2686,6 +2686,16 @@ rustc_queries! {
26862686
desc { |tcx| "looking up anon const kind of `{}`", tcx.def_path_str(def_id) }
26872687
separate_provide_extern
26882688
}
2689+
2690+
/// Checks for the nearest `#[sanitize(xyz = "off")]` or
2691+
/// `#[sanitize(xyz = "on")]` on this def and any enclosing defs, up to the
2692+
/// crate root.
2693+
///
2694+
/// Returns the set of sanitizers that is explicitly disabled for this def.
2695+
query disabled_sanitizers_for(key: LocalDefId) -> SanitizerSet {
2696+
desc { |tcx| "checking what set of sanitizers are enabled on `{}`", tcx.def_path_str(key) }
2697+
feedable
2698+
}
26892699
}
26902700

26912701
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
@@ -673,6 +673,12 @@ passes_rustc_unstable_feature_bound =
673673
attribute should be applied to `impl`, trait or free function
674674
.label = not an `impl`, trait or free function
675675
676+
passes_sanitize_attribute_not_allowed =
677+
sanitize attribute not allowed here
678+
.not_fn_impl_mod = not a function, impl block, or module
679+
.no_body = function has no body
680+
.help = sanitize attribute can be applied to a function (with body), impl block, or module
681+
676682
passes_should_be_applied_to_fn =
677683
attribute should be applied to a function definition
678684
.label = {$on_crate ->

compiler/rustc_passes/src/check_attr.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
347347
[sym::no_sanitize, ..] => {
348348
self.check_no_sanitize(attr, span, target)
349349
}
350+
[sym::sanitize, ..] => {
351+
self.check_sanitize(attr, span, target)
352+
}
350353
[sym::thread_local, ..] => self.check_thread_local(attr, span, target),
351354
[sym::doc, ..] => self.check_doc_attrs(
352355
attr,
@@ -697,6 +700,46 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
697700
}
698701
}
699702

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

compiler/rustc_passes/src/errors.rs

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

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

0 commit comments

Comments
 (0)