rapx/check/opt/data_collection/reallocation/
unreserved_hash.rs

1use std::collections::HashSet;
2
3use crate::{
4    analysis::dataflow::*,
5    check::opt::OptCheck,
6    helpers::def_path::DefPath,
7    utils::log::{relative_pos_range, span_to_filename, span_to_line_number, span_to_source_code},
8};
9use once_cell::sync::OnceCell;
10use rustc_middle::{mir::Local, ty::TyCtxt};
11
12use annotate_snippets::{Level, Renderer, Snippet};
13use rustc_span::Span;
14
15static DEFPATHS: OnceCell<DefPaths> = OnceCell::new();
16
17struct DefPaths {
18    hashset_new: DefPath,
19    hashset_insert: DefPath,
20    hashmap_new: DefPath,
21    hashmap_insert: DefPath,
22    entry: DefPath,
23}
24
25impl DefPaths {
26    pub fn new(tcx: &TyCtxt<'_>) -> Self {
27        Self {
28            hashset_insert: DefPath::new("std::collections::HashSet::insert", tcx),
29            hashmap_insert: DefPath::new("std::collections::HashMap::insert", tcx),
30            hashset_new: DefPath::new("std::collections::HashSet::new", tcx),
31            hashmap_new: DefPath::new("std::collections::HashMap::new", tcx),
32            entry: DefPath::new("std::collections::HashMap::entry", tcx),
33        }
34    }
35}
36
37pub struct UnreservedHashCheck {
38    record: Vec<(Span, Span)>,
39}
40
41fn is_hash_new_node(node: &GraphNode) -> bool {
42    for op in node.ops.iter() {
43        if let NodeOp::Call(def_id) = op {
44            let def_paths = &DEFPATHS.get().unwrap();
45            if *def_id == def_paths.hashmap_new.last_def_id()
46                || *def_id == def_paths.hashset_new.last_def_id()
47            {
48                return true;
49            }
50        }
51    }
52    false
53}
54
55fn find_downside_hash_insert_node(graph: &Graph, node_idx: Local) -> Option<Local> {
56    let mut hash_insert_node_idx = None;
57    let def_paths = &DEFPATHS.get().unwrap();
58    let mut node_operator = |graph: &Graph, idx: Local| -> DFSStatus {
59        let node = &graph.nodes[idx];
60        for op in node.ops.iter() {
61            if let NodeOp::Call(def_id) = op {
62                if *def_id == def_paths.hashmap_insert.last_def_id()
63                    || *def_id == def_paths.hashset_insert.last_def_id()
64                    || *def_id == def_paths.entry.last_def_id()
65                {
66                    hash_insert_node_idx = Some(idx);
67                    return DFSStatus::Stop;
68                }
69            }
70        }
71        DFSStatus::Continue
72    };
73    let mut seen = HashSet::new();
74    graph.dfs(
75        node_idx,
76        Direction::Downside,
77        &mut node_operator,
78        &mut Graph::equivalent_edge_validator,
79        false,
80        &mut seen,
81    );
82    hash_insert_node_idx
83}
84
85impl OptCheck for UnreservedHashCheck {
86    fn new() -> Self {
87        Self { record: Vec::new() }
88    }
89
90    fn check(&mut self, graph: &Graph, tcx: &TyCtxt) {
91        let _ = &DEFPATHS.get_or_init(|| DefPaths::new(tcx));
92        for (node_idx, node) in graph.nodes.iter_enumerated() {
93            if is_hash_new_node(node) {
94                if let Some(insert_idx) = find_downside_hash_insert_node(graph, node_idx) {
95                    let insert_node = &graph.nodes[insert_idx];
96                    self.record.push((node.span, insert_node.span));
97                }
98            }
99        }
100    }
101
102    fn report(&self, graph: &Graph) {
103        for (hash_span, insert_span) in self.record.iter() {
104            report_unreserved_hash_bug(graph, *hash_span, *insert_span);
105        }
106    }
107
108    fn cnt(&self) -> usize {
109        self.record.len()
110    }
111}
112
113fn report_unreserved_hash_bug(graph: &Graph, hash_span: Span, insert_span: Span) {
114    let code_source = span_to_source_code(graph.span);
115    let filename = span_to_filename(hash_span);
116    let snippet: Snippet<'_> = Snippet::source(&code_source)
117        .line_start(span_to_line_number(graph.span))
118        .origin(&filename)
119        .fold(true)
120        .annotation(
121            Level::Error
122                .span(relative_pos_range(graph.span, hash_span))
123                .label("Space unreserved."),
124        )
125        .annotation(
126            Level::Info
127                .span(relative_pos_range(graph.span, insert_span))
128                .label("Insertion happens here."),
129        );
130    let message = Level::Warning
131        .title("Improper data collection detected")
132        .snippet(snippet)
133        .footer(Level::Help.title("Reserve enough space."));
134    let renderer = Renderer::styled();
135    rap_warn!("{}", renderer.render(message));
136}