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