Drupal investigation

ErrorHandler.php 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  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\LogLevel;
  12. use Psr\Log\LoggerInterface;
  13. use Symfony\Component\Debug\Exception\ContextErrorException;
  14. use Symfony\Component\Debug\Exception\FatalErrorException;
  15. use Symfony\Component\Debug\Exception\FatalThrowableError;
  16. use Symfony\Component\Debug\Exception\OutOfMemoryException;
  17. use Symfony\Component\Debug\FatalErrorHandler\UndefinedFunctionFatalErrorHandler;
  18. use Symfony\Component\Debug\FatalErrorHandler\UndefinedMethodFatalErrorHandler;
  19. use Symfony\Component\Debug\FatalErrorHandler\ClassNotFoundFatalErrorHandler;
  20. use Symfony\Component\Debug\FatalErrorHandler\FatalErrorHandlerInterface;
  21. /**
  22. * A generic ErrorHandler for the PHP engine.
  23. *
  24. * Provides five bit fields that control how errors are handled:
  25. * - thrownErrors: errors thrown as \ErrorException
  26. * - loggedErrors: logged errors, when not @-silenced
  27. * - scopedErrors: errors thrown or logged with their local context
  28. * - tracedErrors: errors logged with their stack trace, only once for repeated errors
  29. * - screamedErrors: never @-silenced errors
  30. *
  31. * Each error level can be logged by a dedicated PSR-3 logger object.
  32. * Screaming only applies to logging.
  33. * Throwing takes precedence over logging.
  34. * Uncaught exceptions are logged as E_ERROR.
  35. * E_DEPRECATED and E_USER_DEPRECATED levels never throw.
  36. * E_RECOVERABLE_ERROR and E_USER_ERROR levels always throw.
  37. * Non catchable errors that can be detected at shutdown time are logged when the scream bit field allows so.
  38. * As errors have a performance cost, repeated errors are all logged, so that the developer
  39. * can see them and weight them as more important to fix than others of the same level.
  40. *
  41. * @author Nicolas Grekas <p@tchwork.com>
  42. */
  43. class ErrorHandler
  44. {
  45. /**
  46. * @deprecated since version 2.6, to be removed in 3.0.
  47. */
  48. const TYPE_DEPRECATION = -100;
  49. private $levels = array(
  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 = array(
  67. E_DEPRECATED => array(null, LogLevel::INFO),
  68. E_USER_DEPRECATED => array(null, LogLevel::INFO),
  69. E_NOTICE => array(null, LogLevel::WARNING),
  70. E_USER_NOTICE => array(null, LogLevel::WARNING),
  71. E_STRICT => array(null, LogLevel::WARNING),
  72. E_WARNING => array(null, LogLevel::WARNING),
  73. E_USER_WARNING => array(null, LogLevel::WARNING),
  74. E_COMPILE_WARNING => array(null, LogLevel::WARNING),
  75. E_CORE_WARNING => array(null, LogLevel::WARNING),
  76. E_USER_ERROR => array(null, LogLevel::CRITICAL),
  77. E_RECOVERABLE_ERROR => array(null, LogLevel::CRITICAL),
  78. E_COMPILE_ERROR => array(null, LogLevel::CRITICAL),
  79. E_PARSE => array(null, LogLevel::CRITICAL),
  80. E_ERROR => array(null, LogLevel::CRITICAL),
  81. E_CORE_ERROR => array(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 $loggedTraces = array();
  89. private $isRecursive = 0;
  90. private $isRoot = false;
  91. private $exceptionHandler;
  92. private $bootstrappingLogger;
  93. private static $reservedMemory;
  94. private static $stackedErrors = array();
  95. private static $stackedErrorLevels = array();
  96. private static $toStringException = null;
  97. /**
  98. * Same init value as thrownErrors.
  99. *
  100. * @deprecated since version 2.6, to be removed in 3.0.
  101. */
  102. private $displayErrors = 0x1FFF;
  103. /**
  104. * Registers the error handler.
  105. *
  106. * @param self|null|int $handler The handler to register, or @deprecated (since version 2.6, to be removed in 3.0) bit field of thrown levels
  107. * @param bool $replace Whether to replace or not any existing handler
  108. *
  109. * @return self The registered error handler
  110. */
  111. public static function register($handler = null, $replace = true)
  112. {
  113. if (null === self::$reservedMemory) {
  114. self::$reservedMemory = str_repeat('x', 10240);
  115. register_shutdown_function(__CLASS__.'::handleFatalError');
  116. }
  117. $levels = -1;
  118. if ($handlerIsNew = !$handler instanceof self) {
  119. // @deprecated polymorphism, to be removed in 3.0
  120. if (null !== $handler) {
  121. $levels = $replace ? $handler : 0;
  122. $replace = true;
  123. }
  124. $handler = new static();
  125. }
  126. if (null === $prev = set_error_handler(array($handler, 'handleError'))) {
  127. restore_error_handler();
  128. // Specifying the error types earlier would expose us to https://bugs.php.net/63206
  129. set_error_handler(array($handler, 'handleError'), $handler->thrownErrors | $handler->loggedErrors);
  130. $handler->isRoot = true;
  131. }
  132. if ($handlerIsNew && is_array($prev) && $prev[0] instanceof self) {
  133. $handler = $prev[0];
  134. $replace = false;
  135. }
  136. if ($replace || !$prev) {
  137. $handler->setExceptionHandler(set_exception_handler(array($handler, 'handleException')));
  138. } else {
  139. restore_error_handler();
  140. }
  141. $handler->throwAt($levels & $handler->thrownErrors, true);
  142. return $handler;
  143. }
  144. public function __construct(BufferingLogger $bootstrappingLogger = null)
  145. {
  146. if ($bootstrappingLogger) {
  147. $this->bootstrappingLogger = $bootstrappingLogger;
  148. $this->setDefaultLogger($bootstrappingLogger);
  149. }
  150. }
  151. /**
  152. * Sets a logger to non assigned errors levels.
  153. *
  154. * @param LoggerInterface $logger A PSR-3 logger to put as default for the given levels
  155. * @param array|int $levels An array map of E_* to LogLevel::* or an integer bit field of E_* constants
  156. * @param bool $replace Whether to replace or not any existing logger
  157. */
  158. public function setDefaultLogger(LoggerInterface $logger, $levels = null, $replace = false)
  159. {
  160. $loggers = array();
  161. if (is_array($levels)) {
  162. foreach ($levels as $type => $logLevel) {
  163. if (empty($this->loggers[$type][0]) || $replace || $this->loggers[$type][0] === $this->bootstrappingLogger) {
  164. $loggers[$type] = array($logger, $logLevel);
  165. }
  166. }
  167. } else {
  168. if (null === $levels) {
  169. $levels = E_ALL | E_STRICT;
  170. }
  171. foreach ($this->loggers as $type => $log) {
  172. if (($type & $levels) && (empty($log[0]) || $replace || $log[0] === $this->bootstrappingLogger)) {
  173. $log[0] = $logger;
  174. $loggers[$type] = $log;
  175. }
  176. }
  177. }
  178. $this->setLoggers($loggers);
  179. }
  180. /**
  181. * Sets a logger for each error level.
  182. *
  183. * @param array $loggers Error levels to [LoggerInterface|null, LogLevel::*] map
  184. *
  185. * @return array The previous map
  186. *
  187. * @throws \InvalidArgumentException
  188. */
  189. public function setLoggers(array $loggers)
  190. {
  191. $prevLogged = $this->loggedErrors;
  192. $prev = $this->loggers;
  193. $flush = array();
  194. foreach ($loggers as $type => $log) {
  195. if (!isset($prev[$type])) {
  196. throw new \InvalidArgumentException('Unknown error type: '.$type);
  197. }
  198. if (!is_array($log)) {
  199. $log = array($log);
  200. } elseif (!array_key_exists(0, $log)) {
  201. throw new \InvalidArgumentException('No logger provided');
  202. }
  203. if (null === $log[0]) {
  204. $this->loggedErrors &= ~$type;
  205. } elseif ($log[0] instanceof LoggerInterface) {
  206. $this->loggedErrors |= $type;
  207. } else {
  208. throw new \InvalidArgumentException('Invalid logger provided');
  209. }
  210. $this->loggers[$type] = $log + $prev[$type];
  211. if ($this->bootstrappingLogger && $prev[$type][0] === $this->bootstrappingLogger) {
  212. $flush[$type] = $type;
  213. }
  214. }
  215. $this->reRegister($prevLogged | $this->thrownErrors);
  216. if ($flush) {
  217. foreach ($this->bootstrappingLogger->cleanLogs() as $log) {
  218. $type = $log[2]['type'];
  219. if (!isset($flush[$type])) {
  220. $this->bootstrappingLogger->log($log[0], $log[1], $log[2]);
  221. } elseif ($this->loggers[$type][0]) {
  222. $this->loggers[$type][0]->log($this->loggers[$type][1], $log[1], $log[2]);
  223. }
  224. }
  225. }
  226. return $prev;
  227. }
  228. /**
  229. * Sets a user exception handler.
  230. *
  231. * @param callable $handler A handler that will be called on Exception
  232. *
  233. * @return callable|null The previous exception handler
  234. *
  235. * @throws \InvalidArgumentException
  236. */
  237. public function setExceptionHandler($handler)
  238. {
  239. if (null !== $handler && !is_callable($handler)) {
  240. throw new \LogicException('The exception handler must be a valid PHP callable.');
  241. }
  242. $prev = $this->exceptionHandler;
  243. $this->exceptionHandler = $handler;
  244. return $prev;
  245. }
  246. /**
  247. * Sets the PHP error levels that throw an exception when a PHP error occurs.
  248. *
  249. * @param int $levels A bit field of E_* constants for thrown errors
  250. * @param bool $replace Replace or amend the previous value
  251. *
  252. * @return int The previous value
  253. */
  254. public function throwAt($levels, $replace = false)
  255. {
  256. $prev = $this->thrownErrors;
  257. $this->thrownErrors = ($levels | E_RECOVERABLE_ERROR | E_USER_ERROR) & ~E_USER_DEPRECATED & ~E_DEPRECATED;
  258. if (!$replace) {
  259. $this->thrownErrors |= $prev;
  260. }
  261. $this->reRegister($prev | $this->loggedErrors);
  262. // $this->displayErrors is @deprecated since version 2.6
  263. $this->displayErrors = $this->thrownErrors;
  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($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(array($this, 'handleError'), $this->thrownErrors | $this->loggedErrors);
  330. } else {
  331. set_error_handler(array($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. $level = error_reporting() | 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 $type && $log;
  358. }
  359. $scope = $this->scopedErrors & $type;
  360. if (4 < $numArgs = func_num_args()) {
  361. $context = $scope ? (func_get_arg(4) ?: array()) : array();
  362. $backtrace = 5 < $numArgs ? func_get_arg(5) : null; // defined on HHVM
  363. } else {
  364. $context = array();
  365. $backtrace = null;
  366. }
  367. if (isset($context['GLOBALS']) && $scope) {
  368. $e = $context; // Whatever the signature of the method,
  369. unset($e['GLOBALS'], $context); // $context is always a reference in 5.3
  370. $context = $e;
  371. }
  372. if (null !== $backtrace && $type & E_ERROR) {
  373. // E_ERROR fatal errors are triggered on HHVM when
  374. // hhvm.error_handling.call_user_handler_on_fatals=1
  375. // which is the way to get their backtrace.
  376. $this->handleFatalError(compact('type', 'message', 'file', 'line', 'backtrace'));
  377. return true;
  378. }
  379. if ($throw) {
  380. if (null !== self::$toStringException) {
  381. $throw = self::$toStringException;
  382. self::$toStringException = null;
  383. } elseif ($scope && class_exists('Symfony\Component\Debug\Exception\ContextErrorException')) {
  384. // Checking for class existence is a work around for https://bugs.php.net/42098
  385. $throw = new ContextErrorException($this->levels[$type].': '.$message, 0, $type, $file, $line, $context);
  386. } else {
  387. $throw = new \ErrorException($this->levels[$type].': '.$message, 0, $type, $file, $line);
  388. }
  389. if (PHP_VERSION_ID <= 50407 && (PHP_VERSION_ID >= 50400 || PHP_VERSION_ID <= 50317)) {
  390. // Exceptions thrown from error handlers are sometimes not caught by the exception
  391. // handler and shutdown handlers are bypassed before 5.4.8/5.3.18.
  392. // We temporarily re-enable display_errors to prevent any blank page related to this bug.
  393. $throw->errorHandlerCanary = new ErrorHandlerCanary();
  394. }
  395. if (E_USER_ERROR & $type) {
  396. $backtrace = $backtrace ?: $throw->getTrace();
  397. for ($i = 1; isset($backtrace[$i]); ++$i) {
  398. if (isset($backtrace[$i]['function'], $backtrace[$i]['type'], $backtrace[$i - 1]['function'])
  399. && '__toString' === $backtrace[$i]['function']
  400. && '->' === $backtrace[$i]['type']
  401. && !isset($backtrace[$i - 1]['class'])
  402. && ('trigger_error' === $backtrace[$i - 1]['function'] || 'user_error' === $backtrace[$i - 1]['function'])
  403. ) {
  404. // Here, we know trigger_error() has been called from __toString().
  405. // HHVM is fine with throwing from __toString() but PHP triggers a fatal error instead.
  406. // A small convention allows working around the limitation:
  407. // given a caught $e exception in __toString(), quitting the method with
  408. // `return trigger_error($e, E_USER_ERROR);` allows this error handler
  409. // to make $e get through the __toString() barrier.
  410. foreach ($context as $e) {
  411. if (($e instanceof \Exception || $e instanceof \Throwable) && $e->__toString() === $message) {
  412. if (1 === $i) {
  413. // On HHVM
  414. $throw = $e;
  415. break;
  416. }
  417. self::$toStringException = $e;
  418. return true;
  419. }
  420. }
  421. if (1 < $i) {
  422. // On PHP (not on HHVM), display the original error message instead of the default one.
  423. $this->handleException($throw);
  424. // Stop the process by giving back the error to the native handler.
  425. return false;
  426. }
  427. }
  428. }
  429. }
  430. throw $throw;
  431. }
  432. // For duplicated errors, log the trace only once
  433. $e = md5("{$type}/{$line}/{$file}\x00{$message}", true);
  434. $trace = true;
  435. if (!($this->tracedErrors & $type) || isset($this->loggedTraces[$e])) {
  436. $trace = false;
  437. } else {
  438. $this->loggedTraces[$e] = 1;
  439. }
  440. $e = compact('type', 'file', 'line', 'level');
  441. if ($type & $level) {
  442. if ($scope) {
  443. $e['scope_vars'] = $context;
  444. if ($trace) {
  445. $e['stack'] = $backtrace ?: debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT);
  446. }
  447. } elseif ($trace) {
  448. if (null === $backtrace) {
  449. $e['stack'] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  450. } else {
  451. foreach ($backtrace as &$frame) {
  452. unset($frame['args'], $frame);
  453. }
  454. $e['stack'] = $backtrace;
  455. }
  456. }
  457. }
  458. if ($this->isRecursive) {
  459. $log = 0;
  460. } elseif (self::$stackedErrorLevels) {
  461. self::$stackedErrors[] = array($this->loggers[$type][0], ($type & $level) ? $this->loggers[$type][1] : LogLevel::DEBUG, $message, $e);
  462. } else {
  463. try {
  464. $this->isRecursive = true;
  465. $this->loggers[$type][0]->log(($type & $level) ? $this->loggers[$type][1] : LogLevel::DEBUG, $message, $e);
  466. $this->isRecursive = false;
  467. } catch (\Exception $e) {
  468. $this->isRecursive = false;
  469. throw $e;
  470. } catch (\Throwable $e) {
  471. $this->isRecursive = false;
  472. throw $e;
  473. }
  474. }
  475. return $type && $log;
  476. }
  477. /**
  478. * Handles an exception by logging then forwarding it to another handler.
  479. *
  480. * @param \Exception|\Throwable $exception An exception to handle
  481. * @param array $error An array as returned by error_get_last()
  482. *
  483. * @internal
  484. */
  485. public function handleException($exception, array $error = null)
  486. {
  487. if (!$exception instanceof \Exception) {
  488. $exception = new FatalThrowableError($exception);
  489. }
  490. $type = $exception instanceof FatalErrorException ? $exception->getSeverity() : E_ERROR;
  491. if (($this->loggedErrors & $type) || $exception instanceof FatalThrowableError) {
  492. $e = array(
  493. 'type' => $type,
  494. 'file' => $exception->getFile(),
  495. 'line' => $exception->getLine(),
  496. 'level' => error_reporting(),
  497. 'stack' => $exception->getTrace(),
  498. );
  499. if ($exception instanceof FatalErrorException) {
  500. if ($exception instanceof FatalThrowableError) {
  501. $error = array(
  502. 'type' => $type,
  503. 'message' => $message = $exception->getMessage(),
  504. 'file' => $e['file'],
  505. 'line' => $e['line'],
  506. );
  507. } else {
  508. $message = 'Fatal '.$exception->getMessage();
  509. }
  510. } elseif ($exception instanceof \ErrorException) {
  511. $message = 'Uncaught '.$exception->getMessage();
  512. if ($exception instanceof ContextErrorException) {
  513. $e['context'] = $exception->getContext();
  514. }
  515. } else {
  516. $message = 'Uncaught Exception: '.$exception->getMessage();
  517. }
  518. }
  519. if ($this->loggedErrors & $type) {
  520. try {
  521. $this->loggers[$type][0]->log($this->loggers[$type][1], $message, $e);
  522. } catch (\Exception $handlerException) {
  523. } catch (\Throwable $handlerException) {
  524. }
  525. }
  526. if ($exception instanceof FatalErrorException && !$exception instanceof OutOfMemoryException && $error) {
  527. foreach ($this->getFatalErrorHandlers() as $handler) {
  528. if ($e = $handler->handleError($error, $exception)) {
  529. $exception = $e;
  530. break;
  531. }
  532. }
  533. }
  534. if (empty($this->exceptionHandler)) {
  535. throw $exception; // Give back $exception to the native handler
  536. }
  537. try {
  538. call_user_func($this->exceptionHandler, $exception);
  539. } catch (\Exception $handlerException) {
  540. } catch (\Throwable $handlerException) {
  541. }
  542. if (isset($handlerException)) {
  543. $this->exceptionHandler = null;
  544. $this->handleException($handlerException);
  545. }
  546. }
  547. /**
  548. * Shutdown registered function for handling PHP fatal errors.
  549. *
  550. * @param array $error An array as returned by error_get_last()
  551. *
  552. * @internal
  553. */
  554. public static function handleFatalError(array $error = null)
  555. {
  556. if (null === self::$reservedMemory) {
  557. return;
  558. }
  559. self::$reservedMemory = null;
  560. $handler = set_error_handler('var_dump');
  561. $handler = is_array($handler) ? $handler[0] : null;
  562. restore_error_handler();
  563. if (!$handler instanceof self) {
  564. return;
  565. }
  566. if (null === $error) {
  567. $error = error_get_last();
  568. }
  569. try {
  570. while (self::$stackedErrorLevels) {
  571. static::unstackErrors();
  572. }
  573. } catch (\Exception $exception) {
  574. // Handled below
  575. } catch (\Throwable $exception) {
  576. // Handled below
  577. }
  578. if ($error && $error['type'] &= E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR) {
  579. // Let's not throw anymore but keep logging
  580. $handler->throwAt(0, true);
  581. $trace = isset($error['backtrace']) ? $error['backtrace'] : null;
  582. if (0 === strpos($error['message'], 'Allowed memory') || 0 === strpos($error['message'], 'Out of memory')) {
  583. $exception = new OutOfMemoryException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, false, $trace);
  584. } else {
  585. $exception = new FatalErrorException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, true, $trace);
  586. }
  587. } elseif (!isset($exception)) {
  588. return;
  589. }
  590. try {
  591. $handler->handleException($exception, $error);
  592. } catch (FatalErrorException $e) {
  593. // Ignore this re-throw
  594. }
  595. }
  596. /**
  597. * Configures the error handler for delayed handling.
  598. * Ensures also that non-catchable fatal errors are never silenced.
  599. *
  600. * As shown by http://bugs.php.net/42098 and http://bugs.php.net/60724
  601. * PHP has a compile stage where it behaves unusually. To workaround it,
  602. * we plug an error handler that only stacks errors for later.
  603. *
  604. * The most important feature of this is to prevent
  605. * autoloading until unstackErrors() is called.
  606. */
  607. public static function stackErrors()
  608. {
  609. self::$stackedErrorLevels[] = error_reporting(error_reporting() | E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR);
  610. }
  611. /**
  612. * Unstacks stacked errors and forwards to the logger.
  613. */
  614. public static function unstackErrors()
  615. {
  616. $level = array_pop(self::$stackedErrorLevels);
  617. if (null !== $level) {
  618. $e = error_reporting($level);
  619. if ($e !== ($level | E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR)) {
  620. // If the user changed the error level, do not overwrite it
  621. error_reporting($e);
  622. }
  623. }
  624. if (empty(self::$stackedErrorLevels)) {
  625. $errors = self::$stackedErrors;
  626. self::$stackedErrors = array();
  627. foreach ($errors as $e) {
  628. $e[0]->log($e[1], $e[2], $e[3]);
  629. }
  630. }
  631. }
  632. /**
  633. * Gets the fatal error handlers.
  634. *
  635. * Override this method if you want to define more fatal error handlers.
  636. *
  637. * @return FatalErrorHandlerInterface[] An array of FatalErrorHandlerInterface
  638. */
  639. protected function getFatalErrorHandlers()
  640. {
  641. return array(
  642. new UndefinedFunctionFatalErrorHandler(),
  643. new UndefinedMethodFatalErrorHandler(),
  644. new ClassNotFoundFatalErrorHandler(),
  645. );
  646. }
  647. /**
  648. * Sets the level at which the conversion to Exception is done.
  649. *
  650. * @param int|null $level The level (null to use the error_reporting() value and 0 to disable)
  651. *
  652. * @deprecated since version 2.6, to be removed in 3.0. Use throwAt() instead.
  653. */
  654. public function setLevel($level)
  655. {
  656. @trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in 3.0. Use the throwAt() method instead.', E_USER_DEPRECATED);
  657. $level = null === $level ? error_reporting() : $level;
  658. $this->throwAt($level, true);
  659. }
  660. /**
  661. * Sets the display_errors flag value.
  662. *
  663. * @param int $displayErrors The display_errors flag value
  664. *
  665. * @deprecated since version 2.6, to be removed in 3.0. Use throwAt() instead.
  666. */
  667. public function setDisplayErrors($displayErrors)
  668. {
  669. @trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in 3.0. Use the throwAt() method instead.', E_USER_DEPRECATED);
  670. if ($displayErrors) {
  671. $this->throwAt($this->displayErrors, true);
  672. } else {
  673. $displayErrors = $this->displayErrors;
  674. $this->throwAt(0, true);
  675. $this->displayErrors = $displayErrors;
  676. }
  677. }
  678. /**
  679. * Sets a logger for the given channel.
  680. *
  681. * @param LoggerInterface $logger A logger interface
  682. * @param string $channel The channel associated with the logger (deprecation, emergency or scream)
  683. *
  684. * @deprecated since version 2.6, to be removed in 3.0. Use setLoggers() or setDefaultLogger() instead.
  685. */
  686. public static function setLogger(LoggerInterface $logger, $channel = 'deprecation')
  687. {
  688. @trigger_error('The '.__METHOD__.' static method is deprecated since version 2.6 and will be removed in 3.0. Use the setLoggers() or setDefaultLogger() methods instead.', E_USER_DEPRECATED);
  689. $handler = set_error_handler('var_dump');
  690. $handler = is_array($handler) ? $handler[0] : null;
  691. restore_error_handler();
  692. if (!$handler instanceof self) {
  693. return;
  694. }
  695. if ('deprecation' === $channel) {
  696. $handler->setDefaultLogger($logger, E_DEPRECATED | E_USER_DEPRECATED, true);
  697. $handler->screamAt(E_DEPRECATED | E_USER_DEPRECATED);
  698. } elseif ('scream' === $channel) {
  699. $handler->setDefaultLogger($logger, E_ALL | E_STRICT, false);
  700. $handler->screamAt(E_ALL | E_STRICT);
  701. } elseif ('emergency' === $channel) {
  702. $handler->setDefaultLogger($logger, E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR, true);
  703. $handler->screamAt(E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR);
  704. }
  705. }
  706. /**
  707. * @deprecated since version 2.6, to be removed in 3.0. Use handleError() instead.
  708. */
  709. public function handle($level, $message, $file = 'unknown', $line = 0, $context = array())
  710. {
  711. $this->handleError(E_USER_DEPRECATED, 'The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in 3.0. Use the handleError() method instead.', __FILE__, __LINE__, array());
  712. return $this->handleError($level, $message, $file, $line, (array) $context);
  713. }
  714. /**
  715. * Handles PHP fatal errors.
  716. *
  717. * @deprecated since version 2.6, to be removed in 3.0. Use handleFatalError() instead.
  718. */
  719. public function handleFatal()
  720. {
  721. @trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in 3.0. Use the handleFatalError() method instead.', E_USER_DEPRECATED);
  722. static::handleFatalError();
  723. }
  724. }
  725. /**
  726. * Private class used to work around https://bugs.php.net/54275.
  727. *
  728. * @author Nicolas Grekas <p@tchwork.com>
  729. *
  730. * @internal
  731. */
  732. class ErrorHandlerCanary
  733. {
  734. private static $displayErrors = null;
  735. public function __construct()
  736. {
  737. if (null === self::$displayErrors) {
  738. self::$displayErrors = ini_set('display_errors', 1);
  739. }
  740. }
  741. public function __destruct()
  742. {
  743. if (null !== self::$displayErrors) {
  744. ini_set('display_errors', self::$displayErrors);
  745. self::$displayErrors = null;
  746. }
  747. }
  748. }