pina_lints 0.12.0

Pina's official security lints: a self-contained, Dylint-compatible lint catalog with a built-in rustc driver
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Shared analysis helpers used by several Pina lints.
//!
//! The helpers collect lexical facts (calls, assignments, aliases, paths)
//! from a function body so path-sensitive lints can reason about call order
//! without duplicating traversal code.

extern crate rustc_ast;
extern crate rustc_hir;
extern crate rustc_lint;
extern crate rustc_span;

use std::collections::HashMap;

use rustc_ast::LitKind;
use rustc_hir::Body;
use rustc_hir::Expr;
use rustc_hir::ExprKind;
use rustc_hir::HirId;
use rustc_lint::LateContext;
use rustc_span::Span;

#[derive(Debug, Clone)]
pub struct CallInfo {
	pub span: Span,
	pub method: String,
	pub receiver: Option<String>,
	pub receiver_span: Option<Span>,
	pub path: Option<String>,
	pub def_path: Option<String>,
	pub def_crate: Option<String>,
	pub is_type_relative: bool,
	pub args: Vec<Option<String>>,
	pub arg_def_paths: Vec<Option<String>>,
	pub arg_def_crates: Vec<Option<String>>,
	pub arg_bindings: Vec<Option<HirId>>,
	pub result_binding: Option<String>,
}

#[derive(Debug, Clone)]
pub struct AliasInfo {
	pub identity: String,
	pub binding: Option<HirId>,
}

#[derive(Debug, Clone)]
pub struct AssignmentInfo {
	pub span: Span,
	pub identity: String,
}

#[derive(Debug, Default)]
pub struct FunctionFacts {
	pub calls: Vec<CallInfo>,
	pub has_match: bool,
	pub has_byte_string: bool,
	pub paths: Vec<String>,
	pub assignments: Vec<AssignmentInfo>,
	pub aliases: HashMap<HirId, AliasInfo>,
}

pub fn collect_function_facts(cx: &LateContext<'_>, body: &Body<'_>) -> FunctionFacts {
	let mut facts = FunctionFacts::default();
	collect_from_expr(cx, body.value, &mut facts, None);
	facts
}

fn definition_identity(cx: &LateContext<'_>, def_id: rustc_hir::def_id::DefId) -> (String, String) {
	(
		cx.tcx.def_path_str(def_id),
		cx.tcx.crate_name(def_id.krate).as_str().to_string(),
	)
}

fn expression_definition(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<(String, String)> {
	match &expr.kind {
		ExprKind::Path(path) => {
			match cx.qpath_res(path, expr.hir_id) {
				rustc_hir::def::Res::Def(_, def_id) => Some(definition_identity(cx, def_id)),
				_ => None,
			}
		}
		ExprKind::Unary(_, inner)
		| ExprKind::Cast(inner, _)
		| ExprKind::DropTemps(inner)
		| ExprKind::AddrOf(_, _, inner) => expression_definition(cx, inner),
		_ => None,
	}
}

pub fn receiver_name(expr: &Expr<'_>) -> Option<String> {
	expression_identity(expr)
}

pub fn expression_identity(expr: &Expr<'_>) -> Option<String> {
	match &expr.kind {
		ExprKind::Field(base, ident) => {
			expression_identity(base).map(|base| format!("{base}.{}", ident.name.as_str()))
		}
		ExprKind::Path(rustc_hir::QPath::Resolved(_, path)) => {
			Some(
				path.segments
					.iter()
					.map(|seg| seg.ident.name.as_str())
					.collect::<Vec<_>>()
					.join("::"),
			)
		}
		ExprKind::MethodCall(_, receiver, ..) => expression_identity(receiver),
		ExprKind::Match(scrutinee, ..) => expression_identity(scrutinee),
		ExprKind::Unary(_, expr)
		| ExprKind::Cast(expr, _)
		| ExprKind::DropTemps(expr)
		| ExprKind::AddrOf(_, _, expr)
		| ExprKind::Index(expr, ..) => expression_identity(expr),
		ExprKind::Block(block, _) => block.expr.and_then(expression_identity),
		ExprKind::Call(callee, args) => {
			args.first()
				.and_then(expression_identity)
				.or_else(|| expression_identity(callee))
		}
		_ => None,
	}
}

pub fn expression_local_binding(expr: &Expr<'_>) -> Option<HirId> {
	match &expr.kind {
		ExprKind::Path(rustc_hir::QPath::Resolved(_, path)) => {
			match path.res {
				rustc_hir::def::Res::Local(binding) => Some(binding),
				_ => None,
			}
		}
		ExprKind::MethodCall(_, receiver, ..) | ExprKind::Match(receiver, ..) => {
			expression_local_binding(receiver)
		}
		ExprKind::Unary(_, inner)
		| ExprKind::Cast(inner, _)
		| ExprKind::DropTemps(inner)
		| ExprKind::AddrOf(_, _, inner)
		| ExprKind::Index(inner, ..) => expression_local_binding(inner),
		ExprKind::Block(block, _) => block.expr.and_then(expression_local_binding),
		ExprKind::Call(callee, args) => {
			args.first()
				.and_then(|argument| expression_local_binding(argument))
				.or_else(|| expression_local_binding(callee))
		}
		_ => None,
	}
}

pub fn has_prior_method_with_receiver_match(
	calls: &[CallInfo],
	index: usize,
	methods: &[&str],
	receiver: &Option<String>,
) -> bool {
	calls[..index]
		.iter()
		.any(|call| methods.contains(&call.method.as_str()) && &call.receiver == receiver)
}

pub const CONTROL_FLOW_LIMITATION_HELP: &str = "heuristic limitation: this lint tracks lexical \
                                                call order and merges `if`/`match` branches, so \
                                                review branch-sensitive code manually";

pub fn should_skip_def_path(def_path: &str) -> bool {
	def_path.contains("tests")
		|| def_path.contains("benchmarks")
		|| def_path.contains("fuzz")
		|| def_path.contains("snapshots")
		|| def_path.starts_with("pina::")
		|| def_path.contains("pina_macros::")
}

pub fn def_path_matches(def_path: &str, needles: &[&str]) -> bool {
	needles.iter().any(|needle| def_path.contains(needle))
}

fn collect_from_block(
	cx: &LateContext<'_>,
	block: &rustc_hir::Block<'_>,
	facts: &mut FunctionFacts,
	result_binding: Option<&str>,
) {
	for stmt in block.stmts {
		match &stmt.kind {
			rustc_hir::StmtKind::Let(local) => {
				if let Some(init) = local.init {
					let binding = match local.pat.kind {
						rustc_hir::PatKind::Binding(_, binding, ident, _) => {
							Some((binding, ident.name.as_str().to_string()))
						}
						_ => None,
					};
					if let (Some((binding, _)), Some(identity)) =
						(binding.as_ref(), expression_identity(init))
					{
						facts.aliases.insert(
							*binding,
							AliasInfo {
								identity,
								binding: expression_local_binding(init),
							},
						);
					}
					collect_from_expr(
						cx,
						init,
						facts,
						binding.as_ref().map(|(_, name)| name.as_str()),
					);
				}
			}
			rustc_hir::StmtKind::Expr(expr) | rustc_hir::StmtKind::Semi(expr) => {
				collect_from_expr(cx, expr, facts, None);
			}
			_ => {}
		}
	}
	if let Some(expr) = block.expr {
		collect_from_expr(cx, expr, facts, result_binding);
	}
}

fn collect_from_expr(
	cx: &LateContext<'_>,
	expr: &Expr<'_>,
	facts: &mut FunctionFacts,
	result_binding: Option<&str>,
) {
	collect_from_expr_inner(cx, expr, facts, result_binding, false);
}

fn collect_from_expr_inner(
	cx: &LateContext<'_>,
	expr: &Expr<'_>,
	facts: &mut FunctionFacts,
	result_binding: Option<&str>,
	forward_call_argument_binding: bool,
) {
	match &expr.kind {
		ExprKind::MethodCall(path_segment, receiver, args, _) => {
			collect_from_expr(cx, receiver, facts, result_binding);
			for arg in *args {
				collect_from_expr(cx, arg, facts, None);
			}
			let definition = cx
				.typeck_results()
				.type_dependent_def_id(expr.hir_id)
				.map(|def_id| definition_identity(cx, def_id));
			facts.calls.push(CallInfo {
				span: expr.span,
				method: path_segment.ident.name.as_str().to_string(),
				receiver: expression_identity(receiver),
				receiver_span: Some(receiver.span),
				path: None,
				def_path: definition.as_ref().map(|(path, _)| path.clone()),
				def_crate: definition.map(|(_, crate_name)| crate_name),
				is_type_relative: false,
				args: args.iter().map(expression_identity).collect(),
				arg_def_paths: args
					.iter()
					.map(|argument| expression_definition(cx, argument).map(|(path, _)| path))
					.collect(),
				arg_def_crates: args
					.iter()
					.map(|argument| {
						expression_definition(cx, argument).map(|(_, crate_name)| crate_name)
					})
					.collect(),
				arg_bindings: args.iter().map(expression_local_binding).collect(),
				result_binding: result_binding.map(str::to_string),
			});
		}
		ExprKind::Call(callee, args) => {
			collect_from_expr(cx, callee, facts, None);
			for arg in *args {
				let binding = forward_call_argument_binding
					.then_some(result_binding)
					.flatten();
				collect_from_expr(cx, arg, facts, binding);
			}
			if let rustc_hir::ExprKind::Path(path) = &callee.kind {
				let (path_name, is_type_relative) = match path {
					rustc_hir::QPath::Resolved(_, path) => {
						let path = path
							.segments
							.iter()
							.map(|segment| segment.ident.name.as_str())
							.collect::<Vec<_>>()
							.join("::");
						(path, false)
					}
					rustc_hir::QPath::TypeRelative(_, segment) => {
						(segment.ident.name.as_str().to_string(), true)
					}
				};
				let method = path_name
					.rsplit("::")
					.next()
					.unwrap_or(&path_name)
					.to_string();
				let definition = match cx.qpath_res(path, callee.hir_id) {
					rustc_hir::def::Res::Def(_, def_id) => Some(definition_identity(cx, def_id)),
					_ => None,
				};
				facts.calls.push(CallInfo {
					span: expr.span,
					method,
					receiver: None,
					receiver_span: None,
					path: Some(path_name),
					def_path: definition.as_ref().map(|(path, _)| path.clone()),
					def_crate: definition.map(|(_, crate_name)| crate_name),
					is_type_relative,
					args: args.iter().map(expression_identity).collect(),
					arg_def_paths: args
						.iter()
						.map(|argument| expression_definition(cx, argument).map(|(path, _)| path))
						.collect(),
					arg_def_crates: args
						.iter()
						.map(|argument| {
							expression_definition(cx, argument).map(|(_, crate_name)| crate_name)
						})
						.collect(),
					arg_bindings: args.iter().map(expression_local_binding).collect(),
					result_binding: result_binding.map(str::to_string),
				});
			}
		}
		ExprKind::Block(block, _) | ExprKind::Loop(block, ..) => {
			collect_from_block(cx, block, facts, result_binding);
		}
		ExprKind::Match(scrutinee, arms, source) => {
			facts.has_match = true;
			collect_from_expr_inner(
				cx,
				scrutinee,
				facts,
				result_binding,
				matches!(source, rustc_hir::MatchSource::TryDesugar(_)),
			);
			for arm in *arms {
				collect_from_expr(cx, arm.body, facts, result_binding);
			}
		}
		ExprKind::If(cond, then, else_opt) => {
			collect_from_expr(cx, cond, facts, None);
			collect_from_expr(cx, then, facts, result_binding);
			if let Some(el) = else_opt {
				collect_from_expr(cx, el, facts, result_binding);
			}
		}
		ExprKind::Unary(_, expr)
		| ExprKind::Use(expr, _)
		| ExprKind::Cast(expr, _)
		| ExprKind::Type(expr, _)
		| ExprKind::DropTemps(expr)
		| ExprKind::AddrOf(_, _, expr)
		| ExprKind::Field(expr, _)
		| ExprKind::Repeat(expr, _)
		| ExprKind::Yield(expr, _)
		| ExprKind::Become(expr)
		| ExprKind::UnsafeBinderCast(_, expr, _) => {
			collect_from_expr(cx, expr, facts, result_binding);
		}
		ExprKind::Binary(_, lhs, rhs) => {
			collect_from_expr(cx, lhs, facts, result_binding);
			collect_from_expr(cx, rhs, facts, result_binding);
		}
		ExprKind::Assign(lhs, rhs, _) | ExprKind::AssignOp(_, lhs, rhs) => {
			if let Some(identity) = expression_identity(lhs) {
				facts.assignments.push(AssignmentInfo {
					span: expr.span,
					identity,
				});
			}
			collect_from_expr(cx, lhs, facts, None);
			collect_from_expr(cx, rhs, facts, None);
		}
		ExprKind::Index(base, index, _) => {
			collect_from_expr(cx, base, facts, result_binding);
			collect_from_expr(cx, index, facts, None);
		}
		ExprKind::Let(let_expr) => {
			collect_from_expr(cx, let_expr.init, facts, result_binding);
		}
		ExprKind::Tup(exprs) | ExprKind::Array(exprs) => {
			for e in *exprs {
				collect_from_expr(cx, e, facts, result_binding);
			}
		}
		ExprKind::Struct(_, fields, tail) => {
			for field in *fields {
				collect_from_expr(cx, field.expr, facts, result_binding);
			}
			if let rustc_hir::StructTailExpr::Base(base) = tail {
				collect_from_expr(cx, base, facts, result_binding);
			}
		}
		ExprKind::Ret(Some(inner)) | ExprKind::Break(_, Some(inner)) => {
			collect_from_expr(cx, inner, facts, result_binding);
		}
		ExprKind::Lit(lit) => {
			if matches!(lit.node, LitKind::ByteStr(..)) {
				facts.has_byte_string = true;
			}
		}
		ExprKind::Path(rustc_hir::QPath::Resolved(_, path)) => {
			facts.paths.push(
				path.segments
					.iter()
					.map(|segment| segment.ident.name.as_str())
					.collect::<Vec<_>>()
					.join("::"),
			);
		}
		ExprKind::Path(rustc_hir::QPath::TypeRelative(_, segment)) => {
			facts.paths.push(segment.ident.name.as_str().to_string());
		}
		_ => {}
	}
}