ErrorHandler.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Debug;
  11. use Psr\Log\LoggerInterface;
  12. use Psr\Log\LogLevel;
  13. use Symfony\Component\Debug\Exception\FatalErrorException;
  14. use Symfony\Component\Debug\Exception\FatalThrowableError;
  15. use Symfony\Component\Debug\Exception\FlattenException;
  16. use Symfony\Component\Debug\Exception\OutOfMemoryException;
  17. use Symfony\Component\Debug\Exception\SilencedErrorContext;
  18. use Symfony\Component\Debug\FatalErrorHandler\ClassNotFoundFatalErrorHandler;
  19. use Symfony\Component\Debug\FatalErrorHandler\FatalErrorHandlerInterface;
  20. use Symfony\Component\Debug\FatalErrorHandler\UndefinedFunctionFatalErrorHandler;
  21. use Symfony\Component\Debug\FatalErrorHandler\UndefinedMethodFatalErrorHandler;
  22. /**
  23. * A generic ErrorHandler for the PHP engine.
  24. *
  25. * Provides five bit fields that control how errors are handled:
  26. * - thrownErrors: errors thrown as \ErrorException
  27. * - loggedErrors: logged errors, when not @-silenced
  28. * - scopedErrors: errors thrown or logged with their local context
  29. * - tracedErrors: errors logged with their stack trace
  30. * - screamedErrors: never @-silenced errors
  31. *
  32. * Each error level can be logged by a dedicated PSR-3 logger object.
  33. * Screaming only applies to logging.
  34. * Throwing takes precedence over logging.
  35. * Uncaught exceptions are logged as E_ERROR.
  36. * E_DEPRECATED and E_USER_DEPRECATED levels never throw.
  37. * E_RECOVERABLE_ERROR and E_USER_ERROR levels always throw.
  38. * Non catchable errors that can be detected at shutdown time are logged when the scream bit field allows so.
  39. * As errors have a performance cost, repeated errors are all logged, so that the developer
  40. * can see them and weight them as more important to fix than others of the same level.
  41. *
  42. * @author Nicolas Grekas <p@tchwork.com>
  43. * @author Grégoire Pineau <lyrixx@lyrixx.info>
  44. */
  45. class ErrorHandler
  46. {
  47. private $levels = [
  48. E_DEPRECATED => 'Deprecated',
  49. E_USER_DEPRECATED => 'User Deprecated',
  50. E_NOTICE => 'Notice',
  51. E_USER_NOTICE => 'User Notice',
  52. E_STRICT => 'Runtime Notice',
  53. E_WARNING => 'Warning',
  54. E_USER_WARNING => 'User Warning',
  55. E_COMPILE_WARNING => 'Compile Warning',
  56. E_CORE_WARNING => 'Core Warning',
  57. E_USER_ERROR => 'User Error',
  58. E_RECOVERABLE_ERROR => 'Catchable Fatal Error',
  59. E_COMPILE_ERROR => 'Compile Error',
  60. E_PARSE => 'Parse Error',
  61. E_ERROR => 'Error',
  62. E_CORE_ERROR => 'Core Error',
  63. ];
  64. private $loggers = [
  65. E_DEPRECATED => [null, LogLevel::INFO],
  66. E_USER_DEPRECATED => [null, LogLevel::INFO],
  67. E_NOTICE => [null, LogLevel::WARNING],
  68. E_USER_NOTICE => [null, LogLevel::WARNING],
  69. E_STRICT => [null, LogLevel::WARNING],
  70. E_WARNING => [null, LogLevel::WARNING],
  71. E_USER_WARNING => [null, LogLevel::WARNING],
  72. E_COMPILE_WARNING => [null, LogLevel::WARNING],
  73. E_CORE_WARNING => [null, LogLevel::WARNING],
  74. E_USER_ERROR => [null, LogLevel::CRITICAL],
  75. E_RECOVERABLE_ERROR => [null, LogLevel::CRITICAL],
  76. E_COMPILE_ERROR => [null, LogLevel::CRITICAL],
  77. E_PARSE => [null, LogLevel::CRITICAL],
  78. E_ERROR => [null, LogLevel::CRITICAL],
  79. E_CORE_ERROR => [null, LogLevel::CRITICAL],
  80. ];
  81. private $thrownErrors = 0x1FFF; // E_ALL - E_DEPRECATED - E_USER_DEPRECATED
  82. private $scopedErrors = 0x1FFF; // E_ALL - E_DEPRECATED - E_USER_DEPRECATED
  83. private $tracedErrors = 0x77FB; // E_ALL - E_STRICT - E_PARSE
  84. private $screamedErrors = 0x55; // E_ERROR + E_CORE_ERROR + E_COMPILE_ERROR + E_PARSE
  85. private $loggedErrors = 0;
  86. private $traceReflector;
  87. private $isRecursive = 0;
  88. private $isRoot = false;
  89. private $exceptionHandler;
  90. private $bootstrappingLogger;
  91. private static $reservedMemory;
  92. private static $toStringException = null;
  93. private static $silencedErrorCache = [];
  94. private static $silencedErrorCount = 0;
  95. private static $exitCode = 0;
  96. /**
  97. * Registers the error handler.
  98. *
  99. * @param self|null $handler The handler to register
  100. * @param bool $replace Whether to replace or not any existing handler
  101. *
  102. * @return self The registered error handler
  103. */
  104. public static function register(self $handler = null, $replace = true)
  105. {
  106. if (null === self::$reservedMemory) {
  107. self::$reservedMemory = str_repeat('x', 10240);
  108. register_shutdown_function(__CLASS__.'::handleFatalError');
  109. }
  110. if ($handlerIsNew = null === $handler) {
  111. $handler = new static();
  112. }
  113. if (null === $prev = set_error_handler([$handler, 'handleError'])) {
  114. restore_error_handler();
  115. // Specifying the error types earlier would expose us to https://bugs.php.net/63206
  116. set_error_handler([$handler, 'handleError'], $handler->thrownErrors | $handler->loggedErrors);
  117. $handler->isRoot = true;
  118. }
  119. if ($handlerIsNew && \is_array($prev) && $prev[0] instanceof self) {
  120. $handler = $prev[0];
  121. $replace = false;
  122. }
  123. if (!$replace && $prev) {
  124. restore_error_handler();
  125. $handlerIsRegistered = \is_array($prev) && $handler === $prev[0];
  126. } else {
  127. $handlerIsRegistered = true;
  128. }
  129. if (\is_array($prev = set_exception_handler([$handler, 'handleException'])) && $prev[0] instanceof self) {
  130. restore_exception_handler();
  131. if (!$handlerIsRegistered) {
  132. $handler = $prev[0];
  133. } elseif ($handler !== $prev[0] && $replace) {
  134. set_exception_handler([$handler, 'handleException']);
  135. $p = $prev[0]->setExceptionHandler(null);
  136. $handler->setExceptionHandler($p);
  137. $prev[0]->setExceptionHandler($p);
  138. }
  139. } else {
  140. $handler->setExceptionHandler($prev);
  141. }
  142. $handler->throwAt(E_ALL & $handler->thrownErrors, true);
  143. return $handler;
  144. }
  145. public function __construct(BufferingLogger $bootstrappingLogger = null)
  146. {
  147. if ($bootstrappingLogger) {
  148. $this->bootstrappingLogger = $bootstrappingLogger;
  149. $this->setDefaultLogger($bootstrappingLogger);
  150. }
  151. $this->traceReflector = new \ReflectionProperty('Exception', 'trace');
  152. $this->traceReflector->setAccessible(true);
  153. }
  154. /**
  155. * Sets a logger to non assigned errors levels.
  156. *
  157. * @param LoggerInterface $logger A PSR-3 logger to put as default for the given levels
  158. * @param array|int $levels An array map of E_* to LogLevel::* or an integer bit field of E_* constants
  159. * @param bool $replace Whether to replace or not any existing logger
  160. */
  161. public function setDefaultLogger(LoggerInterface $logger, $levels = E_ALL, $replace = false)
  162. {
  163. $loggers = [];
  164. if (\is_array($levels)) {
  165. foreach ($levels as $type => $logLevel) {
  166. if (empty($this->loggers[$type][0]) || $replace || $this->loggers[$type][0] === $this->bootstrappingLogger) {
  167. $loggers[$type] = [$logger, $logLevel];
  168. }
  169. }
  170. } else {
  171. if (null === $levels) {
  172. $levels = E_ALL;
  173. }
  174. foreach ($this->loggers as $type => $log) {
  175. if (($type & $levels) && (empty($log[0]) || $replace || $log[0] === $this->bootstrappingLogger)) {
  176. $log[0] = $logger;
  177. $loggers[$type] = $log;
  178. }
  179. }
  180. }
  181. $this->setLoggers($loggers);
  182. }
  183. /**
  184. * Sets a logger for each error level.
  185. *
  186. * @param array $loggers Error levels to [LoggerInterface|null, LogLevel::*] map
  187. *
  188. * @return array The previous map
  189. *
  190. * @throws \InvalidArgumentException
  191. */
  192. public function setLoggers(array $loggers)
  193. {
  194. $prevLogged = $this->loggedErrors;
  195. $prev = $this->loggers;
  196. $flush = [];
  197. foreach ($loggers as $type => $log) {
  198. if (!isset($prev[$type])) {
  199. throw new \InvalidArgumentException('Unknown error type: '.$type);
  200. }
  201. if (!\is_array($log)) {
  202. $log = [$log];
  203. } elseif (!array_key_exists(0, $log)) {
  204. throw new \InvalidArgumentException('No logger provided');
  205. }
  206. if (null === $log[0]) {
  207. $this->loggedErrors &= ~$type;
  208. } elseif ($log[0] instanceof LoggerInterface) {
  209. $this->loggedErrors |= $type;
  210. } else {
  211. throw new \InvalidArgumentException('Invalid logger provided');
  212. }
  213. $this->loggers[$type] = $log + $prev[$type];
  214. if ($this->bootstrappingLogger && $prev[$type][0] === $this->bootstrappingLogger) {
  215. $flush[$type] = $type;
  216. }
  217. }
  218. $this->reRegister($prevLogged | $this->thrownErrors);
  219. if ($flush) {
  220. foreach ($this->bootstrappingLogger->cleanLogs() as $log) {
  221. $type = $log[2]['exception'] instanceof \ErrorException ? $log[2]['exception']->getSeverity() : E_ERROR;
  222. if (!isset($flush[$type])) {
  223. $this->bootstrappingLogger->log($log[0], $log[1], $log[2]);
  224. } elseif ($this->loggers[$type][0]) {
  225. $this->loggers[$type][0]->log($this->loggers[$type][1], $log[1], $log[2]);
  226. }
  227. }
  228. }
  229. return $prev;
  230. }
  231. /**
  232. * Sets a user exception handler.
  233. *
  234. * @param callable $handler A handler that will be called on Exception
  235. *
  236. * @return callable|null The previous exception handler
  237. */
  238. public function setExceptionHandler(callable $handler = null)
  239. {
  240. $prev = $this->exceptionHandler;
  241. $this->exceptionHandler = $handler;
  242. return $prev;
  243. }
  244. /**
  245. * Sets the PHP error levels that throw an exception when a PHP error occurs.
  246. *
  247. * @param int $levels A bit field of E_* constants for thrown errors
  248. * @param bool $replace Replace or amend the previous value
  249. *
  250. * @return int The previous value
  251. */
  252. public function throwAt($levels, $replace = false)
  253. {
  254. $prev = $this->thrownErrors;
  255. $this->thrownErrors = ($levels | E_RECOVERABLE_ERROR | E_USER_ERROR) & ~E_USER_DEPRECATED & ~E_DEPRECATED;
  256. if (!$replace) {
  257. $this->thrownErrors |= $prev;
  258. }
  259. $this->reRegister($prev | $this->loggedErrors);
  260. return $prev;
  261. }
  262. /**
  263. * Sets the PHP error levels for which local variables are preserved.
  264. *
  265. * @param int $levels A bit field of E_* constants for scoped errors
  266. * @param bool $replace Replace or amend the previous value
  267. *
  268. * @return int The previous value
  269. */
  270. public function scopeAt($levels, $replace = false)
  271. {
  272. $prev = $this->scopedErrors;
  273. $this->scopedErrors = (int) $levels;
  274. if (!$replace) {
  275. $this->scopedErrors |= $prev;
  276. }
  277. return $prev;
  278. }
  279. /**
  280. * Sets the PHP error levels for which the stack trace is preserved.
  281. *
  282. * @param int $levels A bit field of E_* constants for traced errors
  283. * @param bool $replace Replace or amend the previous value
  284. *
  285. * @return int The previous value
  286. */
  287. public function traceAt($levels, $replace = false)
  288. {
  289. $prev = $this->tracedErrors;
  290. $this->tracedErrors = (int) $levels;
  291. if (!$replace) {
  292. $this->tracedErrors |= $prev;
  293. }
  294. return $prev;
  295. }
  296. /**
  297. * Sets the error levels where the @-operator is ignored.
  298. *
  299. * @param int $levels A bit field of E_* constants for screamed errors
  300. * @param bool $replace Replace or amend the previous value
  301. *
  302. * @return int The previous value
  303. */
  304. public function screamAt($levels, $replace = false)
  305. {
  306. $prev = $this->screamedErrors;
  307. $this->screamedErrors = (int) $levels;
  308. if (!$replace) {
  309. $this->screamedErrors |= $prev;
  310. }
  311. return $prev;
  312. }
  313. /**
  314. * Re-registers as a PHP error handler if levels changed.
  315. */
  316. private function reRegister($prev)
  317. {
  318. if ($prev !== $this->thrownErrors | $this->loggedErrors) {
  319. $handler = set_error_handler('var_dump');
  320. $handler = \is_array($handler) ? $handler[0] : null;
  321. restore_error_handler();
  322. if ($handler === $this) {
  323. restore_error_handler();
  324. if ($this->isRoot) {
  325. set_error_handler([$this, 'handleError'], $this->thrownErrors | $this->loggedErrors);
  326. } else {
  327. set_error_handler([$this, 'handleError']);
  328. }
  329. }
  330. }
  331. }
  332. /**
  333. * Handles errors by filtering then logging them according to the configured bit fields.
  334. *
  335. * @param int $type One of the E_* constants
  336. * @param string $message
  337. * @param string $file
  338. * @param int $line
  339. *
  340. * @return bool Returns false when no handling happens so that the PHP engine can handle the error itself
  341. *
  342. * @throws \ErrorException When $this->thrownErrors requests so
  343. *
  344. * @internal
  345. */
  346. public function handleError($type, $message, $file, $line)
  347. {
  348. // Level is the current error reporting level to manage silent error.
  349. $level = error_reporting();
  350. $silenced = 0 === ($level & $type);
  351. // Strong errors are not authorized to be silenced.
  352. $level |= E_RECOVERABLE_ERROR | E_USER_ERROR | E_DEPRECATED | E_USER_DEPRECATED;
  353. $log = $this->loggedErrors & $type;
  354. $throw = $this->thrownErrors & $type & $level;
  355. $type &= $level | $this->screamedErrors;
  356. if (!$type || (!$log && !$throw)) {
  357. return !$silenced && $type && $log;
  358. }
  359. $scope = $this->scopedErrors & $type;
  360. if (4 < $numArgs = \func_num_args()) {
  361. $context = $scope ? (func_get_arg(4) ?: []) : [];
  362. } else {
  363. $context = [];
  364. }
  365. if (isset($context['GLOBALS']) && $scope) {
  366. $e = $context; // Whatever the signature of the method,
  367. unset($e['GLOBALS'], $context); // $context is always a reference in 5.3
  368. $context = $e;
  369. }
  370. if (false !== strpos($message, "class@anonymous\0")) {
  371. $logMessage = $this->levels[$type].': '.(new FlattenException())->setMessage($message)->getMessage();
  372. } else {
  373. $logMessage = $this->levels[$type].': '.$message;
  374. }
  375. if (null !== self::$toStringException) {
  376. $errorAsException = self::$toStringException;
  377. self::$toStringException = null;
  378. } elseif (!$throw && !($type & $level)) {
  379. if (!isset(self::$silencedErrorCache[$id = $file.':'.$line])) {
  380. $lightTrace = $this->tracedErrors & $type ? $this->cleanTrace(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5), $type, $file, $line, false) : [];
  381. $errorAsException = new SilencedErrorContext($type, $file, $line, isset($lightTrace[1]) ? [$lightTrace[0]] : $lightTrace);
  382. } elseif (isset(self::$silencedErrorCache[$id][$message])) {
  383. $lightTrace = null;
  384. $errorAsException = self::$silencedErrorCache[$id][$message];
  385. ++$errorAsException->count;
  386. } else {
  387. $lightTrace = [];
  388. $errorAsException = null;
  389. }
  390. if (100 < ++self::$silencedErrorCount) {
  391. self::$silencedErrorCache = $lightTrace = [];
  392. self::$silencedErrorCount = 1;
  393. }
  394. if ($errorAsException) {
  395. self::$silencedErrorCache[$id][$message] = $errorAsException;
  396. }
  397. if (null === $lightTrace) {
  398. return;
  399. }
  400. } else {
  401. $errorAsException = new \ErrorException($logMessage, 0, $type, $file, $line);
  402. if ($throw || $this->tracedErrors & $type) {
  403. $backtrace = $errorAsException->getTrace();
  404. $lightTrace = $this->cleanTrace($backtrace, $type, $file, $line, $throw);
  405. $this->traceReflector->setValue($errorAsException, $lightTrace);
  406. } else {
  407. $this->traceReflector->setValue($errorAsException, []);
  408. $backtrace = [];
  409. }
  410. }
  411. if ($throw) {
  412. if (E_USER_ERROR & $type) {
  413. for ($i = 1; isset($backtrace[$i]); ++$i) {
  414. if (isset($backtrace[$i]['function'], $backtrace[$i]['type'], $backtrace[$i - 1]['function'])
  415. && '__toString' === $backtrace[$i]['function']
  416. && '->' === $backtrace[$i]['type']
  417. && !isset($backtrace[$i - 1]['class'])
  418. && ('trigger_error' === $backtrace[$i - 1]['function'] || 'user_error' === $backtrace[$i - 1]['function'])
  419. ) {
  420. // Here, we know trigger_error() has been called from __toString().
  421. // PHP triggers a fatal error when throwing from __toString().
  422. // A small convention allows working around the limitation:
  423. // given a caught $e exception in __toString(), quitting the method with
  424. // `return trigger_error($e, E_USER_ERROR);` allows this error handler
  425. // to make $e get through the __toString() barrier.
  426. foreach ($context as $e) {
  427. if ($e instanceof \Throwable && $e->__toString() === $message) {
  428. self::$toStringException = $e;
  429. return true;
  430. }
  431. }
  432. // Display the original error message instead of the default one.
  433. $this->handleException($errorAsException);
  434. // Stop the process by giving back the error to the native handler.
  435. return false;
  436. }
  437. }
  438. }
  439. throw $errorAsException;
  440. }
  441. if ($this->isRecursive) {
  442. $log = 0;
  443. } else {
  444. try {
  445. $this->isRecursive = true;
  446. $level = ($type & $level) ? $this->loggers[$type][1] : LogLevel::DEBUG;
  447. $this->loggers[$type][0]->log($level, $logMessage, $errorAsException ? ['exception' => $errorAsException] : []);
  448. } finally {
  449. $this->isRecursive = false;
  450. if (!\defined('HHVM_VERSION')) {
  451. set_error_handler([$this, __FUNCTION__]);
  452. }
  453. }
  454. }
  455. return !$silenced && $type && $log;
  456. }
  457. /**
  458. * Handles an exception by logging then forwarding it to another handler.
  459. *
  460. * @param \Exception|\Throwable $exception An exception to handle
  461. * @param array $error An array as returned by error_get_last()
  462. *
  463. * @internal
  464. */
  465. public function handleException($exception, array $error = null)
  466. {
  467. if (null === $error) {
  468. self::$exitCode = 255;
  469. }
  470. if (!$exception instanceof \Exception) {
  471. $exception = new FatalThrowableError($exception);
  472. }
  473. $type = $exception instanceof FatalErrorException ? $exception->getSeverity() : E_ERROR;
  474. $handlerException = null;
  475. if (($this->loggedErrors & $type) || $exception instanceof FatalThrowableError) {
  476. if (false !== strpos($message = $exception->getMessage(), "class@anonymous\0")) {
  477. $message = (new FlattenException())->setMessage($message)->getMessage();
  478. }
  479. if ($exception instanceof FatalErrorException) {
  480. if ($exception instanceof FatalThrowableError) {
  481. $error = [
  482. 'type' => $type,
  483. 'message' => $message,
  484. 'file' => $exception->getFile(),
  485. 'line' => $exception->getLine(),
  486. ];
  487. } else {
  488. $message = 'Fatal '.$message;
  489. }
  490. } elseif ($exception instanceof \ErrorException) {
  491. $message = 'Uncaught '.$message;
  492. } else {
  493. $message = 'Uncaught Exception: '.$message;
  494. }
  495. }
  496. if ($this->loggedErrors & $type) {
  497. try {
  498. $this->loggers[$type][0]->log($this->loggers[$type][1], $message, ['exception' => $exception]);
  499. } catch (\Throwable $handlerException) {
  500. }
  501. }
  502. if ($exception instanceof FatalErrorException && !$exception instanceof OutOfMemoryException && $error) {
  503. foreach ($this->getFatalErrorHandlers() as $handler) {
  504. if ($e = $handler->handleError($error, $exception)) {
  505. $exception = $e;
  506. break;
  507. }
  508. }
  509. }
  510. $exceptionHandler = $this->exceptionHandler;
  511. $this->exceptionHandler = null;
  512. try {
  513. if (null !== $exceptionHandler) {
  514. return $exceptionHandler($exception);
  515. }
  516. $handlerException = $handlerException ?: $exception;
  517. } catch (\Throwable $handlerException) {
  518. }
  519. if ($exception === $handlerException) {
  520. self::$reservedMemory = null; // Disable the fatal error handler
  521. throw $exception; // Give back $exception to the native handler
  522. }
  523. $this->handleException($handlerException);
  524. }
  525. /**
  526. * Shutdown registered function for handling PHP fatal errors.
  527. *
  528. * @param array $error An array as returned by error_get_last()
  529. *
  530. * @internal
  531. */
  532. public static function handleFatalError(array $error = null)
  533. {
  534. if (null === self::$reservedMemory) {
  535. return;
  536. }
  537. $handler = self::$reservedMemory = null;
  538. $handlers = [];
  539. $previousHandler = null;
  540. $sameHandlerLimit = 10;
  541. while (!\is_array($handler) || !$handler[0] instanceof self) {
  542. $handler = set_exception_handler('var_dump');
  543. restore_exception_handler();
  544. if (!$handler) {
  545. break;
  546. }
  547. restore_exception_handler();
  548. if ($handler !== $previousHandler) {
  549. array_unshift($handlers, $handler);
  550. $previousHandler = $handler;
  551. } elseif (0 === --$sameHandlerLimit) {
  552. $handler = null;
  553. break;
  554. }
  555. }
  556. foreach ($handlers as $h) {
  557. set_exception_handler($h);
  558. }
  559. if (!$handler) {
  560. return;
  561. }
  562. if ($handler !== $h) {
  563. $handler[0]->setExceptionHandler($h);
  564. }
  565. $handler = $handler[0];
  566. $handlers = [];
  567. if ($exit = null === $error) {
  568. $error = error_get_last();
  569. }
  570. if ($error && $error['type'] &= E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR) {
  571. // Let's not throw anymore but keep logging
  572. $handler->throwAt(0, true);
  573. $trace = isset($error['backtrace']) ? $error['backtrace'] : null;
  574. if (0 === strpos($error['message'], 'Allowed memory') || 0 === strpos($error['message'], 'Out of memory')) {
  575. $exception = new OutOfMemoryException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, false, $trace);
  576. } else {
  577. $exception = new FatalErrorException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, true, $trace);
  578. }
  579. } else {
  580. $exception = null;
  581. }
  582. try {
  583. if (null !== $exception) {
  584. self::$exitCode = 255;
  585. $handler->handleException($exception, $error);
  586. }
  587. } catch (FatalErrorException $e) {
  588. // Ignore this re-throw
  589. }
  590. if ($exit && self::$exitCode) {
  591. $exitCode = self::$exitCode;
  592. register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); });
  593. }
  594. }
  595. /**
  596. * Gets the fatal error handlers.
  597. *
  598. * Override this method if you want to define more fatal error handlers.
  599. *
  600. * @return FatalErrorHandlerInterface[] An array of FatalErrorHandlerInterface
  601. */
  602. protected function getFatalErrorHandlers()
  603. {
  604. return [
  605. new UndefinedFunctionFatalErrorHandler(),
  606. new UndefinedMethodFatalErrorHandler(),
  607. new ClassNotFoundFatalErrorHandler(),
  608. ];
  609. }
  610. /**
  611. * Cleans the trace by removing function arguments and the frames added by the error handler and DebugClassLoader.
  612. */
  613. private function cleanTrace($backtrace, $type, $file, $line, $throw)
  614. {
  615. $lightTrace = $backtrace;
  616. for ($i = 0; isset($backtrace[$i]); ++$i) {
  617. if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
  618. $lightTrace = \array_slice($lightTrace, 1 + $i);
  619. break;
  620. }
  621. }
  622. if (class_exists(DebugClassLoader::class, false)) {
  623. for ($i = \count($lightTrace) - 2; 0 < $i; --$i) {
  624. if (DebugClassLoader::class === ($lightTrace[$i]['class'] ?? null)) {
  625. array_splice($lightTrace, --$i, 2);
  626. }
  627. }
  628. }
  629. if (!($throw || $this->scopedErrors & $type)) {
  630. for ($i = 0; isset($lightTrace[$i]); ++$i) {
  631. unset($lightTrace[$i]['args'], $lightTrace[$i]['object']);
  632. }
  633. }
  634. return $lightTrace;
  635. }
  636. }