Aucune description

ErrorHandler.php 26KB

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