-
Notifications
You must be signed in to change notification settings - Fork 369
Expand file tree
/
Copy pathSuspiciousParamOrderPlugin.php
More file actions
433 lines (412 loc) · 16.4 KB
/
SuspiciousParamOrderPlugin.php
File metadata and controls
433 lines (412 loc) · 16.4 KB
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
425
426
427
428
429
430
431
432
433
<?php
declare(strict_types=1);
use ast\Node;
use Phan\AST\ContextNode;
use Phan\AST\UnionTypeVisitor;
use Phan\Exception\CodeBaseException;
use Phan\Language\Element\FunctionInterface;
use Phan\PluginV3;
use Phan\PluginV3\PluginAwarePostAnalysisVisitor;
use Phan\PluginV3\PostAnalyzeNodeCapability;
/**
* A plugin that checks if calls to a function or method pass in arguments in a suspicious order.
* E.g. calling `function example($offset, $count)` as `example($count, $offset)`
*/
class SuspiciousParamOrderPlugin extends PluginV3 implements PostAnalyzeNodeCapability
{
/**
* @return string - name of PluginAwarePostAnalysisVisitor subclass
*/
public static function getPostAnalyzeNodeVisitorClassName(): string
{
return SuspiciousParamOrderVisitor::class;
}
}
/**
* Checks for invocations of functions/methods where the return value should be used.
* Also, gathers statistics on how often those functions/methods are used.
*/
class SuspiciousParamOrderVisitor extends PluginAwarePostAnalysisVisitor
{
// phpcs:disable Generic.NamingConventions.UpperCaseConstantName.ClassConstantNotUpperCase
// this is deliberate for issue names
private const SuspiciousParamOrderInternal = 'PhanPluginSuspiciousParamOrderInternal';
private const SuspiciousParamOrder = 'PhanPluginSuspiciousParamOrder';
private const SuspiciousParamPosition = 'PhanPluginSuspiciousParamPosition';
private const SuspiciousParamPositionInternal = 'PhanPluginSuspiciousParamPositionInternal';
// phpcs:enable Generic.NamingConventions.UpperCaseConstantName.ClassConstantNotUpperCase
/**
* @param Node $node a node of type AST_CALL
* @override
*/
public function visitCall(Node $node): void
{
$args = $node->children['args']->children;
if (count($args) < 1) {
// Can't have a suspicious param order/position if there are no params
// (or for AST_CALLABLE_CONVERT)
return;
}
$expression = $node->children['expr'];
try {
$function_list_generator = (new ContextNode(
$this->code_base,
$this->context,
$expression
))->getFunctionFromNode();
foreach ($function_list_generator as $function) {
// @phan-suppress-next-line PhanPartialTypeMismatchArgument
$this->checkCall($function, $args, $node);
}
} catch (CodeBaseException) {
}
}
/**
* @param Node|string|int|float|null $arg_node
*/
private static function extractName(Node|float|int|null|string $arg_node): ?string
{
if (!$arg_node instanceof Node) {
return null;
}
switch ($arg_node->kind) {
case ast\AST_VAR:
$name = $arg_node->children['name'];
break;
/*
case ast\AST_CONST:
$name = $arg_node->children['name']->children['name'];
break;
*/
case ast\AST_PROP:
case ast\AST_STATIC_PROP:
$name = $arg_node->children['prop'];
break;
case ast\AST_METHOD_CALL:
case ast\AST_STATIC_CALL:
$name = $arg_node->children['method'];
break;
case ast\AST_CALL:
$name = $arg_node->children['expr'];
break;
default:
return null;
}
return is_string($name) ? $name : null;
}
/**
* Returns a distance in the range 0..1, inclusive.
*
* A distance of 0 means they are similar (e.g. foo and getFoo()),
* and 1 means there are no letters in common (bar and foo)
*/
private static function computeDistance(string $a, string $b): float
{
$la = strlen($a);
$lb = strlen($b);
return (levenshtein($a, $b) - abs($la - $lb)) / max(1, min($la, $lb));
}
/**
* @param list<Node|string|int|float> $args
*/
private function checkCall(FunctionInterface $function, array $args, Node $node): void
{
$arg_names = [];
foreach ($args as $i => $arg_node) {
$name = self::extractName($arg_node);
if (!is_string($name)) {
continue;
}
$arg_names[$i] = strtolower($name);
}
if (count($arg_names) < 2) {
if (count($arg_names) === 1) {
$this->checkMovedArg($function, $args, $node, $arg_names);
}
return;
}
$parameters = $function->getParameterList();
$parameter_names = [];
foreach ($arg_names as $i => $_) {
if (!isset($parameters[$i])) {
unset($arg_names[$i]);
continue;
}
$parameter_names[$i] = strtolower($parameters[$i]->getName());
}
if (count($arg_names) < 2) {
// $arg_names and $parameter_names have the same keys
$this->checkMovedArg($function, $args, $node, $arg_names);
return;
}
$best_destination_map = [];
foreach ($arg_names as $i => $name) {
// To even be considered, the distance metric must be less than 60% (100% would have nothing in common)
$best_distance = min(
0.6,
self::computeDistance($name, $parameter_names[$i])
);
$best_destination = null;
// echo "Distances for $name to $parameter_names[$i] is $best_distance\n";
foreach ($parameter_names as $j => $parameter_name_j) {
if ($j === $i) {
continue;
}
$d_swap_j = self::computeDistance($name, $parameter_name_j);
// echo "Distances for $name to $parameter_name_j is $d_swap_j\n";
if ($d_swap_j < $best_distance) {
$best_destination = $j;
$best_distance = $d_swap_j;
}
}
if ($best_destination !== null) {
$best_destination_map[$i] = $best_destination;
}
}
if (count($best_destination_map) < 2) {
$this->checkMovedArg($function, $args, $node, $arg_names);
return;
}
$places_set = [];
foreach (self::findCycles($best_destination_map) as $cycle) {
// To reduce false positives, don't warn unless we know the parameter $j would be compatible with what was used at $i
foreach ($cycle as $array_index => $i) {
$j = $cycle[($array_index + 1) % count($cycle)];
$type = UnionTypeVisitor::unionTypeFromNode($this->code_base, $this->context, $args[$i]);
// echo "Checking if $type can cast to $parameters[$j]\n";
if (!$type->canCastToUnionType($parameters[$j]->getUnionType(), $this->code_base)) {
continue 2;
}
}
foreach ($cycle as $i) {
$places_set[$i] = true;
}
$arg_details = implode(' and ', array_map(static function (int $i) use ($args): string {
return self::extractName($args[$i]) ?? 'unknown';
}, $cycle));
$param_details = implode(' and ', array_map(static function (int $i) use ($parameters): string {
$param = $parameters[$i];
return '#' . ($i + 1) . ' (' . trim($param->getUnionType() . ' $' . $param->getName()) . ')';
}, $cycle));
if ($function->isPHPInternal()) {
$this->emitPluginIssue(
$this->code_base,
(clone $this->context)->withLineNumberStart($node->lineno),
self::SuspiciousParamOrderInternal,
'Suspicious order for arguments named {DETAILS} - These are being passed to parameters {DETAILS} of {FUNCTION}',
[
$arg_details,
$param_details,
$function->getRepresentationForIssue(true),
]
);
} else {
$this->emitPluginIssue(
$this->code_base,
(clone $this->context)->withLineNumberStart($node->lineno),
self::SuspiciousParamOrder,
'Suspicious order for arguments named {DETAILS} - These are being passed to parameters {DETAILS} of {FUNCTION} defined at {FILE}:{LINE}',
[
$arg_details,
$param_details,
$function->getRepresentationForIssue(true),
$function->getContext()->getFile(),
$function->getContext()->getLineNumberStart(),
]
);
}
}
$this->checkMovedArg($function, $args, $node, $arg_names, $places_set);
}
/**
* @param FunctionInterface $function the function being called
* @param list<Node|string|int|float> $args
* @param Node $node
* @param associative-array<int,string> $arg_names
* @param associative-array<int,true> $places_set the places that were already warned about being transposed.
*/
private function checkMovedArg(FunctionInterface $function, array $args, Node $node, array $arg_names, array $places_set = []): void
{
$real_parameters = $function->getRealParameterList();
$parameters = $function->getParameterList();
/** @var associative-array<string,?int> maps lowercase param names to their unique index, or null */
$parameter_names = [];
foreach ($real_parameters as $i => $param) {
if (isset($places_set[$i])) {
continue;
}
$name_key = str_replace('_', '', strtolower($param->getName()));
if (array_key_exists($name_key, $parameter_names)) {
$parameter_names[$name_key] = null;
} else {
$parameter_names[$name_key] = $i;
}
}
foreach ($arg_names as $i => $name) {
$other_i = $parameter_names[str_replace('_', '', strtolower($name))] ?? null;
if ($other_i === null || $other_i === $i) {
continue;
}
$real_param = $real_parameters[$other_i];
if ($real_param->isVariadic()) {
// Skip warning about signatures such as var_dump($var, ...$args) or array_unshift($values, $arg, $arg2)
//
// NOTE: For internal functions, some functions such as implode() have alternate signatures where the real parameter is in a different place,
// which is why this checks both $real_param and $param
//
// For user-defined functions, alternates are not supported.
continue;
}
$param = $parameters[$other_i] ?? null;
if ($param && $param->getName() === $real_param->getName()) {
if ($param->isVariadic()) {
continue;
}
$real_param = $param;
}
$real_param_details = '#' . ($other_i + 1) . ' (' . trim($real_param->getUnionType() . ' $' . $real_param->getName()) . ')';
$arg_details = self::extractName($args[$i]) ?? 'unknown';
if ($function->isPHPInternal()) {
$this->emitPluginIssue(
$this->code_base,
(clone $this->context)->withLineNumberStart($args[$i]->lineno ?? $node->lineno),
self::SuspiciousParamPositionInternal,
'Suspicious order for argument {DETAILS} - This is getting passed to parameter {DETAILS} of {FUNCTION}',
[
$arg_details,
$real_param_details,
$function->getRepresentationForIssue(true),
]
);
} else {
$this->emitPluginIssue(
$this->code_base,
(clone $this->context)->withLineNumberStart($args[$i]->lineno ?? $node->lineno),
self::SuspiciousParamPosition,
'Suspicious order for argument {DETAILS} - This is getting passed to parameter {DETAILS} of {FUNCTION} defined at {FILE}:{LINE}',
[
$arg_details,
$real_param_details,
$function->getRepresentationForIssue(true),
$function->getContext()->getFile(),
$function->getContext()->getLineNumberStart(),
]
);
}
}
}
/**
* @param list<int> $values
* @return list<int> the same values of the cycle, rearranged to start with the smallest value.
*/
private static function normalizeCycle(array $values, int $next): array
{
$pos = array_search($next, $values, true);
$values = array_slice($values, $pos ?: 0);
$min_pos = 0;
foreach ($values as $i => $value) {
if ($value < $values[$min_pos]) {
$min_pos = $values[$i];
}
}
return array_merge(array_slice($values, $min_pos), array_slice($values, 0, $min_pos));
}
/**
* Given [1 => 2, 2 => 3, 3 => 1, 4 => 5, 5 => 6, 6 => 5]], return [[1,2,3],[5,6]]
* @param array<int,int> $destination_map
* @return array<int,array<int,int>>
*/
public static function findCycles(array $destination_map): array
{
$result = [];
while (count($destination_map) > 0) {
reset($destination_map);
$key = (int) key($destination_map);
$values = [];
while (count($destination_map) > 0) {
$values[] = $key;
$next = $destination_map[$key];
unset($destination_map[$key]);
if (in_array($next, $values, true)) {
$values = self::normalizeCycle($values, $next);
if (count($values) >= 2) {
$result[] = $values;
}
$values = [];
break;
}
if (!isset($destination_map[$next])) {
break;
}
$key = $next;
}
}
return $result;
}
/**
* @param Node $node a node of type AST_NULLSAFE_METHOD_CALL
* @override
*/
public function visitNullsafeMethodCall(Node $node): void
{
$this->visitMethodCall($node);
}
/**
* @param Node $node a node of type AST_METHOD_CALL
* @override
*/
public function visitMethodCall(Node $node): void
{
$args = $node->children['args']->children;
if (count($args) < 1) {
// Can't have a suspicious param order/position if there are no params
// (or for AST_CALLABLE_CONVERT)
return;
}
$method_name = $node->children['method'];
if (!\is_string($method_name)) {
return;
}
try {
$method = (new ContextNode(
$this->code_base,
$this->context,
$node
))->getMethod($method_name, false, true);
} catch (Exception) {
return;
}
// @phan-suppress-next-line PhanPartialTypeMismatchArgument
$this->checkCall($method, $args, $node);
}
/**
* @param Node $node a node of type AST_STATIC_CALL
* @override
*/
public function visitStaticCall(Node $node): void
{
$args = $node->children['args']->children;
if (count($args) < 1) {
// Can't have a suspicious param order/position if there are no params
return;
}
$method_name = $node->children['method'];
if (!\is_string($method_name)) {
return;
}
try {
$method = (new ContextNode(
$this->code_base,
$this->context,
$node
))->getMethod($method_name, true, true);
} catch (Exception) {
return;
}
// @phan-suppress-next-line PhanPartialTypeMismatchArgument
$this->checkCall($method, $args, $node);
}
}
// Every plugin needs to return an instance of itself at the
// end of the file in which it's defined.
return new SuspiciousParamOrderPlugin();