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

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