ErrorHandler.php 29 KB

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