Process.php 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Process;
  11. use Symfony\Component\Process\Exception\InvalidArgumentException;
  12. use Symfony\Component\Process\Exception\LogicException;
  13. use Symfony\Component\Process\Exception\ProcessFailedException;
  14. use Symfony\Component\Process\Exception\ProcessSignaledException;
  15. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  16. use Symfony\Component\Process\Exception\RuntimeException;
  17. use Symfony\Component\Process\Pipes\PipesInterface;
  18. use Symfony\Component\Process\Pipes\UnixPipes;
  19. use Symfony\Component\Process\Pipes\WindowsPipes;
  20. /**
  21. * Process is a thin wrapper around proc_* functions to easily
  22. * start independent PHP processes.
  23. *
  24. * @author Fabien Potencier <fabien@symfony.com>
  25. * @author Romain Neutron <imprec@gmail.com>
  26. */
  27. class Process implements \IteratorAggregate
  28. {
  29. const ERR = 'err';
  30. const OUT = 'out';
  31. const STATUS_READY = 'ready';
  32. const STATUS_STARTED = 'started';
  33. const STATUS_TERMINATED = 'terminated';
  34. const STDIN = 0;
  35. const STDOUT = 1;
  36. const STDERR = 2;
  37. // Timeout Precision in seconds.
  38. const TIMEOUT_PRECISION = 0.2;
  39. const ITER_NON_BLOCKING = 1; // By default, iterating over outputs is a blocking call, use this flag to make it non-blocking
  40. const ITER_KEEP_OUTPUT = 2; // By default, outputs are cleared while iterating, use this flag to keep them in memory
  41. const ITER_SKIP_OUT = 4; // Use this flag to skip STDOUT while iterating
  42. const ITER_SKIP_ERR = 8; // Use this flag to skip STDERR while iterating
  43. private $callback;
  44. private $hasCallback = false;
  45. private $commandline;
  46. private $cwd;
  47. private $env;
  48. private $input;
  49. private $starttime;
  50. private $lastOutputTime;
  51. private $timeout;
  52. private $idleTimeout;
  53. private $exitcode;
  54. private $fallbackStatus = [];
  55. private $processInformation;
  56. private $outputDisabled = false;
  57. private $stdout;
  58. private $stderr;
  59. private $process;
  60. private $status = self::STATUS_READY;
  61. private $incrementalOutputOffset = 0;
  62. private $incrementalErrorOutputOffset = 0;
  63. private $tty = false;
  64. private $pty;
  65. private $useFileHandles = false;
  66. /** @var PipesInterface */
  67. private $processPipes;
  68. private $latestSignal;
  69. private static $sigchild;
  70. /**
  71. * Exit codes translation table.
  72. *
  73. * User-defined errors must use exit codes in the 64-113 range.
  74. */
  75. public static $exitCodes = [
  76. 0 => 'OK',
  77. 1 => 'General error',
  78. 2 => 'Misuse of shell builtins',
  79. 126 => 'Invoked command cannot execute',
  80. 127 => 'Command not found',
  81. 128 => 'Invalid exit argument',
  82. // signals
  83. 129 => 'Hangup',
  84. 130 => 'Interrupt',
  85. 131 => 'Quit and dump core',
  86. 132 => 'Illegal instruction',
  87. 133 => 'Trace/breakpoint trap',
  88. 134 => 'Process aborted',
  89. 135 => 'Bus error: "access to undefined portion of memory object"',
  90. 136 => 'Floating point exception: "erroneous arithmetic operation"',
  91. 137 => 'Kill (terminate immediately)',
  92. 138 => 'User-defined 1',
  93. 139 => 'Segmentation violation',
  94. 140 => 'User-defined 2',
  95. 141 => 'Write to pipe with no one reading',
  96. 142 => 'Signal raised by alarm',
  97. 143 => 'Termination (request to terminate)',
  98. // 144 - not defined
  99. 145 => 'Child process terminated, stopped (or continued*)',
  100. 146 => 'Continue if stopped',
  101. 147 => 'Stop executing temporarily',
  102. 148 => 'Terminal stop signal',
  103. 149 => 'Background process attempting to read from tty ("in")',
  104. 150 => 'Background process attempting to write to tty ("out")',
  105. 151 => 'Urgent data available on socket',
  106. 152 => 'CPU time limit exceeded',
  107. 153 => 'File size limit exceeded',
  108. 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
  109. 155 => 'Profiling timer expired',
  110. // 156 - not defined
  111. 157 => 'Pollable event',
  112. // 158 - not defined
  113. 159 => 'Bad syscall',
  114. ];
  115. /**
  116. * @param array $command The command to run and its arguments listed as separate entries
  117. * @param string|null $cwd The working directory or null to use the working dir of the current PHP process
  118. * @param array|null $env The environment variables or null to use the same environment as the current PHP process
  119. * @param mixed|null $input The input as stream resource, scalar or \Traversable, or null for no input
  120. * @param int|float|null $timeout The timeout in seconds or null to disable
  121. *
  122. * @throws RuntimeException When proc_open is not installed
  123. */
  124. public function __construct($command, string $cwd = null, array $env = null, $input = null, ?float $timeout = 60)
  125. {
  126. if (!\function_exists('proc_open')) {
  127. throw new LogicException('The Process class relies on proc_open, which is not available on your PHP installation.');
  128. }
  129. if (!\is_array($command)) {
  130. @trigger_error(sprintf('Passing a command as string when creating a "%s" instance is deprecated since Symfony 4.2, pass it as an array of its arguments instead, or use the "Process::fromShellCommandline()" constructor if you need features provided by the shell.', __CLASS__), E_USER_DEPRECATED);
  131. }
  132. $this->commandline = $command;
  133. $this->cwd = $cwd;
  134. // on Windows, if the cwd changed via chdir(), proc_open defaults to the dir where PHP was started
  135. // on Gnu/Linux, PHP builds with --enable-maintainer-zts are also affected
  136. // @see : https://bugs.php.net/51800
  137. // @see : https://bugs.php.net/50524
  138. if (null === $this->cwd && (\defined('ZEND_THREAD_SAFE') || '\\' === \DIRECTORY_SEPARATOR)) {
  139. $this->cwd = getcwd();
  140. }
  141. if (null !== $env) {
  142. $this->setEnv($env);
  143. }
  144. $this->setInput($input);
  145. $this->setTimeout($timeout);
  146. $this->useFileHandles = '\\' === \DIRECTORY_SEPARATOR;
  147. $this->pty = false;
  148. }
  149. /**
  150. * Creates a Process instance as a command-line to be run in a shell wrapper.
  151. *
  152. * Command-lines are parsed by the shell of your OS (/bin/sh on Unix-like, cmd.exe on Windows.)
  153. * This allows using e.g. pipes or conditional execution. In this mode, signals are sent to the
  154. * shell wrapper and not to your commands.
  155. *
  156. * In order to inject dynamic values into command-lines, we strongly recommend using placeholders.
  157. * This will save escaping values, which is not portable nor secure anyway:
  158. *
  159. * $process = Process::fromShellCommandline('my_command "$MY_VAR"');
  160. * $process->run(null, ['MY_VAR' => $theValue]);
  161. *
  162. * @param string $command The command line to pass to the shell of the OS
  163. * @param string|null $cwd The working directory or null to use the working dir of the current PHP process
  164. * @param array|null $env The environment variables or null to use the same environment as the current PHP process
  165. * @param mixed|null $input The input as stream resource, scalar or \Traversable, or null for no input
  166. * @param int|float|null $timeout The timeout in seconds or null to disable
  167. *
  168. * @return static
  169. *
  170. * @throws RuntimeException When proc_open is not installed
  171. */
  172. public static function fromShellCommandline(string $command, string $cwd = null, array $env = null, $input = null, ?float $timeout = 60)
  173. {
  174. $process = new static([], $cwd, $env, $input, $timeout);
  175. $process->commandline = $command;
  176. return $process;
  177. }
  178. public function __destruct()
  179. {
  180. $this->stop(0);
  181. }
  182. public function __clone()
  183. {
  184. $this->resetProcessData();
  185. }
  186. /**
  187. * Runs the process.
  188. *
  189. * The callback receives the type of output (out or err) and
  190. * some bytes from the output in real-time. It allows to have feedback
  191. * from the independent process during execution.
  192. *
  193. * The STDOUT and STDERR are also available after the process is finished
  194. * via the getOutput() and getErrorOutput() methods.
  195. *
  196. * @param callable|null $callback A PHP callback to run whenever there is some
  197. * output available on STDOUT or STDERR
  198. *
  199. * @return int The exit status code
  200. *
  201. * @throws RuntimeException When process can't be launched
  202. * @throws RuntimeException When process stopped after receiving signal
  203. * @throws LogicException In case a callback is provided and output has been disabled
  204. *
  205. * @final
  206. */
  207. public function run(callable $callback = null, array $env = []): int
  208. {
  209. $this->start($callback, $env);
  210. return $this->wait();
  211. }
  212. /**
  213. * Runs the process.
  214. *
  215. * This is identical to run() except that an exception is thrown if the process
  216. * exits with a non-zero exit code.
  217. *
  218. * @return $this
  219. *
  220. * @throws ProcessFailedException if the process didn't terminate successfully
  221. *
  222. * @final
  223. */
  224. public function mustRun(callable $callback = null, array $env = []): self
  225. {
  226. if (0 !== $this->run($callback, $env)) {
  227. throw new ProcessFailedException($this);
  228. }
  229. return $this;
  230. }
  231. /**
  232. * Starts the process and returns after writing the input to STDIN.
  233. *
  234. * This method blocks until all STDIN data is sent to the process then it
  235. * returns while the process runs in the background.
  236. *
  237. * The termination of the process can be awaited with wait().
  238. *
  239. * The callback receives the type of output (out or err) and some bytes from
  240. * the output in real-time while writing the standard input to the process.
  241. * It allows to have feedback from the independent process during execution.
  242. *
  243. * @param callable|null $callback A PHP callback to run whenever there is some
  244. * output available on STDOUT or STDERR
  245. *
  246. * @throws RuntimeException When process can't be launched
  247. * @throws RuntimeException When process is already running
  248. * @throws LogicException In case a callback is provided and output has been disabled
  249. */
  250. public function start(callable $callback = null, array $env = [])
  251. {
  252. if ($this->isRunning()) {
  253. throw new RuntimeException('Process is already running');
  254. }
  255. $this->resetProcessData();
  256. $this->starttime = $this->lastOutputTime = microtime(true);
  257. $this->callback = $this->buildCallback($callback);
  258. $this->hasCallback = null !== $callback;
  259. $descriptors = $this->getDescriptors();
  260. if ($this->env) {
  261. $env += $this->env;
  262. }
  263. $env += $this->getDefaultEnv();
  264. if (\is_array($commandline = $this->commandline)) {
  265. $commandline = implode(' ', array_map([$this, 'escapeArgument'], $commandline));
  266. if ('\\' !== \DIRECTORY_SEPARATOR) {
  267. // exec is mandatory to deal with sending a signal to the process
  268. $commandline = 'exec '.$commandline;
  269. }
  270. } else {
  271. $commandline = $this->replacePlaceholders($commandline, $env);
  272. }
  273. $options = ['suppress_errors' => true];
  274. if ('\\' === \DIRECTORY_SEPARATOR) {
  275. $options['bypass_shell'] = true;
  276. $commandline = $this->prepareWindowsCommandLine($commandline, $env);
  277. } elseif (!$this->useFileHandles && $this->isSigchildEnabled()) {
  278. // last exit code is output on the fourth pipe and caught to work around --enable-sigchild
  279. $descriptors[3] = ['pipe', 'w'];
  280. // See https://unix.stackexchange.com/questions/71205/background-process-pipe-input
  281. $commandline = '{ ('.$commandline.') <&3 3<&- 3>/dev/null & } 3<&0;';
  282. $commandline .= 'pid=$!; echo $pid >&3; wait $pid; code=$?; echo $code >&3; exit $code';
  283. // Workaround for the bug, when PTS functionality is enabled.
  284. // @see : https://bugs.php.net/69442
  285. $ptsWorkaround = fopen(__FILE__, 'r');
  286. }
  287. $envPairs = [];
  288. foreach ($env as $k => $v) {
  289. if (false !== $v) {
  290. $envPairs[] = $k.'='.$v;
  291. }
  292. }
  293. if (!is_dir($this->cwd)) {
  294. throw new RuntimeException(sprintf('The provided cwd "%s" does not exist.', $this->cwd));
  295. }
  296. $this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $envPairs, $options);
  297. if (!\is_resource($this->process)) {
  298. throw new RuntimeException('Unable to launch a new process.');
  299. }
  300. $this->status = self::STATUS_STARTED;
  301. if (isset($descriptors[3])) {
  302. $this->fallbackStatus['pid'] = (int) fgets($this->processPipes->pipes[3]);
  303. }
  304. if ($this->tty) {
  305. return;
  306. }
  307. $this->updateStatus(false);
  308. $this->checkTimeout();
  309. }
  310. /**
  311. * Restarts the process.
  312. *
  313. * Be warned that the process is cloned before being started.
  314. *
  315. * @param callable|null $callback A PHP callback to run whenever there is some
  316. * output available on STDOUT or STDERR
  317. *
  318. * @return static
  319. *
  320. * @throws RuntimeException When process can't be launched
  321. * @throws RuntimeException When process is already running
  322. *
  323. * @see start()
  324. *
  325. * @final
  326. */
  327. public function restart(callable $callback = null, array $env = []): self
  328. {
  329. if ($this->isRunning()) {
  330. throw new RuntimeException('Process is already running');
  331. }
  332. $process = clone $this;
  333. $process->start($callback, $env);
  334. return $process;
  335. }
  336. /**
  337. * Waits for the process to terminate.
  338. *
  339. * The callback receives the type of output (out or err) and some bytes
  340. * from the output in real-time while writing the standard input to the process.
  341. * It allows to have feedback from the independent process during execution.
  342. *
  343. * @param callable|null $callback A valid PHP callback
  344. *
  345. * @return int The exitcode of the process
  346. *
  347. * @throws RuntimeException When process timed out
  348. * @throws RuntimeException When process stopped after receiving signal
  349. * @throws LogicException When process is not yet started
  350. */
  351. public function wait(callable $callback = null)
  352. {
  353. $this->requireProcessIsStarted(__FUNCTION__);
  354. $this->updateStatus(false);
  355. if (null !== $callback) {
  356. if (!$this->processPipes->haveReadSupport()) {
  357. $this->stop(0);
  358. throw new \LogicException('Pass the callback to the "Process::start" method or call enableOutput to use a callback with "Process::wait"');
  359. }
  360. $this->callback = $this->buildCallback($callback);
  361. }
  362. do {
  363. $this->checkTimeout();
  364. $running = '\\' === \DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
  365. $this->readPipes($running, '\\' !== \DIRECTORY_SEPARATOR || !$running);
  366. } while ($running);
  367. while ($this->isRunning()) {
  368. $this->checkTimeout();
  369. usleep(1000);
  370. }
  371. if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) {
  372. throw new ProcessSignaledException($this);
  373. }
  374. return $this->exitcode;
  375. }
  376. /**
  377. * Waits until the callback returns true.
  378. *
  379. * The callback receives the type of output (out or err) and some bytes
  380. * from the output in real-time while writing the standard input to the process.
  381. * It allows to have feedback from the independent process during execution.
  382. *
  383. * @throws RuntimeException When process timed out
  384. * @throws LogicException When process is not yet started
  385. */
  386. public function waitUntil(callable $callback): bool
  387. {
  388. $this->requireProcessIsStarted(__FUNCTION__);
  389. $this->updateStatus(false);
  390. if (!$this->processPipes->haveReadSupport()) {
  391. $this->stop(0);
  392. throw new \LogicException('Pass the callback to the "Process::start" method or call enableOutput to use a callback with "Process::waitUntil".');
  393. }
  394. $callback = $this->buildCallback($callback);
  395. $ready = false;
  396. while (true) {
  397. $this->checkTimeout();
  398. $running = '\\' === \DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
  399. $output = $this->processPipes->readAndWrite($running, '\\' !== \DIRECTORY_SEPARATOR || !$running);
  400. foreach ($output as $type => $data) {
  401. if (3 !== $type) {
  402. $ready = $callback(self::STDOUT === $type ? self::OUT : self::ERR, $data) || $ready;
  403. } elseif (!isset($this->fallbackStatus['signaled'])) {
  404. $this->fallbackStatus['exitcode'] = (int) $data;
  405. }
  406. }
  407. if ($ready) {
  408. return true;
  409. }
  410. if (!$running) {
  411. return false;
  412. }
  413. usleep(1000);
  414. }
  415. }
  416. /**
  417. * Returns the Pid (process identifier), if applicable.
  418. *
  419. * @return int|null The process id if running, null otherwise
  420. */
  421. public function getPid()
  422. {
  423. return $this->isRunning() ? $this->processInformation['pid'] : null;
  424. }
  425. /**
  426. * Sends a POSIX signal to the process.
  427. *
  428. * @param int $signal A valid POSIX signal (see https://php.net/pcntl.constants)
  429. *
  430. * @return $this
  431. *
  432. * @throws LogicException In case the process is not running
  433. * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed
  434. * @throws RuntimeException In case of failure
  435. */
  436. public function signal($signal)
  437. {
  438. $this->doSignal($signal, true);
  439. return $this;
  440. }
  441. /**
  442. * Disables fetching output and error output from the underlying process.
  443. *
  444. * @return $this
  445. *
  446. * @throws RuntimeException In case the process is already running
  447. * @throws LogicException if an idle timeout is set
  448. */
  449. public function disableOutput()
  450. {
  451. if ($this->isRunning()) {
  452. throw new RuntimeException('Disabling output while the process is running is not possible.');
  453. }
  454. if (null !== $this->idleTimeout) {
  455. throw new LogicException('Output can not be disabled while an idle timeout is set.');
  456. }
  457. $this->outputDisabled = true;
  458. return $this;
  459. }
  460. /**
  461. * Enables fetching output and error output from the underlying process.
  462. *
  463. * @return $this
  464. *
  465. * @throws RuntimeException In case the process is already running
  466. */
  467. public function enableOutput()
  468. {
  469. if ($this->isRunning()) {
  470. throw new RuntimeException('Enabling output while the process is running is not possible.');
  471. }
  472. $this->outputDisabled = false;
  473. return $this;
  474. }
  475. /**
  476. * Returns true in case the output is disabled, false otherwise.
  477. *
  478. * @return bool
  479. */
  480. public function isOutputDisabled()
  481. {
  482. return $this->outputDisabled;
  483. }
  484. /**
  485. * Returns the current output of the process (STDOUT).
  486. *
  487. * @return string The process output
  488. *
  489. * @throws LogicException in case the output has been disabled
  490. * @throws LogicException In case the process is not started
  491. */
  492. public function getOutput()
  493. {
  494. $this->readPipesForOutput(__FUNCTION__);
  495. if (false === $ret = stream_get_contents($this->stdout, -1, 0)) {
  496. return '';
  497. }
  498. return $ret;
  499. }
  500. /**
  501. * Returns the output incrementally.
  502. *
  503. * In comparison with the getOutput method which always return the whole
  504. * output, this one returns the new output since the last call.
  505. *
  506. * @return string The process output since the last call
  507. *
  508. * @throws LogicException in case the output has been disabled
  509. * @throws LogicException In case the process is not started
  510. */
  511. public function getIncrementalOutput()
  512. {
  513. $this->readPipesForOutput(__FUNCTION__);
  514. $latest = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset);
  515. $this->incrementalOutputOffset = ftell($this->stdout);
  516. if (false === $latest) {
  517. return '';
  518. }
  519. return $latest;
  520. }
  521. /**
  522. * Returns an iterator to the output of the process, with the output type as keys (Process::OUT/ERR).
  523. *
  524. * @param int $flags A bit field of Process::ITER_* flags
  525. *
  526. * @throws LogicException in case the output has been disabled
  527. * @throws LogicException In case the process is not started
  528. *
  529. * @return \Generator
  530. */
  531. public function getIterator($flags = 0)
  532. {
  533. $this->readPipesForOutput(__FUNCTION__, false);
  534. $clearOutput = !(self::ITER_KEEP_OUTPUT & $flags);
  535. $blocking = !(self::ITER_NON_BLOCKING & $flags);
  536. $yieldOut = !(self::ITER_SKIP_OUT & $flags);
  537. $yieldErr = !(self::ITER_SKIP_ERR & $flags);
  538. while (null !== $this->callback || ($yieldOut && !feof($this->stdout)) || ($yieldErr && !feof($this->stderr))) {
  539. if ($yieldOut) {
  540. $out = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset);
  541. if (isset($out[0])) {
  542. if ($clearOutput) {
  543. $this->clearOutput();
  544. } else {
  545. $this->incrementalOutputOffset = ftell($this->stdout);
  546. }
  547. yield self::OUT => $out;
  548. }
  549. }
  550. if ($yieldErr) {
  551. $err = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset);
  552. if (isset($err[0])) {
  553. if ($clearOutput) {
  554. $this->clearErrorOutput();
  555. } else {
  556. $this->incrementalErrorOutputOffset = ftell($this->stderr);
  557. }
  558. yield self::ERR => $err;
  559. }
  560. }
  561. if (!$blocking && !isset($out[0]) && !isset($err[0])) {
  562. yield self::OUT => '';
  563. }
  564. $this->checkTimeout();
  565. $this->readPipesForOutput(__FUNCTION__, $blocking);
  566. }
  567. }
  568. /**
  569. * Clears the process output.
  570. *
  571. * @return $this
  572. */
  573. public function clearOutput()
  574. {
  575. ftruncate($this->stdout, 0);
  576. fseek($this->stdout, 0);
  577. $this->incrementalOutputOffset = 0;
  578. return $this;
  579. }
  580. /**
  581. * Returns the current error output of the process (STDERR).
  582. *
  583. * @return string The process error output
  584. *
  585. * @throws LogicException in case the output has been disabled
  586. * @throws LogicException In case the process is not started
  587. */
  588. public function getErrorOutput()
  589. {
  590. $this->readPipesForOutput(__FUNCTION__);
  591. if (false === $ret = stream_get_contents($this->stderr, -1, 0)) {
  592. return '';
  593. }
  594. return $ret;
  595. }
  596. /**
  597. * Returns the errorOutput incrementally.
  598. *
  599. * In comparison with the getErrorOutput method which always return the
  600. * whole error output, this one returns the new error output since the last
  601. * call.
  602. *
  603. * @return string The process error output since the last call
  604. *
  605. * @throws LogicException in case the output has been disabled
  606. * @throws LogicException In case the process is not started
  607. */
  608. public function getIncrementalErrorOutput()
  609. {
  610. $this->readPipesForOutput(__FUNCTION__);
  611. $latest = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset);
  612. $this->incrementalErrorOutputOffset = ftell($this->stderr);
  613. if (false === $latest) {
  614. return '';
  615. }
  616. return $latest;
  617. }
  618. /**
  619. * Clears the process output.
  620. *
  621. * @return $this
  622. */
  623. public function clearErrorOutput()
  624. {
  625. ftruncate($this->stderr, 0);
  626. fseek($this->stderr, 0);
  627. $this->incrementalErrorOutputOffset = 0;
  628. return $this;
  629. }
  630. /**
  631. * Returns the exit code returned by the process.
  632. *
  633. * @return int|null The exit status code, null if the Process is not terminated
  634. */
  635. public function getExitCode()
  636. {
  637. $this->updateStatus(false);
  638. return $this->exitcode;
  639. }
  640. /**
  641. * Returns a string representation for the exit code returned by the process.
  642. *
  643. * This method relies on the Unix exit code status standardization
  644. * and might not be relevant for other operating systems.
  645. *
  646. * @return string|null A string representation for the exit status code, null if the Process is not terminated
  647. *
  648. * @see http://tldp.org/LDP/abs/html/exitcodes.html
  649. * @see http://en.wikipedia.org/wiki/Unix_signal
  650. */
  651. public function getExitCodeText()
  652. {
  653. if (null === $exitcode = $this->getExitCode()) {
  654. return null;
  655. }
  656. return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error';
  657. }
  658. /**
  659. * Checks if the process ended successfully.
  660. *
  661. * @return bool true if the process ended successfully, false otherwise
  662. */
  663. public function isSuccessful()
  664. {
  665. return 0 === $this->getExitCode();
  666. }
  667. /**
  668. * Returns true if the child process has been terminated by an uncaught signal.
  669. *
  670. * It always returns false on Windows.
  671. *
  672. * @return bool
  673. *
  674. * @throws LogicException In case the process is not terminated
  675. */
  676. public function hasBeenSignaled()
  677. {
  678. $this->requireProcessIsTerminated(__FUNCTION__);
  679. return $this->processInformation['signaled'];
  680. }
  681. /**
  682. * Returns the number of the signal that caused the child process to terminate its execution.
  683. *
  684. * It is only meaningful if hasBeenSignaled() returns true.
  685. *
  686. * @return int
  687. *
  688. * @throws RuntimeException In case --enable-sigchild is activated
  689. * @throws LogicException In case the process is not terminated
  690. */
  691. public function getTermSignal()
  692. {
  693. $this->requireProcessIsTerminated(__FUNCTION__);
  694. if ($this->isSigchildEnabled() && -1 === $this->processInformation['termsig']) {
  695. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  696. }
  697. return $this->processInformation['termsig'];
  698. }
  699. /**
  700. * Returns true if the child process has been stopped by a signal.
  701. *
  702. * It always returns false on Windows.
  703. *
  704. * @return bool
  705. *
  706. * @throws LogicException In case the process is not terminated
  707. */
  708. public function hasBeenStopped()
  709. {
  710. $this->requireProcessIsTerminated(__FUNCTION__);
  711. return $this->processInformation['stopped'];
  712. }
  713. /**
  714. * Returns the number of the signal that caused the child process to stop its execution.
  715. *
  716. * It is only meaningful if hasBeenStopped() returns true.
  717. *
  718. * @return int
  719. *
  720. * @throws LogicException In case the process is not terminated
  721. */
  722. public function getStopSignal()
  723. {
  724. $this->requireProcessIsTerminated(__FUNCTION__);
  725. return $this->processInformation['stopsig'];
  726. }
  727. /**
  728. * Checks if the process is currently running.
  729. *
  730. * @return bool true if the process is currently running, false otherwise
  731. */
  732. public function isRunning()
  733. {
  734. if (self::STATUS_STARTED !== $this->status) {
  735. return false;
  736. }
  737. $this->updateStatus(false);
  738. return $this->processInformation['running'];
  739. }
  740. /**
  741. * Checks if the process has been started with no regard to the current state.
  742. *
  743. * @return bool true if status is ready, false otherwise
  744. */
  745. public function isStarted()
  746. {
  747. return self::STATUS_READY != $this->status;
  748. }
  749. /**
  750. * Checks if the process is terminated.
  751. *
  752. * @return bool true if process is terminated, false otherwise
  753. */
  754. public function isTerminated()
  755. {
  756. $this->updateStatus(false);
  757. return self::STATUS_TERMINATED == $this->status;
  758. }
  759. /**
  760. * Gets the process status.
  761. *
  762. * The status is one of: ready, started, terminated.
  763. *
  764. * @return string The current process status
  765. */
  766. public function getStatus()
  767. {
  768. $this->updateStatus(false);
  769. return $this->status;
  770. }
  771. /**
  772. * Stops the process.
  773. *
  774. * @param int|float $timeout The timeout in seconds
  775. * @param int $signal A POSIX signal to send in case the process has not stop at timeout, default is SIGKILL (9)
  776. *
  777. * @return int|null The exit-code of the process or null if it's not running
  778. */
  779. public function stop($timeout = 10, $signal = null)
  780. {
  781. $timeoutMicro = microtime(true) + $timeout;
  782. if ($this->isRunning()) {
  783. // given SIGTERM may not be defined and that "proc_terminate" uses the constant value and not the constant itself, we use the same here
  784. $this->doSignal(15, false);
  785. do {
  786. usleep(1000);
  787. } while ($this->isRunning() && microtime(true) < $timeoutMicro);
  788. if ($this->isRunning()) {
  789. // Avoid exception here: process is supposed to be running, but it might have stopped just
  790. // after this line. In any case, let's silently discard the error, we cannot do anything.
  791. $this->doSignal($signal ?: 9, false);
  792. }
  793. }
  794. if ($this->isRunning()) {
  795. if (isset($this->fallbackStatus['pid'])) {
  796. unset($this->fallbackStatus['pid']);
  797. return $this->stop(0, $signal);
  798. }
  799. $this->close();
  800. }
  801. return $this->exitcode;
  802. }
  803. /**
  804. * Adds a line to the STDOUT stream.
  805. *
  806. * @internal
  807. */
  808. public function addOutput(string $line)
  809. {
  810. $this->lastOutputTime = microtime(true);
  811. fseek($this->stdout, 0, SEEK_END);
  812. fwrite($this->stdout, $line);
  813. fseek($this->stdout, $this->incrementalOutputOffset);
  814. }
  815. /**
  816. * Adds a line to the STDERR stream.
  817. *
  818. * @internal
  819. */
  820. public function addErrorOutput(string $line)
  821. {
  822. $this->lastOutputTime = microtime(true);
  823. fseek($this->stderr, 0, SEEK_END);
  824. fwrite($this->stderr, $line);
  825. fseek($this->stderr, $this->incrementalErrorOutputOffset);
  826. }
  827. /**
  828. * Gets the last output time in seconds.
  829. *
  830. * @return float|null The last output time in seconds or null if it isn't started
  831. */
  832. public function getLastOutputTime(): ?float
  833. {
  834. return $this->lastOutputTime;
  835. }
  836. /**
  837. * Gets the command line to be executed.
  838. *
  839. * @return string The command to execute
  840. */
  841. public function getCommandLine()
  842. {
  843. return \is_array($this->commandline) ? implode(' ', array_map([$this, 'escapeArgument'], $this->commandline)) : $this->commandline;
  844. }
  845. /**
  846. * Sets the command line to be executed.
  847. *
  848. * @param string|array $commandline The command to execute
  849. *
  850. * @return $this
  851. *
  852. * @deprecated since Symfony 4.2.
  853. */
  854. public function setCommandLine($commandline)
  855. {
  856. @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.2.', __METHOD__), E_USER_DEPRECATED);
  857. $this->commandline = $commandline;
  858. return $this;
  859. }
  860. /**
  861. * Gets the process timeout (max. runtime).
  862. *
  863. * @return float|null The timeout in seconds or null if it's disabled
  864. */
  865. public function getTimeout()
  866. {
  867. return $this->timeout;
  868. }
  869. /**
  870. * Gets the process idle timeout (max. time since last output).
  871. *
  872. * @return float|null The timeout in seconds or null if it's disabled
  873. */
  874. public function getIdleTimeout()
  875. {
  876. return $this->idleTimeout;
  877. }
  878. /**
  879. * Sets the process timeout (max. runtime) in seconds.
  880. *
  881. * To disable the timeout, set this value to null.
  882. *
  883. * @param int|float|null $timeout The timeout in seconds
  884. *
  885. * @return $this
  886. *
  887. * @throws InvalidArgumentException if the timeout is negative
  888. */
  889. public function setTimeout($timeout)
  890. {
  891. $this->timeout = $this->validateTimeout($timeout);
  892. return $this;
  893. }
  894. /**
  895. * Sets the process idle timeout (max. time since last output).
  896. *
  897. * To disable the timeout, set this value to null.
  898. *
  899. * @param int|float|null $timeout The timeout in seconds
  900. *
  901. * @return $this
  902. *
  903. * @throws LogicException if the output is disabled
  904. * @throws InvalidArgumentException if the timeout is negative
  905. */
  906. public function setIdleTimeout($timeout)
  907. {
  908. if (null !== $timeout && $this->outputDisabled) {
  909. throw new LogicException('Idle timeout can not be set while the output is disabled.');
  910. }
  911. $this->idleTimeout = $this->validateTimeout($timeout);
  912. return $this;
  913. }
  914. /**
  915. * Enables or disables the TTY mode.
  916. *
  917. * @param bool $tty True to enabled and false to disable
  918. *
  919. * @return $this
  920. *
  921. * @throws RuntimeException In case the TTY mode is not supported
  922. */
  923. public function setTty($tty)
  924. {
  925. if ('\\' === \DIRECTORY_SEPARATOR && $tty) {
  926. throw new RuntimeException('TTY mode is not supported on Windows platform.');
  927. }
  928. if ($tty && !self::isTtySupported()) {
  929. throw new RuntimeException('TTY mode requires /dev/tty to be read/writable.');
  930. }
  931. $this->tty = (bool) $tty;
  932. return $this;
  933. }
  934. /**
  935. * Checks if the TTY mode is enabled.
  936. *
  937. * @return bool true if the TTY mode is enabled, false otherwise
  938. */
  939. public function isTty()
  940. {
  941. return $this->tty;
  942. }
  943. /**
  944. * Sets PTY mode.
  945. *
  946. * @param bool $bool
  947. *
  948. * @return $this
  949. */
  950. public function setPty($bool)
  951. {
  952. $this->pty = (bool) $bool;
  953. return $this;
  954. }
  955. /**
  956. * Returns PTY state.
  957. *
  958. * @return bool
  959. */
  960. public function isPty()
  961. {
  962. return $this->pty;
  963. }
  964. /**
  965. * Gets the working directory.
  966. *
  967. * @return string|null The current working directory or null on failure
  968. */
  969. public function getWorkingDirectory()
  970. {
  971. if (null === $this->cwd) {
  972. // getcwd() will return false if any one of the parent directories does not have
  973. // the readable or search mode set, even if the current directory does
  974. return getcwd() ?: null;
  975. }
  976. return $this->cwd;
  977. }
  978. /**
  979. * Sets the current working directory.
  980. *
  981. * @param string $cwd The new working directory
  982. *
  983. * @return $this
  984. */
  985. public function setWorkingDirectory($cwd)
  986. {
  987. $this->cwd = $cwd;
  988. return $this;
  989. }
  990. /**
  991. * Gets the environment variables.
  992. *
  993. * @return array The current environment variables
  994. */
  995. public function getEnv()
  996. {
  997. return $this->env;
  998. }
  999. /**
  1000. * Sets the environment variables.
  1001. *
  1002. * Each environment variable value should be a string.
  1003. * If it is an array, the variable is ignored.
  1004. * If it is false or null, it will be removed when
  1005. * env vars are otherwise inherited.
  1006. *
  1007. * That happens in PHP when 'argv' is registered into
  1008. * the $_ENV array for instance.
  1009. *
  1010. * @param array $env The new environment variables
  1011. *
  1012. * @return $this
  1013. */
  1014. public function setEnv(array $env)
  1015. {
  1016. // Process can not handle env values that are arrays
  1017. $env = array_filter($env, function ($value) {
  1018. return !\is_array($value);
  1019. });
  1020. $this->env = $env;
  1021. return $this;
  1022. }
  1023. /**
  1024. * Gets the Process input.
  1025. *
  1026. * @return resource|string|\Iterator|null The Process input
  1027. */
  1028. public function getInput()
  1029. {
  1030. return $this->input;
  1031. }
  1032. /**
  1033. * Sets the input.
  1034. *
  1035. * This content will be passed to the underlying process standard input.
  1036. *
  1037. * @param string|int|float|bool|resource|\Traversable|null $input The content
  1038. *
  1039. * @return $this
  1040. *
  1041. * @throws LogicException In case the process is running
  1042. */
  1043. public function setInput($input)
  1044. {
  1045. if ($this->isRunning()) {
  1046. throw new LogicException('Input can not be set while the process is running.');
  1047. }
  1048. $this->input = ProcessUtils::validateInput(__METHOD__, $input);
  1049. return $this;
  1050. }
  1051. /**
  1052. * Sets whether environment variables will be inherited or not.
  1053. *
  1054. * @param bool $inheritEnv
  1055. *
  1056. * @return $this
  1057. *
  1058. * @deprecated since Symfony 4.4, env variables are always inherited
  1059. */
  1060. public function inheritEnvironmentVariables($inheritEnv = true)
  1061. {
  1062. @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.4, env variables are always inherited.', __METHOD__), E_USER_DEPRECATED);
  1063. if (!$inheritEnv) {
  1064. throw new InvalidArgumentException('Not inheriting environment variables is not supported.');
  1065. }
  1066. return $this;
  1067. }
  1068. /**
  1069. * Performs a check between the timeout definition and the time the process started.
  1070. *
  1071. * In case you run a background process (with the start method), you should
  1072. * trigger this method regularly to ensure the process timeout
  1073. *
  1074. * @throws ProcessTimedOutException In case the timeout was reached
  1075. */
  1076. public function checkTimeout()
  1077. {
  1078. if (self::STATUS_STARTED !== $this->status) {
  1079. return;
  1080. }
  1081. if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
  1082. $this->stop(0);
  1083. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_GENERAL);
  1084. }
  1085. if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) {
  1086. $this->stop(0);
  1087. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_IDLE);
  1088. }
  1089. }
  1090. /**
  1091. * Returns whether TTY is supported on the current operating system.
  1092. */
  1093. public static function isTtySupported(): bool
  1094. {
  1095. static $isTtySupported;
  1096. if (null === $isTtySupported) {
  1097. $isTtySupported = (bool) @proc_open('echo 1 >/dev/null', [['file', '/dev/tty', 'r'], ['file', '/dev/tty', 'w'], ['file', '/dev/tty', 'w']], $pipes);
  1098. }
  1099. return $isTtySupported;
  1100. }
  1101. /**
  1102. * Returns whether PTY is supported on the current operating system.
  1103. *
  1104. * @return bool
  1105. */
  1106. public static function isPtySupported()
  1107. {
  1108. static $result;
  1109. if (null !== $result) {
  1110. return $result;
  1111. }
  1112. if ('\\' === \DIRECTORY_SEPARATOR) {
  1113. return $result = false;
  1114. }
  1115. return $result = (bool) @proc_open('echo 1 >/dev/null', [['pty'], ['pty'], ['pty']], $pipes);
  1116. }
  1117. /**
  1118. * Creates the descriptors needed by the proc_open.
  1119. */
  1120. private function getDescriptors(): array
  1121. {
  1122. if ($this->input instanceof \Iterator) {
  1123. $this->input->rewind();
  1124. }
  1125. if ('\\' === \DIRECTORY_SEPARATOR) {
  1126. $this->processPipes = new WindowsPipes($this->input, !$this->outputDisabled || $this->hasCallback);
  1127. } else {
  1128. $this->processPipes = new UnixPipes($this->isTty(), $this->isPty(), $this->input, !$this->outputDisabled || $this->hasCallback);
  1129. }
  1130. return $this->processPipes->getDescriptors();
  1131. }
  1132. /**
  1133. * Builds up the callback used by wait().
  1134. *
  1135. * The callbacks adds all occurred output to the specific buffer and calls
  1136. * the user callback (if present) with the received output.
  1137. *
  1138. * @param callable|null $callback The user defined PHP callback
  1139. *
  1140. * @return \Closure A PHP closure
  1141. */
  1142. protected function buildCallback(callable $callback = null)
  1143. {
  1144. if ($this->outputDisabled) {
  1145. return function ($type, $data) use ($callback): bool {
  1146. return null !== $callback && $callback($type, $data);
  1147. };
  1148. }
  1149. $out = self::OUT;
  1150. return function ($type, $data) use ($callback, $out): bool {
  1151. if ($out == $type) {
  1152. $this->addOutput($data);
  1153. } else {
  1154. $this->addErrorOutput($data);
  1155. }
  1156. return null !== $callback && $callback($type, $data);
  1157. };
  1158. }
  1159. /**
  1160. * Updates the status of the process, reads pipes.
  1161. *
  1162. * @param bool $blocking Whether to use a blocking read call
  1163. */
  1164. protected function updateStatus($blocking)
  1165. {
  1166. if (self::STATUS_STARTED !== $this->status) {
  1167. return;
  1168. }
  1169. $this->processInformation = proc_get_status($this->process);
  1170. $running = $this->processInformation['running'];
  1171. $this->readPipes($running && $blocking, '\\' !== \DIRECTORY_SEPARATOR || !$running);
  1172. if ($this->fallbackStatus && $this->isSigchildEnabled()) {
  1173. $this->processInformation = $this->fallbackStatus + $this->processInformation;
  1174. }
  1175. if (!$running) {
  1176. $this->close();
  1177. }
  1178. }
  1179. /**
  1180. * Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
  1181. *
  1182. * @return bool
  1183. */
  1184. protected function isSigchildEnabled()
  1185. {
  1186. if (null !== self::$sigchild) {
  1187. return self::$sigchild;
  1188. }
  1189. if (!\function_exists('phpinfo')) {
  1190. return self::$sigchild = false;
  1191. }
  1192. ob_start();
  1193. phpinfo(INFO_GENERAL);
  1194. return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  1195. }
  1196. /**
  1197. * Reads pipes for the freshest output.
  1198. *
  1199. * @param string $caller The name of the method that needs fresh outputs
  1200. * @param bool $blocking Whether to use blocking calls or not
  1201. *
  1202. * @throws LogicException in case output has been disabled or process is not started
  1203. */
  1204. private function readPipesForOutput(string $caller, bool $blocking = false)
  1205. {
  1206. if ($this->outputDisabled) {
  1207. throw new LogicException('Output has been disabled.');
  1208. }
  1209. $this->requireProcessIsStarted($caller);
  1210. $this->updateStatus($blocking);
  1211. }
  1212. /**
  1213. * Validates and returns the filtered timeout.
  1214. *
  1215. * @throws InvalidArgumentException if the given timeout is a negative number
  1216. */
  1217. private function validateTimeout(?float $timeout): ?float
  1218. {
  1219. $timeout = (float) $timeout;
  1220. if (0.0 === $timeout) {
  1221. $timeout = null;
  1222. } elseif ($timeout < 0) {
  1223. throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
  1224. }
  1225. return $timeout;
  1226. }
  1227. /**
  1228. * Reads pipes, executes callback.
  1229. *
  1230. * @param bool $blocking Whether to use blocking calls or not
  1231. * @param bool $close Whether to close file handles or not
  1232. */
  1233. private function readPipes(bool $blocking, bool $close)
  1234. {
  1235. $result = $this->processPipes->readAndWrite($blocking, $close);
  1236. $callback = $this->callback;
  1237. foreach ($result as $type => $data) {
  1238. if (3 !== $type) {
  1239. $callback(self::STDOUT === $type ? self::OUT : self::ERR, $data);
  1240. } elseif (!isset($this->fallbackStatus['signaled'])) {
  1241. $this->fallbackStatus['exitcode'] = (int) $data;
  1242. }
  1243. }
  1244. }
  1245. /**
  1246. * Closes process resource, closes file handles, sets the exitcode.
  1247. *
  1248. * @return int The exitcode
  1249. */
  1250. private function close(): int
  1251. {
  1252. $this->processPipes->close();
  1253. if (\is_resource($this->process)) {
  1254. proc_close($this->process);
  1255. }
  1256. $this->exitcode = $this->processInformation['exitcode'];
  1257. $this->status = self::STATUS_TERMINATED;
  1258. if (-1 === $this->exitcode) {
  1259. if ($this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) {
  1260. // if process has been signaled, no exitcode but a valid termsig, apply Unix convention
  1261. $this->exitcode = 128 + $this->processInformation['termsig'];
  1262. } elseif ($this->isSigchildEnabled()) {
  1263. $this->processInformation['signaled'] = true;
  1264. $this->processInformation['termsig'] = -1;
  1265. }
  1266. }
  1267. // Free memory from self-reference callback created by buildCallback
  1268. // Doing so in other contexts like __destruct or by garbage collector is ineffective
  1269. // Now pipes are closed, so the callback is no longer necessary
  1270. $this->callback = null;
  1271. return $this->exitcode;
  1272. }
  1273. /**
  1274. * Resets data related to the latest run of the process.
  1275. */
  1276. private function resetProcessData()
  1277. {
  1278. $this->starttime = null;
  1279. $this->callback = null;
  1280. $this->exitcode = null;
  1281. $this->fallbackStatus = [];
  1282. $this->processInformation = null;
  1283. $this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+b');
  1284. $this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+b');
  1285. $this->process = null;
  1286. $this->latestSignal = null;
  1287. $this->status = self::STATUS_READY;
  1288. $this->incrementalOutputOffset = 0;
  1289. $this->incrementalErrorOutputOffset = 0;
  1290. }
  1291. /**
  1292. * Sends a POSIX signal to the process.
  1293. *
  1294. * @param int $signal A valid POSIX signal (see https://php.net/pcntl.constants)
  1295. * @param bool $throwException Whether to throw exception in case signal failed
  1296. *
  1297. * @return bool True if the signal was sent successfully, false otherwise
  1298. *
  1299. * @throws LogicException In case the process is not running
  1300. * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed
  1301. * @throws RuntimeException In case of failure
  1302. */
  1303. private function doSignal(int $signal, bool $throwException): bool
  1304. {
  1305. if (null === $pid = $this->getPid()) {
  1306. if ($throwException) {
  1307. throw new LogicException('Can not send signal on a non running process.');
  1308. }
  1309. return false;
  1310. }
  1311. if ('\\' === \DIRECTORY_SEPARATOR) {
  1312. exec(sprintf('taskkill /F /T /PID %d 2>&1', $pid), $output, $exitCode);
  1313. if ($exitCode && $this->isRunning()) {
  1314. if ($throwException) {
  1315. throw new RuntimeException(sprintf('Unable to kill the process (%s).', implode(' ', $output)));
  1316. }
  1317. return false;
  1318. }
  1319. } else {
  1320. if (!$this->isSigchildEnabled()) {
  1321. $ok = @proc_terminate($this->process, $signal);
  1322. } elseif (\function_exists('posix_kill')) {
  1323. $ok = @posix_kill($pid, $signal);
  1324. } elseif ($ok = proc_open(sprintf('kill -%d %d', $signal, $pid), [2 => ['pipe', 'w']], $pipes)) {
  1325. $ok = false === fgets($pipes[2]);
  1326. }
  1327. if (!$ok) {
  1328. if ($throwException) {
  1329. throw new RuntimeException(sprintf('Error while sending signal "%s".', $signal));
  1330. }
  1331. return false;
  1332. }
  1333. }
  1334. $this->latestSignal = $signal;
  1335. $this->fallbackStatus['signaled'] = true;
  1336. $this->fallbackStatus['exitcode'] = -1;
  1337. $this->fallbackStatus['termsig'] = $this->latestSignal;
  1338. return true;
  1339. }
  1340. private function prepareWindowsCommandLine(string $cmd, array &$env): string
  1341. {
  1342. $uid = uniqid('', true);
  1343. $varCount = 0;
  1344. $varCache = [];
  1345. $cmd = preg_replace_callback(
  1346. '/"(?:(
  1347. [^"%!^]*+
  1348. (?:
  1349. (?: !LF! | "(?:\^[%!^])?+" )
  1350. [^"%!^]*+
  1351. )++
  1352. ) | [^"]*+ )"/x',
  1353. function ($m) use (&$env, &$varCache, &$varCount, $uid) {
  1354. if (!isset($m[1])) {
  1355. return $m[0];
  1356. }
  1357. if (isset($varCache[$m[0]])) {
  1358. return $varCache[$m[0]];
  1359. }
  1360. if (false !== strpos($value = $m[1], "\0")) {
  1361. $value = str_replace("\0", '?', $value);
  1362. }
  1363. if (false === strpbrk($value, "\"%!\n")) {
  1364. return '"'.$value.'"';
  1365. }
  1366. $value = str_replace(['!LF!', '"^!"', '"^%"', '"^^"', '""'], ["\n", '!', '%', '^', '"'], $value);
  1367. $value = '"'.preg_replace('/(\\\\*)"/', '$1$1\\"', $value).'"';
  1368. $var = $uid.++$varCount;
  1369. $env[$var] = $value;
  1370. return $varCache[$m[0]] = '!'.$var.'!';
  1371. },
  1372. $cmd
  1373. );
  1374. $cmd = 'cmd /V:ON /E:ON /D /C ('.str_replace("\n", ' ', $cmd).')';
  1375. foreach ($this->processPipes->getFiles() as $offset => $filename) {
  1376. $cmd .= ' '.$offset.'>"'.$filename.'"';
  1377. }
  1378. return $cmd;
  1379. }
  1380. /**
  1381. * Ensures the process is running or terminated, throws a LogicException if the process has a not started.
  1382. *
  1383. * @throws LogicException if the process has not run
  1384. */
  1385. private function requireProcessIsStarted(string $functionName)
  1386. {
  1387. if (!$this->isStarted()) {
  1388. throw new LogicException(sprintf('Process must be started before calling %s.', $functionName));
  1389. }
  1390. }
  1391. /**
  1392. * Ensures the process is terminated, throws a LogicException if the process has a status different than "terminated".
  1393. *
  1394. * @throws LogicException if the process is not yet terminated
  1395. */
  1396. private function requireProcessIsTerminated(string $functionName)
  1397. {
  1398. if (!$this->isTerminated()) {
  1399. throw new LogicException(sprintf('Process must be terminated before calling %s.', $functionName));
  1400. }
  1401. }
  1402. /**
  1403. * Escapes a string to be used as a shell argument.
  1404. */
  1405. private function escapeArgument(?string $argument): string
  1406. {
  1407. if ('' === $argument || null === $argument) {
  1408. return '""';
  1409. }
  1410. if ('\\' !== \DIRECTORY_SEPARATOR) {
  1411. return "'".str_replace("'", "'\\''", $argument)."'";
  1412. }
  1413. if (false !== strpos($argument, "\0")) {
  1414. $argument = str_replace("\0", '?', $argument);
  1415. }
  1416. if (!preg_match('/[\/()%!^"<>&|\s]/', $argument)) {
  1417. return $argument;
  1418. }
  1419. $argument = preg_replace('/(\\\\+)$/', '$1$1', $argument);
  1420. return '"'.str_replace(['"', '^', '%', '!', "\n"], ['""', '"^^"', '"^%"', '"^!"', '!LF!'], $argument).'"';
  1421. }
  1422. private function replacePlaceholders(string $commandline, array $env)
  1423. {
  1424. return preg_replace_callback('/"\$\{:([_a-zA-Z]++[_a-zA-Z0-9]*+)\}"/', function ($matches) use ($commandline, $env) {
  1425. if (!isset($env[$matches[1]]) || false === $env[$matches[1]]) {
  1426. throw new InvalidArgumentException(sprintf('Command line is missing a value for parameter "%s": %s.', $matches[1], $commandline));
  1427. }
  1428. return $this->escapeArgument($env[$matches[1]]);
  1429. }, $commandline);
  1430. }
  1431. private function getDefaultEnv(): array
  1432. {
  1433. $env = [];
  1434. foreach ($_SERVER as $k => $v) {
  1435. if (\is_string($v) && false !== $v = getenv($k)) {
  1436. $env[$k] = $v;
  1437. }
  1438. }
  1439. foreach ($_ENV as $k => $v) {
  1440. if (\is_string($v)) {
  1441. $env[$k] = $v;
  1442. }
  1443. }
  1444. return $env;
  1445. }
  1446. }