xref: /php-src/scripts/dev/check_parameters.php (revision 9fcc1bca)
1#!/usr/bin/env php
2<?php
3/*
4  +----------------------------------------------------------------------+
5  | Copyright (c) The PHP Group                                          |
6  +----------------------------------------------------------------------+
7  | This source file is subject to version 3.01 of the PHP license,      |
8  | that is bundled with this package in the file LICENSE, and is        |
9  | available through the world-wide-web at the following url:           |
10  | https://www.php.net/license/3_01.txt                                 |
11  | If you did not receive a copy of the PHP license and are unable to   |
12  | obtain it through the world-wide-web, please send a note to          |
13  | license@php.net so we can mail you a copy immediately.               |
14  +----------------------------------------------------------------------+
15  | Author: Nuno Lopes <nlopess@php.net>                                 |
16  +----------------------------------------------------------------------+
17*/
18
19define('REPORT_LEVEL', 1); // 0 reports less false-positives. up to level 5.
20define('VERSION', '7.0');  // minimum is 7.0
21define('PHPDIR', realpath(dirname(__FILE__) . '/../..'));
22
23// be sure you have enough memory and stack for PHP. pcre will push the limits!
24ini_set('pcre.backtrack_limit', 10000000);
25
26// ------------------------ end of config ----------------------------
27
28$API_params = array(
29    'a' => array('zval**'), // array
30    'A' => array('zval**'), // array or object
31    'b' => array('bool*'), // boolean
32    'd' => array('double*'), // double
33    'f' => array('zend_fcall_info*', 'zend_fcall_info_cache*'), // function
34    'h' => array('HashTable**'), // array as an HashTable*
35    'H' => array('HashTable**'), // array or HASH_OF(object)
36    'l' => array('zend_long*'), // long
37    //TODO 'L' => array('zend_long*, '), // long
38    'o' => array('zval**'), //object
39    'O' => array('zval**', 'zend_class_entry*'), // object of given type
40    'P' => array('zend_string**'), // valid path
41    'r' => array('zval**'), // resource
42    'S' => array('zend_string**'), // string
43    'z' => array('zval**'), // zval*
44    'Z' => array('zval***') // zval**
45    // 's', 'p', 'C' handled separately
46);
47
48/** reports an error, according to its level */
49function error($str, $level = 0)
50{
51    global $current_file, $current_function, $line, $error_reported;
52
53    if ($level <= REPORT_LEVEL) {
54        if (strpos($current_file,PHPDIR) === 0) {
55            $filename = substr($current_file, strlen(PHPDIR)+1);
56        } else {
57            $filename = $current_file;
58        }
59        echo $filename , " [$line] $current_function : $str\n";
60        $error_reported = true;
61    }
62}
63
64/** this updates the global var $line (for error reporting) */
65function update_lineno($offset)
66{
67    global $lines_offset, $line;
68
69    $left  = 0;
70    $right = $count = count($lines_offset)-1;
71
72    // a nice binary search :)
73    do {
74        $mid = intval(($left + $right)/2);
75        $val = $lines_offset[$mid];
76
77        if ($val < $offset) {
78            if (++$mid > $count || $lines_offset[$mid] > $offset) {
79                $line = $mid;
80                return;
81            } else {
82                $left = $mid;
83            }
84        } else if ($val > $offset) {
85            if ($lines_offset[--$mid] < $offset) {
86                $line = $mid+1;
87                return;
88            } else {
89                $right = $mid;
90            }
91        } else {
92            $line = $mid+1;
93            return;
94        }
95    } while (true);
96}
97
98/** parses the sources and fetches its vars name, type and if they are initialized or not */
99function get_vars($txt)
100{
101    $ret =  array();
102    preg_match_all('/((?:(?:unsigned|struct)\s+)?\w+)(?:\s*(\*+)\s+|\s+(\**))(\w+(?:\[\s*\w*\s*\])?)\s*(?:(=)[^,;]+)?((?:\s*,\s*\**\s*\w+(?:\[\s*\w*\s*\])?\s*(?:=[^,;]+)?)*)\s*;/S', $txt, $m, PREG_SET_ORDER);
103
104    foreach ($m as $x) {
105        // the first parameter is special
106        if (!in_array($x[1], array('else', 'endif', 'return'))) // hack to skip reserved words
107            $ret[$x[4]] = array($x[1] . $x[2] . $x[3], $x[5]);
108
109        // are there more vars?
110        if ($x[6]) {
111            preg_match_all('/(\**)\s*(\w+(?:\[\s*\w*\s*\])?)\s*(=?)/S', $x[6], $y, PREG_SET_ORDER);
112            foreach ($y as $z) {
113                $ret[$z[2]] = array($x[1] . $z[1], $z[3]);
114            }
115        }
116    }
117
118// if ($GLOBALS['current_function'] == 'for_debugging') { print_r($m);print_r($ret); }
119    return $ret;
120}
121
122/** run diagnostic checks against one var. */
123function check_param($db, $idx, $exp, $optional, $allow_uninit = false)
124{
125    global $error_few_vars_given;
126
127    if ($idx >= count($db)) {
128        if (!$error_few_vars_given) {
129            error("too few variables passed to function");
130            $error_few_vars_given = true;
131        }
132        return;
133    } elseif ($db[$idx][0] === '**dummy**') {
134        return;
135    }
136
137    if ($db[$idx][1] != $exp) {
138        error("{$db[$idx][0]}: expected '$exp' but got '{$db[$idx][1]}' [".($idx+1).']');
139    }
140
141    if (!$optional && $db[$idx][2]) {
142        error("not optional var is initialized: {$db[$idx][0]} [".($idx+1).']', 2);
143    }
144    if (!$allow_uninit && $optional && !$db[$idx][2]) {
145        error("optional var not initialized: {$db[$idx][0]} [".($idx+1).']', 1);
146    }
147}
148
149/** fetch params passed to zend_parse_params*() */
150function get_params($vars, $str)
151{
152    $ret = array();
153    preg_match_all('/(?:\([^)]+\))?(&?)([\w>.()-]+(?:\[\w+\])?)\s*,?((?:\)*\s*=)?)/S', $str, $m, PREG_SET_ORDER);
154
155    foreach ($m as $x) {
156        $name = $x[2];
157
158        // little hack for last parameter
159        if (strpos($name, '(') === false) {
160            $name = rtrim($name, ')');
161        }
162
163        if (empty($vars[$name][0])) {
164            error("variable not found: '$name'", 3);
165            $ret[][] = '**dummy**';
166
167        } else {
168            $ret[] = array($name, $vars[$name][0] . ($x[1] ? '*' : ''), $vars[$name][1]);
169        }
170
171        // the end (yes, this is a little hack :P)
172        if ($x[3]) {
173            break;
174        }
175    }
176
177// if ($GLOBALS['current_function'] == 'for_debugging') { var_dump($m); var_dump($ret); }
178    return $ret;
179}
180
181/** run tests on a function. the code is passed in $txt */
182function check_function($name, $txt, $offset)
183{
184    global $API_params;
185
186    $regex = '/
187        (?: zend_parse_parameters(?:_throw)?               \s*\([^,]+
188        |   zend_parse_(?:parameters_ex|method_parameters) \s*\([^,]+,[^,]+
189        |   zend_parse_method_parameters_ex                \s*\([^,]+,[^,]+,[^,+]
190        )
191        ,\s*"([^"]*)"\s*
192        ,\s*([^{;]*)
193    /Sx';
194    if (preg_match_all($regex, $txt, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) {
195
196        $GLOBALS['current_function'] = $name;
197
198        foreach ($matches as $m) {
199            $GLOBALS['error_few_vars_given'] = false;
200            update_lineno($offset + $m[2][1]);
201
202            $vars = get_vars(substr($txt, 0, $m[0][1])); // limit var search to current location
203            $params = get_params($vars, $m[2][0]);
204            $optional = $varargs = false;
205            $last_char = '';
206            $j = -1;
207
208            $spec = $m[1][0];
209            $len = strlen($spec);
210            for ($i = 0; $i < $len; ++$i) {
211                $char = $spec[$i];
212                switch ($char = $spec[$i]) {
213                    // separator for optional parameters
214                    case '|':
215                        if ($optional) {
216                            error("more than one optional separator at char #$i");
217                        } else {
218                            $optional = true;
219                            if ($i == $len-1) {
220                                error("unnecessary optional separator");
221                            }
222                        }
223                    break;
224
225                    // separate_zval_if_not_ref
226                    case '/':
227                        if (in_array($last_char, array('l', 'L', 'd', 'b'))) {
228                            error("the '/' specifier should not be applied to '$last_char'");
229                        }
230                    break;
231
232                    // nullable arguments
233                    case '!':
234                        if (in_array($last_char, array('l', 'L', 'd', 'b'))) {
235                            check_param($params, ++$j, 'bool*', $optional);
236                        }
237                    break;
238
239                    // variadic arguments
240                    case '+':
241                    case '*':
242                        if ($varargs) {
243                            error("A varargs specifier can only be used once. repeated char at column $i");
244                        } else {
245                            check_param($params, ++$j, 'zval**', $optional);
246                            check_param($params, ++$j, 'int*', $optional);
247                            $varargs = true;
248                        }
249                    break;
250
251                    case 's':
252                    case 'p':
253                        check_param($params, ++$j, 'char**', $optional, $allow_uninit=true);
254                        check_param($params, ++$j, 'size_t*', $optional, $allow_uninit=true);
255                        if ($optional && !$params[$j-1][2] && !$params[$j][2]
256                                && $params[$j-1][0] !== '**dummy**' && $params[$j][0] !== '**dummy**') {
257                            error("one of optional vars {$params[$j-1][0]} or {$params[$j][0]} must be initialized", 1);
258                        }
259                    break;
260
261                    case 'C':
262                        // C must always be initialized, independently of whether it's optional
263                        check_param($params, ++$j, 'zend_class_entry**', false);
264                    break;
265
266                    default:
267                        if (!isset($API_params[$char])) {
268                            error("unknown char ('$char') at column $i");
269                        }
270
271                        // If an is_null flag is in use, only that flag is required to be
272                        // initialized
273                        $allow_uninit = $i+1 < $len && $spec[$i+1] === '!'
274                                && in_array($char, array('l', 'L', 'd', 'b'));
275
276                        foreach ($API_params[$char] as $exp) {
277                            check_param($params, ++$j, $exp, $optional, $allow_uninit);
278                        }
279                }
280
281                $last_char = $char;
282            }
283        }
284    }
285}
286
287/** the main recursion function. splits files in functions and calls the other functions */
288function recurse($path)
289{
290    foreach (scandir($path) as $file) {
291        if ($file == '.' || $file == '..' || $file == 'CVS') continue;
292
293        $file = "$path/$file";
294        if (is_dir($file)) {
295            recurse($file);
296            continue;
297        }
298
299        // parse only .c and .cpp files
300        if (substr_compare($file, '.c', -2) && substr_compare($file, '.cpp', -4)) continue;
301
302        $txt = file_get_contents($file);
303        // remove comments (but preserve the number of lines)
304        $txt = preg_replace('@//.*@S', '', $txt);
305        $txt = preg_replace_callback('@/\*.*\*/@SsU', function($matches) {
306            return preg_replace("/[^\r\n]+/S", "", $matches[0]);
307        }, $txt);
308
309        $split = preg_split('/PHP_(?:NAMED_)?(?:FUNCTION|METHOD)\s*\((\w+(?:,\s*\w+)?)\)/S', $txt, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_OFFSET_CAPTURE);
310
311        if (count($split) < 2) continue; // no functions defined on this file
312        array_shift($split); // the first part isn't relevant
313
314        // generate the line offsets array
315        $j = 0;
316        $lines = preg_split("/(\r\n?|\n)/S", $txt, -1, PREG_SPLIT_DELIM_CAPTURE);
317        $lines_offset = array();
318
319        for ($i = 0; $i < count($lines); ++$i) {
320            $j += strlen($lines[$i]) + strlen(@$lines[++$i]);
321            $lines_offset[] = $j;
322        }
323
324        $GLOBALS['lines_offset'] = $lines_offset;
325        $GLOBALS['current_file'] = $file;
326
327        for ($i = 0; $i < count($split); $i+=2) {
328            // if the /* }}} */ comment is found use it to reduce false positives
329            // TODO: check the other indexes
330            list($f) = preg_split('@/\*\s*}}}\s*\*/@S', $split[$i+1][0]);
331            check_function(preg_replace('/\s*,\s*/S', '::', $split[$i][0]), $f, $split[$i][1]);
332        }
333    }
334}
335
336$dirs = array();
337
338if (isset($argc) && $argc > 1) {
339    if ($argv[1] == '-h' || $argv[1] == '-help' || $argv[1] == '--help') {
340        echo <<<HELP
341Synopsis:
342    php check_parameters.php [directories]
343
344HELP;
345        exit(0);
346    }
347    for ($i = 1; $i < $argc; $i++) {
348        $dirs[] = $argv[$i];
349    }
350} else {
351    $dirs[] = PHPDIR;
352}
353
354foreach($dirs as $dir) {
355    if (is_dir($dir)) {
356        if (!is_readable($dir)) {
357            echo "ERROR: directory '", $dir ,"' is not readable\n";
358            exit(1);
359        }
360    } else {
361        echo "ERROR: bogus directory '", $dir ,"'\n";
362        exit(1);
363    }
364}
365
366$error_reported = false;
367foreach ($dirs as $dir) {
368    recurse(realpath($dir));
369}
370
371exit($error_reported === false ? 0 : 2);
372