Builder.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. <?php
  2. /**
  3. * PEAR_Builder for building PHP extensions (PECL packages)
  4. *
  5. * PHP versions 4 and 5
  6. *
  7. * @category pear
  8. * @package PEAR
  9. * @author Stig Bakken <ssb@php.net>
  10. * @author Greg Beaver <cellog@php.net>
  11. * @copyright 1997-2009 The Authors
  12. * @license http://opensource.org/licenses/bsd-license.php New BSD License
  13. * @link http://pear.php.net/package/PEAR
  14. * @since File available since Release 0.1
  15. *
  16. * TODO: log output parameters in PECL command line
  17. * TODO: msdev path in configuration
  18. */
  19. /**
  20. * Needed for extending PEAR_Builder
  21. */
  22. require_once 'PEAR/Common.php';
  23. require_once 'PEAR/PackageFile.php';
  24. require_once 'System.php';
  25. /**
  26. * Class to handle building (compiling) extensions.
  27. *
  28. * @category pear
  29. * @package PEAR
  30. * @author Stig Bakken <ssb@php.net>
  31. * @author Greg Beaver <cellog@php.net>
  32. * @copyright 1997-2009 The Authors
  33. * @license http://opensource.org/licenses/bsd-license.php New BSD License
  34. * @version Release: 1.10.10
  35. * @link http://pear.php.net/package/PEAR
  36. * @since Class available since PHP 4.0.2
  37. * @see http://pear.php.net/manual/en/core.ppm.pear-builder.php
  38. */
  39. class PEAR_Builder extends PEAR_Common
  40. {
  41. var $php_api_version = 0;
  42. var $zend_module_api_no = 0;
  43. var $zend_extension_api_no = 0;
  44. var $extensions_built = array();
  45. /**
  46. * @var string Used for reporting when it is not possible to pass function
  47. * via extra parameter, e.g. log, msdevCallback
  48. */
  49. var $current_callback = null;
  50. // used for msdev builds
  51. var $_lastline = null;
  52. var $_firstline = null;
  53. /**
  54. * Parsed --configureoptions.
  55. *
  56. * @var mixed[]
  57. */
  58. var $_parsed_configure_options;
  59. /**
  60. * PEAR_Builder constructor.
  61. *
  62. * @param mixed[] $configureoptions
  63. * @param object $ui user interface object (instance of PEAR_Frontend_*)
  64. *
  65. * @access public
  66. */
  67. function __construct($configureoptions, &$ui)
  68. {
  69. parent::__construct();
  70. $this->setFrontendObject($ui);
  71. $this->_parseConfigureOptions($configureoptions);
  72. }
  73. /**
  74. * Parse --configureoptions string.
  75. *
  76. * @param string Options, in the form "X=1 Y=2 Z='there\'s always one'"
  77. */
  78. function _parseConfigureOptions($options)
  79. {
  80. $data = '<XML><PROPERTIES ' . $options . ' /></XML>';
  81. $parser = xml_parser_create('ISO-8859-1');
  82. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  83. xml_set_element_handler(
  84. $parser, array($this, '_parseConfigureOptionsStartElement'),
  85. array($this, '_parseConfigureOptionsEndElement'));
  86. xml_parse($parser, $data, true);
  87. xml_parser_free($parser);
  88. }
  89. /**
  90. * Handle element start.
  91. *
  92. * @see PEAR_Builder::_parseConfigureOptions()
  93. *
  94. * @param resource $parser
  95. * @param string $tagName
  96. * @param mixed[] $attribs
  97. */
  98. function _parseConfigureOptionsStartElement($parser, $tagName, $attribs)
  99. {
  100. if ($tagName !== 'PROPERTIES') {
  101. return;
  102. }
  103. $this->_parsed_configure_options = $attribs;
  104. }
  105. /**
  106. * Handle element end.
  107. *
  108. * @see PEAR_Builder::_parseConfigureOptions()
  109. *
  110. * @param resource
  111. * @param string $element
  112. */
  113. function _parseConfigureOptionsEndElement($parser, $element)
  114. {
  115. }
  116. /**
  117. * Build an extension from source on windows.
  118. * requires msdev
  119. */
  120. function _build_win32($descfile, $callback = null)
  121. {
  122. if (is_object($descfile)) {
  123. $pkg = $descfile;
  124. $descfile = $pkg->getPackageFile();
  125. } else {
  126. $pf = new PEAR_PackageFile($this->config, $this->debug);
  127. $pkg = &$pf->fromPackageFile($descfile, PEAR_VALIDATE_NORMAL);
  128. if (PEAR::isError($pkg)) {
  129. return $pkg;
  130. }
  131. }
  132. $dir = dirname($descfile);
  133. $old_cwd = getcwd();
  134. if (!file_exists($dir) || !is_dir($dir) || !chdir($dir)) {
  135. return $this->raiseError("could not chdir to $dir");
  136. }
  137. // packages that were in a .tar have the packagefile in this directory
  138. $vdir = $pkg->getPackage() . '-' . $pkg->getVersion();
  139. if (file_exists($dir) && is_dir($vdir)) {
  140. if (!chdir($vdir)) {
  141. return $this->raiseError("could not chdir to " . realpath($vdir));
  142. }
  143. $dir = getcwd();
  144. }
  145. $this->log(2, "building in $dir");
  146. $dsp = $pkg->getPackage().'.dsp';
  147. if (!file_exists("$dir/$dsp")) {
  148. return $this->raiseError("The DSP $dsp does not exist.");
  149. }
  150. // XXX TODO: make release build type configurable
  151. $command = 'msdev '.$dsp.' /MAKE "'.$pkg->getPackage(). ' - Release"';
  152. $err = $this->_runCommand($command, array(&$this, 'msdevCallback'));
  153. if (PEAR::isError($err)) {
  154. return $err;
  155. }
  156. // figure out the build platform and type
  157. $platform = 'Win32';
  158. $buildtype = 'Release';
  159. if (preg_match('/.*?'.$pkg->getPackage().'\s-\s(\w+)\s(.*?)-+/i',$this->_firstline,$matches)) {
  160. $platform = $matches[1];
  161. $buildtype = $matches[2];
  162. }
  163. if (preg_match('/(.*)?\s-\s(\d+).*?(\d+)/', $this->_lastline, $matches)) {
  164. if ($matches[2]) {
  165. // there were errors in the build
  166. return $this->raiseError("There were errors during compilation.");
  167. }
  168. $out = $matches[1];
  169. } else {
  170. return $this->raiseError("Did not understand the completion status returned from msdev.exe.");
  171. }
  172. // msdev doesn't tell us the output directory :/
  173. // open the dsp, find /out and use that directory
  174. $dsptext = join(file($dsp),'');
  175. // this regex depends on the build platform and type having been
  176. // correctly identified above.
  177. $regex ='/.*?!IF\s+"\$\(CFG\)"\s+==\s+("'.
  178. $pkg->getPackage().'\s-\s'.
  179. $platform.'\s'.
  180. $buildtype.'").*?'.
  181. '\/out:"(.*?)"/is';
  182. if ($dsptext && preg_match($regex, $dsptext, $matches)) {
  183. // what we get back is a relative path to the output file itself.
  184. $outfile = realpath($matches[2]);
  185. } else {
  186. return $this->raiseError("Could not retrieve output information from $dsp.");
  187. }
  188. // realpath returns false if the file doesn't exist
  189. if ($outfile && copy($outfile, "$dir/$out")) {
  190. $outfile = "$dir/$out";
  191. }
  192. $built_files[] = array(
  193. 'file' => "$outfile",
  194. 'php_api' => $this->php_api_version,
  195. 'zend_mod_api' => $this->zend_module_api_no,
  196. 'zend_ext_api' => $this->zend_extension_api_no,
  197. );
  198. return $built_files;
  199. }
  200. // }}}
  201. // {{{ msdevCallback()
  202. function msdevCallback($what, $data)
  203. {
  204. if (!$this->_firstline)
  205. $this->_firstline = $data;
  206. $this->_lastline = $data;
  207. call_user_func($this->current_callback, $what, $data);
  208. }
  209. /**
  210. * @param string
  211. * @param string
  212. * @param array
  213. * @access private
  214. */
  215. function _harvestInstDir($dest_prefix, $dirname, &$built_files)
  216. {
  217. $d = opendir($dirname);
  218. if (!$d)
  219. return false;
  220. $ret = true;
  221. while (($ent = readdir($d)) !== false) {
  222. if ($ent[0] == '.')
  223. continue;
  224. $full = $dirname . DIRECTORY_SEPARATOR . $ent;
  225. if (is_dir($full)) {
  226. if (!$this->_harvestInstDir(
  227. $dest_prefix . DIRECTORY_SEPARATOR . $ent,
  228. $full, $built_files)) {
  229. $ret = false;
  230. break;
  231. }
  232. } else {
  233. $dest = $dest_prefix . DIRECTORY_SEPARATOR . $ent;
  234. $built_files[] = array(
  235. 'file' => $full,
  236. 'dest' => $dest,
  237. 'php_api' => $this->php_api_version,
  238. 'zend_mod_api' => $this->zend_module_api_no,
  239. 'zend_ext_api' => $this->zend_extension_api_no,
  240. );
  241. }
  242. }
  243. closedir($d);
  244. return $ret;
  245. }
  246. /**
  247. * Build an extension from source. Runs "phpize" in the source
  248. * directory, but compiles in a temporary directory
  249. * (TMPDIR/pear-build-USER/PACKAGE-VERSION).
  250. *
  251. * @param string|PEAR_PackageFile_v* $descfile path to XML package description file, or
  252. * a PEAR_PackageFile object
  253. *
  254. * @param mixed $callback callback function used to report output,
  255. * see PEAR_Builder::_runCommand for details
  256. *
  257. * @return array an array of associative arrays with built files,
  258. * format:
  259. * array( array( 'file' => '/path/to/ext.so',
  260. * 'php_api' => YYYYMMDD,
  261. * 'zend_mod_api' => YYYYMMDD,
  262. * 'zend_ext_api' => YYYYMMDD ),
  263. * ... )
  264. *
  265. * @access public
  266. *
  267. * @see PEAR_Builder::_runCommand
  268. */
  269. function build($descfile, $callback = null)
  270. {
  271. if (preg_match('/(\\/|\\\\|^)([^\\/\\\\]+)?php([^\\/\\\\]+)?$/',
  272. $this->config->get('php_bin'), $matches)) {
  273. if (isset($matches[2]) && strlen($matches[2]) &&
  274. trim($matches[2]) != trim($this->config->get('php_prefix'))) {
  275. $this->log(0, 'WARNING: php_bin ' . $this->config->get('php_bin') .
  276. ' appears to have a prefix ' . $matches[2] . ', but' .
  277. ' config variable php_prefix does not match');
  278. }
  279. if (isset($matches[3]) && strlen($matches[3]) &&
  280. trim($matches[3]) != trim($this->config->get('php_suffix'))) {
  281. $this->log(0, 'WARNING: php_bin ' . $this->config->get('php_bin') .
  282. ' appears to have a suffix ' . $matches[3] . ', but' .
  283. ' config variable php_suffix does not match');
  284. }
  285. }
  286. $this->current_callback = $callback;
  287. if (PEAR_OS == "Windows") {
  288. return $this->_build_win32($descfile, $callback);
  289. }
  290. if (PEAR_OS != 'Unix') {
  291. return $this->raiseError("building extensions not supported on this platform");
  292. }
  293. if (is_object($descfile)) {
  294. $pkg = $descfile;
  295. $descfile = $pkg->getPackageFile();
  296. if (is_a($pkg, 'PEAR_PackageFile_v1')) {
  297. $dir = dirname($descfile);
  298. } else {
  299. $dir = $pkg->_config->get('temp_dir') . '/' . $pkg->getName();
  300. // automatically delete at session end
  301. self::addTempFile($dir);
  302. }
  303. } else {
  304. $pf = new PEAR_PackageFile($this->config);
  305. $pkg = &$pf->fromPackageFile($descfile, PEAR_VALIDATE_NORMAL);
  306. if (PEAR::isError($pkg)) {
  307. return $pkg;
  308. }
  309. $dir = dirname($descfile);
  310. }
  311. // Find config. outside of normal path - e.g. config.m4
  312. foreach (array_keys($pkg->getInstallationFileList()) as $item) {
  313. if (stristr(basename($item), 'config.m4') && dirname($item) != '.') {
  314. $dir .= DIRECTORY_SEPARATOR . dirname($item);
  315. break;
  316. }
  317. }
  318. $old_cwd = getcwd();
  319. if (!file_exists($dir) || !is_dir($dir) || !chdir($dir)) {
  320. return $this->raiseError("could not chdir to $dir");
  321. }
  322. $vdir = $pkg->getPackage() . '-' . $pkg->getVersion();
  323. if (is_dir($vdir)) {
  324. chdir($vdir);
  325. }
  326. $dir = getcwd();
  327. $this->log(2, "building in $dir");
  328. $binDir = $this->config->get('bin_dir');
  329. if (!preg_match('@(^|:)' . preg_quote($binDir, '@') . '(:|$)@', getenv('PATH'))) {
  330. putenv('PATH=' . $binDir . ':' . getenv('PATH'));
  331. }
  332. $err = $this->_runCommand($this->config->get('php_prefix')
  333. . "phpize" .
  334. $this->config->get('php_suffix'),
  335. array(&$this, 'phpizeCallback'));
  336. if (PEAR::isError($err)) {
  337. return $err;
  338. }
  339. if (!$err) {
  340. return $this->raiseError("`phpize' failed");
  341. }
  342. // {{{ start of interactive part
  343. $configure_command = "$dir/configure";
  344. $phpConfigName = $this->config->get('php_prefix')
  345. . 'php-config'
  346. . $this->config->get('php_suffix');
  347. $phpConfigPath = System::which($phpConfigName);
  348. if ($phpConfigPath !== false) {
  349. $configure_command .= ' --with-php-config='
  350. . $phpConfigPath;
  351. }
  352. $configure_options = $pkg->getConfigureOptions();
  353. if ($configure_options) {
  354. foreach ($configure_options as $option) {
  355. $default = array_key_exists('default', $option) ? $option['default'] : null;
  356. if (array_key_exists($option['name'], $this->_parsed_configure_options)) {
  357. $response = $this->_parsed_configure_options[$option['name']];
  358. } else {
  359. list($response) = $this->ui->userDialog(
  360. 'build', [$option['prompt']], ['text'], [$default]);
  361. }
  362. if (substr($option['name'], 0, 5) === 'with-' &&
  363. ($response === 'yes' || $response === 'autodetect')) {
  364. $configure_command .= " --{$option[name]}";
  365. } else {
  366. $configure_command .= " --{$option[name]}=".trim($response);
  367. }
  368. }
  369. }
  370. // }}} end of interactive part
  371. // FIXME make configurable
  372. if (!$user=getenv('USER')) {
  373. $user='defaultuser';
  374. }
  375. $tmpdir = $this->config->get('temp_dir');
  376. $build_basedir = System::mktemp(' -t "' . $tmpdir . '" -d "pear-build-' . $user . '"');
  377. $build_dir = "$build_basedir/$vdir";
  378. $inst_dir = "$build_basedir/install-$vdir";
  379. $this->log(1, "building in $build_dir");
  380. if (is_dir($build_dir)) {
  381. System::rm(array('-rf', $build_dir));
  382. }
  383. if (!System::mkDir(array('-p', $build_dir))) {
  384. return $this->raiseError("could not create build dir: $build_dir");
  385. }
  386. self::addTempFile($build_dir);
  387. if (!System::mkDir(array('-p', $inst_dir))) {
  388. return $this->raiseError("could not create temporary install dir: $inst_dir");
  389. }
  390. self::addTempFile($inst_dir);
  391. $make_command = getenv('MAKE') ? getenv('MAKE') : 'make';
  392. $to_run = array(
  393. $configure_command,
  394. $make_command,
  395. "$make_command INSTALL_ROOT=\"$inst_dir\" install",
  396. "find \"$inst_dir\" | xargs ls -dils"
  397. );
  398. if (!file_exists($build_dir) || !is_dir($build_dir) || !chdir($build_dir)) {
  399. return $this->raiseError("could not chdir to $build_dir");
  400. }
  401. putenv('PHP_PEAR_VERSION=1.10.10');
  402. foreach ($to_run as $cmd) {
  403. $err = $this->_runCommand($cmd, $callback);
  404. if (PEAR::isError($err)) {
  405. chdir($old_cwd);
  406. return $err;
  407. }
  408. if (!$err) {
  409. chdir($old_cwd);
  410. return $this->raiseError("`$cmd' failed");
  411. }
  412. }
  413. if (!($dp = opendir("modules"))) {
  414. chdir($old_cwd);
  415. return $this->raiseError("no `modules' directory found");
  416. }
  417. $built_files = array();
  418. $prefix = exec($this->config->get('php_prefix')
  419. . "php-config" .
  420. $this->config->get('php_suffix') . " --prefix");
  421. $this->_harvestInstDir($prefix, $inst_dir . DIRECTORY_SEPARATOR . $prefix, $built_files);
  422. chdir($old_cwd);
  423. return $built_files;
  424. }
  425. /**
  426. * Message callback function used when running the "phpize"
  427. * program. Extracts the API numbers used. Ignores other message
  428. * types than "cmdoutput".
  429. *
  430. * @param string $what the type of message
  431. * @param mixed $data the message
  432. *
  433. * @return void
  434. *
  435. * @access public
  436. */
  437. function phpizeCallback($what, $data)
  438. {
  439. if ($what != 'cmdoutput') {
  440. return;
  441. }
  442. $this->log(1, rtrim($data));
  443. if (preg_match('/You should update your .aclocal.m4/', $data)) {
  444. return;
  445. }
  446. $matches = array();
  447. if (preg_match('/^\s+(\S[^:]+):\s+(\d{8})/', $data, $matches)) {
  448. $member = preg_replace('/[^a-z]/', '_', strtolower($matches[1]));
  449. $apino = (int)$matches[2];
  450. if (isset($this->$member)) {
  451. $this->$member = $apino;
  452. //$msg = sprintf("%-22s : %d", $matches[1], $apino);
  453. //$this->log(1, $msg);
  454. }
  455. }
  456. }
  457. /**
  458. * Run an external command, using a message callback to report
  459. * output. The command will be run through popen and output is
  460. * reported for every line with a "cmdoutput" message with the
  461. * line string, including newlines, as payload.
  462. *
  463. * @param string $command the command to run
  464. *
  465. * @param mixed $callback (optional) function to use as message
  466. * callback
  467. *
  468. * @return bool whether the command was successful (exit code 0
  469. * means success, any other means failure)
  470. *
  471. * @access private
  472. */
  473. function _runCommand($command, $callback = null)
  474. {
  475. $this->log(1, "running: $command");
  476. $pp = popen("$command 2>&1", "r");
  477. if (!$pp) {
  478. return $this->raiseError("failed to run `$command'");
  479. }
  480. if ($callback && $callback[0]->debug == 1) {
  481. $olddbg = $callback[0]->debug;
  482. $callback[0]->debug = 2;
  483. }
  484. while ($line = fgets($pp, 1024)) {
  485. if ($callback) {
  486. call_user_func($callback, 'cmdoutput', $line);
  487. } else {
  488. $this->log(2, rtrim($line));
  489. }
  490. }
  491. if ($callback && isset($olddbg)) {
  492. $callback[0]->debug = $olddbg;
  493. }
  494. $exitcode = is_resource($pp) ? pclose($pp) : -1;
  495. return ($exitcode == 0);
  496. }
  497. function log($level, $msg, $append_crlf = true)
  498. {
  499. if ($this->current_callback) {
  500. if ($this->debug >= $level) {
  501. call_user_func($this->current_callback, 'output', $msg);
  502. }
  503. return;
  504. }
  505. return parent::log($level, $msg, $append_crlf);
  506. }
  507. }