xhprof_lib.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. <?php
  2. // Copyright (c) 2009 Facebook
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. //
  17. // This file contains various XHProf library (utility) functions.
  18. // Do not add any display specific code here.
  19. //
  20. function xhprof_error($message) {
  21. error_log($message);
  22. }
  23. /*
  24. * The list of possible metrics collected as part of XHProf that
  25. * require inclusive/exclusive handling while reporting.
  26. *
  27. * @author Kannan
  28. */
  29. function xhprof_get_possible_metrics() {
  30. static $possible_metrics =
  31. array("wt" => array("Wall", "microsecs", "walltime" ),
  32. "ut" => array("User", "microsecs", "user cpu time" ),
  33. "st" => array("Sys", "microsecs", "system cpu time"),
  34. "cpu" => array("Cpu", "microsecs", "cpu time"),
  35. "mu" => array("MUse", "bytes", "memory usage"),
  36. "pmu" => array("PMUse", "bytes", "peak memory usage"),
  37. "samples" => array("Samples", "samples", "cpu time"));
  38. return $possible_metrics;
  39. }
  40. /*
  41. * Get the list of metrics present in $xhprof_data as an array.
  42. *
  43. * @author Kannan
  44. */
  45. function xhprof_get_metrics($xhprof_data) {
  46. // get list of valid metrics
  47. $possible_metrics = xhprof_get_possible_metrics();
  48. // return those that are present in the raw data.
  49. // We'll just look at the root of the subtree for this.
  50. $metrics = array();
  51. foreach ($possible_metrics as $metric => $desc) {
  52. if (isset($xhprof_data["main()"][$metric])) {
  53. $metrics[] = $metric;
  54. }
  55. }
  56. return $metrics;
  57. }
  58. /**
  59. * Takes a parent/child function name encoded as
  60. * "a==>b" and returns array("a", "b").
  61. *
  62. * @author Kannan
  63. */
  64. function xhprof_parse_parent_child($parent_child) {
  65. $ret = explode("==>", $parent_child);
  66. // Return if both parent and child are set
  67. if (isset($ret[1])) {
  68. return $ret;
  69. }
  70. return array(null, $ret[0]);
  71. }
  72. /**
  73. * Given parent & child function name, composes the key
  74. * in the format present in the raw data.
  75. *
  76. * @author Kannan
  77. */
  78. function xhprof_build_parent_child_key($parent, $child) {
  79. if ($parent) {
  80. return $parent . "==>" . $child;
  81. } else {
  82. return $child;
  83. }
  84. }
  85. /**
  86. * Checks if XHProf raw data appears to be valid and not corrupted.
  87. *
  88. * @param int $run_id Run id of run to be pruned.
  89. * [Used only for reporting errors.]
  90. * @param array $raw_data XHProf raw data to be pruned
  91. * & validated.
  92. *
  93. * @return bool true on success, false on failure
  94. *
  95. * @author Kannan
  96. */
  97. function xhprof_valid_run($run_id, $raw_data) {
  98. $main_info = $raw_data["main()"];
  99. if (empty($main_info)) {
  100. xhprof_error("XHProf: main() missing in raw data for Run ID: $run_id");
  101. return false;
  102. }
  103. // raw data should contain either wall time or samples information...
  104. if (isset($main_info["wt"])) {
  105. $metric = "wt";
  106. } else if (isset($main_info["samples"])) {
  107. $metric = "samples";
  108. } else {
  109. xhprof_error("XHProf: Wall Time information missing from Run ID: $run_id");
  110. return false;
  111. }
  112. foreach ($raw_data as $info) {
  113. $val = $info[$metric];
  114. // basic sanity checks...
  115. if ($val < 0) {
  116. xhprof_error("XHProf: $metric should not be negative: Run ID $run_id"
  117. . serialize($info));
  118. return false;
  119. }
  120. if ($val > (86400000000)) {
  121. xhprof_error("XHProf: $metric > 1 day found in Run ID: $run_id "
  122. . serialize($info));
  123. return false;
  124. }
  125. }
  126. return true;
  127. }
  128. /**
  129. * Return a trimmed version of the XHProf raw data. Note that the raw
  130. * data contains one entry for each unique parent/child function
  131. * combination.The trimmed version of raw data will only contain
  132. * entries where either the parent or child function is in the list
  133. * of $functions_to_keep.
  134. *
  135. * Note: Function main() is also always kept so that overall totals
  136. * can still be obtained from the trimmed version.
  137. *
  138. * @param array XHProf raw data
  139. * @param array array of function names
  140. *
  141. * @return array Trimmed XHProf Report
  142. *
  143. * @author Kannan
  144. */
  145. function xhprof_trim_run($raw_data, $functions_to_keep) {
  146. // convert list of functions to a hash with function as the key
  147. $function_map = array_fill_keys($functions_to_keep, 1);
  148. // always keep main() as well so that overall totals can still
  149. // be computed if need be.
  150. $function_map['main()'] = 1;
  151. $new_raw_data = array();
  152. foreach ($raw_data as $parent_child => $info) {
  153. list($parent, $child) = xhprof_parse_parent_child($parent_child);
  154. if (isset($function_map[$parent]) || isset($function_map[$child])) {
  155. $new_raw_data[$parent_child] = $info;
  156. }
  157. }
  158. return $new_raw_data;
  159. }
  160. /**
  161. * Takes raw XHProf data that was aggregated over "$num_runs" number
  162. * of runs averages/nomalizes the data. Essentially the various metrics
  163. * collected are divided by $num_runs.
  164. *
  165. * @author Kannan
  166. */
  167. function xhprof_normalize_metrics($raw_data, $num_runs) {
  168. if (empty($raw_data) || ($num_runs == 0)) {
  169. return $raw_data;
  170. }
  171. $raw_data_total = array();
  172. if (isset($raw_data["==>main()"]) && isset($raw_data["main()"])) {
  173. xhprof_error("XHProf Error: both ==>main() and main() set in raw data...");
  174. }
  175. foreach ($raw_data as $parent_child => $info) {
  176. foreach ($info as $metric => $value) {
  177. $raw_data_total[$parent_child][$metric] = ($value / $num_runs);
  178. }
  179. }
  180. return $raw_data_total;
  181. }
  182. /**
  183. * Get raw data corresponding to specified array of runs
  184. * aggregated by certain weightage.
  185. *
  186. * Suppose you have run:5 corresponding to page1.php,
  187. * run:6 corresponding to page2.php,
  188. * and run:7 corresponding to page3.php
  189. *
  190. * and you want to accumulate these runs in a 2:4:1 ratio. You
  191. * can do so by calling:
  192. *
  193. * xhprof_aggregate_runs(array(5, 6, 7), array(2, 4, 1));
  194. *
  195. * The above will return raw data for the runs aggregated
  196. * in 2:4:1 ratio.
  197. *
  198. * @param object $xhprof_runs_impl An object that implements
  199. * the iXHProfRuns interface
  200. * @param array $runs run ids of the XHProf runs..
  201. * @param array $wts integral (ideally) weights for $runs
  202. * @param string $source source to fetch raw data for run from
  203. * @param bool $use_script_name If true, a fake edge from main() to
  204. * to __script::<scriptname> is introduced
  205. * in the raw data so that after aggregations
  206. * the script name is still preserved.
  207. *
  208. * @return array Return aggregated raw data
  209. *
  210. * @author Kannan
  211. */
  212. function xhprof_aggregate_runs($xhprof_runs_impl, $runs,
  213. $wts, $source="phprof",
  214. $use_script_name=false) {
  215. $raw_data_total = null;
  216. $raw_data = null;
  217. $metrics = array();
  218. $run_count = count($runs);
  219. $wts_count = count($wts);
  220. if (($run_count == 0) ||
  221. (($wts_count > 0) && ($run_count != $wts_count))) {
  222. return array('description' => 'Invalid input..',
  223. 'raw' => null);
  224. }
  225. $bad_runs = array();
  226. foreach($runs as $idx => $run_id) {
  227. $raw_data = $xhprof_runs_impl->get_run($run_id, $source, $description);
  228. // use the first run to derive what metrics to aggregate on.
  229. if ($idx == 0) {
  230. foreach ($raw_data["main()"] as $metric => $val) {
  231. if ($metric != "pmu") {
  232. // for now, just to keep data size small, skip "peak" memory usage
  233. // data while aggregating.
  234. // The "regular" memory usage data will still be tracked.
  235. if (isset($val)) {
  236. $metrics[] = $metric;
  237. }
  238. }
  239. }
  240. }
  241. if (!xhprof_valid_run($run_id, $raw_data)) {
  242. $bad_runs[] = $run_id;
  243. continue;
  244. }
  245. if ($use_script_name) {
  246. $page = $description;
  247. // create a fake function '__script::$page', and have and edge from
  248. // main() to '__script::$page'. We will also need edges to transfer
  249. // all edges originating from main() to now originate from
  250. // '__script::$page' to all function called from main().
  251. //
  252. // We also weight main() ever so slightly higher so that
  253. // it shows up above the new entry in reports sorted by
  254. // inclusive metrics or call counts.
  255. if ($page) {
  256. foreach($raw_data["main()"] as $metric => $val) {
  257. $fake_edge[$metric] = $val;
  258. $new_main[$metric] = $val + 0.00001;
  259. }
  260. $raw_data["main()"] = $new_main;
  261. $raw_data[xhprof_build_parent_child_key("main()",
  262. "__script::$page")]
  263. = $fake_edge;
  264. } else {
  265. $use_script_name = false;
  266. }
  267. }
  268. // if no weights specified, use 1 as the default weightage..
  269. $wt = ($wts_count == 0) ? 1 : $wts[$idx];
  270. // aggregate $raw_data into $raw_data_total with appropriate weight ($wt)
  271. foreach ($raw_data as $parent_child => $info) {
  272. if ($use_script_name) {
  273. // if this is an old edge originating from main(), it now
  274. // needs to be from '__script::$page'
  275. if (substr($parent_child, 0, 9) == "main()==>") {
  276. $child =substr($parent_child, 9);
  277. // ignore the newly added edge from main()
  278. if (substr($child, 0, 10) != "__script::") {
  279. $parent_child = xhprof_build_parent_child_key("__script::$page",
  280. $child);
  281. }
  282. }
  283. }
  284. if (!isset($raw_data_total[$parent_child])) {
  285. foreach ($metrics as $metric) {
  286. $raw_data_total[$parent_child][$metric] = ($wt * $info[$metric]);
  287. }
  288. } else {
  289. foreach ($metrics as $metric) {
  290. $raw_data_total[$parent_child][$metric] += ($wt * $info[$metric]);
  291. }
  292. }
  293. }
  294. }
  295. $runs_string = implode(",", $runs);
  296. if (isset($wts)) {
  297. $wts_string = "in the ratio (" . implode(":", $wts) . ")";
  298. $normalization_count = array_sum($wts);
  299. } else {
  300. $wts_string = "";
  301. $normalization_count = $run_count;
  302. }
  303. $run_count = $run_count - count($bad_runs);
  304. $data['description'] = "Aggregated Report for $run_count runs: ".
  305. "$runs_string $wts_string\n";
  306. $data['raw'] = xhprof_normalize_metrics($raw_data_total,
  307. $normalization_count);
  308. $data['bad_runs'] = $bad_runs;
  309. return $data;
  310. }
  311. /**
  312. * Analyze hierarchical raw data, and compute per-function (flat)
  313. * inclusive and exclusive metrics.
  314. *
  315. * Also, store overall totals in the 2nd argument.
  316. *
  317. * @param array $raw_data XHProf format raw profiler data.
  318. * @param array &$overall_totals OUT argument for returning
  319. * overall totals for various
  320. * metrics.
  321. * @return array Returns a map from function name to its
  322. * call count and inclusive & exclusive metrics
  323. * (such as wall time, etc.).
  324. *
  325. * @author Kannan Muthukkaruppan
  326. */
  327. function xhprof_compute_flat_info($raw_data, &$overall_totals) {
  328. global $display_calls;
  329. $metrics = xhprof_get_metrics($raw_data);
  330. $overall_totals = array( "ct" => 0,
  331. "wt" => 0,
  332. "ut" => 0,
  333. "st" => 0,
  334. "cpu" => 0,
  335. "mu" => 0,
  336. "pmu" => 0,
  337. "samples" => 0
  338. );
  339. // compute inclusive times for each function
  340. $symbol_tab = xhprof_compute_inclusive_times($raw_data);
  341. /* total metric value is the metric value for "main()" */
  342. foreach ($metrics as $metric) {
  343. $overall_totals[$metric] = $symbol_tab["main()"][$metric];
  344. }
  345. /*
  346. * initialize exclusive (self) metric value to inclusive metric value
  347. * to start with.
  348. * In the same pass, also add up the total number of function calls.
  349. */
  350. foreach ($symbol_tab as $symbol => $info) {
  351. foreach ($metrics as $metric) {
  352. $symbol_tab[$symbol]["excl_" . $metric] = $symbol_tab[$symbol][$metric];
  353. }
  354. if ($display_calls) {
  355. /* keep track of total number of calls */
  356. $overall_totals["ct"] += $info["ct"];
  357. }
  358. }
  359. /* adjust exclusive times by deducting inclusive time of children */
  360. foreach ($raw_data as $parent_child => $info) {
  361. list($parent, $child) = xhprof_parse_parent_child($parent_child);
  362. if ($parent) {
  363. foreach ($metrics as $metric) {
  364. // make sure the parent exists hasn't been pruned.
  365. if (isset($symbol_tab[$parent])) {
  366. $symbol_tab[$parent]["excl_" . $metric] -= $info[$metric];
  367. }
  368. }
  369. }
  370. }
  371. return $symbol_tab;
  372. }
  373. /**
  374. * Hierarchical diff:
  375. * Compute and return difference of two call graphs: Run2 - Run1.
  376. *
  377. * @author Kannan
  378. */
  379. function xhprof_compute_diff($xhprof_data1, $xhprof_data2) {
  380. global $display_calls;
  381. // use the second run to decide what metrics we will do the diff on
  382. $metrics = xhprof_get_metrics($xhprof_data2);
  383. $xhprof_delta = $xhprof_data2;
  384. foreach ($xhprof_data1 as $parent_child => $info) {
  385. if (!isset($xhprof_delta[$parent_child])) {
  386. // this pc combination was not present in run1;
  387. // initialize all values to zero.
  388. if ($display_calls) {
  389. $xhprof_delta[$parent_child] = array("ct" => 0);
  390. } else {
  391. $xhprof_delta[$parent_child] = array();
  392. }
  393. foreach ($metrics as $metric) {
  394. $xhprof_delta[$parent_child][$metric] = 0;
  395. }
  396. }
  397. if ($display_calls) {
  398. $xhprof_delta[$parent_child]["ct"] -= $info["ct"];
  399. }
  400. foreach ($metrics as $metric) {
  401. $xhprof_delta[$parent_child][$metric] -= $info[$metric];
  402. }
  403. }
  404. return $xhprof_delta;
  405. }
  406. /**
  407. * Compute inclusive metrics for function. This code was factored out
  408. * of xhprof_compute_flat_info().
  409. *
  410. * The raw data contains inclusive metrics of a function for each
  411. * unique parent function it is called from. The total inclusive metrics
  412. * for a function is therefore the sum of inclusive metrics for the
  413. * function across all parents.
  414. *
  415. * @return array Returns a map of function name to total (across all parents)
  416. * inclusive metrics for the function.
  417. *
  418. * @author Kannan
  419. */
  420. function xhprof_compute_inclusive_times($raw_data) {
  421. global $display_calls;
  422. $metrics = xhprof_get_metrics($raw_data);
  423. $symbol_tab = array();
  424. /*
  425. * First compute inclusive time for each function and total
  426. * call count for each function across all parents the
  427. * function is called from.
  428. */
  429. foreach ($raw_data as $parent_child => $info) {
  430. list($parent, $child) = xhprof_parse_parent_child($parent_child);
  431. if ($parent == $child) {
  432. /*
  433. * XHProf PHP extension should never trigger this situation any more.
  434. * Recursion is handled in the XHProf PHP extension by giving nested
  435. * calls a unique recursion-depth appended name (for example, foo@1).
  436. */
  437. xhprof_error("Error in Raw Data: parent & child are both: $parent");
  438. return;
  439. }
  440. if (!isset($symbol_tab[$child])) {
  441. if ($display_calls) {
  442. $symbol_tab[$child] = array("ct" => $info["ct"]);
  443. } else {
  444. $symbol_tab[$child] = array();
  445. }
  446. foreach ($metrics as $metric) {
  447. $symbol_tab[$child][$metric] = $info[$metric];
  448. }
  449. } else {
  450. if ($display_calls) {
  451. /* increment call count for this child */
  452. $symbol_tab[$child]["ct"] += $info["ct"];
  453. }
  454. /* update inclusive times/metric for this child */
  455. foreach ($metrics as $metric) {
  456. $symbol_tab[$child][$metric] += $info[$metric];
  457. }
  458. }
  459. }
  460. return $symbol_tab;
  461. }
  462. /*
  463. * Prunes XHProf raw data:
  464. *
  465. * Any node whose inclusive walltime accounts for less than $prune_percent
  466. * of total walltime is pruned. [It is possible that a child function isn't
  467. * pruned, but one or more of its parents get pruned. In such cases, when
  468. * viewing the child function's hierarchical information, the cost due to
  469. * the pruned parent(s) will be attributed to a special function/symbol
  470. * "__pruned__()".]
  471. *
  472. * @param array $raw_data XHProf raw data to be pruned & validated.
  473. * @param double $prune_percent Any edges that account for less than
  474. * $prune_percent of time will be pruned
  475. * from the raw data.
  476. *
  477. * @return array Returns the pruned raw data.
  478. *
  479. * @author Kannan
  480. */
  481. function xhprof_prune_run($raw_data, $prune_percent) {
  482. $main_info = $raw_data["main()"];
  483. if (empty($main_info)) {
  484. xhprof_error("XHProf: main() missing in raw data");
  485. return false;
  486. }
  487. // raw data should contain either wall time or samples information...
  488. if (isset($main_info["wt"])) {
  489. $prune_metric = "wt";
  490. } else if (isset($main_info["samples"])) {
  491. $prune_metric = "samples";
  492. } else {
  493. xhprof_error("XHProf: for main() we must have either wt "
  494. ."or samples attribute set");
  495. return false;
  496. }
  497. // determine the metrics present in the raw data..
  498. $metrics = array();
  499. foreach ($main_info as $metric => $val) {
  500. if (isset($val)) {
  501. $metrics[] = $metric;
  502. }
  503. }
  504. $prune_threshold = (($main_info[$prune_metric] * $prune_percent) / 100.0);
  505. init_metrics($raw_data, null, null, false);
  506. $flat_info = xhprof_compute_inclusive_times($raw_data);
  507. foreach ($raw_data as $parent_child => $info) {
  508. list($parent, $child) = xhprof_parse_parent_child($parent_child);
  509. // is this child's overall total from all parents less than threshold?
  510. if ($flat_info[$child][$prune_metric] < $prune_threshold) {
  511. unset($raw_data[$parent_child]); // prune the edge
  512. } else if ($parent &&
  513. ($parent != "__pruned__()") &&
  514. ($flat_info[$parent][$prune_metric] < $prune_threshold)) {
  515. // Parent's overall inclusive metric is less than a threshold.
  516. // All edges to the parent node will get nuked, and this child will
  517. // be a dangling child.
  518. // So instead change its parent to be a special function __pruned__().
  519. $pruned_edge = xhprof_build_parent_child_key("__pruned__()", $child);
  520. if (isset($raw_data[$pruned_edge])) {
  521. foreach ($metrics as $metric) {
  522. $raw_data[$pruned_edge][$metric]+=$raw_data[$parent_child][$metric];
  523. }
  524. } else {
  525. $raw_data[$pruned_edge] = $raw_data[$parent_child];
  526. }
  527. unset($raw_data[$parent_child]); // prune the edge
  528. }
  529. }
  530. return $raw_data;
  531. }
  532. /**
  533. * Set one key in an array and return the array
  534. *
  535. * @author Kannan
  536. */
  537. function xhprof_array_set($arr, $k, $v) {
  538. $arr[$k] = $v;
  539. return $arr;
  540. }
  541. /**
  542. * Removes/unsets one key in an array and return the array
  543. *
  544. * @author Kannan
  545. */
  546. function xhprof_array_unset($arr, $k) {
  547. unset($arr[$k]);
  548. return $arr;
  549. }
  550. /**
  551. * Type definitions for URL params
  552. */
  553. define('XHPROF_STRING_PARAM', 1);
  554. define('XHPROF_UINT_PARAM', 2);
  555. define('XHPROF_FLOAT_PARAM', 3);
  556. define('XHPROF_BOOL_PARAM', 4);
  557. /**
  558. * Internal helper function used by various
  559. * xhprof_get_param* flavors for various
  560. * types of parameters.
  561. *
  562. * @param string name of the URL query string param
  563. *
  564. * @author Kannan
  565. */
  566. function xhprof_get_param_helper($param) {
  567. $val = null;
  568. if (isset($_GET[$param]))
  569. $val = $_GET[$param];
  570. else if (isset($_POST[$param])) {
  571. $val = $_POST[$param];
  572. }
  573. return $val;
  574. }
  575. /**
  576. * Extracts value for string param $param from query
  577. * string. If param is not specified, return the
  578. * $default value.
  579. *
  580. * @author Kannan
  581. */
  582. function xhprof_get_string_param($param, $default = '') {
  583. $val = xhprof_get_param_helper($param);
  584. if ($val === null)
  585. return $default;
  586. return $val;
  587. }
  588. /**
  589. * Extracts value for unsigned integer param $param from
  590. * query string. If param is not specified, return the
  591. * $default value.
  592. *
  593. * If value is not a valid unsigned integer, logs error
  594. * and returns null.
  595. *
  596. * @author Kannan
  597. */
  598. function xhprof_get_uint_param($param, $default = 0) {
  599. $val = xhprof_get_param_helper($param);
  600. if ($val === null)
  601. $val = $default;
  602. // trim leading/trailing whitespace
  603. $val = trim($val);
  604. // if it only contains digits, then ok..
  605. if (ctype_digit($val)) {
  606. return $val;
  607. }
  608. xhprof_error("$param is $val. It must be an unsigned integer.");
  609. return null;
  610. }
  611. /**
  612. * Extracts value for a float param $param from
  613. * query string. If param is not specified, return
  614. * the $default value.
  615. *
  616. * If value is not a valid unsigned integer, logs error
  617. * and returns null.
  618. *
  619. * @author Kannan
  620. */
  621. function xhprof_get_float_param($param, $default = 0) {
  622. $val = xhprof_get_param_helper($param);
  623. if ($val === null)
  624. $val = $default;
  625. // trim leading/trailing whitespace
  626. $val = trim($val);
  627. // TBD: confirm the value is indeed a float.
  628. if (true) // for now..
  629. return (float)$val;
  630. xhprof_error("$param is $val. It must be a float.");
  631. return null;
  632. }
  633. /**
  634. * Extracts value for a boolean param $param from
  635. * query string. If param is not specified, return
  636. * the $default value.
  637. *
  638. * If value is not a valid unsigned integer, logs error
  639. * and returns null.
  640. *
  641. * @author Kannan
  642. */
  643. function xhprof_get_bool_param($param, $default = false) {
  644. $val = xhprof_get_param_helper($param);
  645. if ($val === null)
  646. $val = $default;
  647. // trim leading/trailing whitespace
  648. $val = trim($val);
  649. switch (strtolower($val)) {
  650. case '0':
  651. case '1':
  652. $val = (bool)$val;
  653. break;
  654. case 'true':
  655. case 'on':
  656. case 'yes':
  657. $val = true;
  658. break;
  659. case 'false':
  660. case 'off':
  661. case 'no':
  662. $val = false;
  663. break;
  664. default:
  665. xhprof_error("$param is $val. It must be a valid boolean string.");
  666. return null;
  667. }
  668. return $val;
  669. }
  670. /**
  671. * Initialize params from URL query string. The function
  672. * creates globals variables for each of the params
  673. * and if the URL query string doesn't specify a particular
  674. * param initializes them with the corresponding default
  675. * value specified in the input.
  676. *
  677. * @params array $params An array whose keys are the names
  678. * of URL params who value needs to
  679. * be retrieved from the URL query
  680. * string. PHP globals are created
  681. * with these names. The value is
  682. * itself an array with 2-elems (the
  683. * param type, and its default value).
  684. * If a param is not specified in the
  685. * query string the default value is
  686. * used.
  687. * @author Kannan
  688. */
  689. function xhprof_param_init($params) {
  690. /* Create variables specified in $params keys, init defaults */
  691. foreach ($params as $k => $v) {
  692. switch ($v[0]) {
  693. case XHPROF_STRING_PARAM:
  694. $p = xhprof_get_string_param($k, $v[1]);
  695. break;
  696. case XHPROF_UINT_PARAM:
  697. $p = xhprof_get_uint_param($k, $v[1]);
  698. break;
  699. case XHPROF_FLOAT_PARAM:
  700. $p = xhprof_get_float_param($k, $v[1]);
  701. break;
  702. case XHPROF_BOOL_PARAM:
  703. $p = xhprof_get_bool_param($k, $v[1]);
  704. break;
  705. default:
  706. xhprof_error("Invalid param type passed to xhprof_param_init: "
  707. . $v[0]);
  708. exit();
  709. }
  710. // create a global variable using the parameter name.
  711. $GLOBALS[$k] = $p;
  712. }
  713. }
  714. /**
  715. * Given a partial query string $q return matching function names in
  716. * specified XHProf run. This is used for the type ahead function
  717. * selector.
  718. *
  719. * @author Kannan
  720. */
  721. function xhprof_get_matching_functions($q, $xhprof_data) {
  722. $matches = array();
  723. foreach ($xhprof_data as $parent_child => $info) {
  724. list($parent, $child) = xhprof_parse_parent_child($parent_child);
  725. if (stripos($parent, $q) !== false) {
  726. $matches[$parent] = 1;
  727. }
  728. if (stripos($child, $q) !== false) {
  729. $matches[$child] = 1;
  730. }
  731. }
  732. $res = array_keys($matches);
  733. // sort it so the answers are in some reliable order...
  734. asort($res);
  735. return ($res);
  736. }