XdebugHandler.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. <?php
  2. /*
  3. * This file is part of composer/xdebug-handler.
  4. *
  5. * (c) Composer <https://github.com/composer>
  6. *
  7. * For the full copyright and license information, please view
  8. * the LICENSE file that was distributed with this source code.
  9. */
  10. declare(strict_types=1);
  11. namespace Composer\XdebugHandler;
  12. use Composer\Pcre\Preg;
  13. use Psr\Log\LoggerInterface;
  14. /**
  15. * @author John Stevenson <john-stevenson@blueyonder.co.uk>
  16. *
  17. * @phpstan-import-type restartData from PhpConfig
  18. */
  19. class XdebugHandler
  20. {
  21. const SUFFIX_ALLOW = '_ALLOW_XDEBUG';
  22. const SUFFIX_INIS = '_ORIGINAL_INIS';
  23. const RESTART_ID = 'internal';
  24. const RESTART_SETTINGS = 'XDEBUG_HANDLER_SETTINGS';
  25. const DEBUG = 'XDEBUG_HANDLER_DEBUG';
  26. /** @var string|null */
  27. protected $tmpIni;
  28. /** @var bool */
  29. private static $inRestart;
  30. /** @var string */
  31. private static $name;
  32. /** @var string|null */
  33. private static $skipped;
  34. /** @var bool */
  35. private static $xdebugActive;
  36. /** @var string|null */
  37. private static $xdebugMode;
  38. /** @var string|null */
  39. private static $xdebugVersion;
  40. /** @var bool */
  41. private $cli;
  42. /** @var string|null */
  43. private $debug;
  44. /** @var string */
  45. private $envAllowXdebug;
  46. /** @var string */
  47. private $envOriginalInis;
  48. /** @var bool */
  49. private $persistent;
  50. /** @var string|null */
  51. private $script;
  52. /** @var Status */
  53. private $statusWriter;
  54. /**
  55. * Constructor
  56. *
  57. * The $envPrefix is used to create distinct environment variables. It is
  58. * uppercased and prepended to the default base values. For example 'myapp'
  59. * would result in MYAPP_ALLOW_XDEBUG and MYAPP_ORIGINAL_INIS.
  60. *
  61. * @param string $envPrefix Value used in environment variables
  62. * @throws \RuntimeException If the parameter is invalid
  63. */
  64. public function __construct(string $envPrefix)
  65. {
  66. if ($envPrefix === '') {
  67. throw new \RuntimeException('Invalid constructor parameter');
  68. }
  69. self::$name = strtoupper($envPrefix);
  70. $this->envAllowXdebug = self::$name.self::SUFFIX_ALLOW;
  71. $this->envOriginalInis = self::$name.self::SUFFIX_INIS;
  72. self::setXdebugDetails();
  73. self::$inRestart = false;
  74. if ($this->cli = PHP_SAPI === 'cli') {
  75. $this->debug = (string) getenv(self::DEBUG);
  76. }
  77. $this->statusWriter = new Status($this->envAllowXdebug, (bool) $this->debug);
  78. }
  79. /**
  80. * Activates status message output to a PSR3 logger
  81. */
  82. public function setLogger(LoggerInterface $logger): self
  83. {
  84. $this->statusWriter->setLogger($logger);
  85. return $this;
  86. }
  87. /**
  88. * Sets the main script location if it cannot be called from argv
  89. */
  90. public function setMainScript(string $script): self
  91. {
  92. $this->script = $script;
  93. return $this;
  94. }
  95. /**
  96. * Persist the settings to keep Xdebug out of sub-processes
  97. */
  98. public function setPersistent(): self
  99. {
  100. $this->persistent = true;
  101. return $this;
  102. }
  103. /**
  104. * Checks if Xdebug is loaded and the process needs to be restarted
  105. *
  106. * This behaviour can be disabled by setting the MYAPP_ALLOW_XDEBUG
  107. * environment variable to 1. This variable is used internally so that
  108. * the restarted process is created only once.
  109. */
  110. public function check(): void
  111. {
  112. $this->notify(Status::CHECK, self::$xdebugVersion.'|'.self::$xdebugMode);
  113. $envArgs = explode('|', (string) getenv($this->envAllowXdebug));
  114. if (!((bool) $envArgs[0]) && $this->requiresRestart(self::$xdebugActive)) {
  115. // Restart required
  116. $this->notify(Status::RESTART);
  117. if ($this->prepareRestart()) {
  118. $command = $this->getCommand();
  119. $this->restart($command);
  120. }
  121. return;
  122. }
  123. if (self::RESTART_ID === $envArgs[0] && count($envArgs) === 5) {
  124. // Restarted, so unset environment variable and use saved values
  125. $this->notify(Status::RESTARTED);
  126. Process::setEnv($this->envAllowXdebug);
  127. self::$inRestart = true;
  128. if (self::$xdebugVersion === null) {
  129. // Skipped version is only set if Xdebug is not loaded
  130. self::$skipped = $envArgs[1];
  131. }
  132. $this->tryEnableSignals();
  133. // Put restart settings in the environment
  134. $this->setEnvRestartSettings($envArgs);
  135. return;
  136. }
  137. $this->notify(Status::NORESTART);
  138. $settings = self::getRestartSettings();
  139. if ($settings !== null) {
  140. // Called with existing settings, so sync our settings
  141. $this->syncSettings($settings);
  142. }
  143. }
  144. /**
  145. * Returns an array of php.ini locations with at least one entry
  146. *
  147. * The equivalent of calling php_ini_loaded_file then php_ini_scanned_files.
  148. * The loaded ini location is the first entry and may be empty.
  149. *
  150. * @return string[]
  151. */
  152. public static function getAllIniFiles(): array
  153. {
  154. if (self::$name !== null) {
  155. $env = getenv(self::$name.self::SUFFIX_INIS);
  156. if (false !== $env) {
  157. return explode(PATH_SEPARATOR, $env);
  158. }
  159. }
  160. $paths = [(string) php_ini_loaded_file()];
  161. $scanned = php_ini_scanned_files();
  162. if ($scanned !== false) {
  163. $paths = array_merge($paths, array_map('trim', explode(',', $scanned)));
  164. }
  165. return $paths;
  166. }
  167. /**
  168. * Returns an array of restart settings or null
  169. *
  170. * Settings will be available if the current process was restarted, or
  171. * called with the settings from an existing restart.
  172. *
  173. * @phpstan-return restartData|null
  174. */
  175. public static function getRestartSettings(): ?array
  176. {
  177. $envArgs = explode('|', (string) getenv(self::RESTART_SETTINGS));
  178. if (count($envArgs) !== 6
  179. || (!self::$inRestart && php_ini_loaded_file() !== $envArgs[0])) {
  180. return null;
  181. }
  182. return [
  183. 'tmpIni' => $envArgs[0],
  184. 'scannedInis' => (bool) $envArgs[1],
  185. 'scanDir' => '*' === $envArgs[2] ? false : $envArgs[2],
  186. 'phprc' => '*' === $envArgs[3] ? false : $envArgs[3],
  187. 'inis' => explode(PATH_SEPARATOR, $envArgs[4]),
  188. 'skipped' => $envArgs[5],
  189. ];
  190. }
  191. /**
  192. * Returns the Xdebug version that triggered a successful restart
  193. */
  194. public static function getSkippedVersion(): string
  195. {
  196. return (string) self::$skipped;
  197. }
  198. /**
  199. * Returns whether Xdebug is loaded and active
  200. *
  201. * true: if Xdebug is loaded and is running in an active mode.
  202. * false: if Xdebug is not loaded, or it is running with xdebug.mode=off.
  203. */
  204. public static function isXdebugActive(): bool
  205. {
  206. self::setXdebugDetails();
  207. return self::$xdebugActive;
  208. }
  209. /**
  210. * Allows an extending class to decide if there should be a restart
  211. *
  212. * The default is to restart if Xdebug is loaded and its mode is not "off".
  213. */
  214. protected function requiresRestart(bool $default): bool
  215. {
  216. return $default;
  217. }
  218. /**
  219. * Allows an extending class to access the tmpIni
  220. *
  221. * @param string[] $command *
  222. */
  223. protected function restart(array $command): void
  224. {
  225. $this->doRestart($command);
  226. }
  227. /**
  228. * Executes the restarted command then deletes the tmp ini
  229. *
  230. * @param string[] $command
  231. * @phpstan-return never
  232. */
  233. private function doRestart(array $command): void
  234. {
  235. $this->tryEnableSignals();
  236. $this->notify(Status::RESTARTING, implode(' ', $command));
  237. if (PHP_VERSION_ID >= 70400) {
  238. $cmd = $command;
  239. } else {
  240. $cmd = Process::escapeShellCommand($command);
  241. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  242. // Outer quotes required on cmd string below PHP 8
  243. $cmd = '"'.$cmd.'"';
  244. }
  245. }
  246. $process = proc_open($cmd, [], $pipes);
  247. if (is_resource($process)) {
  248. $exitCode = proc_close($process);
  249. }
  250. if (!isset($exitCode)) {
  251. // Unlikely that php or the default shell cannot be invoked
  252. $this->notify(Status::ERROR, 'Unable to restart process');
  253. $exitCode = -1;
  254. } else {
  255. $this->notify(Status::INFO, 'Restarted process exited '.$exitCode);
  256. }
  257. if ($this->debug === '2') {
  258. $this->notify(Status::INFO, 'Temp ini saved: '.$this->tmpIni);
  259. } else {
  260. @unlink((string) $this->tmpIni);
  261. }
  262. exit($exitCode);
  263. }
  264. /**
  265. * Returns true if everything was written for the restart
  266. *
  267. * If any of the following fails (however unlikely) we must return false to
  268. * stop potential recursion:
  269. * - tmp ini file creation
  270. * - environment variable creation
  271. */
  272. private function prepareRestart(): bool
  273. {
  274. $error = null;
  275. $iniFiles = self::getAllIniFiles();
  276. $scannedInis = count($iniFiles) > 1;
  277. $tmpDir = sys_get_temp_dir();
  278. if (!$this->cli) {
  279. $error = 'Unsupported SAPI: '.PHP_SAPI;
  280. } elseif (!$this->checkConfiguration($info)) {
  281. $error = $info;
  282. } elseif (!$this->checkMainScript()) {
  283. $error = 'Unable to access main script: '.$this->script;
  284. } elseif (!$this->writeTmpIni($iniFiles, $tmpDir, $error)) {
  285. $error = $error !== null ? $error : 'Unable to create temp ini file at: '.$tmpDir;
  286. } elseif (!$this->setEnvironment($scannedInis, $iniFiles)) {
  287. $error = 'Unable to set environment variables';
  288. }
  289. if ($error !== null) {
  290. $this->notify(Status::ERROR, $error);
  291. }
  292. return $error === null;
  293. }
  294. /**
  295. * Returns true if the tmp ini file was written
  296. *
  297. * @param string[] $iniFiles All ini files used in the current process
  298. */
  299. private function writeTmpIni(array $iniFiles, string $tmpDir, ?string &$error): bool
  300. {
  301. if (($tmpfile = @tempnam($tmpDir, '')) === false) {
  302. return false;
  303. }
  304. $this->tmpIni = $tmpfile;
  305. // $iniFiles has at least one item and it may be empty
  306. if ($iniFiles[0] === '') {
  307. array_shift($iniFiles);
  308. }
  309. $content = '';
  310. $sectionRegex = '/^\s*\[(?:PATH|HOST)\s*=/mi';
  311. $xdebugRegex = '/^\s*(zend_extension\s*=.*xdebug.*)$/mi';
  312. foreach ($iniFiles as $file) {
  313. // Check for inaccessible ini files
  314. if (($data = @file_get_contents($file)) === false) {
  315. $error = 'Unable to read ini: '.$file;
  316. return false;
  317. }
  318. // Check and remove directives after HOST and PATH sections
  319. if (Preg::isMatchWithOffsets($sectionRegex, $data, $matches, PREG_OFFSET_CAPTURE)) {
  320. $data = substr($data, 0, $matches[0][1]);
  321. }
  322. $content .= Preg::replace($xdebugRegex, ';$1', $data).PHP_EOL;
  323. }
  324. // Merge loaded settings into our ini content, if it is valid
  325. $config = parse_ini_string($content);
  326. $loaded = ini_get_all(null, false);
  327. if (false === $config || false === $loaded) {
  328. $error = 'Unable to parse ini data';
  329. return false;
  330. }
  331. $content .= $this->mergeLoadedConfig($loaded, $config);
  332. // Work-around for https://bugs.php.net/bug.php?id=75932
  333. $content .= 'opcache.enable_cli=0'.PHP_EOL;
  334. return (bool) @file_put_contents($this->tmpIni, $content);
  335. }
  336. /**
  337. * Returns the command line arguments for the restart
  338. *
  339. * @return string[]
  340. */
  341. private function getCommand(): array
  342. {
  343. $php = [PHP_BINARY];
  344. $args = array_slice($_SERVER['argv'], 1);
  345. if (!$this->persistent) {
  346. // Use command-line options
  347. array_push($php, '-n', '-c', $this->tmpIni);
  348. }
  349. return array_merge($php, [$this->script], $args);
  350. }
  351. /**
  352. * Returns true if the restart environment variables were set
  353. *
  354. * No need to update $_SERVER since this is set in the restarted process.
  355. *
  356. * @param string[] $iniFiles All ini files used in the current process
  357. */
  358. private function setEnvironment(bool $scannedInis, array $iniFiles): bool
  359. {
  360. $scanDir = getenv('PHP_INI_SCAN_DIR');
  361. $phprc = getenv('PHPRC');
  362. // Make original inis available to restarted process
  363. if (!putenv($this->envOriginalInis.'='.implode(PATH_SEPARATOR, $iniFiles))) {
  364. return false;
  365. }
  366. if ($this->persistent) {
  367. // Use the environment to persist the settings
  368. if (!putenv('PHP_INI_SCAN_DIR=') || !putenv('PHPRC='.$this->tmpIni)) {
  369. return false;
  370. }
  371. }
  372. // Flag restarted process and save values for it to use
  373. $envArgs = [
  374. self::RESTART_ID,
  375. self::$xdebugVersion,
  376. (int) $scannedInis,
  377. false === $scanDir ? '*' : $scanDir,
  378. false === $phprc ? '*' : $phprc,
  379. ];
  380. return putenv($this->envAllowXdebug.'='.implode('|', $envArgs));
  381. }
  382. /**
  383. * Logs status messages
  384. */
  385. private function notify(string $op, ?string $data = null): void
  386. {
  387. $this->statusWriter->report($op, $data);
  388. }
  389. /**
  390. * Returns default, changed and command-line ini settings
  391. *
  392. * @param mixed[] $loadedConfig All current ini settings
  393. * @param mixed[] $iniConfig Settings from user ini files
  394. *
  395. */
  396. private function mergeLoadedConfig(array $loadedConfig, array $iniConfig): string
  397. {
  398. $content = '';
  399. foreach ($loadedConfig as $name => $value) {
  400. // Value will either be null, string or array (HHVM only)
  401. if (!is_string($value)
  402. || strpos($name, 'xdebug') === 0
  403. || $name === 'apc.mmap_file_mask') {
  404. continue;
  405. }
  406. if (!isset($iniConfig[$name]) || $iniConfig[$name] !== $value) {
  407. // Double-quote escape each value
  408. $content .= $name.'="'.addcslashes($value, '\\"').'"'.PHP_EOL;
  409. }
  410. }
  411. return $content;
  412. }
  413. /**
  414. * Returns true if the script name can be used
  415. */
  416. private function checkMainScript(): bool
  417. {
  418. if ($this->script !== null) {
  419. // Allow an application to set -- for standard input
  420. return file_exists($this->script) || '--' === $this->script;
  421. }
  422. if (file_exists($this->script = $_SERVER['argv'][0])) {
  423. return true;
  424. }
  425. // Use a backtrace to resolve Phar and chdir issues.
  426. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  427. $main = end($trace);
  428. if ($main !== false && isset($main['file'])) {
  429. return file_exists($this->script = $main['file']);
  430. }
  431. return false;
  432. }
  433. /**
  434. * Adds restart settings to the environment
  435. *
  436. * @param string[] $envArgs
  437. */
  438. private function setEnvRestartSettings(array $envArgs): void
  439. {
  440. $settings = [
  441. php_ini_loaded_file(),
  442. $envArgs[2],
  443. $envArgs[3],
  444. $envArgs[4],
  445. getenv($this->envOriginalInis),
  446. self::$skipped,
  447. ];
  448. Process::setEnv(self::RESTART_SETTINGS, implode('|', $settings));
  449. }
  450. /**
  451. * Syncs settings and the environment if called with existing settings
  452. *
  453. * @phpstan-param restartData $settings
  454. */
  455. private function syncSettings(array $settings): void
  456. {
  457. if (false === getenv($this->envOriginalInis)) {
  458. // Called by another app, so make original inis available
  459. Process::setEnv($this->envOriginalInis, implode(PATH_SEPARATOR, $settings['inis']));
  460. }
  461. self::$skipped = $settings['skipped'];
  462. $this->notify(Status::INFO, 'Process called with existing restart settings');
  463. }
  464. /**
  465. * Returns true if there are no known configuration issues
  466. */
  467. private function checkConfiguration(?string &$info): bool
  468. {
  469. if (!function_exists('proc_open')) {
  470. $info = 'proc_open function is disabled';
  471. return false;
  472. }
  473. if (extension_loaded('uopz') && !((bool) ini_get('uopz.disable'))) {
  474. // uopz works at opcode level and disables exit calls
  475. if (function_exists('uopz_allow_exit')) {
  476. @uopz_allow_exit(true);
  477. } else {
  478. $info = 'uopz extension is not compatible';
  479. return false;
  480. }
  481. }
  482. // Check UNC paths when using cmd.exe
  483. if (defined('PHP_WINDOWS_VERSION_BUILD') && PHP_VERSION_ID < 70400) {
  484. $workingDir = getcwd();
  485. if ($workingDir === false) {
  486. $info = 'unable to determine working directory';
  487. return false;
  488. }
  489. if (0 === strpos($workingDir, '\\\\')) {
  490. $info = 'cmd.exe does not support UNC paths: '.$workingDir;
  491. return false;
  492. }
  493. }
  494. return true;
  495. }
  496. /**
  497. * Enables async signals and control interrupts in the restarted process
  498. *
  499. * Available on Unix PHP 7.1+ with the pcntl extension and Windows PHP 7.4+.
  500. */
  501. private function tryEnableSignals(): void
  502. {
  503. if (function_exists('pcntl_async_signals') && function_exists('pcntl_signal')) {
  504. pcntl_async_signals(true);
  505. $message = 'Async signals enabled';
  506. if (!self::$inRestart) {
  507. // Restarting, so ignore SIGINT in parent
  508. pcntl_signal(SIGINT, SIG_IGN);
  509. } elseif (is_int(pcntl_signal_get_handler(SIGINT))) {
  510. // Restarted, no handler set so force default action
  511. pcntl_signal(SIGINT, SIG_DFL);
  512. }
  513. }
  514. if (!self::$inRestart && function_exists('sapi_windows_set_ctrl_handler')) {
  515. // Restarting, so set a handler to ignore CTRL events in the parent.
  516. // This ensures that CTRL+C events will be available in the child
  517. // process without having to enable them there, which is unreliable.
  518. sapi_windows_set_ctrl_handler(function ($evt) {});
  519. }
  520. }
  521. /**
  522. * Sets static properties $xdebugActive, $xdebugVersion and $xdebugMode
  523. */
  524. private static function setXdebugDetails(): void
  525. {
  526. if (self::$xdebugActive !== null) {
  527. return;
  528. }
  529. self::$xdebugActive = false;
  530. if (!extension_loaded('xdebug')) {
  531. return;
  532. }
  533. $version = phpversion('xdebug');
  534. self::$xdebugVersion = $version !== false ? $version : 'unknown';
  535. if (version_compare(self::$xdebugVersion, '3.1', '>=')) {
  536. $modes = xdebug_info('mode');
  537. self::$xdebugMode = count($modes) === 0 ? 'off' : implode(',', $modes);
  538. self::$xdebugActive = self::$xdebugMode !== 'off';
  539. return;
  540. }
  541. // See if xdebug.mode is supported in this version
  542. $iniMode = ini_get('xdebug.mode');
  543. if ($iniMode === false) {
  544. self::$xdebugActive = true;
  545. return;
  546. }
  547. // Environment value wins but cannot be empty
  548. $envMode = (string) getenv('XDEBUG_MODE');
  549. if ($envMode !== '') {
  550. self::$xdebugMode = $envMode;
  551. } else {
  552. self::$xdebugMode = $iniMode !== '' ? $iniMode : 'off';
  553. }
  554. // An empty comma-separated list is treated as mode 'off'
  555. if (Preg::isMatch('/^,+$/', str_replace(' ', '', self::$xdebugMode))) {
  556. self::$xdebugMode = 'off';
  557. }
  558. self::$xdebugActive = self::$xdebugMode !== 'off';
  559. }
  560. }