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
/// Analysis context — carries type state through statement/expression analysis.
use std::collections::HashSet;
use std::sync::Arc;
use indexmap::IndexMap;
use mir_types::Union;
// ---------------------------------------------------------------------------
// Context
// ---------------------------------------------------------------------------
#[derive(Debug, Clone)]
pub struct Context {
/// Types of variables at this point in execution.
pub vars: IndexMap<String, Union>,
/// Variables that are definitely assigned at this point.
pub assigned_vars: HashSet<String>,
/// Variables that *might* be assigned (e.g. only in one if branch).
pub possibly_assigned_vars: HashSet<String>,
/// The class in whose body we are analysing (`self`).
pub self_fqcn: Option<Arc<str>>,
/// The parent class (`parent`).
pub parent_fqcn: Option<Arc<str>>,
/// Late-static-binding class (`static`).
pub static_fqcn: Option<Arc<str>>,
/// Declared return type for the current function/method.
pub fn_return_type: Option<Union>,
/// Whether we are currently inside a loop.
pub inside_loop: bool,
/// Whether we are currently inside a finally block.
pub inside_finally: bool,
/// Whether we are inside a constructor.
pub inside_constructor: bool,
/// Whether `strict_types=1` is declared for this file.
pub strict_types: bool,
/// Variables that carry tainted (user-controlled) values at this point.
/// Used by taint analysis (M19).
pub tainted_vars: HashSet<String>,
/// Variables that have been read at least once in this scope.
/// Used by UnusedParam detection (M18).
pub read_vars: HashSet<String>,
/// Names of function/method parameters in this scope (stripped of `$`).
/// Used to exclude parameters from UnusedVariable detection.
pub param_names: HashSet<String>,
/// Whether every execution path through this context has diverged
/// (returned, thrown, or exited). Used to detect "all catch branches
/// return" so that variables assigned only in the try body are
/// considered definitely assigned after the try/catch.
pub diverges: bool,
}
impl Context {
pub fn new() -> Self {
let mut ctx = Self {
vars: IndexMap::new(),
assigned_vars: HashSet::new(),
possibly_assigned_vars: HashSet::new(),
self_fqcn: None,
parent_fqcn: None,
static_fqcn: None,
fn_return_type: None,
inside_loop: false,
inside_finally: false,
inside_constructor: false,
strict_types: false,
tainted_vars: HashSet::new(),
read_vars: HashSet::new(),
param_names: HashSet::new(),
diverges: false,
};
// PHP superglobals — always in scope in any context
for sg in &[
"_SERVER", "_GET", "_POST", "_REQUEST", "_SESSION", "_COOKIE", "_FILES", "_ENV",
"GLOBALS",
] {
ctx.vars.insert(sg.to_string(), mir_types::Union::mixed());
ctx.assigned_vars.insert(sg.to_string());
}
ctx
}
/// Create a context seeded with the given parameters.
pub fn for_function(
params: &[mir_codebase::FnParam],
return_type: Option<Union>,
self_fqcn: Option<Arc<str>>,
parent_fqcn: Option<Arc<str>>,
static_fqcn: Option<Arc<str>>,
strict_types: bool,
) -> Self {
Self::for_method(
params,
return_type,
self_fqcn,
parent_fqcn,
static_fqcn,
strict_types,
false,
)
}
/// Like `for_function` but also sets `inside_constructor`.
pub fn for_method(
params: &[mir_codebase::FnParam],
return_type: Option<Union>,
self_fqcn: Option<Arc<str>>,
parent_fqcn: Option<Arc<str>>,
static_fqcn: Option<Arc<str>>,
strict_types: bool,
inside_constructor: bool,
) -> Self {
let mut ctx = Self::new();
ctx.fn_return_type = return_type;
ctx.self_fqcn = self_fqcn;
ctx.parent_fqcn = parent_fqcn;
ctx.static_fqcn = static_fqcn;
ctx.strict_types = strict_types;
ctx.inside_constructor = inside_constructor;
for p in params {
let elem_ty = p.ty.clone().unwrap_or_else(Union::mixed);
// Variadic params like `Type ...$name` are accessed as `list<Type>` in the body.
// If the docblock already provides a list/array collection type, don't double-wrap.
let ty = if p.is_variadic {
let already_collection = elem_ty.types.iter().any(|a| {
matches!(
a,
mir_types::Atomic::TList { .. }
| mir_types::Atomic::TNonEmptyList { .. }
| mir_types::Atomic::TArray { .. }
| mir_types::Atomic::TNonEmptyArray { .. }
)
});
if already_collection {
elem_ty
} else {
mir_types::Union::single(mir_types::Atomic::TList {
value: Box::new(elem_ty),
})
}
} else {
elem_ty
};
let name = p.name.as_ref().trim_start_matches('$').to_string();
ctx.vars.insert(name.clone(), ty);
ctx.assigned_vars.insert(name.clone());
ctx.param_names.insert(name);
}
ctx
}
/// Get the type of a variable. Returns `mixed` if not found.
pub fn get_var(&self, name: &str) -> Union {
let name = name.trim_start_matches('$');
self.vars.get(name).cloned().unwrap_or_else(Union::mixed)
}
/// Set the type of a variable and mark it as assigned.
pub fn set_var(&mut self, name: impl Into<String>, ty: Union) {
let name: String = name.into();
let name = name.trim_start_matches('$').to_string();
self.vars.insert(name.clone(), ty);
self.assigned_vars.insert(name);
}
/// Check if a variable is definitely in scope.
pub fn var_is_defined(&self, name: &str) -> bool {
let name = name.trim_start_matches('$');
self.assigned_vars.contains(name)
}
/// Check if a variable might be defined (but not certainly).
pub fn var_possibly_defined(&self, name: &str) -> bool {
let name = name.trim_start_matches('$');
self.assigned_vars.contains(name) || self.possibly_assigned_vars.contains(name)
}
/// Mark a variable as carrying tainted (user-controlled) data.
pub fn taint_var(&mut self, name: &str) {
let name = name.trim_start_matches('$').to_string();
self.tainted_vars.insert(name);
}
/// Returns true if the variable is known to carry tainted data.
pub fn is_tainted(&self, name: &str) -> bool {
let name = name.trim_start_matches('$');
self.tainted_vars.contains(name)
}
/// Remove a variable from the context (after `unset`).
pub fn unset_var(&mut self, name: &str) {
let name = name.trim_start_matches('$');
self.vars.shift_remove(name);
self.assigned_vars.remove(name);
self.possibly_assigned_vars.remove(name);
}
/// Fork this context for a branch (e.g. the `if` branch).
pub fn fork(&self) -> Context {
self.clone()
}
/// Merge two branch contexts at a join point (e.g. end of if/else).
///
/// - vars present in both: merged union of types
/// - vars present in only one branch: marked `possibly_undefined`
/// - pre-existing vars from before the branch: preserved
pub fn merge_branches(pre: &Context, if_ctx: Context, else_ctx: Option<Context>) -> Context {
let else_ctx = else_ctx.unwrap_or_else(|| pre.clone());
// If the then-branch always diverges, the code after the if runs only
// in the else-branch — use that as the result directly.
if if_ctx.diverges && !else_ctx.diverges {
let mut result = else_ctx;
result.diverges = false;
return result;
}
// If the else-branch always diverges, code after the if runs only
// in the then-branch.
if else_ctx.diverges && !if_ctx.diverges {
let mut result = if_ctx;
result.diverges = false;
return result;
}
// If both diverge, the code after the if is unreachable.
if if_ctx.diverges && else_ctx.diverges {
let mut result = pre.clone();
result.diverges = true;
return result;
}
let mut result = pre.clone();
// Collect all variable names from both branch contexts
let all_names: HashSet<&String> = if_ctx.vars.keys().chain(else_ctx.vars.keys()).collect();
for name in all_names {
let in_if = if_ctx.assigned_vars.contains(name);
let in_else = else_ctx.assigned_vars.contains(name);
let in_pre = pre.assigned_vars.contains(name);
let ty_if = if_ctx.vars.get(name);
let ty_else = else_ctx.vars.get(name);
match (ty_if, ty_else) {
(Some(a), Some(b)) => {
let merged = Union::merge(a, b);
result.vars.insert(name.clone(), merged);
if in_if && in_else {
result.assigned_vars.insert(name.clone());
} else {
result.possibly_assigned_vars.insert(name.clone());
}
}
(Some(a), None) => {
if in_pre {
// var existed before: merge with pre type
let pre_ty = pre.vars.get(name).cloned().unwrap_or_else(Union::mixed);
let merged = Union::merge(a, &pre_ty);
result.vars.insert(name.clone(), merged);
result.assigned_vars.insert(name.clone());
} else {
// only assigned in if branch
let ty = a.clone().possibly_undefined();
result.vars.insert(name.clone(), ty);
result.possibly_assigned_vars.insert(name.clone());
}
}
(None, Some(b)) => {
if in_pre {
let pre_ty = pre.vars.get(name).cloned().unwrap_or_else(Union::mixed);
let merged = Union::merge(&pre_ty, b);
result.vars.insert(name.clone(), merged);
result.assigned_vars.insert(name.clone());
} else {
let ty = b.clone().possibly_undefined();
result.vars.insert(name.clone(), ty);
result.possibly_assigned_vars.insert(name.clone());
}
}
(None, None) => {}
}
}
// Taint: conservative union — if either branch taints a var, it stays tainted
for name in if_ctx
.tainted_vars
.iter()
.chain(else_ctx.tainted_vars.iter())
{
result.tainted_vars.insert(name.clone());
}
// Read vars: union — if either branch reads a var, it counts as read
for name in if_ctx.read_vars.iter().chain(else_ctx.read_vars.iter()) {
result.read_vars.insert(name.clone());
}
// After merging branches, the merged context does not diverge
// (at least one path through the merge reaches the next statement).
result.diverges = false;
result
}
}
impl Default for Context {
fn default() -> Self {
Self::new()
}
}