Stacktrace.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. <?php
  2. /**
  3. * Small helper class to inspect the stacktrace
  4. *
  5. * @package raven
  6. */
  7. class Raven_Stacktrace
  8. {
  9. public static $statements = array(
  10. 'include',
  11. 'include_once',
  12. 'require',
  13. 'require_once',
  14. );
  15. public static function get_stack_info($frames,
  16. $trace = false,
  17. $errcontext = null,
  18. $frame_var_limit = Raven_Client::MESSAGE_LIMIT,
  19. $strip_prefixes = null,
  20. $app_path = null,
  21. $excluded_app_paths = null,
  22. Raven_Serializer $serializer = null,
  23. Raven_ReprSerializer $reprSerializer = null)
  24. {
  25. $serializer = $serializer ?: new Raven_Serializer();
  26. $reprSerializer = $reprSerializer ?: new Raven_ReprSerializer();
  27. /**
  28. * PHP stores calls in the stacktrace, rather than executing context. Sentry
  29. * wants to know "when Im calling this code, where am I", and PHP says "I'm
  30. * calling this function" not "I'm in this function". Due to that, we shift
  31. * the context for a frame up one, meaning the variables (which are the calling
  32. * args) come from the previous frame.
  33. */
  34. $result = array();
  35. for ($i = 0; $i < count($frames); $i++) {
  36. $frame = isset($frames[$i]) ? $frames[$i] : null;
  37. $nextframe = isset($frames[$i + 1]) ? $frames[$i + 1] : null;
  38. if (!array_key_exists('file', $frame)) {
  39. $context = array();
  40. if (!empty($frame['class'])) {
  41. $context['line'] = sprintf('%s%s%s', $frame['class'], $frame['type'], $frame['function']);
  42. try {
  43. $reflect = new ReflectionClass($frame['class']);
  44. $context['filename'] = $filename = $reflect->getFileName();
  45. } catch (ReflectionException $e) {
  46. // Forget it if we run into errors, it's not worth it.
  47. }
  48. } else {
  49. $context['line'] = sprintf('%s(anonymous)', $frame['function']);
  50. }
  51. if (empty($context['filename'])) {
  52. $context['filename'] = $filename = '[Anonymous function]';
  53. }
  54. $abs_path = '';
  55. $context['prefix'] = '';
  56. $context['suffix'] = '';
  57. $context['lineno'] = 0;
  58. } else {
  59. $context = self::read_source_file($frame['file'], $frame['line']);
  60. $abs_path = $frame['file'];
  61. }
  62. // strip base path if present
  63. $context['filename'] = self::strip_prefixes($context['filename'], $strip_prefixes);
  64. if ($i === 0 && isset($errcontext)) {
  65. // If we've been given an error context that can be used as the vars for the first frame.
  66. $vars = $errcontext;
  67. } else {
  68. if ($trace) {
  69. $vars = self::get_frame_context($nextframe, $frame_var_limit);
  70. } else {
  71. $vars = array();
  72. }
  73. }
  74. $data = array(
  75. 'filename' => $context['filename'],
  76. 'lineno' => (int) $context['lineno'],
  77. 'function' => isset($nextframe['function']) ? $nextframe['function'] : null,
  78. 'pre_context' => $serializer->serialize($context['prefix']),
  79. 'context_line' => $serializer->serialize($context['line']),
  80. 'post_context' => $serializer->serialize($context['suffix']),
  81. );
  82. // detect in_app based on app path
  83. if ($app_path) {
  84. $norm_abs_path = @realpath($abs_path) ?: $abs_path;
  85. if (!$abs_path) {
  86. $in_app = false;
  87. } else {
  88. $in_app = (bool)(substr($norm_abs_path, 0, strlen($app_path)) === $app_path);
  89. }
  90. if ($in_app && $excluded_app_paths) {
  91. foreach ($excluded_app_paths as $path) {
  92. if (substr($norm_abs_path, 0, strlen($path)) === $path) {
  93. $in_app = false;
  94. break;
  95. }
  96. }
  97. }
  98. $data['in_app'] = $in_app;
  99. }
  100. // dont set this as an empty array as PHP will treat it as a numeric array
  101. // instead of a mapping which goes against the defined Sentry spec
  102. if (!empty($vars)) {
  103. $cleanVars = array();
  104. foreach ($vars as $key => $value) {
  105. $value = $reprSerializer->serialize($value);
  106. if (is_string($value) || is_numeric($value)) {
  107. $cleanVars[(string)$key] = substr($value, 0, $frame_var_limit);
  108. } else {
  109. $cleanVars[(string)$key] = $value;
  110. }
  111. }
  112. $data['vars'] = $cleanVars;
  113. }
  114. $result[] = $data;
  115. }
  116. return array_reverse($result);
  117. }
  118. public static function get_default_context($frame, $frame_arg_limit = Raven_Client::MESSAGE_LIMIT)
  119. {
  120. if (!isset($frame['args'])) {
  121. return array();
  122. }
  123. $i = 1;
  124. $args = array();
  125. foreach ($frame['args'] as $arg) {
  126. $args['param'.$i] = self::serialize_argument($arg, $frame_arg_limit);
  127. $i++;
  128. }
  129. return $args;
  130. }
  131. public static function get_frame_context($frame, $frame_arg_limit = Raven_Client::MESSAGE_LIMIT)
  132. {
  133. if (!isset($frame['args'])) {
  134. return array();
  135. }
  136. // The reflection API seems more appropriate if we associate it with the frame
  137. // where the function is actually called (since we're treating them as function context)
  138. if (!isset($frame['function'])) {
  139. return self::get_default_context($frame, $frame_arg_limit);
  140. }
  141. if (strpos($frame['function'], '__lambda_func') !== false) {
  142. return self::get_default_context($frame, $frame_arg_limit);
  143. }
  144. if (isset($frame['class']) && $frame['class'] == 'Closure') {
  145. return self::get_default_context($frame, $frame_arg_limit);
  146. }
  147. if (strpos($frame['function'], '{closure}') !== false) {
  148. return self::get_default_context($frame, $frame_arg_limit);
  149. }
  150. if (in_array($frame['function'], self::$statements)) {
  151. if (empty($frame['args'])) {
  152. // No arguments
  153. return array();
  154. } else {
  155. // Sanitize the file path
  156. return array(
  157. 'param1' => self::serialize_argument($frame['args'][0], $frame_arg_limit),
  158. );
  159. }
  160. }
  161. try {
  162. if (isset($frame['class'])) {
  163. if (method_exists($frame['class'], $frame['function'])) {
  164. $reflection = new ReflectionMethod($frame['class'], $frame['function']);
  165. } elseif ($frame['type'] === '::') {
  166. $reflection = new ReflectionMethod($frame['class'], '__callStatic');
  167. } else {
  168. $reflection = new ReflectionMethod($frame['class'], '__call');
  169. }
  170. } elseif (function_exists($frame['function'])) {
  171. $reflection = new ReflectionFunction($frame['function']);
  172. } else {
  173. return self::get_default_context($frame, $frame_arg_limit);
  174. }
  175. } catch (ReflectionException $e) {
  176. return self::get_default_context($frame, $frame_arg_limit);
  177. }
  178. $params = $reflection->getParameters();
  179. $args = array();
  180. foreach ($frame['args'] as $i => $arg) {
  181. $arg = self::serialize_argument($arg, $frame_arg_limit);
  182. if (isset($params[$i])) {
  183. // Assign the argument by the parameter name
  184. $args[$params[$i]->name] = $arg;
  185. } else {
  186. $args['param'.$i] = $arg;
  187. }
  188. }
  189. return $args;
  190. }
  191. private static function serialize_argument($arg, $frame_arg_limit)
  192. {
  193. if (is_array($arg)) {
  194. $_arg = array();
  195. foreach ($arg as $key => $value) {
  196. if (is_string($value) || is_numeric($value)) {
  197. $_arg[$key] = substr($value, 0, $frame_arg_limit);
  198. } else {
  199. $_arg[$key] = $value;
  200. }
  201. }
  202. return $_arg;
  203. } elseif (is_string($arg) || is_numeric($arg)) {
  204. return substr($arg, 0, $frame_arg_limit);
  205. } else {
  206. return $arg;
  207. }
  208. }
  209. private static function strip_prefixes($filename, $prefixes)
  210. {
  211. if ($prefixes === null) {
  212. return $filename;
  213. }
  214. foreach ($prefixes as $prefix) {
  215. if (substr($filename, 0, strlen($prefix)) === $prefix) {
  216. return substr($filename, strlen($prefix));
  217. }
  218. }
  219. return $filename;
  220. }
  221. private static function read_source_file($filename, $lineno, $context_lines = 5)
  222. {
  223. $frame = array(
  224. 'prefix' => array(),
  225. 'line' => '',
  226. 'suffix' => array(),
  227. 'filename' => $filename,
  228. 'lineno' => $lineno,
  229. );
  230. if ($filename === null || $lineno === null) {
  231. return $frame;
  232. }
  233. // Code which is eval'ed have a modified filename.. Extract the
  234. // correct filename + linenumber from the string.
  235. $matches = array();
  236. $matched = preg_match("/^(.*?)\\((\\d+)\\) : eval\\(\\)'d code$/",
  237. $filename, $matches);
  238. if ($matched) {
  239. $frame['filename'] = $filename = $matches[1];
  240. $frame['lineno'] = $lineno = $matches[2];
  241. }
  242. // In the case of an anonymous function, the filename is sent as:
  243. // "</path/to/filename>(<lineno>) : runtime-created function"
  244. // Extract the correct filename + linenumber from the string.
  245. $matches = array();
  246. $matched = preg_match("/^(.*?)\\((\\d+)\\) : runtime-created function$/",
  247. $filename, $matches);
  248. if ($matched) {
  249. $frame['filename'] = $filename = $matches[1];
  250. $frame['lineno'] = $lineno = $matches[2];
  251. }
  252. if (!file_exists($filename)) {
  253. return $frame;
  254. }
  255. try {
  256. $file = new SplFileObject($filename);
  257. $target = max(0, ($lineno - ($context_lines + 1)));
  258. $file->seek($target);
  259. $cur_lineno = $target+1;
  260. while (!$file->eof()) {
  261. $line = rtrim($file->current(), "\r\n");
  262. if ($cur_lineno == $lineno) {
  263. $frame['line'] = $line;
  264. } elseif ($cur_lineno < $lineno) {
  265. $frame['prefix'][] = $line;
  266. } elseif ($cur_lineno > $lineno) {
  267. $frame['suffix'][] = $line;
  268. }
  269. $cur_lineno++;
  270. if ($cur_lineno > $lineno + $context_lines) {
  271. break;
  272. }
  273. $file->next();
  274. }
  275. } catch (RuntimeException $exc) {
  276. return $frame;
  277. }
  278. return $frame;
  279. }
  280. }