rapx/check/opt/checking/encoding_checking/
array_encoding.rs1use std::collections::HashSet;
2
3use once_cell::sync::OnceCell;
4
5use rustc_middle::{mir::Local, ty::TyCtxt};
6use rustc_span::Span;
7
8use super::{report_encoding_bug, value_is_from_const};
9use crate::analysis::dataflow::*;
10use crate::check::opt::OptCheck;
11use crate::helpers::def_path::DefPath;
12
13static DEFPATHS: OnceCell<DefPaths> = OnceCell::new();
14
15struct DefPaths {
16 str_from_utf8: DefPath,
17}
18
19impl DefPaths {
20 pub fn new(tcx: &TyCtxt<'_>) -> Self {
21 Self {
22 str_from_utf8: DefPath::new("std::str::from_utf8", &tcx),
23 }
24 }
25}
26
27pub struct ArrayEncodingCheck {
28 record: Vec<Span>,
29}
30
31fn extract_ancestor_set_if_is_str_from(
32 graph: &Graph,
33 node_idx: Local,
34 node: &GraphNode,
35) -> Option<HashSet<Local>> {
36 let def_paths = DEFPATHS.get().unwrap();
37 for op in node.ops.iter() {
38 if let NodeOp::Call(def_id) = op {
39 if *def_id == def_paths.str_from_utf8.last_def_id() {
40 return Some(graph.collect_ancestor_locals(node_idx, false));
41 }
42 }
43 }
44 None
45}
46
47fn is_valid_index_edge(graph: &Graph, edge: &GraphEdge) -> bool {
48 if let EdgeOp::Index = edge.op {
49 let dst_node = &graph.nodes[edge.dst];
51 if dst_node.in_edges.len() > 2 {
52 let rvalue_edge_idx = dst_node.in_edges[2];
54 let rvalue_idx = graph.edges[rvalue_edge_idx].src;
55 if value_is_from_const(graph, rvalue_idx) {
56 return true;
57 }
58 }
59 }
60 false
61}
62
63impl OptCheck for ArrayEncodingCheck {
64 fn new() -> Self {
65 Self { record: Vec::new() }
66 }
67
68 fn check(&mut self, graph: &Graph, tcx: &TyCtxt) {
69 let _ = &DEFPATHS.get_or_init(|| DefPaths::new(tcx));
70 let common_ancestor = graph
71 .edges
72 .iter()
73 .filter_map(|edge| {
74 if is_valid_index_edge(graph, edge) {
76 Some(graph.collect_ancestor_locals(edge.src, true))
77 } else {
78 None
79 }
80 })
81 .reduce(|set1, set2| set1.into_iter().filter(|k| set2.contains(k)).collect());
82
83 if let Some(common_ancestor) = common_ancestor {
84 for (node_idx, node) in graph.nodes.iter_enumerated() {
85 if let Some(str_from_ancestor_set) =
86 extract_ancestor_set_if_is_str_from(graph, node_idx, node)
87 {
88 if !common_ancestor
89 .intersection(&str_from_ancestor_set)
90 .next()
91 .is_some()
92 {
93 self.record.clear();
94 return;
95 }
96 self.record.push(node.span);
97 }
98 }
99 }
100 }
101
102 fn report(&self, graph: &Graph) {
103 for span in self.record.iter() {
104 report_encoding_bug(graph, *span);
105 }
106 }
107
108 fn cnt(&self) -> usize {
109 self.record.len()
110 }
111}