use super::value_is_from_const;
use crate::{
analysis::dataflow::*,
};
use rustc_middle::{mir::Local, ty::TyCtxt};
use rustc_span::Span;
use annotate_snippets::Level;
use crate::check::opt::report::OptReport;
crate::def_paths! {
string_new: "std::string::String::new",
string_push: "std::string::String::push",
}
use crate::check::opt::OptCheck;
pub struct StringPushCheck {
record: Vec<Span>,
}
fn extract_value_if_is_string_push(graph: &Graph, node: &GraphNode) -> Option<Local> {
let def_paths = DEFPATHS.get().unwrap();
for op in node.ops.iter() {
if let NodeOp::Call(def_id) = op {
if *def_id == def_paths.string_push.last_def_id() {
let push_value_idx = graph.edges[node.in_edges[1]].src; return Some(push_value_idx);
}
}
}
None
}
fn find_upside_string_new(graph: &Graph, node_idx: Local) -> Option<Local> {
let def_paths = DEFPATHS.get().unwrap();
graph.find_first_node(
node_idx,
Direction::Upside,
&mut |graph: &Graph, idx: Local| {
let node = &graph.nodes[idx];
for op in node.ops.iter() {
if let NodeOp::Call(def_id) = op {
if *def_id == def_paths.string_new.last_def_id() {
return true;
}
}
}
false
},
&mut Graph::always_true_edge_validator,
)
}
impl OptCheck for StringPushCheck {
fn new() -> Self {
Self { record: Vec::new() }
}
fn check(&mut self, graph: &Graph, tcx: &TyCtxt) {
let _ = &DEFPATHS.get_or_init(|| DefPaths::new(tcx));
for (node_idx, node) in graph.nodes.iter_enumerated() {
if let Some(pushed_value_idx) = extract_value_if_is_string_push(graph, node) {
if find_upside_string_new(graph, node_idx).is_some() {
if !value_is_from_const(graph, pushed_value_idx) {
self.record.clear(); return;
}
self.record.push(node.span);
}
}
}
}
fn report(&self, graph: &Graph) {
if !self.record.is_empty() {
report_string_push_bug(graph, &self.record);
}
}
fn cnt(&self) -> usize {
self.record.len()
}
}
fn report_string_push_bug(graph: &Graph, spans: &Vec<Span>) {
let mut report = OptReport::from_graph(graph)
.title("Unnecessary encoding checkings detected");
for span in spans.iter() {
report = report.annotate(Level::Error, *span, "Checked here.");
}
report.footer("Use unsafe APIs instead.").emit();
}