Skip to content

Commit 53c1bbf

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 2c1ac85 commit 53c1bbf

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
@@ -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

@@ -504,6 +508,16 @@ fn check_result(
504508
lint.span_note(inline_span, "inlining requested here");
505509
})
506510
}
511+
if !codegen_fn_attrs.no_sanitize.is_empty()
512+
&& codegen_fn_attrs.inline.always()
513+
&& let (Some(sanitize_span), Some(inline_span)) = (interesting_spans.sanitize, interesting_spans.inline)
514+
{
515+
let hir_id = tcx.local_def_id_to_hir_id(did);
516+
tcx.node_span_lint(lint::builtin::INLINE_NO_SANITIZE, hir_id, sanitize_span, |lint| {
517+
lint.primary_message("setting `sanitize` off will have no effect after inlining");
518+
lint.span_note(inline_span, "inlining requested here");
519+
})
520+
}
507521

508522
// error when specifying link_name together with link_ordinal
509523
if let Some(_) = codegen_fn_attrs.link_name
@@ -626,6 +640,84 @@ fn opt_trait_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
626640
}
627641
}
628642

643+
/// For an attr that has the `sanitize` attribute, read the list of
644+
/// disabled sanitizers.
645+
fn parse_sanitize_attr(tcx: TyCtxt<'_>, attr: &Attribute) -> SanitizerSet {
646+
let mut result = SanitizerSet::empty();
647+
if let Some(list) = attr.meta_item_list() {
648+
for item in list.iter() {
649+
let MetaItemInner::MetaItem(set) = item else {
650+
tcx.dcx().emit_err(errors::InvalidSanitize { span: attr.span() });
651+
break;
652+
};
653+
let segments = set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
654+
match segments.as_slice() {
655+
[sym::address] if set.value_str() == Some(sym::off) => {
656+
result |= SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS
657+
}
658+
[sym::address] if set.value_str() == Some(sym::on) => {
659+
result &= !SanitizerSet::ADDRESS;
660+
result &= !SanitizerSet::KERNELADDRESS;
661+
}
662+
[sym::cfi] if set.value_str() == Some(sym::off) => result |= SanitizerSet::CFI,
663+
[sym::cfi] if set.value_str() == Some(sym::on) => result &= !SanitizerSet::CFI,
664+
[sym::kcfi] if set.value_str() == Some(sym::off) => result |= SanitizerSet::KCFI,
665+
[sym::kcfi] if set.value_str() == Some(sym::on) => result &= !SanitizerSet::KCFI,
666+
[sym::memory] if set.value_str() == Some(sym::off) => {
667+
result |= SanitizerSet::MEMORY
668+
}
669+
[sym::memory] if set.value_str() == Some(sym::on) => {
670+
result &= !SanitizerSet::MEMORY
671+
}
672+
[sym::memtag] if set.value_str() == Some(sym::off) => {
673+
result |= SanitizerSet::MEMTAG
674+
}
675+
[sym::memtag] if set.value_str() == Some(sym::on) => {
676+
result &= !SanitizerSet::MEMTAG
677+
}
678+
[sym::shadow_call_stack] if set.value_str() == Some(sym::off) => {
679+
result |= SanitizerSet::SHADOWCALLSTACK
680+
}
681+
[sym::shadow_call_stack] if set.value_str() == Some(sym::on) => {
682+
result &= !SanitizerSet::SHADOWCALLSTACK
683+
}
684+
[sym::thread] if set.value_str() == Some(sym::off) => {
685+
result |= SanitizerSet::THREAD
686+
}
687+
[sym::thread] if set.value_str() == Some(sym::on) => {
688+
result &= !SanitizerSet::THREAD
689+
}
690+
[sym::hwaddress] if set.value_str() == Some(sym::off) => {
691+
result |= SanitizerSet::HWADDRESS
692+
}
693+
[sym::hwaddress] if set.value_str() == Some(sym::on) => {
694+
result &= !SanitizerSet::HWADDRESS
695+
}
696+
_ => {
697+
tcx.dcx().emit_err(errors::InvalidSanitize { span: attr.span() });
698+
}
699+
}
700+
}
701+
}
702+
result
703+
}
704+
705+
fn disabled_sanitizers_for(tcx: TyCtxt<'_>, did: LocalDefId) -> SanitizerSet {
706+
// Check for a sanitize annotation directly on this def.
707+
if let Some(attr) = tcx.get_attr(did, sym::sanitize) {
708+
return parse_sanitize_attr(tcx, attr);
709+
}
710+
711+
// Otherwise backtrack.
712+
match tcx.opt_local_parent(did) {
713+
// Check the parent (recursively).
714+
Some(parent) => tcx.disabled_sanitizers_for(parent),
715+
// We reached the crate root without seeing an attribute, so
716+
// there is no sanitizers to exclude.
717+
None => SanitizerSet::empty(),
718+
}
719+
}
720+
629721
/// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
630722
/// applied to the method prototype.
631723
fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
@@ -750,6 +842,11 @@ fn autodiff_attrs(tcx: TyCtxt<'_>, id: DefId) -> Option<AutoDiffAttrs> {
750842
}
751843

752844
pub(crate) fn provide(providers: &mut Providers) {
753-
*providers =
754-
Providers { codegen_fn_attrs, should_inherit_track_caller, inherited_align, ..*providers };
845+
*providers = Providers {
846+
codegen_fn_attrs,
847+
should_inherit_track_caller,
848+
inherited_align,
849+
disabled_sanitizers_for,
850+
..*providers
851+
};
755852
}

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
@@ -344,6 +344,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
344344
[sym::no_sanitize, ..] => {
345345
self.check_no_sanitize(attr, span, target)
346346
}
347+
[sym::sanitize, ..] => {
348+
self.check_sanitize(attr, span, target)
349+
}
347350
[sym::thread_local, ..] => self.check_thread_local(attr, span, target),
348351
[sym::doc, ..] => self.check_doc_attrs(
349352
attr,
@@ -695,6 +698,46 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
695698
}
696699
}
697700

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