paralegal_flow/ann/
side_effect_detection.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use std::collections::HashSet;

use flowistry_pdg_construction::utils::is_virtual;
use paralegal_spdg::Identifier;

use rustc_data_structures::fx::FxHashSet;
use rustc_hir::def_id::DefId;
use rustc_middle::{mir, ty};

use either::Either;

use crate::{ann::db::AutoMarkers, MarkerCtx};

const ALLOWED_INTRINSICS: &[&str] = &[
    // Prefetching.
    "prefetch_read_data",
    "prefetch_write_data",
    "prefetch_read_instruction",
    "prefetch_write_instruction",
    // Optimizer.
    "likely",
    "unlikely",
    "unreachable",
    "assume",
    "black_box",
    // Breakpoint.
    "breakpoint",
    // size_of and others.
    "size_of",
    "min_align_of",
    "pref_align_of",
    "size_of_val",
    "min_align_of_val",
    // Assertions.
    "assert_inhabited",
    "assert_zero_valid",
    "assert_mem_uninitialized_valid",
    // Needs drop.
    "needs_drop",
    // Offsets.
    "arith_offset",
    "offset",
    // Ptr mask.
    "ptr_mask",
    // Number operations.
    "sqrtf32",
    "sqrtf64",
    "powif32",
    "powif64",
    "sinf32",
    "sinf64",
    "cosf32",
    "cosf64",
    "powf32",
    "powf64",
    "expf32",
    "expf64",
    "exp2f32",
    "exp2f64",
    "logf32",
    "logf64",
    "log10f32",
    "log10f64",
    "log2f32",
    "log2f64",
    "fmaf32",
    "fmaf64",
    "fabsf32",
    "fabsf64",
    "minnumf32",
    "minnumf64",
    "maxnumf32",
    "maxnumf64",
    "copysignf32",
    "copysignf64",
    "floorf32",
    "floorf64",
    "ceilf32",
    "ceilf64",
    "truncf32",
    "truncf64",
    "rintf32",
    "rintf64",
    "nearbyintf32",
    "nearbyintf64",
    "roundf32",
    "roundf64",
    "roundevenf32",
    "roundevenf64",
    "fadd_fast",
    "fsub_fast",
    "fmul_fast",
    "fdiv_fast",
    "frem_fast",
    "float_to_int_unchecked",
    // Bit operations
    "ctpop",
    "ctlz",
    "ctlz_nonzero",
    "cttz",
    "cttz_nonzero",
    "bswap",
    "bitreverse",
    // Arithmetic operations with overflow.
    "add_with_overflow",
    "sub_with_overflow",
    "mul_with_overflow",
    // Rotates.
    "rotate_left",
    "rotate_right",
    // Wrapping arithmetic operations.
    "wrapping_add",
    "wrapping_sub",
    "wrapping_mul",
    // Saturating arithmetic operations.
    "saturating_add",
    "saturating_sub",
    // Read arbitrary memory.
    "read_via_copy",
    // Discriminants.
    "discriminant_value",
    // Variants.
    "variant_count",
    // const* business.
    "ptr_offset_from",
    "ptr_offset_from_unsigned",
    "ptr_guaranteed_cmp",
    // Constant evaluation.
    "const_allocate",
    "const_deallocate",
    "const_eval_select",
    // Raw equality comparison.
    "raw_eq",
    "compare_bytes",
    // Vtable.
    "vtable_size",
    "vtable_align",
    // Unchecked arithmetic operations.
    "exact_div",
    "unchecked_add",
    "unchecked_div",
    "unchecked_mul",
    "unchecked_rem",
    "unchecked_shl",
    "unchecked_shr",
    "unchecked_sub",
    // Dynamic typing.
    "type_id",
    "type_name",
    // Transmute is allowlisted as an intrinsic, but is checked for separately.
    // Justus: I don't know why Artem was checking for this separately. For now
    // I disallow this, though I still special case it with it's own effect
    // type.
    // "transmute",
];

pub(super) fn allowed_intrinsics() -> FxHashSet<rustc_span::Symbol> {
    ALLOWED_INTRINSICS
        .iter()
        .copied()
        .map(rustc_span::Symbol::intern)
        .collect()
}

pub fn is_allowed_as_clone_unit_instance<'tcx>(
    tcx: ty::TyCtxt<'tcx>,
    instance: ty::Instance<'tcx>,
) -> bool {
    let fn_id = instance.def_id();
    let generics = instance.args;

    tcx.lang_items().clone_fn().is_some_and(|c| c == fn_id)
        && matches!(generics.as_slice(), [ty] if ty.as_type().is_some_and(ty::Ty::is_unit))
}

pub fn analyze_body<'tcx>(
    body: &mir::Body<'tcx>,
    auto_markers: &AutoMarkers,
    tcx: ty::TyCtxt<'tcx>,
) -> FxHashSet<Identifier> {
    use mir::visit::Visitor;
    let mut analyzer = BodyAnalyzer::new(body, auto_markers, tcx);
    analyzer.visit_body(body);
    analyzer.found_markers
}

pub fn analyze_statement<'tcx>(
    body: &mir::Body<'tcx>,
    location: mir::Location, // we take location here so we can guarantee that the statement is within the body
    auto_markers: &AutoMarkers,
    tcx: ty::TyCtxt<'tcx>,
) -> FxHashSet<Identifier> {
    use mir::visit::Visitor;

    let mut analyzer = BodyAnalyzer::new(body, auto_markers, tcx);
    match body.stmt_at(location) {
        Either::Left(statement) => {
            analyzer.visit_statement(statement, location);
            trace!(
                "Checking statement {:?}, found {:?}",
                statement.kind,
                analyzer.found_markers
            );
        }
        Either::Right(terminator) => {
            analyzer.visit_terminator(terminator, location);
        }
    }
    analyzer.found_markers
}

struct BodyAnalyzer<'tcx, 'b> {
    body: &'b mir::Body<'tcx>,
    found_markers: FxHashSet<Identifier>,
    auto_markers: &'b AutoMarkers,
    tcx: ty::TyCtxt<'tcx>,
}

impl<'tcx, 'b> BodyAnalyzer<'tcx, 'b> {
    fn new(
        body: &'b mir::Body<'tcx>,
        auto_markers: &'b AutoMarkers,
        tcx: ty::TyCtxt<'tcx>,
    ) -> Self {
        Self {
            body,
            found_markers: HashSet::default(),
            auto_markers,
            tcx,
        }
    }
}

impl<'tcx> mir::visit::Visitor<'tcx> for BodyAnalyzer<'tcx, '_> {
    fn visit_projection_elem(
        &mut self,
        place_ref: mir::PlaceRef<'tcx>,
        projection_elem: mir::PlaceElem<'tcx>,
        context: mir::visit::PlaceContext,
        location: mir::Location,
    ) {
        if matches!(projection_elem, mir::ProjectionElem::Deref) {
            let ty = place_ref.ty(self.body, self.tcx).ty;

            if ty.is_mutable_ptr() && ty.is_unsafe_ptr() {
                self.found_markers
                    .insert(self.auto_markers.side_effect_raw_ptr);
            }
        }
        self.super_projection_elem(place_ref, projection_elem, context, location);
    }

    fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>, location: mir::Location) {
        if let mir::Rvalue::Cast(mir::CastKind::Transmute, _, to) = rvalue {
            trace!("Found transmute in {rvalue:?}");
            if contains_mut_ref(*to, self.tcx) {
                self.found_markers
                    .insert(self.auto_markers.side_effect_transmute);
            }
        }
        self.super_rvalue(rvalue, location);
    }
}

fn contains_mut_ref<'tcx>(ty: ty::Ty<'tcx>, tcx: ty::TyCtxt<'tcx>) -> bool {
    use ty::{TypeSuperVisitable, TypeVisitable};
    struct ContainsMutRefVisitor<'tcx> {
        tcx: ty::TyCtxt<'tcx>,
        has_mut_ref: bool,
    }

    impl<'tcx> ty::TypeVisitor<ty::TyCtxt<'tcx>> for ContainsMutRefVisitor<'tcx> {
        fn visit_ty(&mut self, t: ty::Ty<'tcx>) {
            if let ty::TyKind::Adt(adt_def, substs) = t.kind() {
                for field in adt_def.all_fields() {
                    field.ty(self.tcx, substs).visit_with(self);
                }
            }

            if let Some(mir::Mutability::Mut) = t.ref_mutability() {
                trace!("Found mut ref in {t:?}");
                self.has_mut_ref = true;
            }
            t.super_visit_with(self)
        }
    }

    let mut visitor = ContainsMutRefVisitor {
        tcx,
        has_mut_ref: false,
    };
    ty.visit_with(&mut visitor);
    visitor.has_mut_ref
}

impl MarkerCtx<'_> {
    pub fn marker_if_unloadable(&self, def_id: DefId) -> Option<&Identifier> {
        let auto_markers = self.auto_markers();
        let tcx = self.tcx();
        if is_virtual(tcx, def_id) {
            trace!("  Is virtual");
            Some(&auto_markers.side_effect_unknown_virtual)
        } else if tcx.is_foreign_item(def_id) {
            trace!("  Is foreign");
            Some(&auto_markers.side_effect_foreign)
        } else if let Some(idef) = tcx.intrinsic(def_id) {
            if idef.name.as_str() == "transmute" {
                Some(&auto_markers.side_effect_transmute)
            } else if self.is_allowed_intrinsic(idef.name) {
                None
            } else {
                Some(&auto_markers.side_effect_intrinsic)
            }
        } else {
            None
        }
    }
}