ErrorHandler.php 28 KB

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