Skip to main content

rustc_session/options/
mitigation_coverage.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::str::FromStr;
3
4use rustc_macros::{BlobDecodable, Encodable};
5use rustc_span::edition::Edition;
6use rustc_target::spec::StackProtector;
7
8use crate::Session;
9use crate::config::Options;
10use crate::options::CFGuard;
11
12#[derive(#[automatically_derived]impl ::core::marker::Copy for
    DeniedPartialMitigationLevel {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DeniedPartialMitigationLevel {
}
#[automatically_derived]impl ::core::clone::Clone for
    DeniedPartialMitigationLevel {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<StackProtector>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for
    DeniedPartialMitigationLevel {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Enabled(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Enabled", &__self_0),
            Self::StackProtector(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "StackProtector", &__self_0),
        }
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    DeniedPartialMitigationLevel {
}
#[automatically_derived]impl ::core::cmp::PartialEq for
    DeniedPartialMitigationLevel {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Enabled(__self_0), Self::Enabled(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::StackProtector(__self_0),
                    Self::StackProtector(__arg1_0)) => __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for DeniedPartialMitigationLevel
    {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<bool>;
        let _: ::core::cmp::AssertParamIsEq<StackProtector>;
    }
}Eq, #[automatically_derived]impl ::core::cmp::PartialOrd for
    DeniedPartialMitigationLevel {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]impl ::core::cmp::Ord for DeniedPartialMitigationLevel
    {
    #[inline]
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
        match (self, other) {
            (Self::Enabled(__self_0), Self::Enabled(__arg1_0)) =>
                ::core::cmp::Ord::cmp(__self_0, __arg1_0),
            (Self::StackProtector(__self_0), Self::StackProtector(__arg1_0))
                => ::core::cmp::Ord::cmp(__self_0, __arg1_0),
            _ =>
                ::core::cmp::Ord::cmp(&::core::intrinsics::discriminant_value(self),
                    &::core::intrinsics::discriminant_value(other)),
        }
    }
}Ord, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for DeniedPartialMitigationLevel {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        DeniedPartialMitigationLevel::Enabled(ref __binding_0) => {
                            0usize
                        }
                        DeniedPartialMitigationLevel::StackProtector(ref __binding_0)
                            => {
                            1usize
                        }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    DeniedPartialMitigationLevel::Enabled(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    DeniedPartialMitigationLevel::StackProtector(ref __binding_0)
                        => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::BlobDecoder> ::rustc_serialize::Decodable<__D>
            for DeniedPartialMitigationLevel {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => {
                        DeniedPartialMitigationLevel::Enabled(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    1usize => {
                        DeniedPartialMitigationLevel::StackProtector(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `DeniedPartialMitigationLevel`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };BlobDecodable)]
13pub enum DeniedPartialMitigationLevel {
14    // Enabled(false) should be the bottom of the Ord hierarchy
15    Enabled(bool),
16    StackProtector(StackProtector),
17}
18
19impl DeniedPartialMitigationLevel {
20    pub fn level_str(&self) -> &'static str {
21        match self {
22            DeniedPartialMitigationLevel::StackProtector(StackProtector::All) => "=all",
23            DeniedPartialMitigationLevel::StackProtector(StackProtector::Strong) => "=strong",
24            // currently `=disabled` should not appear
25            DeniedPartialMitigationLevel::Enabled(false) => "=disabled",
26            DeniedPartialMitigationLevel::StackProtector(StackProtector::None)
27            | DeniedPartialMitigationLevel::Enabled(true) => "",
28        }
29    }
30}
31
32impl std::fmt::Display for DeniedPartialMitigationLevel {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        match self {
35            DeniedPartialMitigationLevel::StackProtector(StackProtector::All) => {
36                f.write_fmt(format_args!("all"))write!(f, "all")
37            }
38            DeniedPartialMitigationLevel::StackProtector(StackProtector::Strong) => {
39                f.write_fmt(format_args!("strong"))write!(f, "strong")
40            }
41            DeniedPartialMitigationLevel::Enabled(true) => {
42                f.write_fmt(format_args!("enabled"))write!(f, "enabled")
43            }
44            DeniedPartialMitigationLevel::StackProtector(StackProtector::None)
45            | DeniedPartialMitigationLevel::Enabled(false) => {
46                f.write_fmt(format_args!("disabled"))write!(f, "disabled")
47            }
48        }
49    }
50}
51
52impl From<bool> for DeniedPartialMitigationLevel {
53    fn from(value: bool) -> Self {
54        DeniedPartialMitigationLevel::Enabled(value)
55    }
56}
57
58impl From<StackProtector> for DeniedPartialMitigationLevel {
59    fn from(value: StackProtector) -> Self {
60        DeniedPartialMitigationLevel::StackProtector(value)
61    }
62}
63
64#[derive(#[automatically_derived]impl ::core::marker::Copy for MitigationStatus { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for MitigationStatus {
}
#[automatically_derived]impl ::core::clone::Clone for MitigationStatus {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<usize>;
        let _: ::core::clone::AssertParamIsClone<Option<bool>>;
        *self
    }
}Clone)]
65struct MitigationStatus {
66    // This is the index of the option in the command line. This is needed because
67    // re-enabling a mitigation resets the partial mitigation status if it's later in the command
68    // line, and this works across `-C` and `-Z` args.
69    //
70    // e.g. `-Z stack-protector=strong` resets `-C allow-partial-mitigations=stack-protector`.
71    index: usize,
72    allowed: Option<bool>,
73}
74
75#[derive(#[automatically_derived]impl ::core::clone::Clone for MitigationCoverageMap {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        MitigationCoverageMap { map: ::core::clone::Clone::clone(&self.map) }
    }
}Clone, #[automatically_derived]impl ::core::default::Default for
    MitigationCoverageMap {
    #[inline]
    fn default() -> Self {
        MitigationCoverageMap { map: ::core::default::Default::default() }
    }
}Default)]
76pub struct MitigationCoverageMap {
77    map: BTreeMap<DeniedPartialMitigationKind, MitigationStatus>,
78}
79
80impl MitigationCoverageMap {
81    fn apply_mitigation(
82        &mut self,
83        kind: DeniedPartialMitigationKind,
84        index: usize,
85        allowed: Option<bool>,
86    ) {
87        self.map
88            .entry(kind)
89            .and_modify(|e| {
90                if index >= e.index {
91                    *e = MitigationStatus { index, allowed }
92                }
93            })
94            .or_insert(MitigationStatus { index, allowed });
95    }
96
97    pub(crate) fn handle_allowdeny_mitigation_option(
98        &mut self,
99        v: Option<&str>,
100        index: usize,
101        allowed: bool,
102    ) -> bool {
103        match v {
104            Some(s) => {
105                for sub in s.split(',') {
106                    match sub.parse() {
107                        Ok(kind) => self.apply_mitigation(kind, index, Some(allowed)),
108                        Err(_) => return false,
109                    }
110                }
111                true
112            }
113            None => false,
114        }
115    }
116
117    pub(crate) fn reset_mitigation(&mut self, kind: DeniedPartialMitigationKind, index: usize) {
118        self.apply_mitigation(kind, index, None);
119    }
120}
121
122pub struct DeniedPartialMitigationKindParseError;
123
124macro_rules! intersperse {
125    ($sep:expr, ($first:expr $(, $rest:expr)* $(,)?)) => {
126        concat!($first $(, $sep, $rest)*)
127    };
128}
129
130macro_rules! denied_partial_mitigations {
131    ([$self:ident] enum $kind:ident {$(($name:ident, $text:expr, $since:ident, $code:expr)),*}) => {
132        #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Encodable, BlobDecodable)]
133        pub enum DeniedPartialMitigationKind {
134            $($name),*
135        }
136
137        impl std::fmt::Display for DeniedPartialMitigationKind {
138            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139                match self {
140                    $(DeniedPartialMitigationKind::$name => write!(f, $text)),*
141                }
142            }
143        }
144
145        impl DeniedPartialMitigationKind {
146            pub(crate) const KINDS: &'static str = concat!("comma-separated list of mitigation kinds (available: ",
147                intersperse!(", ", ($(concat!("`", $text, "`")),*)), ")");
148        }
149
150        impl FromStr for DeniedPartialMitigationKind {
151            type Err = DeniedPartialMitigationKindParseError;
152
153            fn from_str(v: &str) -> Result<DeniedPartialMitigationKind, DeniedPartialMitigationKindParseError> {
154                match v {
155                    $($text => Ok(DeniedPartialMitigationKind::$name)),*
156                    ,
157                    _ => Err(DeniedPartialMitigationKindParseError),
158                }
159            }
160        }
161
162        #[allow(unused)]
163        impl DeniedPartialMitigationKind {
164            pub fn allowed_by_default_at(&self, edition: Edition) -> bool {
165                let denied_since = match self {
166                    // Should change the denied-since edition of StackProtector to 2015
167                    // (all editions) when `-C stack-protector` is stabilized.
168                    $(DeniedPartialMitigationKind::$name => Edition::$since),*
169                };
170                edition < denied_since
171            }
172        }
173
174        impl Options {
175            pub fn all_denied_partial_mitigations(&self) -> impl Iterator<Item = DeniedPartialMitigationKind> {
176                [$(DeniedPartialMitigationKind::$name),*].into_iter()
177            }
178        }
179
180        impl Session {
181            pub fn gather_enabled_denied_partial_mitigations(&$self) -> Vec<DeniedPartialMitigation> {
182                let mut mitigations = [
183                    $(
184                    DeniedPartialMitigation {
185                        kind: DeniedPartialMitigationKind::$name,
186                        level: From::from($code),
187                    }
188                    ),*
189                ];
190                mitigations.sort();
191                mitigations.into_iter().collect()
192            }
193        }
194    }
195}
196
197pub enum DeniedPartialMitigationKind { StackProtector, ControlFlowGuard, }
#[automatically_derived]impl ::core::marker::Copy for
    DeniedPartialMitigationKind {
}
#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DeniedPartialMitigationKind {
}
#[automatically_derived]impl ::core::clone::Clone for
    DeniedPartialMitigationKind {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}
#[automatically_derived]impl ::core::fmt::Debug for
    DeniedPartialMitigationKind {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                DeniedPartialMitigationKind::StackProtector =>
                    "StackProtector",
                DeniedPartialMitigationKind::ControlFlowGuard =>
                    "ControlFlowGuard",
            })
    }
}
#[automatically_derived]impl ::core::marker::StructuralPartialEq for
    DeniedPartialMitigationKind {
}
#[automatically_derived]impl ::core::cmp::PartialEq for
    DeniedPartialMitigationKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}
#[automatically_derived]impl ::core::cmp::Eq for DeniedPartialMitigationKind {
}
#[automatically_derived]impl ::core::hash::Hash for
    DeniedPartialMitigationKind {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state)
    }
}
#[automatically_derived]impl ::core::cmp::PartialOrd for
    DeniedPartialMitigationKind {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}
#[automatically_derived]impl ::core::cmp::Ord for DeniedPartialMitigationKind
    {
    #[inline]
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&::core::intrinsics::discriminant_value(self),
            &::core::intrinsics::discriminant_value(other))
    }
}
const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for DeniedPartialMitigationKind {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        DeniedPartialMitigationKind::StackProtector => { 0usize }
                        DeniedPartialMitigationKind::ControlFlowGuard => { 1usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
            }
        }
    };
const _: () =
    {
        impl<__D: ::rustc_span::BlobDecoder> ::rustc_serialize::Decodable<__D>
            for DeniedPartialMitigationKind {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { DeniedPartialMitigationKind::StackProtector }
                    1usize => { DeniedPartialMitigationKind::ControlFlowGuard }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `DeniedPartialMitigationKind`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };
impl std::fmt::Display for DeniedPartialMitigationKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DeniedPartialMitigationKind::StackProtector =>
                f.write_fmt(format_args!("stack-protector")),
            DeniedPartialMitigationKind::ControlFlowGuard =>
                f.write_fmt(format_args!("control-flow-guard")),
        }
    }
}
impl DeniedPartialMitigationKind {
    pub(crate) const KINDS: &'static str =
        "comma-separated list of mitigation kinds (available: `stack-protector`, `control-flow-guard`)";
}
impl FromStr for DeniedPartialMitigationKind {
    type Err = DeniedPartialMitigationKindParseError;
    fn from_str(v: &str)
        ->
            Result<DeniedPartialMitigationKind,
            DeniedPartialMitigationKindParseError> {
        match v {
            "stack-protector" =>
                Ok(DeniedPartialMitigationKind::StackProtector),
            "control-flow-guard" =>
                Ok(DeniedPartialMitigationKind::ControlFlowGuard),
            _ => Err(DeniedPartialMitigationKindParseError),
        }
    }
}
#[allow(unused)]
impl DeniedPartialMitigationKind {
    pub fn allowed_by_default_at(&self, edition: Edition) -> bool {
        let denied_since =
            match self {
                DeniedPartialMitigationKind::StackProtector =>
                    Edition::Edition2015,
                DeniedPartialMitigationKind::ControlFlowGuard =>
                    Edition::EditionFuture,
            };
        edition < denied_since
    }
}
impl Options {
    pub fn all_denied_partial_mitigations(&self)
        -> impl Iterator<Item = DeniedPartialMitigationKind> {
        [DeniedPartialMitigationKind::StackProtector,
                    DeniedPartialMitigationKind::ControlFlowGuard].into_iter()
    }
}
impl Session {
    pub fn gather_enabled_denied_partial_mitigations(&self)
        -> Vec<DeniedPartialMitigation> {
        let mut mitigations =
            [DeniedPartialMitigation {
                        kind: DeniedPartialMitigationKind::StackProtector,
                        level: From::from(self.stack_protector()),
                    },
                    DeniedPartialMitigation {
                        kind: DeniedPartialMitigationKind::ControlFlowGuard,
                        level: From::from(self.opts.cg.control_flow_guard ==
                                CFGuard::Checks),
                    }];
        mitigations.sort();
        mitigations.into_iter().collect()
    }
}denied_partial_mitigations! {
198    [self]
199    enum DeniedPartialMitigationKind {
200        // The mitigation name should match the option name in rustc_session::options,
201        // to allow for resetting the mitigation
202
203        // stack-protector is an unstable option, so it can be denied-partial
204        (StackProtector, "stack-protector", Edition2015, self.stack_protector()),
205        (ControlFlowGuard, "control-flow-guard", EditionFuture, self.opts.cg.control_flow_guard == CFGuard::Checks)
206    }
207}
208
209/// A mitigation that cannot be partially enabled (see
210/// [RFC 3855](https://github.com/rust-lang/rfcs/pull/3855)), but are currently enabled for this
211/// crate.
212#[derive(#[automatically_derived]impl ::core::marker::Copy for DeniedPartialMitigation
    {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DeniedPartialMitigation {
}
#[automatically_derived]impl ::core::clone::Clone for DeniedPartialMitigation
    {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<DeniedPartialMitigationKind>;
        let _:
                ::core::clone::AssertParamIsClone<DeniedPartialMitigationLevel>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for DeniedPartialMitigation {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "DeniedPartialMitigation kind level", &self.kind, &&self.level)
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    DeniedPartialMitigation {
}
#[automatically_derived]impl ::core::cmp::PartialEq for
    DeniedPartialMitigation {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.kind == other.kind && self.level == other.level
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for DeniedPartialMitigation {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<DeniedPartialMitigationKind>;
        let _: ::core::cmp::AssertParamIsEq<DeniedPartialMitigationLevel>;
    }
}Eq, #[automatically_derived]impl ::core::cmp::PartialOrd for
    DeniedPartialMitigation {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]impl ::core::cmp::Ord for DeniedPartialMitigation {
    #[inline]
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
        match ::core::cmp::Ord::cmp(&self.kind, &other.kind) {
            ::core::cmp::Ordering::Equal =>
                ::core::cmp::Ord::cmp(&self.level, &other.level),
            cmp => cmp,
        }
    }
}Ord, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for DeniedPartialMitigation {
            fn encode(&self, __encoder: &mut __E) {
                let DeniedPartialMitigation {
                        kind: ref __binding_0, level: ref __binding_1 } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::BlobDecoder> ::rustc_serialize::Decodable<__D>
            for DeniedPartialMitigation {
            fn decode(__decoder: &mut __D) -> Self {
                DeniedPartialMitigation {
                    kind: ::rustc_serialize::Decodable::decode(__decoder),
                    level: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };BlobDecodable)]
213pub struct DeniedPartialMitigation {
214    pub kind: DeniedPartialMitigationKind,
215    pub level: DeniedPartialMitigationLevel,
216}
217
218impl Options {
219    // Return the list of mitigations that are allowed to be partial
220    pub fn allowed_partial_mitigations(
221        &self,
222        edition: Edition,
223    ) -> impl Iterator<Item = DeniedPartialMitigationKind> {
224        let mut result: BTreeSet<_> = self
225            .all_denied_partial_mitigations()
226            .filter(|mitigation| mitigation.allowed_by_default_at(edition))
227            .collect();
228        for (kind, MitigationStatus { index: _, allowed }) in &self.mitigation_coverage_map.map {
229            match allowed {
230                Some(true) => {
231                    result.insert(*kind);
232                }
233                Some(false) => {
234                    result.remove(kind);
235                }
236                None => {}
237            }
238        }
239        result.into_iter()
240    }
241}