XdebugHandler.php 8.8 KB

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