rapx/check/opt/checking/encoding_checking/
string_push.rs1use super::value_is_from_const;
2use crate::analysis::dataflow::*;
3use rustc_middle::{mir::Local, ty::TyCtxt};
4use rustc_span::Span;
5
6use annotate_snippets::Level;
7
8use crate::check::opt::report::OptReport;
9
10crate::def_paths! {
11 string_new: "std::string::String::new",
12 string_push: "std::string::String::push",
13}
14
15use crate::check::opt::OptCheck;
16
17pub struct StringPushCheck {
18 record: Vec<Span>,
19}
20
21fn extract_value_if_is_string_push(graph: &Graph, node: &GraphNode) -> Option<Local> {
22 let def_paths = DEFPATHS.get().unwrap();
23 for op in node.ops.iter() {
24 if let NodeOp::Call(def_id) = op {
25 if *def_id == def_paths.string_push.last_def_id() {
26 let push_value_idx = graph.edges[node.in_edges[1]].src; return Some(push_value_idx);
28 }
29 }
30 }
31 None
32}
33
34fn find_upside_string_new(graph: &Graph, node_idx: Local) -> Option<Local> {
35 let def_paths = DEFPATHS.get().unwrap();
36 graph.find_first_node(
37 node_idx,
38 Direction::Upside,
39 &mut |graph: &Graph, idx: Local| {
40 let node = &graph.nodes[idx];
41 for op in node.ops.iter() {
42 if let NodeOp::Call(def_id) = op {
43 if *def_id == def_paths.string_new.last_def_id() {
44 return true;
45 }
46 }
47 }
48 false
49 },
50 &mut Graph::always_true_edge_validator,
51 )
52}
53
54impl OptCheck for StringPushCheck {
55 fn new() -> Self {
56 Self { record: Vec::new() }
57 }
58
59 fn check(&mut self, graph: &Graph, tcx: &TyCtxt) {
60 DEFPATHS.get_or_init(|| DefPaths::new(tcx));
61 for (node_idx, node) in graph.nodes.iter_enumerated() {
62 if let Some(pushed_value_idx) = extract_value_if_is_string_push(graph, node) {
63 if find_upside_string_new(graph, node_idx).is_some() {
64 if !value_is_from_const(graph, pushed_value_idx) {
65 self.record.clear(); return;
67 }
68 self.record.push(node.span);
69 }
70 }
71 }
72 }
73
74 fn report(&self, graph: &Graph) {
75 if !self.record.is_empty() {
76 report_string_push_bug(graph, &self.record);
77 }
78 }
79
80 fn cnt(&self) -> usize {
81 self.record.len()
82 }
83}
84
85fn report_string_push_bug(graph: &Graph, spans: &Vec<Span>) {
86 let mut report = OptReport::from_graph(graph).title("Unnecessary encoding checkings detected");
87 for span in spans.iter() {
88 report = report.annotate(Level::Error, *span, "Checked here.");
89 }
90 report.footer("Use unsafe APIs instead.").emit();
91}