XdebugHandler.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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 .= PHP_EOL.'memory_limit='.ini_get('memory_limit').PHP_EOL;
  152. return @file_put_contents($this->tmpIni, $content);
  153. }
  154. /**
  155. * Returns the restart command line
  156. *
  157. * @return string
  158. */
  159. private function getCommand()
  160. {
  161. $phpArgs = array(PHP_BINARY, '-c', $this->tmpIni);
  162. $params = array_merge($phpArgs, $this->getScriptArgs($_SERVER['argv']));
  163. return implode(' ', array_map(array($this, 'escape'), $params));
  164. }
  165. /**
  166. * Returns true if the restart environment variables were set
  167. *
  168. * @param bool $additional Whether there were additional inis
  169. * @param array $iniPaths Locations used by the current prcoess
  170. *
  171. * @return bool
  172. */
  173. private function setEnvironment($additional, array $iniPaths)
  174. {
  175. // Set scan dir to an empty value if additional ini files were used
  176. if ($additional && !putenv('PHP_INI_SCAN_DIR=')) {
  177. return false;
  178. }
  179. // Make original inis available to restarted process
  180. if (!putenv(IniHelper::ENV_ORIGINAL.'='.implode(PATH_SEPARATOR, $iniPaths))) {
  181. return false;
  182. }
  183. // Make xdebug version available to restarted process
  184. if (!putenv(self::ENV_VERSION.'='.$this->version)) {
  185. return false;
  186. }
  187. // Flag restarted process and save env scan dir state
  188. $args = array(self::RESTART_ID);
  189. if (false !== $this->envScanDir) {
  190. // Save current PHP_INI_SCAN_DIR
  191. $args[] = $this->envScanDir;
  192. }
  193. return putenv(self::ENV_ALLOW.'='.implode('|', $args));
  194. }
  195. /**
  196. * Returns the restart script arguments, adding --ansi if required
  197. *
  198. * If we are a terminal with color support we must ensure that the --ansi
  199. * option is set, because the restarted output is piped.
  200. *
  201. * @param array $args The argv array
  202. *
  203. * @return array
  204. */
  205. private function getScriptArgs(array $args)
  206. {
  207. if (in_array('--no-ansi', $args) || in_array('--ansi', $args)) {
  208. return $args;
  209. }
  210. if ($this->output->isDecorated()) {
  211. $offset = count($args) > 1 ? 2: 1;
  212. array_splice($args, $offset, 0, '--ansi');
  213. }
  214. return $args;
  215. }
  216. /**
  217. * Escapes a string to be used as a shell argument.
  218. *
  219. * From https://github.com/johnstevenson/winbox-args
  220. * MIT Licensed (c) John Stevenson <john-stevenson@blueyonder.co.uk>
  221. *
  222. * @param string $arg The argument to be escaped
  223. * @param bool $meta Additionally escape cmd.exe meta characters
  224. *
  225. * @return string The escaped argument
  226. */
  227. private function escape($arg, $meta = true)
  228. {
  229. if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
  230. return escapeshellarg($arg);
  231. }
  232. $quote = strpbrk($arg, " \t") !== false || $arg === '';
  233. $arg = preg_replace('/(\\\\*)"/', '$1$1\\"', $arg, -1, $dquotes);
  234. if ($meta) {
  235. $meta = $dquotes || preg_match('/%[^%]+%/', $arg);
  236. if (!$meta && !$quote) {
  237. $quote = strpbrk($arg, '^&|<>()') !== false;
  238. }
  239. }
  240. if ($quote) {
  241. $arg = preg_replace('/(\\\\*)$/', '$1$1', $arg);
  242. $arg = '"'.$arg.'"';
  243. }
  244. if ($meta) {
  245. $arg = preg_replace('/(["^&|<>()%])/', '^$1', $arg);
  246. }
  247. return $arg;
  248. }
  249. }