XdebugHandler.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer;
  12. use Composer\Util\IniHelper;
  13. use Symfony\Component\Console\Output\OutputInterface;
  14. /**
  15. * @author John Stevenson <john-stevenson@blueyonder.co.uk>
  16. */
  17. class XdebugHandler
  18. {
  19. const ENV_ALLOW = 'COMPOSER_ALLOW_XDEBUG';
  20. const ENV_VERSION = 'COMPOSER_XDEBUG_VERSION';
  21. const RESTART_ID = 'internal';
  22. private $output;
  23. private $loaded;
  24. private $envScanDir;
  25. private $version;
  26. private $tmpIni;
  27. /**
  28. * Constructor
  29. */
  30. public function __construct(OutputInterface $output)
  31. {
  32. $this->output = $output;
  33. $this->loaded = extension_loaded('xdebug');
  34. $this->envScanDir = getenv('PHP_INI_SCAN_DIR');
  35. if ($this->loaded) {
  36. $ext = new \ReflectionExtension('xdebug');
  37. $this->version = strval($ext->getVersion());
  38. }
  39. }
  40. /**
  41. * Checks if xdebug is loaded and composer needs to be restarted
  42. *
  43. * If so, then a tmp ini is created with the xdebug ini entry commented out.
  44. * If additional inis have been loaded, these are combined into the tmp ini
  45. * and PHP_INI_SCAN_DIR is set to an empty value. Current ini locations are
  46. * are stored in COMPOSER_ORIGINAL_INIS, for use in the restarted process.
  47. *
  48. * This behaviour can be disabled by setting the COMPOSER_ALLOW_XDEBUG
  49. * environment variable to 1. This variable is used internally so that the
  50. * restarted process is created only once and PHP_INI_SCAN_DIR can be
  51. * restored to its original value.
  52. */
  53. public function check()
  54. {
  55. $args = explode('|', strval(getenv(self::ENV_ALLOW)), 2);
  56. if ($this->needsRestart($args[0])) {
  57. if ($this->prepareRestart()) {
  58. $command = $this->getCommand();
  59. $this->restart($command);
  60. }
  61. return;
  62. }
  63. // Restore environment variables if we are restarting
  64. if (self::RESTART_ID === $args[0]) {
  65. putenv(self::ENV_ALLOW);
  66. if (false !== $this->envScanDir) {
  67. // $args[1] contains the original value
  68. if (isset($args[1])) {
  69. putenv('PHP_INI_SCAN_DIR='.$args[1]);
  70. } else {
  71. putenv('PHP_INI_SCAN_DIR');
  72. }
  73. }
  74. // Clear version if the restart failed to disable xdebug
  75. if ($this->loaded) {
  76. putenv(self::ENV_VERSION);
  77. }
  78. }
  79. }
  80. /**
  81. * Executes the restarted command then deletes the tmp ini
  82. *
  83. * @param string $command
  84. */
  85. protected function restart($command)
  86. {
  87. passthru($command, $exitCode);
  88. if (!empty($this->tmpIni)) {
  89. @unlink($this->tmpIni);
  90. }
  91. exit($exitCode);
  92. }
  93. /**
  94. * Returns true if a restart is needed
  95. *
  96. * @param string $allow Environment value
  97. *
  98. * @return bool
  99. */
  100. private function needsRestart($allow)
  101. {
  102. if (PHP_SAPI !== 'cli' || !defined('PHP_BINARY')) {
  103. return false;
  104. }
  105. return empty($allow) && $this->loaded;
  106. }
  107. /**
  108. * Returns true if everything was written for the restart
  109. *
  110. * If any of the following fails (however unlikely) we must return false to
  111. * stop potential recursion:
  112. * - tmp ini file creation
  113. * - environment variable creation
  114. *
  115. * @return bool
  116. */
  117. private function prepareRestart()
  118. {
  119. $this->tmpIni = '';
  120. $iniPaths = IniHelper::getAll();
  121. $additional = count($iniPaths) > 1;
  122. if (empty($iniPaths[0])) {
  123. // There is no loaded ini
  124. array_shift($iniPaths);
  125. }
  126. if ($this->writeTmpIni($iniPaths)) {
  127. return $this->setEnvironment($additional, $iniPaths);
  128. }
  129. return false;
  130. }
  131. /**
  132. * Returns true if the tmp ini file was written
  133. *
  134. * The filename is passed as the -c option when the process restarts.
  135. *
  136. * @param array $iniFiles The php.ini locations
  137. *
  138. * @return bool
  139. */
  140. private function writeTmpIni(array $iniFiles)
  141. {
  142. if (!$this->tmpIni = tempnam(sys_get_temp_dir(), '')) {
  143. return false;
  144. }
  145. $content = '';
  146. $regex = '/^\s*(zend_extension\s*=.*xdebug.*)$/mi';
  147. foreach ($iniFiles as $file) {
  148. $data = preg_replace($regex, ';$1', file_get_contents($file));
  149. $content .= $data.PHP_EOL;
  150. }
  151. $content .= 'allow_url_fopen='.ini_get('allow_url_fopen').PHP_EOL;
  152. $content .= 'disable_functions="'.ini_get('disable_functions').'"'.PHP_EOL;
  153. $content .= 'memory_limit='.ini_get('memory_limit').PHP_EOL;
  154. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  155. // Work-around for PHP windows bug, see issue #6052
  156. $content .= 'opcache.enable_cli=0'.PHP_EOL;
  157. }
  158. return @file_put_contents($this->tmpIni, $content);
  159. }
  160. /**
  161. * Returns the restart command line
  162. *
  163. * @return string
  164. */
  165. private function getCommand()
  166. {
  167. $phpArgs = array(PHP_BINARY, '-c', $this->tmpIni);
  168. $params = array_merge($phpArgs, $this->getScriptArgs($_SERVER['argv']));
  169. return implode(' ', array_map(array($this, 'escape'), $params));
  170. }
  171. /**
  172. * Returns true if the restart environment variables were set
  173. *
  174. * @param bool $additional Whether there were additional inis
  175. * @param array $iniPaths Locations used by the current prcoess
  176. *
  177. * @return bool
  178. */
  179. private function setEnvironment($additional, array $iniPaths)
  180. {
  181. // Set scan dir to an empty value if additional ini files were used
  182. if ($additional && !putenv('PHP_INI_SCAN_DIR=')) {
  183. return false;
  184. }
  185. // Make original inis available to restarted process
  186. if (!putenv(IniHelper::ENV_ORIGINAL.'='.implode(PATH_SEPARATOR, $iniPaths))) {
  187. return false;
  188. }
  189. // Make xdebug version available to restarted process
  190. if (!putenv(self::ENV_VERSION.'='.$this->version)) {
  191. return false;
  192. }
  193. // Flag restarted process and save env scan dir state
  194. $args = array(self::RESTART_ID);
  195. if (false !== $this->envScanDir) {
  196. // Save current PHP_INI_SCAN_DIR
  197. $args[] = $this->envScanDir;
  198. }
  199. return putenv(self::ENV_ALLOW.'='.implode('|', $args));
  200. }
  201. /**
  202. * Returns the restart script arguments, adding --ansi if required
  203. *
  204. * If we are a terminal with color support we must ensure that the --ansi
  205. * option is set, because the restarted output is piped.
  206. *
  207. * @param array $args The argv array
  208. *
  209. * @return array
  210. */
  211. private function getScriptArgs(array $args)
  212. {
  213. if (in_array('--no-ansi', $args) || in_array('--ansi', $args)) {
  214. return $args;
  215. }
  216. if ($this->output->isDecorated()) {
  217. $offset = count($args) > 1 ? 2 : 1;
  218. array_splice($args, $offset, 0, '--ansi');
  219. }
  220. return $args;
  221. }
  222. /**
  223. * Escapes a string to be used as a shell argument.
  224. *
  225. * From https://github.com/johnstevenson/winbox-args
  226. * MIT Licensed (c) John Stevenson <john-stevenson@blueyonder.co.uk>
  227. *
  228. * @param string $arg The argument to be escaped
  229. * @param bool $meta Additionally escape cmd.exe meta characters
  230. *
  231. * @return string The escaped argument
  232. */
  233. private function escape($arg, $meta = true)
  234. {
  235. if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
  236. return escapeshellarg($arg);
  237. }
  238. $quote = strpbrk($arg, " \t") !== false || $arg === '';
  239. $arg = preg_replace('/(\\\\*)"/', '$1$1\\"', $arg, -1, $dquotes);
  240. if ($meta) {
  241. $meta = $dquotes || preg_match('/%[^%]+%/', $arg);
  242. if (!$meta && !$quote) {
  243. $quote = strpbrk($arg, '^&|<>()') !== false;
  244. }
  245. }
  246. if ($quote) {
  247. $arg = preg_replace('/(\\\\*)$/', '$1$1', $arg);
  248. $arg = '"'.$arg.'"';
  249. }
  250. if ($meta) {
  251. $arg = preg_replace('/(["^&|<>()%])/', '^$1', $arg);
  252. }
  253. return $arg;
  254. }
  255. }