MediaWiki  master
MWExceptionHandler.php
Go to the documentation of this file.
1 <?php
22 
28 
32  protected static $reservedMemory;
36  protected static $fatalErrorTypes = [
37  E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR,
38  /* HHVM's FATAL_ERROR level */ 16777217,
39  ];
43  protected static $handledFatalCallback = false;
44 
48  public static function installHandler() {
49  set_exception_handler( 'MWExceptionHandler::handleException' );
50  set_error_handler( 'MWExceptionHandler::handleError' );
51 
52  // Reserve 16k of memory so we can report OOM fatals
53  self::$reservedMemory = str_repeat( ' ', 16384 );
54  register_shutdown_function( 'MWExceptionHandler::handleFatalError' );
55  }
56 
61  protected static function report( $e ) {
63 
64  $cmdLine = MWException::isCommandLine();
65 
66  if ( $e instanceof MWException ) {
67  try {
68  // Try and show the exception prettily, with the normal skin infrastructure
69  $e->report();
70  } catch ( Exception $e2 ) {
71  // Exception occurred from within exception handler
72  // Show a simpler message for the original exception,
73  // don't try to invoke report()
74  $message = "MediaWiki internal error.\n\n";
75 
76  if ( $wgShowExceptionDetails ) {
77  $message .= 'Original exception: ' . self::getLogMessage( $e ) .
78  "\nBacktrace:\n" . self::getRedactedTraceAsString( $e ) .
79  "\n\nException caught inside exception handler: " . self::getLogMessage( $e2 ) .
80  "\nBacktrace:\n" . self::getRedactedTraceAsString( $e2 );
81  } else {
82  $message .= "Exception caught inside exception handler.\n\n" .
83  "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
84  "to show detailed debugging information.";
85  }
86 
87  $message .= "\n";
88 
89  if ( $cmdLine ) {
90  self::printError( $message );
91  } else {
92  echo nl2br( htmlspecialchars( $message ) ) . "\n";
93  }
94  }
95  } else {
96  if ( !$wgShowExceptionDetails ) {
97  $message = self::getPublicLogMessage( $e );
98  } else {
99  $message = self::getLogMessage( $e ) .
100  "\nBacktrace:\n" .
101  self::getRedactedTraceAsString( $e ) . "\n";
102  }
103 
104  if ( $cmdLine ) {
105  self::printError( $message );
106  } else {
107  echo nl2br( htmlspecialchars( $message ) ) . "\n";
108  }
109 
110  }
111  }
112 
119  public static function printError( $message ) {
120  # NOTE: STDERR may not be available, especially if php-cgi is used from the
121  # command line (bug #15602). Try to produce meaningful output anyway. Using
122  # echo may corrupt output to STDOUT though.
123  if ( defined( 'STDERR' ) ) {
124  fwrite( STDERR, $message );
125  } else {
126  echo $message;
127  }
128  }
129 
138  public static function rollbackMasterChangesAndLog( $e ) {
140  if ( $factory->hasMasterChanges() ) {
141  $logger = LoggerFactory::getInstance( 'Bug56269' );
142  $logger->warning(
143  'Exception thrown with an uncommited database transaction: ' .
144  self::getLogMessage( $e ),
145  self::getLogContext( $e )
146  );
147  $factory->rollbackMasterChanges( __METHOD__ );
148  }
149  }
150 
165  public static function handleException( $e ) {
166  try {
167  // Rollback DBs to avoid transaction notices. This may fail
168  // to rollback some DB due to connection issues or exceptions.
169  // However, any sane DB driver will rollback implicitly anyway.
170  self::rollbackMasterChangesAndLog( $e );
171  } catch ( DBError $e2 ) {
172  // If the DB is unreacheable, rollback() will throw an error
173  // and the error report() method might need messages from the DB,
174  // which would result in an exception loop. PHP may escalate such
175  // errors to "Exception thrown without a stack frame" fatals, but
176  // it's better to be explicit here.
177  self::logException( $e2 );
178  }
179 
180  self::logException( $e );
181  self::report( $e );
182 
183  // Exit value should be nonzero for the benefit of shell jobs
184  exit( 1 );
185  }
186 
205  public static function handleError(
206  $level, $message, $file = null, $line = null
207  ) {
208  if ( in_array( $level, self::$fatalErrorTypes ) ) {
209  return call_user_func_array(
210  'MWExceptionHandler::handleFatalError', func_get_args()
211  );
212  }
213 
214  // Map error constant to error name (reverse-engineer PHP error
215  // reporting)
216  switch ( $level ) {
217  case E_RECOVERABLE_ERROR:
218  $levelName = 'Error';
219  break;
220  case E_WARNING:
221  case E_CORE_WARNING:
222  case E_COMPILE_WARNING:
223  case E_USER_WARNING:
224  $levelName = 'Warning';
225  break;
226  case E_NOTICE:
227  case E_USER_NOTICE:
228  $levelName = 'Notice';
229  break;
230  case E_STRICT:
231  $levelName = 'Strict Standards';
232  break;
233  case E_DEPRECATED:
234  case E_USER_DEPRECATED:
235  $levelName = 'Deprecated';
236  break;
237  default:
238  $levelName = 'Unknown error';
239  break;
240  }
241 
242  $e = new ErrorException( "PHP $levelName: $message", 0, $level, $file, $line );
243  self::logError( $e, 'error' );
244 
245  // This handler is for logging only. Return false will instruct PHP
246  // to continue regular handling.
247  return false;
248  }
249 
271  public static function handleFatalError(
272  $level = null, $message = null, $file = null, $line = null,
273  $context = null, $trace = null
274  ) {
275  // Free reserved memory so that we have space to process OOM
276  // errors
277  self::$reservedMemory = null;
278 
279  if ( $level === null ) {
280  // Called as a shutdown handler, get data from error_get_last()
281  if ( static::$handledFatalCallback ) {
282  // Already called once (probably as an error handler callback
283  // under HHVM) so don't log again.
284  return false;
285  }
286 
287  $lastError = error_get_last();
288  if ( $lastError !== null ) {
289  $level = $lastError['type'];
290  $message = $lastError['message'];
291  $file = $lastError['file'];
292  $line = $lastError['line'];
293  } else {
294  $level = 0;
295  $message = '';
296  }
297  }
298 
299  if ( !in_array( $level, self::$fatalErrorTypes ) ) {
300  // Only interested in fatal errors, others should have been
301  // handled by MWExceptionHandler::handleError
302  return false;
303  }
304 
305  $msg = "[{exception_id}] PHP Fatal Error: {$message}";
306 
307  // Look at message to see if this is a class not found failure
308  // HHVM: Class undefined: foo
309  // PHP5: Class 'foo' not found
310  if ( preg_match( "/Class (undefined: \w+|'\w+' not found)/", $msg ) ) {
311  // @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
312  $msg = <<<TXT
313 {$msg}
314 
315 MediaWiki or an installed extension requires this class but it is not embedded directly in MediaWiki's git repository and must be installed separately by the end user.
316 
317 Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git#Fetch_external_libraries">mediawiki.org</a> for help on installing the required components.
318 TXT;
319  // @codingStandardsIgnoreEnd
320  }
321 
322  // We can't just create an exception and log it as it is likely that
323  // the interpreter has unwound the stack already. If that is true the
324  // stacktrace we would get would be functionally empty. If however we
325  // have been called as an error handler callback *and* HHVM is in use
326  // we will have been provided with a useful stacktrace that we can
327  // log.
328  $trace = $trace ?: debug_backtrace();
329  $logger = LoggerFactory::getInstance( 'fatal' );
330  $logger->error( $msg, [
331  'exception' => [
332  'class' => 'ErrorException',
333  'message' => "PHP Fatal Error: {$message}",
334  'code' => $level,
335  'file' => $file,
336  'line' => $line,
337  'trace' => static::redactTrace( $trace ),
338  ],
339  'exception_id' => wfRandomString( 8 ),
340  ] );
341 
342  // Remember call so we don't double process via HHVM's fatal
343  // notifications and the shutdown hook behavior
344  static::$handledFatalCallback = true;
345  return false;
346  }
347 
358  public static function getRedactedTraceAsString( $e ) {
359  return self::prettyPrintTrace( self::getRedactedTrace( $e ) );
360  }
361 
370  public static function prettyPrintTrace( array $trace, $pad = '' ) {
371  $text = '';
372 
373  $level = 0;
374  foreach ( $trace as $level => $frame ) {
375  if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
376  $text .= "{$pad}#{$level} {$frame['file']}({$frame['line']}): ";
377  } else {
378  // 'file' and 'line' are unset for calls via call_user_func
379  // (bug 55634) This matches behaviour of
380  // Exception::getTraceAsString to instead display "[internal
381  // function]".
382  $text .= "{$pad}#{$level} [internal function]: ";
383  }
384 
385  if ( isset( $frame['class'] ) && isset( $frame['type'] ) && isset( $frame['function'] ) ) {
386  $text .= $frame['class'] . $frame['type'] . $frame['function'];
387  } elseif ( isset( $frame['function'] ) ) {
388  $text .= $frame['function'];
389  } else {
390  $text .= 'NO_FUNCTION_GIVEN';
391  }
392 
393  if ( isset( $frame['args'] ) ) {
394  $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
395  } else {
396  $text .= "()\n";
397  }
398  }
399 
400  $level = $level + 1;
401  $text .= "{$pad}#{$level} {main}";
402 
403  return $text;
404  }
405 
417  public static function getRedactedTrace( $e ) {
418  return static::redactTrace( $e->getTrace() );
419  }
420 
431  public static function redactTrace( array $trace ) {
432  return array_map( function ( $frame ) {
433  if ( isset( $frame['args'] ) ) {
434  $frame['args'] = array_map( function ( $arg ) {
435  return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
436  }, $frame['args'] );
437  }
438  return $frame;
439  }, $trace );
440  }
441 
453  public static function getLogId( $e ) {
454  wfDeprecated( __METHOD__, '1.27' );
455  return WebRequest::getRequestId();
456  }
457 
465  public static function getURL() {
467  if ( !isset( $wgRequest ) || $wgRequest instanceof FauxRequest ) {
468  return false;
469  }
470  return $wgRequest->getRequestURL();
471  }
472 
480  public static function getLogMessage( $e ) {
481  $id = WebRequest::getRequestId();
482  $type = get_class( $e );
483  $file = $e->getFile();
484  $line = $e->getLine();
485  $message = $e->getMessage();
486  $url = self::getURL() ?: '[no req]';
487 
488  return "[$id] $url $type from line $line of $file: $message";
489  }
490 
495  public static function getPublicLogMessage( $e ) {
496  $reqId = WebRequest::getRequestId();
497  $type = get_class( $e );
498  return '[' . $reqId . '] '
499  . gmdate( 'Y-m-d H:i:s' ) . ': '
500  . 'Fatal exception of type "' . $type . '"';
501  }
502 
513  public static function getLogContext( $e ) {
514  return [
515  'exception' => $e,
516  'exception_id' => WebRequest::getRequestId(),
517  ];
518  }
519 
531  public static function getStructuredExceptionData( $e ) {
533  $data = [
534  'id' => WebRequest::getRequestId(),
535  'type' => get_class( $e ),
536  'file' => $e->getFile(),
537  'line' => $e->getLine(),
538  'message' => $e->getMessage(),
539  'code' => $e->getCode(),
540  'url' => self::getURL() ?: null,
541  ];
542 
543  if ( $e instanceof ErrorException &&
544  ( error_reporting() & $e->getSeverity() ) === 0
545  ) {
546  // Flag surpressed errors
547  $data['suppressed'] = true;
548  }
549 
550  if ( $wgLogExceptionBacktrace ) {
551  $data['backtrace'] = self::getRedactedTrace( $e );
552  }
553 
554  $previous = $e->getPrevious();
555  if ( $previous !== null ) {
556  $data['previous'] = self::getStructuredExceptionData( $previous );
557  }
558 
559  return $data;
560  }
561 
615  public static function jsonSerializeException( $e, $pretty = false, $escaping = 0 ) {
616  $data = self::getStructuredExceptionData( $e );
617  return FormatJson::encode( $data, $pretty, $escaping );
618  }
619 
629  public static function logException( $e ) {
630  if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
631  $logger = LoggerFactory::getInstance( 'exception' );
632  $logger->error(
633  self::getLogMessage( $e ),
634  self::getLogContext( $e )
635  );
636 
637  $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
638  if ( $json !== false ) {
639  $logger = LoggerFactory::getInstance( 'exception-json' );
640  $logger->error( $json, [ 'private' => true ] );
641  }
642 
643  Hooks::run( 'LogException', [ $e, false ] );
644  }
645  }
646 
654  protected static function logError( ErrorException $e, $channel ) {
655  // The set_error_handler callback is independent from error_reporting.
656  // Filter out unwanted errors manually (e.g. when
657  // MediaWiki\suppressWarnings is active).
658  $suppressed = ( error_reporting() & $e->getSeverity() ) === 0;
659  if ( !$suppressed ) {
660  $logger = LoggerFactory::getInstance( $channel );
661  $logger->error(
662  self::getLogMessage( $e ),
663  self::getLogContext( $e )
664  );
665  }
666 
667  // Include all errors in the json log (surpressed errors will be flagged)
668  $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
669  if ( $json !== false ) {
670  $logger = LoggerFactory::getInstance( "{$channel}-json" );
671  $logger->error( $json, [ 'private' => true ] );
672  }
673 
674  Hooks::run( 'LogException', [ $e, $suppressed ] );
675  }
676 }
$wgLogExceptionBacktrace
If true, send the exception backtrace to the error log.
static printError($message)
Print a message, if possible to STDERR.
static getStructuredExceptionData($e)
Get a structured representation of an Exception.
static handleFatalError($level=null, $message=null, $file=null, $line=null, $context=null, $trace=null)
Dual purpose callback used as both a set_error_handler() callback and a registered shutdown function...
Database error base class.
the array() calling protocol came about after MediaWiki 1.4rc1.
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:268
static getLogMessage($e)
Get a message formatting the exception message and its origin.
$context
Definition: load.php:43
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1980
static handleError($level, $message, $file=null, $line=null)
Handler for set_error_handler() callback notifications.
const ALL_OK
Skip escaping as many characters as reasonably possible.
Definition: FormatJson.php:55
Handler class for MWExceptions.
The MediaWiki class is the helper class for the index.php entry point.
Definition: MediaWiki.php:28
$wgShowExceptionDetails
If set to true, uncaught exceptions will print a complete stack trace to output.
static handleException($e)
Exception handler which simulates the appropriate catch() handling:
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
wfRandomString($length=32)
Get a random string containing a number of pseudo-random hex characters.
static logError(ErrorException $e, $channel)
Log an exception that wasn't thrown but made to wrap an error.
$factory
MediaWiki exception.
Definition: MWException.php:26
static encode($value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:127
static getURL()
If the exception occurred in the course of responding to a request, returns the requested URL...
wfDeprecated($function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
static redactTrace(array $trace)
Redact a stacktrace generated by Exception::getTrace(), debug_backtrace() or similar means...
static getRedactedTraceAsString($e)
Generate a string representation of an exception's stack trace.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
static isCommandLine()
Check whether we are in command line mode or not to report the exception in the correct format...
static rollbackMasterChangesAndLog($e)
If there are any open database transactions, roll them back and log the stack trace of the exception ...
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
wfGetLBFactory()
Get the load balancer factory object.
static installHandler()
Install handlers with PHP.
static getLogContext($e)
Get a PSR-3 log event context from an Exception.
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:33
$line
Definition: cdb.php:59
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method.MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances.The"Spi"in MediaWiki\Logger\Spi stands for"service provider interface".An SPI is an API intended to be implemented or extended by a third party.This software design pattern is intended to enable framework extension and replaceable components.It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki.The service provider interface allows the backend logging library to be implemented in multiple ways.The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime.This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance.Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going on
Definition: hooks.txt:86
static jsonSerializeException($e, $pretty=false, $escaping=0)
Serialize an Exception object to JSON.
static getRedactedTrace($e)
Return a copy of an exception's backtrace as an array.
static prettyPrintTrace(array $trace, $pad= '')
Generate a string representation of a stacktrace.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging a wrapping ErrorException $suppressed
Definition: hooks.txt:1980
static logException($e)
Log an exception to the exception log (if enabled).
static report($e)
Report an exception to the user.
static getLogId($e)
Get the ID for this exception.
if(is_null($wgLocalTZoffset)) if(!$wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:663
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2376