PageRenderTime 89ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/cons-2.2.0/cons

https://github.com/gitpan/AutoCons
Perl | 5713 lines | 4417 code | 731 blank | 565 comment | 523 complexity | 9fa817b66048fefa015c1b0d9428ea10 MD5 | raw file
Possible License(s): GPL-2.0
  1. #!/usr/bin/env perl
  2. # NOTE: Cons intentionally does not use the "perl -w" option or
  3. # "use strict." Because Cons "configuration files" are actually
  4. # Perl scripts, enabling those restrictions here would force them
  5. # on every user's config files, wanted or not. Would users write
  6. # "better" Construct and Conscript files if we forced "use strict"
  7. # on them? Probably. But we want people to use Cons to get work
  8. # done, not force everyone to become a Perl guru to use it, so we
  9. # don't insist.
  10. #
  11. # That said, Cons' code is both "perl -w" and "use strict" clean.
  12. # Regression tests keep the code honest by checking for warnings
  13. # and "use strict" failures.
  14. # $Id: cons.pl,v 1.129 2000/11/16 12:22:37 knight Exp $
  15. use vars qw( $ver_num $ver_rev $version );
  16. $ver_num = "2.2";
  17. $ver_rev = ".0";
  18. $version = sprintf "This is Cons %s%s " .
  19. '($Id: cons.pl,v 1.129 2000/11/16 12:22:37 knight Exp $)'. "\n",
  20. $ver_num, $ver_rev;
  21. # Cons: A Software Construction Tool.
  22. # Copyright (c) 1996-2000 Free Software Foundation, Inc.
  23. #
  24. # This program is free software; you can redistribute it and/or modify
  25. # it under the terms of the GNU General Public License as published by
  26. # the Free Software Foundation; either version 2 of the License, or
  27. # (at your option) any later version.
  28. #
  29. # This program is distributed in the hope that it will be useful,
  30. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  31. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  32. # GNU General Public License for more details.
  33. #
  34. # You should have received a copy of the GNU General Public License
  35. # along with this program; see the file COPYING. If not, write to
  36. # the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  37. # Boston, MA 02111-1307, USA.
  38. require 5.002;
  39. # See the NOTE above about why Cons doesn't "use strict".
  40. use integer;
  41. use Cwd;
  42. use File::Copy;
  43. use vars qw( $_WIN32 $_a $_exe $_o $_so );
  44. #------------------------------------------------------------------
  45. # Determine if running on win32 platform - either Windows NT or 95
  46. #------------------------------------------------------------------
  47. use vars qw( $PATH_SEPARATOR $iswin32 $_WIN32 $usage $indent @targets );
  48. BEGIN {
  49. use Config;
  50. # if the version is 5.003, we can check $^O
  51. if ($] < 5.003) {
  52. eval("require Win32");
  53. $_WIN32 = (!$@);
  54. } else {
  55. $_WIN32 = ($^O eq "MSWin32") ? 1 : 0;
  56. }
  57. # Fetch the PATH separator from Config;
  58. # provide our old defaults in case it's not set.
  59. $PATH_SEPARATOR = $Config{path_sep};
  60. $PATH_SEPARATOR = $_WIN32 ? ';' : ':' if ! defined $PATH_SEPARATOR;
  61. # Fetch file suffixes from Config,
  62. # accomodating differences in the Config variables
  63. # used by different Perl versions.
  64. $_exe = $Config{_exe};
  65. $_exe = $Config{exe_ext} if ! defined $_exe;
  66. $_exe = $_WIN32 ? '.exe' : '' if ! defined $_exe;
  67. $_o = $Config{_o};
  68. $_o = $Config{obj_ext} if ! defined $_o;
  69. $_o = $_WIN32 ? '.obj' : '.o' if ! defined $_o;
  70. $_a = $Config{_a};
  71. $_a = $Config{lib_ext} if ! defined $_a;
  72. $_a = $_WIN32 ? '.lib' : '.a' if ! defined $_a;
  73. $_so = ".$Config{so}";
  74. $_so = $_WIN32 ? '.dll' : '.so' if ! defined $_so;
  75. }
  76. # Flush stdout each time.
  77. $| = 1;
  78. # Seed random number generator.
  79. srand(time . $$); # this works better than time ^ $$ in perlfunc manpage.
  80. $usage = q(
  81. Usage: cons <arguments> -- <construct-args>
  82. Arguments can be any of the following, in any order:
  83. <targets> Build the specified targets. If <target> is a directory
  84. recursively build everything within that directory.
  85. +<pattern> Limit the cons scripts considered to just those that
  86. match <pattern>. Multiple + arguments are accepted.
  87. <name>=<val> Sets <name> to value <val> in the ARG hash passed to the
  88. top-level Construct file.
  89. -cc Show command that would have been executed, when
  90. retrieving from cache. No indication that the file
  91. has been retrieved is given; this is useful for
  92. generating build logs that can be compared with
  93. real build logs.
  94. -cd Disable all caching. Do not retrieve from cache nor
  95. flush to cache.
  96. -cr Build dependencies in random order. This is useful when
  97. building multiple similar trees with caching enabled.
  98. -cs Synchronize existing build targets that are found to be
  99. up-to-date with cache. This is useful if caching has
  100. been disabled with -cc or just recently enabled with
  101. UseCache.
  102. -d Enable dependency debugging.
  103. -f <file> Use the specified file instead of "Construct" (but first
  104. change to containing directory of <file>).
  105. -h Show a help message local to the current build if
  106. one such is defined, and exit.
  107. -k Keep going as far as possible after errors.
  108. -o <file> Read override file <file>.
  109. -p Show construction products in specified trees.
  110. -pa Show construction products and associated actions.
  111. -pw Show products and where they are defined.
  112. -q Be quiet about Installing and Removing targets.
  113. -r Remove construction products associated with <targets>
  114. -R <repos> Search for files in <repos>. Multiple -R <repos>
  115. directories are searched in the order specified.
  116. -t Traverse up the directory hierarchy looking for a
  117. Construct file, if none exists in the current directory.
  118. (Targets will be modified to be relative to the
  119. Construct file.)
  120. -v Show cons version and continue processing.
  121. -V Show cons version and exit.
  122. -wf <file> Write all filenames considered into <file>.
  123. -x Show this message and exit.
  124. Please report any suggestions through the cons-discuss@gnu.org mailing
  125. list.
  126. To subscribe, send mail to cons-discuss-request@gnu.org with body
  127. 'subscribe'.
  128. If you find a bug, please report it through the bug-cons@gnu.org
  129. mailing list.
  130. Information about CONS can be obtained from the official cons web site
  131. http://www.dsmit.com/cons/ or its mirrors (listed there).
  132. The cons maintainers can be contacted by email at cons-maintainers@gnu.org
  133. User documentation of cons is contained in cons and can be obtained
  134. by doing 'perldoc /path/to/cons'.
  135. );
  136. # Simplify program name, if it is a path.
  137. {
  138. my ($vol, $dir, $file) = File::Spec->splitpath(File::Spec->canonpath($0));
  139. $0 = $file;
  140. }
  141. # Default parameters.
  142. $param::topfile = 'Construct'; # Top-level construction file.
  143. $param::install = 1; # Show installations
  144. $param::build = 1; # Build targets
  145. ### $param::show = 1; # Show building of targets.
  146. $param::sigpro = 'md5'; # Signature protocol.
  147. $param::depfile = ''; # Write all deps out to this file
  148. $param::salt = ''; # Salt derived file signatures with this.
  149. $param::rep_sig_times_ok = 1; # Repository .consign times are in sync
  150. # w/files.
  151. $param::conscript_chdir = 0; # Change dir to Conscript directory
  152. $param::quiet = 0; # should we show the command being executed.
  153. #
  154. $indent = '';
  155. # Display a command while executing or otherwise. This
  156. # should be called by command builder action methods.
  157. sub showcom {
  158. print($indent . $_[0] . "\n");
  159. }
  160. # Default environment.
  161. # This contains only the completely platform-independent information
  162. # we can figure out. Platform-specific information (UNIX, Win32)
  163. # gets added below.
  164. @param::defaults = (
  165. 'SUFEXE' => $_exe, # '' on UNIX systems
  166. 'SUFLIB' => $_a, # '.a' on UNIX systems
  167. 'SUFLIBS' => "$_so:$_a", # '.so:.a' on UNIX
  168. 'SUFOBJ' => $_o, # '.o' on UNIX systems
  169. 'SUFMAP' => {
  170. '.c' => 'build::command::cc',
  171. '.s' => 'build::command::cc',
  172. '.S' => 'build::command::cc',
  173. '.C' => 'build::command::cxx',
  174. '.cc' => 'build::command::cxx',
  175. '.cxx'=> 'build::command::cxx',
  176. '.cpp'=> 'build::command::cxx',
  177. '.c++'=> 'build::command::cxx',
  178. '.C++'=> 'build::command::cxx',
  179. },
  180. );
  181. if ($_WIN32) {
  182. # Defaults for Win32.
  183. # Defined for VC++ 6.0 by Greg Spencer <greg_spencer@acm.org>.
  184. # Your mileage may vary.
  185. my @win = (
  186. 'CC' => 'cl',
  187. 'CFLAGS' => '/nologo',
  188. 'CCCOM' => '%CC %CFLAGS %_IFLAGS /c %< /Fo%>',
  189. 'CXX' => '%CC',
  190. 'CXXFLAGS' => '%CFLAGS',
  191. 'CXXCOM' => '%CXX %CXXFLAGS %_IFLAGS /c %< /Fo%>',
  192. 'INCDIRPREFIX' => '/I',
  193. 'LINK' => 'link',
  194. 'LINKCOM' => '%LINK %LDFLAGS /out:%> %< %_LDIRS %LIBS',
  195. 'LINKMODULECOM' => '%LD /r /o %> %<',
  196. 'LIBDIRPREFIX' => '/LIBPATH:',
  197. 'AR' => 'lib',
  198. 'ARFLAGS' => '/nologo ',
  199. 'ARCOM' => "%AR %ARFLAGS /out:%> %<",
  200. 'RANLIB' => '',
  201. 'LD' => 'link',
  202. 'LDFLAGS' => '/nologo ',
  203. 'PREFLIB' => '',
  204. );
  205. push(@param::defaults, @win);
  206. } else {
  207. # Defaults for a typical (?) UNIX platform.
  208. # Your mileage may vary.
  209. my @unix = (
  210. 'CC' => 'cc',
  211. 'CFLAGS' => '',
  212. 'CCCOM' => '%CC %CFLAGS %_IFLAGS -c %< -o %>',
  213. 'CXX' => '%CC',
  214. 'CXXFLAGS' => '%CFLAGS',
  215. 'CXXCOM' => '%CXX %CXXFLAGS %_IFLAGS -c %< -o %>',
  216. 'INCDIRPREFIX' => '-I',
  217. 'LINK' => '%CXX',
  218. 'LINKCOM' => '%LINK %LDFLAGS -o %> %< %_LDIRS %LIBS',
  219. 'LINKMODULECOM' => '%LD -r -o %> %<',
  220. 'LIBDIRPREFIX' => '-L',
  221. 'AR' => 'ar',
  222. 'ARFLAGS' => 'r', # rs?
  223. 'ARCOM' => "%AR %ARFLAGS %> %<\n%RANLIB %>",
  224. 'RANLIB' => 'ranlib',
  225. 'AS' => 'as',
  226. 'ASFLAGS' => '',
  227. 'ASCOM' => '%AS %ASFLAGS %< -o %>',
  228. 'LD' => 'ld',
  229. 'LDFLAGS' => '',
  230. 'PREFLIB' => 'lib',
  231. 'ENV' => { 'PATH' => '/bin:/usr/bin' },
  232. );
  233. push(@param::defaults, @unix);
  234. }
  235. # Handle command line arguments.
  236. while (@ARGV) {
  237. $_ = shift @ARGV;
  238. last if /^--$/; # Argument passing to Construct.
  239. &option, next if s/^-//;
  240. push (@param::include, $_), next if s/^\+//;
  241. &equate, next if /=/;
  242. push (@targets, $_), next;
  243. }
  244. sub option {
  245. my %opt = (
  246. 'cc' => sub { $param::cachecom = 1; },
  247. 'cd' => sub { $param::cachedisable = 1; },
  248. 'cr' => sub { $param::random = 1; },
  249. 'cs' => sub { $param::cachesync = 1; },
  250. 'd' => sub { $param::depends = 1; },
  251. 'h' => sub { $param::localhelp = 1; },
  252. 'k' => sub { $param::kflag = 1; },
  253. 'p' => sub { $param::pflag = 1;
  254. $param::build = 0; },
  255. 'pa' => sub { $param::pflag = 1;
  256. $param::aflag = 1;
  257. $indent = "... ";
  258. $param::build = 0; },
  259. 'pw' => sub { $param::pflag = 1;
  260. $param::wflag = 1;
  261. $param::build = 0; },
  262. 'q' => sub { $param::quiet = 1; },
  263. 'r' => sub { $param::rflag = 1;
  264. $param::build = 0; },
  265. 't' => sub { $param::traverse = 1; },
  266. 'v' => sub { print($version); },
  267. 'V' => sub { print($version), exit(0); },
  268. 'x' => sub { print($usage), exit 0; },
  269. );
  270. my %opt_arg = (
  271. 'f' => sub { $param::topfile = $_[0]; },
  272. 'o' => sub { $param::overfile = $_[0]; },
  273. 'R' => sub { script::Repository($_[0]); },
  274. 'wf' => sub { $param::depfile = $_[0]; },
  275. );
  276. if (defined $opt{$_}) {
  277. &{$opt{$_}}();
  278. return;
  279. }
  280. $_ =~ m/(.)(.*)/;
  281. if (defined $opt_arg{$1}) {
  282. if (! $2) {
  283. $_ = shift @ARGV;
  284. die("$0: -$1 option requires an argument.\n") if ! $_;
  285. }
  286. &{$opt_arg{$1}}($2 || $_);
  287. return;
  288. }
  289. $_ =~ m/(..)(.*)/;
  290. if (defined $opt_arg{$1}) {
  291. if (! $2) {
  292. $_ = shift @ARGV;
  293. die("$0: -$1 option requires an argument.\n") if ! $_;
  294. }
  295. &{$opt_arg{$1}}($2 || $_);
  296. return;
  297. }
  298. if ($_) {
  299. die qq($0: unrecognized option "-$_". Use -x for a usage message.\n);
  300. }
  301. }
  302. # Process an equate argument (var=val).
  303. sub equate {
  304. my($var, $val) = /([^=]*)=(.*)/;
  305. $script::ARG{$var} = $val;
  306. }
  307. # Define file signature protocol.
  308. 'sig'->select($param::sigpro);
  309. # Cleanup after an interrupt.
  310. $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = sub {
  311. $SIG{PIPE} = $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = 'IGNORE';
  312. $SIG{HUP} = $SIG{INT} if ! $main::_WIN32;
  313. warn("\n$0: killed\n");
  314. # Call this first, to make sure that this processing
  315. # occurs even if a child process does not die (and we
  316. # hang on the wait).
  317. sig::hash::END();
  318. wait();
  319. exit(1);
  320. };
  321. $SIG{HUP} = $SIG{INT} if ! $main::_WIN32;
  322. # Cleanup after a broken pipe (someone piped our stdout?)
  323. $SIG{PIPE} = sub {
  324. $SIG{PIPE} = $SIG{HUP} = $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = 'IGNORE';
  325. warn("\n$0: broken pipe\n");
  326. sig::hash::END();
  327. wait();
  328. exit(1);
  329. };
  330. if ($param::depfile) {
  331. open (main::DEPFILE, ">".$param::depfile) ||
  332. die ("$0: couldn't open $param::depfile ($!)\n");
  333. }
  334. # If the supplied top-level Conscript file is not in the
  335. # current directory, then change to that directory.
  336. {
  337. my ($vol, $dir, $file) = File::Spec->splitpath(File::Spec->canonpath($param::topfile));
  338. if ($vol || $dir) {
  339. my($cd) = File::Spec->catpath($vol, $dir, undef);
  340. chdir($cd) || die("$0: couldn't change to directory $cd ($!)\n");
  341. $param::topfile = $file;
  342. }
  343. }
  344. # Walk up the directory hierarchy looking for a Conscript file (if -t set).
  345. my($target_top);
  346. my(@targetdir) = ();
  347. if ($param::traverse && ! -f $param::topfile) {
  348. my($vol, $dirs, $file) = File::Spec->splitpath(cwd());
  349. my(@dirs) = (File::Spec->splitdir($dirs), $file);
  350. while (! -f File::Spec->catpath($vol, File::Spec->catdir(@dirs), $param::topfile)) {
  351. die("$0: unable to find $param::topfile.\n") if ! @dirs;
  352. unshift(@targetdir, pop(@dirs));
  353. }
  354. my($cwd) = File::Spec->catpath($vol, File::Spec->catdir(@dirs), '');
  355. print "$0: Entering directory `$cwd'\n";
  356. chdir($cwd);
  357. @targets = map {File::Spec->catdir(@targetdir, $_)} @targets;
  358. }
  359. # Set up $dir::top and $dir::cwd, now that we are in the right directory.
  360. dir::init();
  361. #
  362. if (@targetdir) {
  363. $target_top = $dir::top->lookupdir(File::Spec->catdir(@targetdir));
  364. }
  365. # Now handle override file.
  366. package override;
  367. if ($param::overfile) {
  368. my($ov) = $param::overfile;
  369. die qq($0: can\'t read override file "$ov" ($!)\n) if ! -f $ov; #'
  370. do $ov;
  371. if ($@) {
  372. chop($@);
  373. die qq($0: errors in override file "$ov" ($@)\n);
  374. }
  375. }
  376. # Provide this to user to setup override patterns.
  377. sub Override {
  378. my($re, @env) = @_;
  379. return if $param::overrides{$re}; # if identical, first will win.
  380. $param::overrides = 1;
  381. $param::overrides{$re} = \@env;
  382. push(@param::overrides, $re);
  383. }
  384. package main;
  385. use vars qw( %priority $errors );
  386. # Check script inclusion regexps
  387. my $re;
  388. for $re (@param::include) {
  389. if (! defined eval {"" =~ /$re/}) {
  390. my($err) = $@;
  391. $err =~ s/in regexp at .*$//;
  392. die("$0: error in regexp $err");
  393. }
  394. }
  395. # Read the top-level construct file and its included scripts.
  396. doscripts($param::topfile);
  397. # Status priorities. This lets us aggregate status for directories
  398. # and print an appropriate message (at the top-level).
  399. %priority =
  400. ('none' => 1, 'handled' => 2, 'built' => 3, 'unknown' => 4, 'errors' => 5);
  401. # If no targets were specified, supply default targets (if any).
  402. @targets = @param::default_targets if ! @targets;
  403. $errors = 0;
  404. # Build the supplied target patterns.
  405. my $tgt;
  406. for $tgt (map($dir::top->lookup($_), @targets)) {
  407. if ($target_top && ! $tgt->is_under($target_top)) {
  408. # A -t option was used, and this target is not underneath
  409. # the directory where we were invoked via -t.
  410. # If the target is a directory and the -t directory
  411. # is underneath it, then build the -t directory.
  412. if (ref $tgt ne "dir" || ! $target_top->is_under($tgt)) {
  413. next;
  414. }
  415. $tgt = $target_top;
  416. }
  417. buildtoptarget($tgt);
  418. }
  419. exit 0 + ($errors != 0);
  420. sub buildtoptarget {
  421. my($tgt) = @_;
  422. return if ! $tgt;
  423. my($status) = buildtarget($tgt);
  424. if ($status ne 'built') {
  425. my($path) = $tgt->path;
  426. if ($status eq "errors") {
  427. print qq($0: "$path" not remade because of errors.\n);
  428. $errors++;
  429. } elsif ($status eq "handled") {
  430. print qq($0: "$path" is up-to-date.\n);
  431. } elsif ($status eq "unknown") {
  432. # cons error already reported.
  433. $errors++;
  434. } elsif ($status eq "none") {
  435. # search for targets that may be linked to the given path.
  436. my @linked = dir::linked_targets($tgt) if $target_top;
  437. if (@linked) {
  438. my @names = map($_->path, @linked);
  439. print "Linked targets: @names\n" unless ($param::quiet);
  440. map(buildtoptarget($_), @linked);
  441. } else {
  442. print qq($0: nothing to be built in "$path".\n) if $param::build;
  443. }
  444. } else {
  445. print qq($0: don\'t know how to construct "$path".\n); #'
  446. $errors++;
  447. }
  448. }
  449. }
  450. # Build the supplied target directory or files. Return aggregated status.
  451. sub buildtarget {
  452. my($tgt) = @_;
  453. if (ref($tgt) eq "dir") {
  454. my($result) = "none";
  455. my($priority) = $priority{$result};
  456. if (exists $tgt->{member}) {
  457. my($members) = $tgt->{member};
  458. my $entry;
  459. for $entry (sort keys %$members) {
  460. next if $entry eq $dir::CURDIR || $entry eq $dir::UPDIR;
  461. my($tgt) = $members->{$entry};
  462. next if ref($tgt) ne "dir" && !exists($tgt->{builder});
  463. my($stat) = buildtarget($members->{$entry});
  464. my($pri) = $priority{$stat};
  465. if ($pri > $priority) {
  466. $priority = $pri;
  467. $result = $stat;
  468. }
  469. }
  470. }
  471. return $result;
  472. }
  473. if ($param::depends) {
  474. my($path) = $tgt->path;
  475. if ($tgt->{builder}) {
  476. my(@dep) = (@{$tgt->{dep}}, @{$tgt->{sources}});
  477. my($dep) = join(' ',map($_->path, @dep));
  478. print("Target $path: $dep\n");
  479. } else {
  480. print("Target $path: not a derived file\n");
  481. }
  482. }
  483. if ($param::build) {
  484. return build $tgt;
  485. } elsif ($param::pflag || $param::wflag || $param::aflag) {
  486. if ($tgt->{builder}) {
  487. if ($param::wflag) {
  488. print qq(${\$tgt->path}: $tgt->{script}\n);
  489. } elsif ($param::pflag) {
  490. print qq(${\$tgt->path}:\n) if $param::aflag;
  491. print qq(${\$tgt->path}\n) if !$param::aflag;
  492. }
  493. if ($param::aflag) {
  494. $tgt->{builder}->action($tgt);
  495. }
  496. }
  497. } elsif ($param::rflag && $tgt->{builder}) {
  498. my($path) = $tgt->path;
  499. if (-f $path) {
  500. if (unlink($path)) {
  501. print("Removed $path\n") unless ($param::quiet);
  502. } else {
  503. warn("$0: couldn't remove $path\n");
  504. }
  505. }
  506. }
  507. return "none";
  508. }
  509. package NameSpace;
  510. # Return a hash that maps the name of symbols in a namespace to an
  511. # array of refs for all types for which the name has a defined value.
  512. # A list of symbols may be specified; default is all symbols in the
  513. # name space.
  514. sub save {
  515. my $package = shift;
  516. my(%namerefs, $var, $type);
  517. no strict 'refs';
  518. @_ = keys %{$package."::"} if ! @_;
  519. foreach $var (@_) {
  520. $namerefs{$var} = [];
  521. my $fqvar = $package."::".$var;
  522. # If the scalar for this variable name doesn't already
  523. # exist, *foo{SCALAR} will autovivify the reference
  524. # instead of returning undef, so unlike the other types,
  525. # we have to dereference to find out if it exists.
  526. push(@{$namerefs{$var}}, *{$fqvar}{SCALAR})
  527. if defined ${*{$fqvar}{SCALAR}};
  528. foreach $type (qw(ARRAY HASH CODE IO)) {
  529. push(@{$namerefs{$var}}, *{$fqvar}{$type})
  530. if defined *{$fqvar}{$type};
  531. }
  532. }
  533. return \%namerefs;
  534. }
  535. # Remove the specified symbols from the namespace.
  536. # Default is to remove all.
  537. sub remove {
  538. my $package = shift;
  539. my(%namerefs, $var);
  540. no strict 'refs';
  541. @_ = keys %{$package."::"} if ! @_;
  542. foreach $var (@_) {
  543. delete ${$package."::"}{$var};
  544. }
  545. }
  546. # Restore values to symbols specified in a hash as returned
  547. # by NameSpace::save.
  548. sub restore {
  549. my($package, $namerefs) = @_;
  550. my($var, $ref);
  551. no strict 'refs';
  552. foreach $var (keys %$namerefs) {
  553. my $fqvar = $package."::".$var;
  554. foreach $ref (@{$namerefs->{$var}}) {
  555. *{$fqvar} = $ref;
  556. }
  557. }
  558. }
  559. # Support for "building" scripts, importing and exporting variables.
  560. # With the exception of the top-level routine here (invoked from the
  561. # main package by cons), these are all invoked by user scripts.
  562. package script;
  563. use vars qw( $ARG $caller_dir_path %special_var );
  564. BEGIN {
  565. # We can't Export or Import the following variables because Perl always
  566. # treats them as part of the "main::" package (see perlvar(1)).
  567. %special_var = map {$_ => 1} qw(ENV INC ARGV ARGVOUT SIG
  568. STDIN STDOUT STDERR);
  569. }
  570. # This is called from main to interpret/run the top-level Construct
  571. # file, passed in as the single argument.
  572. sub main::doscripts {
  573. my($script) = @_;
  574. Build($script);
  575. # Now set up the includes/excludes (after the Construct file is read).
  576. $param::include = join('|', @param::include);
  577. # Save the original variable names from the script package.
  578. # These will stay intact, but any other "script::" variables
  579. # defined in a Conscript file will get saved, deleted,
  580. # and (when necessary) restored.
  581. my(%orig_script_var) = map {$_ => 1} keys %script::;
  582. $caller_dir_path = undef;
  583. my $cwd = Cwd::cwd();
  584. my(@scripts) = pop(@priv::scripts);
  585. while ($priv::self = shift(@scripts)) {
  586. my($path) = $priv::self->{script}->rsrcpath;
  587. if (-f $path) {
  588. $dir::cwd = $priv::self->{script}->{dir};
  589. # Handle chdir to the Conscript file directory, if necessary.
  590. my ($vol, $dir, $file);
  591. if ($param::conscript_chdir) {
  592. ($vol, $dir, $file) = File::Spec->splitpath(File::Spec->canonpath($path));
  593. if ($vol ne '' || $dir ne '') {
  594. $caller_dir_path = File::Spec->catpath($vol, $dir, undef);
  595. chdir($caller_dir_path) ||
  596. die "Could not chdir to $caller_dir_path: $!\n";
  597. }
  598. } else {
  599. $file = $path;
  600. }
  601. # Actually process the Conscript file.
  602. do $file;
  603. # Save any variables defined by the Conscript file
  604. # so we can restore them later, if needed;
  605. # then delete them from the script:: namespace.
  606. my(@del) = grep(! $orig_script_var{$_}, keys %script::);
  607. if (@del) {
  608. $priv::self->{script}->{pkgvars} =
  609. NameSpace::save('script', @del);
  610. NameSpace::remove('script', @del);
  611. }
  612. if ($caller_dir_path) {
  613. chdir($cwd);
  614. $caller_dir_path = undef;
  615. }
  616. if ($@) {
  617. chomp($@);
  618. my $err = ($@ =~ /\n/ms) ? ":\n$@" : " ($@)";
  619. print qq($0: error in file "$path"$err\n);
  620. $run::errors++;
  621. } else {
  622. # Only process subsidiary scripts if no errors in parent.
  623. unshift(@scripts, @priv::scripts);
  624. }
  625. undef @priv::scripts;
  626. } else {
  627. my $where = '';
  628. my $cref = $priv::self->{script}->creator;
  629. if (defined $cref) {
  630. my($_foo, $script, $line, $sub) = @$cref;
  631. $where = " ($sub in $script, line $line)";
  632. }
  633. warn qq(Ignoring missing script "$path"$where);
  634. }
  635. }
  636. die("$0: script errors encountered: construction aborted\n")
  637. if $run::errors;
  638. }
  639. # Return caller info about the method being invoked.
  640. # This is everything from the Perl "caller" builtin function,
  641. # including which Construct/Conscript file, line number,
  642. # subroutine name, etc.
  643. sub caller_info {
  644. my($lev) = 1;
  645. my(@frame);
  646. do {
  647. @frame = caller ++$lev;
  648. if (defined($frame[3]) && $frame[3] eq '(eval)') {
  649. @frame = caller --$lev;
  650. if ($caller_dir_path) {
  651. $frame[1] = File::Spec->catfile($caller_dir_path, $frame[1]);
  652. }
  653. return @frame;
  654. }
  655. } while ($frame[3]);
  656. return;
  657. }
  658. # Link a directory to another. This simply means set up the *source*
  659. # for the directory to be the other directory.
  660. sub Link {
  661. dir::link(@_);
  662. }
  663. # Add directories to the repository search path for files.
  664. # We're careful about stripping our current directory from
  665. # the list, which we do by comparing the `pwd` results from
  666. # the current directory and the specified directory. This
  667. # is cumbersome, but assures that the paths will be reported
  668. # the same regardless of symbolic links.
  669. sub Repository {
  670. my($my_dir) = Cwd::cwd();
  671. my $dir;
  672. foreach $dir (@_) {
  673. my($d) = `$^X -e "use Cwd; chdir('$dir') && print cwd"`;
  674. next if ! $d || ! -d $d || $d eq $my_dir;
  675. # We know we can get away with passing undef to lookupdir
  676. # as the directory because $dir is an absolute path.
  677. push(@param::rpath, dir::lookupdir(undef, $dir));
  678. push @INC, $d;
  679. }
  680. }
  681. # Return the list of Repository directories specified.
  682. sub Repository_List {
  683. map($_->path, @param::rpath);
  684. }
  685. # Specify whether the .consign signature times in repository files are,
  686. # in fact, consistent with the times on the files themselves.
  687. sub Repository_Sig_Times_OK {
  688. $param::rep_sig_times_ok = shift;
  689. }
  690. # Specify whether we should chdir to the containing directories
  691. # of Conscript files.
  692. sub Conscript_chdir {
  693. $param::conscript_chdir = shift;
  694. }
  695. # Specify files/targets that must be present and built locally,
  696. # even if they exist already-built in a Repository.
  697. sub Local {
  698. my(@files) = map($dir::cwd->lookupfile($_), @_);
  699. map($_->local(1), @files);
  700. }
  701. # Export variables to any scripts invoked from this one.
  702. sub Export {
  703. my(@illegal) = grep($special_var{$_}, @_);
  704. if (@illegal) {
  705. die qq($0: cannot Export special Perl variables: @illegal\n);
  706. }
  707. @{$priv::self->{exports}} = grep(! defined $special_var{$_}, @_);
  708. }
  709. # Import variables from the export list of the caller
  710. # of the current script.
  711. sub Import {
  712. my(@illegal) = grep($special_var{$_}, @_);
  713. if (@illegal) {
  714. die qq($0: cannot Import special Perl variables: @illegal\n");
  715. }
  716. my($parent) = $priv::self->{parent};
  717. my($imports) = $priv::self->{imports};
  718. @{$priv::self->{exports}} = keys %$imports;
  719. my($var);
  720. foreach $var (grep(! defined $special_var{$_}, @_)) {
  721. if (!exists $imports->{$var}) {
  722. my($path) = $parent->{script}->path;
  723. die qq($0: variable "$var" not exported by file "$path"\n);
  724. }
  725. if (!defined $imports->{$var}) {
  726. my $path = $parent->{script}->path;
  727. my $err = "$0: variable \"$var\" exported but not " .
  728. "defined by file \"$path\"\n";
  729. die $err;
  730. }
  731. ${"script::$var"} = $imports->{$var};
  732. }
  733. }
  734. # Build an inferior script. That is, arrange to read and execute
  735. # the specified script, passing to it any exported variables from
  736. # the current script.
  737. sub Build {
  738. my(@files) = map($dir::cwd->lookupfile($_), @_);
  739. my(%imports) = map {$_ => ${"script::$_"}} @{$priv::self->{exports}};
  740. my $file;
  741. for $file (@files) {
  742. next if $param::include && $file->path !~ /$param::include/o;
  743. my($self) = {'script' => $file,
  744. 'parent' => $priv::self,
  745. 'imports' => \%imports};
  746. bless $self; # may want to bless into class of parent in future
  747. push(@priv::scripts, $self);
  748. }
  749. }
  750. # Set up regexps dependencies to ignore. Should only be called once.
  751. sub Ignore {
  752. die("Ignore called more than once\n") if $param::ignore;
  753. $param::ignore = join("|", map("($_)", @_)) if @_;
  754. }
  755. # Specification of default targets.
  756. sub Default {
  757. push(@param::default_targets, map($dir::cwd->lookup($_)->path, @_));
  758. }
  759. # Local Help. Should only be called once.
  760. sub Help {
  761. if ($param::localhelp) {
  762. print "@_\n";
  763. exit 2;
  764. }
  765. }
  766. # Return the build name(s) of a file or file list.
  767. sub FilePath {
  768. wantarray
  769. ? map($dir::cwd->lookupfile($_)->path, @_)
  770. : $dir::cwd->lookupfile($_[0])->path;
  771. }
  772. # Return the build name(s) of a directory or directory list.
  773. sub DirPath {
  774. wantarray
  775. ? map($dir::cwd->lookupdir($_)->path, @_)
  776. : $dir::cwd->lookupdir($_[0])->path;
  777. }
  778. # Split the search path provided into components. Look each up
  779. # relative to the current directory.
  780. # The usual path separator problems abound; for now we'll use :
  781. sub SplitPath {
  782. my($dirs) = @_;
  783. if (ref($dirs) ne "ARRAY") {
  784. $dirs = [ split(/$main::PATH_SEPARATOR/o, $dirs) ];
  785. }
  786. map { DirPath($_) } @$dirs;
  787. }
  788. # Return true if the supplied path is available as a source file
  789. # or is buildable (by rules seen to-date in the build).
  790. sub ConsPath {
  791. my($path) = @_;
  792. my($file) = $dir::cwd->lookup($path);
  793. return $file->accessible;
  794. }
  795. # Return the source path of the supplied path.
  796. sub SourcePath {
  797. wantarray
  798. ? map($dir::cwd->lookupfile($_)->rsrcpath, @_)
  799. : $dir::cwd->lookupfile($_[0])->rsrcpath;
  800. }
  801. # Search up the tree for the specified cache directory, starting with
  802. # the current directory. Returns undef if not found, 1 otherwise.
  803. # If the directory is found, then caching is enabled. The directory
  804. # must be readable and writable. If the argument "mixtargets" is provided,
  805. # then targets may be mixed in the cache (two targets may share the same
  806. # cache file--not recommended).
  807. sub UseCache($@) {
  808. my($dir, @args) = @_;
  809. # NOTE: it's important to process arguments here regardless of whether
  810. # the cache is disabled temporarily, since the mixtargets option affects
  811. # the salt for derived signatures.
  812. for (@args) {
  813. if ($_ eq "mixtargets") {
  814. # When mixtargets is enabled, we salt the target signatures.
  815. # This is done purely to avoid a scenario whereby if
  816. # mixtargets is turned on or off after doing builds, and
  817. # if cache synchronization with -cs is used, then
  818. # cache files may be shared in the cache itself (linked
  819. # under more than one name in the cache). This is not bad,
  820. # per se, but simply would mean that a cache cleaning algorithm
  821. # that looked for a link count of 1 would never find those
  822. # particular files; they would always appear to be in use.
  823. $param::salt = 'M' . $param::salt;
  824. $param::mixtargets = 1;
  825. } else {
  826. die qq($0: UseCache unrecognized option "$_"\n);
  827. }
  828. }
  829. if ($param::cachedisable) {
  830. warn("Note: caching disabled by -cd flag\n");
  831. return 1;
  832. }
  833. my($depth) = 15;
  834. while ($depth-- && ! -d $dir) {
  835. $dir = File::Spec->catdir($dir::UPDIR, $dir);
  836. }
  837. if (-d $dir) {
  838. $param::cache = $dir;
  839. return 1;
  840. }
  841. return undef;
  842. }
  843. # Salt the signature generator. The salt (a number of string) is added
  844. # into the signature of each derived file. Changing the salt will
  845. # force recompilation of all derived files.
  846. sub Salt($) {
  847. # We append the value, so that UseCache and Salt may be used
  848. # in either order without changing the signature calculation.
  849. $param::salt .= $_[0];
  850. }
  851. # Mark files (or directories) to not be removed before building.
  852. sub Precious {
  853. map($_->{precious} = 1, map($dir::cwd->lookup($_), @_));
  854. }
  855. # These methods are callable from Conscript files, via a cons
  856. # object. Procs beginning with _ are intended for internal use.
  857. package cons;
  858. use vars qw( %envcache );
  859. # This is passed the name of the base environment to instantiate.
  860. # Overrides to the base environment may also be passed in
  861. # as key/value pairs.
  862. sub new {
  863. my($package) = shift;
  864. my ($env) = {@param::defaults, @_};
  865. @{$env->{_envcopy}} = %$env; # Note: we never change PATH
  866. $env->{_cwd} = $dir::cwd; # Save directory of environment for
  867. bless $env, $package; # any deferred name interpretation.
  868. }
  869. # Clone an environment.
  870. # Note that the working directory will be the initial directory
  871. # of the original environment.
  872. sub clone {
  873. my($env) = shift;
  874. my $clone = {@{$env->{_envcopy}}, @_};
  875. @{$clone->{_envcopy}} = %$clone; # Note: we never change PATH
  876. $clone->{_cwd} = $env->{_cwd};
  877. bless $clone, ref $env;
  878. }
  879. # Create a flattened hash representing the environment.
  880. # It also contains a copy of the PATH, so that the path
  881. # may be modified if it is converted back to a hash.
  882. sub copy {
  883. my($env) = shift;
  884. (@{$env->{_envcopy}}, 'ENV' => {%{$env->{ENV}}}, @_)
  885. }
  886. # Resolve which environment to actually use for a given
  887. # target. This is just used for simple overrides.
  888. sub _resolve {
  889. return $_[0] if !$param::overrides;
  890. my($env, $tgt) = @_;
  891. my($path) = $tgt->path;
  892. my $re;
  893. for $re (@param::overrides) {
  894. next if $path !~ /$re/;
  895. # Found one. Return a combination of the original environment
  896. # and the override.
  897. my($ovr) = $param::overrides{$re};
  898. return $envcache{$env,$re} if $envcache{$env,$re};
  899. my($newenv) = {@{$env->{_envcopy}}, @$ovr};
  900. @{$newenv->{_envcopy}} = %$env;
  901. $newenv->{_cwd} = $env->{_cwd};
  902. return $envcache{$env,$re} = bless $newenv, ref $env;
  903. }
  904. return $env;
  905. }
  906. # Substitute construction environment variables into a string.
  907. # Internal function/method.
  908. sub _subst {
  909. my($env, $str) = @_;
  910. if (! defined $str) {
  911. return undef;
  912. } elsif (ref($str) eq "ARRAY") {
  913. return [ map($env->_subst($_), @$str) ];
  914. } else {
  915. # % expansion. %% gets converted to % later, so expand any
  916. # %keyword construction that doesn't have a % in front of it,
  917. # modulo multiple %% pairs in between.
  918. # In Perl 5.005 and later, we could actually do this in one regex
  919. # using a conditional expression as follows,
  920. # while ($str =~ s/($pre)\%(\{)?([_a-zA-Z]\w*)(?(2)\})/"$1".$env->{$3}/ge) {}
  921. # The following two-step approach is backwards-compatible
  922. # to (at least) Perl5.003.
  923. my $pre = '^|[^\%](?:\%\%)*';
  924. while (($str =~ s/($pre)\%([_a-zA-Z]\w*)/$1.($env->{$2}||'')/ge) ||
  925. ($str =~ s/($pre)\%\{([_a-zA-Z]\w*)\}/$1.($env->{$2}||'')/ge)) {}
  926. return $str;
  927. }
  928. }
  929. sub Install {
  930. my($env) = shift;
  931. my($tgtdir) = $dir::cwd->lookupdir($env->_subst(shift));
  932. my $file;
  933. for $file (map($dir::cwd->lookupfile($env->_subst($_)), @_)) {
  934. my($tgt) = $tgtdir->lookupfile($file->{entry});
  935. $tgt->bind(find build::install, $file);
  936. }
  937. }
  938. sub InstallAs {
  939. my $env = shift;
  940. my $tgt = shift;
  941. my $src = shift;
  942. my @sources = ();
  943. my @targets = ();
  944. if (ref $tgt) {
  945. die "InstallAs: Source is a file and target is a list!\n"
  946. if (!ref($src));
  947. @sources = @$src;
  948. @targets = @$tgt;
  949. } elsif (ref $src) {
  950. die "InstallAs: Target is a file and source is a list!\n";
  951. } else {
  952. push @sources, $src;
  953. push @targets, $tgt;
  954. }
  955. if ($#sources != $#targets) {
  956. my $tn = $#targets+1;
  957. my $sn = $#sources+1;
  958. die "InstallAs: Source file list ($sn) and target file list ($tn) " .
  959. "are inconsistent in length!\n";
  960. } else {
  961. foreach (0..$#sources) {
  962. my $tfile = $dir::cwd->lookupfile($env->_subst($targets[$_]));
  963. my $sfile = $dir::cwd->lookupfile($env->_subst($sources[$_]));
  964. $tfile->bind(find build::install, $sfile);
  965. }
  966. }
  967. }
  968. # Installation in a local build directory,
  969. # copying from the repository if it's already built there.
  970. # Functionally equivalent to:
  971. # Install $env $dir, $file;
  972. # Local "$dir/$file";
  973. sub Install_Local {
  974. my($env) = shift;
  975. my($tgtdir) = $dir::cwd->lookupdir($env->_subst(shift));
  976. my $file;
  977. for $file (map($dir::cwd->lookupfile($env->_subst($_)), @_)) {
  978. my($tgt) = $tgtdir->lookupfile($file->{entry});
  979. $tgt->bind(find build::install, $file);
  980. $tgt->local(1);
  981. }
  982. }
  983. sub Objects {
  984. my($env) = shift;
  985. map($dir::cwd->relpath($_),
  986. _Objects($env, map($dir::cwd->lookupfile($env->_subst($_)), @_)))
  987. }
  988. # Called with multiple source file references (or object files).
  989. # Returns corresponding object files references.
  990. sub _Objects {
  991. my($env) = shift;
  992. my($suffix) = $env->{SUFOBJ};
  993. map(_Object($env, $_, $_->{dir}->lookupfile($_->base_suf($suffix))), @_);
  994. }
  995. # Called with an object and source reference. If no object reference
  996. # is supplied, then the object file is determined implicitly from the
  997. # source file's extension. Sets up the appropriate rules for creating
  998. # the object from the source. Returns the object reference.
  999. sub _Object {
  1000. my($env, $src, $obj) = @_;
  1001. return $obj if $src eq $obj; # don't need to build self from self.
  1002. my($objenv) = $env->_resolve($obj);
  1003. my($suffix) = $src->suffix;
  1004. my($builder) = $env->{SUFMAP}{$suffix};
  1005. if ($builder) {
  1006. $obj->bind((find $builder($objenv)), $src);
  1007. } else {
  1008. die("don't know how to construct ${\$obj->path} from " .
  1009. "${\$src->path}.\n");
  1010. }
  1011. $obj
  1012. }
  1013. sub Program {
  1014. my($env) = shift;
  1015. my($tgt) = $dir::cwd->lookupfile(file::addsuffix($env->_subst(shift),
  1016. $env->{SUFEXE}));
  1017. my($progenv) = $env->_resolve($tgt);
  1018. $tgt->bind(find build::command::link($progenv, $progenv->{LINKCOM}),
  1019. $env->_Objects(map($dir::cwd->lookupfile($env->_subst($_)), @_)));
  1020. }
  1021. sub Module {
  1022. my($env) = shift;
  1023. my($tgt) = $dir::cwd->lookupfile($env->_subst(shift));
  1024. my($modenv) = $env->_resolve($tgt);
  1025. my($com) = pop(@_);
  1026. $tgt->bind(find build::command::link($modenv, $com),
  1027. $env->_Objects(map($dir::cwd->lookupfile($env->_subst($_)), @_)));
  1028. }
  1029. sub LinkedModule {
  1030. my($env) = shift;
  1031. my($tgt) = $dir::cwd->lookupfile($env->_subst(shift));
  1032. my($progenv) = $env->_resolve($tgt);
  1033. $tgt->bind(find build::command::linkedmodule
  1034. ($progenv, $progenv->{LINKMODULECOM}),
  1035. $env->_Objects(map($dir::cwd->lookupfile($env->_subst($_)), @_)));
  1036. }
  1037. sub Library {
  1038. my($env) = shift;
  1039. my($lib) = $dir::cwd->lookupfile(file::addsuffix($env->_subst(shift),
  1040. $env->{SUFLIB}));
  1041. my($libenv) = $env->_resolve($lib);
  1042. $lib->bind(find build::command::library($libenv),
  1043. $env->_Objects(map($dir::cwd->lookupfile($env->_subst($_)), @_)));
  1044. }
  1045. # Simple derivation: you provide target, source(s), command.
  1046. # Special variables substitute into the rule.
  1047. # Target may be a reference, in which case it is taken
  1048. # to be a multiple target (all targets built at once).
  1049. sub Command {
  1050. my($env) = shift;
  1051. my($tgt) = $env->_subst(shift);
  1052. my($com) = pop(@_);
  1053. my(@sources) = map($dir::cwd->lookupfile($env->_subst($_)), @_);
  1054. if (ref($tgt)) {
  1055. # A multi-target command.
  1056. my(@tgts) = map($dir::cwd->lookupfile($_), @$tgt);
  1057. die("empty target list in multi-target command\n") if !@tgts;
  1058. $env = $env->_resolve($tgts[0]);
  1059. my $builder = find build::command::user($env, $com, 'script');
  1060. my($multi) = build::multiple->new($builder, \@tgts);
  1061. for $tgt (@tgts) {
  1062. $tgt->bind($multi, @sources);
  1063. }
  1064. } else {
  1065. $tgt = $dir::cwd->lookupfile($tgt);
  1066. $env = $env->_resolve($tgt);
  1067. my $builder = find build::command::user($env, $com, 'script');
  1068. $tgt->bind($builder, @sources);
  1069. }
  1070. }
  1071. sub Depends {
  1072. my($env) = shift;
  1073. my($tgt) = $env->_subst(shift);
  1074. my(@deps) = map($dir::cwd->lookup($env->_subst($_)), @_);
  1075. if (! ref($tgt)) {
  1076. $tgt = [ $tgt ];
  1077. }
  1078. my($t);
  1079. foreach $t (map($dir::cwd->lookupfile($_), @$tgt)) {
  1080. push(@{$t->{dep}}, @deps);
  1081. }
  1082. }
  1083. # Setup a quick scanner for the specified input file, for the
  1084. # associated environment. Any use of the input file will cause the
  1085. # scanner to be invoked, once only. The scanner sees just one line at
  1086. # a time of the file, and is expected to return a list of
  1087. # dependencies.
  1088. sub QuickScan {
  1089. my($env, $code, $file, $path) = @_;
  1090. $dir::cwd->lookup($env->_subst($file))->{'srcscan',$env} =
  1091. find scan::quickscan($code, $env, $env->_subst($path));
  1092. }
  1093. # Generic builder module. Just a few default methods. Every derivable
  1094. # file must have a builder object of some sort attached. Usually
  1095. # builder objects are shared.
  1096. package build;
  1097. # Null signature for dynamic includes.
  1098. sub includes { () }
  1099. # Null signature for build script.
  1100. sub script { () }
  1101. # Not compatible with any other builder, by default.
  1102. sub compatible { 0 }
  1103. # Builder module for the Install command.
  1104. package build::install;
  1105. use vars qw( @ISA $installer );
  1106. BEGIN {
  1107. @ISA = qw(build);
  1108. bless $installer = {} # handle for this class.
  1109. }
  1110. sub find {
  1111. $installer
  1112. }
  1113. # Caching not supported for Install: generally install is trivial anyway,
  1114. # and we don't want to clutter the cache.
  1115. sub cachin { undef }
  1116. sub cachout { }
  1117. # Do the installation.
  1118. sub action {
  1119. my($self, $tgt) = @_;
  1120. my($src) = $tgt->{sources}[0];
  1121. main::showcom("Install ${\$src->rpath} as ${\$tgt->path}")
  1122. if ($param::install && !$param::quiet);
  1123. return unless $param::build;
  1124. futil::install($src->rpath, $tgt);
  1125. return 1;
  1126. }
  1127. # Builder module for generic UNIX commands.
  1128. package build::command;
  1129. use vars qw( @ISA %com );
  1130. BEGIN { @ISA = qw(build) }
  1131. sub find {
  1132. my ($class, $env, $com, $package) = @_;
  1133. $com = $env->_subst($com);
  1134. $package ||= '';
  1135. $com{$env,$com,$package} || do {
  1136. # Remove unwanted bits from signature -- those bracketed by %( ... %)
  1137. my $comsig = $com;
  1138. $comsig =~ s/^\@\s*//mg;
  1139. while ($comsig =~ s/%\(([^%]|%[^\(])*?%\)//g) { }
  1140. my $self = { env => $env, com => $com, 'package' => $package,
  1141. comsig => $comsig };
  1142. $com{$env,$com,$package} = bless $self, $class;
  1143. }
  1144. }
  1145. # Default cache in function.
  1146. sub cachin {
  1147. my($self, $tgt, $sig) = @_;
  1148. if (cache::in($tgt, $sig)) {
  1149. if ($param::cachecom) {
  1150. map { if (! s/^\@\s*//) { main::showcom($_) } } $self->getcoms($tgt);
  1151. } else {
  1152. printf("Retrieved %s from cache\n", $tgt->path)
  1153. unless ($param::quiet);
  1154. }
  1155. return 1;
  1156. }
  1157. return undef;
  1158. }
  1159. # Default cache out function.
  1160. sub cachout {
  1161. my($self, $tgt, $sig) = @_;
  1162. cache::out($tgt, $sig);
  1163. }
  1164. # internal routine to process variable options.
  1165. # f: return file part
  1166. # F: return file part, but strip any suffix
  1167. # d: return directory part
  1168. # b: return full path, but strip any suffix (a.k.a. return basename)
  1169. # s: return only the suffix (or an empty string, if no suffix is there)
  1170. # a: return the absolute path to the file
  1171. # no option: return full path to file
  1172. sub _variant {
  1173. my($opt, $file) = @_;
  1174. $opt = '' if ! defined $opt;
  1175. if ($opt eq 'f') { return $file->{entry}; }
  1176. elsif ($opt eq 'd') { return $file->{dir}->path; }
  1177. elsif ($opt eq 'F') {
  1178. my $subst = $file->{entry};
  1179. $subst =~ s/\.[^\.]+$//;
  1180. return $subst;
  1181. }
  1182. elsif ($opt eq 'b') {
  1183. my $subst = $file->path;
  1184. $subst =~ s/\.[^\.]+$//;
  1185. return $subst;
  1186. }
  1187. elsif ($opt eq 's') {
  1188. my $subst = $file->{entry};
  1189. $subst =~ m/(\.[^\.]+)$/;
  1190. return $1;
  1191. }
  1192. elsif ($opt eq 'a') {
  1193. my $path = $file->path;
  1194. if (! File::Spec->file_name_is_absolute($path)) {
  1195. $path = File::Spec->catfile(Cwd::cwd(), $path);
  1196. }
  1197. return $path;
  1198. }
  1199. else { return $file->path; }
  1200. }
  1201. # For the signature of a basic command, we don't bother
  1202. # including the command itself. This is not strictly correct,
  1203. # and if we wanted to be rigorous, we might want to insist
  1204. # that the command was checked for all the basic commands
  1205. # like gcc, etc. For this reason we don't have an includes
  1206. # method.
  1207. # Call this to get the command line script: an array of
  1208. # fully substituted commands.
  1209. sub getcoms {
  1210. my($self, $tgt) = @_;
  1211. my(@coms);
  1212. my $com;
  1213. for $com (split(/\n/, $self->{com})) {
  1214. my(@src) = (undef, @{$tgt->{sources}});
  1215. my(@src1) = @src;
  1216. next if $com =~ /^\s*$/;
  1217. # NOTE: we used to have a more elegant s//.../e solution
  1218. # for the items below, but this caused a bus error...
  1219. # Remove %( and %) -- those are only used to bracket parts
  1220. # of the command that we don't depend on.
  1221. $com =~ s/%[()]//g;
  1222. # Deal with %n, n=1,9 and variants.
  1223. while ($com =~ /%([1-9])(:([fdbsFa]?))?/) {
  1224. my($match) = $&;
  1225. my($src) = $src1[$1];
  1226. my($subst) = _variant($3, $src1[$1]->rfile);
  1227. undef $src[$1];
  1228. $com =~ s/$match/$subst/;
  1229. }
  1230. # Deal with %0 aka %> and variants.
  1231. while ($com =~ /%[0>](:([fdbsFa]?))?/) {
  1232. my($match) = $&;
  1233. my($subst) = _variant($2, $tgt);
  1234. $com =~ s/$match/$subst/;
  1235. }
  1236. # Deal with %< (all sources except %n's already used)
  1237. while ($com =~ /%<(:([fdbsFa]?))?/) {
  1238. my($match) = $&;
  1239. my @list = ();
  1240. foreach (@src) {
  1241. push(@list, _variant($2, $_->rfile)) if $_;
  1242. }
  1243. my($subst) = join(' ', @list);
  1244. $com =~ s/$match/$subst/;
  1245. }
  1246. # Deal with %[ %].
  1247. $com =~ s{%\[(.*?)%\]}{
  1248. my($func, @args) = grep { $_ ne '' } split(/\s+/, $1);
  1249. die("$0: \"$func\" is not defined.\n")
  1250. unless ($self->{env}->{$func});
  1251. &{$self->{env}->{$func}}(@args);
  1252. }gex;
  1253. # Convert left-over %% into %.
  1254. $com =~ s/%%/%/g;
  1255. # White space cleanup. XXX NO WAY FOR USER TO HAVE QUOTED SPACES
  1256. $com = join(' ', split(' ', $com));
  1257. next if $com =~ /^:/ && $com !~ /^:\S/;
  1258. push(@coms, $com);
  1259. }
  1260. @coms
  1261. }
  1262. # Build the target using the previously specified commands.
  1263. sub action {
  1264. my($self, $tgt) = @_;
  1265. my($env) = $self->{env};
  1266. if ($param::build) {
  1267. futil::mkdir($tgt->{dir});
  1268. unlink($tgt->path) if ! $tgt->precious;
  1269. }
  1270. # Set environment.
  1271. map(delete $ENV{$_}, keys %ENV);
  1272. %ENV = %{$env->{ENV}};
  1273. # Handle multi-line commands.
  1274. my $com;
  1275. for $com ($self->getcoms($tgt)) {
  1276. if ($com !~ s/^\@\s*//) {
  1277. main::showcom($com);
  1278. }
  1279. if ($param::build) {
  1280. if ($com =~ /^\[perl\]\s*/) {
  1281. my $perlcmd = $';
  1282. my $status;
  1283. {
  1284. # Restore the script package variables that were defined
  1285. # in the Conscript file that defined this [perl] build,
  1286. # so the code executes with the expected variables.
  1287. my($package) = $self->{'package'};
  1288. my($pkgvars) = $tgt->{conscript}->{pkgvars};
  1289. NameSpace::restore($package, $pkgvars) if $pkgvars;
  1290. # Actually execute the [perl] command to build the target.
  1291. $status = eval "package $package; $perlcmd";
  1292. # Clean up the namespace by deleting the package variables
  1293. # we just restored.
  1294. NameSpace::remove($package, keys %$pkgvars) if $pkgvars;
  1295. }
  1296. if (!defined($status)) {
  1297. warn "$0: *** Error during perl command eval: $@.\n";
  1298. return undef;
  1299. } elsif ($status == 0) {
  1300. warn "$0: *** Perl command returned $status (this indicates an error).\n";
  1301. return undef;
  1302. }
  1303. next;
  1304. }
  1305. #---------------------
  1306. # Can't fork on Win32
  1307. #---------------------
  1308. if ($main::_WIN32) {
  1309. system($com);
  1310. if ($?) {
  1311. my ($b0, $b1) = ($? & 0xFF, $? >> 8);
  1312. my $err = $b1 || $?;
  1313. my $path = $tgt->path;
  1314. my $warn = qq($0: *** [$path] Error $err);
  1315. $warn .= " (executable not found in path?)" if $b1 == 0xFF;
  1316. warn "$warn\n";
  1317. return undef;
  1318. }
  1319. } else {
  1320. my($pid) = fork();
  1321. die("$0: unable to fork child process ($!)\n") if !defined $pid;
  1322. if (!$pid) {
  1323. # This is the child. We eval the command to suppress -w
  1324. # warnings about not reaching the statements afterwards.
  1325. eval 'exec($com)';
  1326. $com =~ s/\s.*//;
  1327. die qq($0: failed to execute "$com" ($!). )
  1328. . qq(Is this an executable on path "$ENV{PATH}"?\n);
  1329. }
  1330. for (;;) {
  1331. do {} until wait() == $pid;
  1332. my ($b0, $b1) = ($? & 0xFF, $? >> 8);
  1333. # Don't actually see 0177 on stopped process; is this necessary?
  1334. next if $b0 == 0177; # process stopped; we can wait.
  1335. if ($b0) {
  1336. my($core, $sig) = ($b0 & 0200, $b0 & 0177);
  1337. my($coremsg) = $core ? "; core dumped" : "";
  1338. $com =~ s/\s.*//;
  1339. my $path = $tgt->path;
  1340. my $err = "$0: *** \[$path\] $com terminated by signal " .
  1341. "$sig$coremsg\n";
  1342. warn $err;
  1343. return undef;
  1344. }
  1345. if ($b1) {
  1346. my($path) = $tgt->path;
  1347. warn qq($0: *** [$path] Error $b1\n); # trying to be like make.
  1348. return undef;
  1349. }
  1350. last;
  1351. }
  1352. }
  1353. }
  1354. }
  1355. # success.
  1356. return 1;
  1357. }
  1358. # Return script signature.
  1359. sub script {
  1360. $_[0]->{comsig}
  1361. }
  1362. # Create a linked module.
  1363. package build::command::link;
  1364. use vars qw( @ISA );
  1365. BEGIN { @ISA = qw(build::command) }
  1366. # Find an appropriate linker.
  1367. sub find {
  1368. my($class, $env, $command) = @_;
  1369. if (!exists $env->{_LDIRS}) {
  1370. my($ldirs) = '';
  1371. my($wd) = $env->{_cwd};
  1372. my($pdirs) = $env->{LIBPATH};
  1373. if (! defined $pdirs) {
  1374. $pdirs = [ ];
  1375. } elsif (ref($pdirs) ne 'ARRAY') {
  1376. $pdirs = [ split(/$main::PATH_SEPARATOR/o, $pdirs) ];
  1377. }
  1378. my $dir;
  1379. for $dir (map($wd->lookupdir($env->_subst($_)), @$pdirs)) {
  1380. my($dpath) = $dir->path;
  1381. $ldirs .= " ".$env->{LIBDIRPREFIX}.$dpath;
  1382. next if File::Spec->file_name_is_absolute($dpath);
  1383. if (@param::rpath) {
  1384. my $d;
  1385. if ($dpath eq $dir::CURDIR) {
  1386. foreach $d (map($_->path, @param::rpath)) {
  1387. $ldirs .= " ".$env->{LIBDIRPREFIX}.$d;
  1388. }
  1389. } else {
  1390. foreach $d (map($_->path, @param::rpath)) {
  1391. $ldirs .= " ".$env->{LIBDIRPREFIX}.File::Spec->catfile($d, $dpath);
  1392. }
  1393. }
  1394. }
  1395. }
  1396. $env->{_LDIRS} = "%($ldirs%)";
  1397. }
  1398. # Introduce a new magic _LIBS symbol which allows to use the
  1399. # Unix-style -lNAME syntax for Win32 only. -lNAME will be replaced
  1400. # with %{PREFLIB}NAME%{SUFLIB}. <schwarze@isa.de> 1998-06-18
  1401. if ($main::_WIN32 && !exists $env->{_LIBS}) {
  1402. my $libs;
  1403. my $name;
  1404. for $name (split(' ', $env->_subst($env->{LIBS} || ''))) {
  1405. if ($name =~ /^-l(.*)/) {
  1406. $name = "$env->{PREFLIB}$1$env->{SUFLIB}";
  1407. }
  1408. $libs .= ' ' . $name;
  1409. }
  1410. $env->{_LIBS} = $libs ? "%($libs%)" : '';
  1411. }
  1412. bless find build::command($env, $command);
  1413. }
  1414. # Called from file::build. Make sure any libraries needed by the
  1415. # environment are built, and return the collected signatures
  1416. # of the libraries in the path.
  1417. sub includes {
  1418. return $_[0]->{sig} if exists $_[0]->{sig};
  1419. my($self, $tgt) = @_;
  1420. my($env) = $self->{env};
  1421. my($ewd) = $env->{_cwd};
  1422. my $ldirs = $env->{LIBPATH};
  1423. if (! defined $ldirs) {
  1424. $ldirs = [ ];
  1425. } elsif (ref($ldirs) ne 'ARRAY') {
  1426. $ldirs = [ split(/$main::PATH_SEPARATOR/o, $ldirs) ];
  1427. }
  1428. my @lpath = map($ewd->lookupdir($_), @$ldirs);
  1429. my(@sigs);
  1430. my(@names);
  1431. if ($main::_WIN32) {
  1432. # Pass %LIBS symbol through %-substituition
  1433. # <schwarze@isa.de> 1998-06-18
  1434. @names = split(' ', $env->_subst($env->{LIBS} || ''));
  1435. } else {
  1436. @names = split(' ', $env->{LIBS} || '');
  1437. }
  1438. my $name;
  1439. for $name (@names) {
  1440. my ($lpath, @allnames);
  1441. if ($name =~ /^-l(.*)/) {
  1442. # -l style names are looked up on LIBPATH, using all
  1443. # possible lib suffixes in the same search order the
  1444. # linker uses (according to SUFLIBS).
  1445. # Recognize new PREFLIB symbol, which should be 'lib' on
  1446. # Unix, and empty on Win32. TODO: What about shared
  1447. # library suffixes? <schwarze@isa.de> 1998-05-13
  1448. @allnames = map("$env->{PREFLIB}$1$_",
  1449. split(/:/, $env->{SUFLIBS}));
  1450. $lpath = \@lpath;
  1451. } else {
  1452. @allnames = ($name);
  1453. # On Win32, all library names are looked up in LIBPATH
  1454. # <schwarze@isa.de> 1998-05-13
  1455. if ($main::_WIN32) {
  1456. $lpath = [$dir::top, @lpath];
  1457. }
  1458. else {
  1459. $lpath = [$dir::top];
  1460. }
  1461. }
  1462. my $dir;
  1463. DIR: for $dir (@$lpath) {
  1464. my $n;
  1465. for $n (@allnames) {
  1466. my($lib) = $dir->lookup_accessible($n);
  1467. if ($lib) {
  1468. last DIR if $lib->ignore;
  1469. if ((build $lib) eq 'errors') {
  1470. $tgt->{status} = 'errors';
  1471. return undef;
  1472. }
  1473. push(@sigs, 'sig'->signature($lib));
  1474. last DIR;
  1475. }
  1476. }
  1477. }
  1478. }
  1479. $self->{sig} = 'sig'->collect(@sigs);
  1480. }
  1481. # Always compatible with other such builders, so the user
  1482. # can define a single program or module from multiple places.
  1483. sub compatible {
  1484. my($self, $other) = @_;
  1485. ref($other) eq "build::command::link";
  1486. }
  1487. # Link a program.
  1488. package build::command::linkedmodule;
  1489. use vars qw( @ISA );
  1490. BEGIN { @ISA = qw(build::command) }
  1491. # Always compatible with other such builders, so the user
  1492. # can define a single linked module from multiple places.
  1493. sub compatible {
  1494. my($self, $other) = @_;
  1495. ref($other) eq "build::command::linkedmodule";
  1496. }
  1497. # Builder for a C module
  1498. package build::command::cc;
  1499. use vars qw( @ISA );
  1500. BEGIN { @ISA = qw(build::command) }
  1501. sub find {
  1502. $_[1]->{_cc} || do {
  1503. my($class, $env) = @_;
  1504. my($cpppath) = $env->_subst($env->{CPPPATH});
  1505. my($cscanner) = find scan::cpp($env->{_cwd}, $cpppath);
  1506. $env->{_IFLAGS} = "%(" . $cscanner->iflags($env) . "%)";
  1507. my($self) = find build::command($env, $env->{CCCOM});
  1508. $self->{scanner} = $cscanner;
  1509. bless $env->{_cc} = $self;
  1510. }
  1511. }
  1512. # Invoke the associated C scanner to get signature of included files.
  1513. sub includes {
  1514. my($self, $tgt) = @_;
  1515. $self->{scanner}->includes($tgt, $tgt->{sources}[0]);
  1516. }
  1517. # Builder for a C++ module
  1518. package build::command::cxx;
  1519. use vars qw( @ISA );
  1520. BEGIN { @ISA = qw(build::command) }
  1521. sub find {
  1522. $_[1]->{_cxx} || do {
  1523. my($class, $env) = @_;
  1524. my($cpppath) = $env->_subst($env->{CPPPATH});
  1525. my($cscanner) = find scan::cpp($env->{_cwd}, $cpppath);
  1526. $env->{_IFLAGS} = "%(" . $cscanner->iflags($env) . "%)";
  1527. my($self) = find build::command($env, $env->{CXXCOM});
  1528. $self->{scanner} = $cscanner;
  1529. bless $env->{_cxx} = $self;
  1530. }
  1531. }
  1532. # Invoke the associated C scanner to get signature of included files.
  1533. sub includes {
  1534. my($self, $tgt) = @_;
  1535. $self->{scanner}->includes($tgt, $tgt->{sources}[0]);
  1536. }
  1537. # Builder for a user command (cons::Command). We assume that a user
  1538. # command might be built and implement the appropriate dependencies on
  1539. # the command itself (actually, just on the first word of the command
  1540. # line).
  1541. package build::command::user;
  1542. use vars qw( @ISA );
  1543. BEGIN { @ISA = qw(build::command) }
  1544. # XXX Optimize this to not use ignored paths.
  1545. sub comsig {
  1546. return $_[0]->{_comsig} if exists $_[0]->{_comsig};
  1547. my($self, $tgt) = @_;
  1548. my($env) = $self->{env};
  1549. $self->{_comsig} = '';
  1550. my $com;
  1551. com:
  1552. for $com (split(/[\n;]/, $self->script)) {
  1553. # Isolate command word.
  1554. $com =~ s/^\s*//;
  1555. $com =~ s/\s.*//;
  1556. next if !$com; # blank line
  1557. my($pdirs) = $env->{ENV}->{PATH};
  1558. if (! defined $pdirs) {
  1559. $pdirs = [ ];
  1560. } elsif (ref($pdirs) ne 'ARRAY') {
  1561. $pdirs = [ split(/$main::PATH_SEPARATOR/o, $pdirs) ];
  1562. }
  1563. my $dir;
  1564. for $dir (map($dir::top->lookupdir($_), @$pdirs)) {
  1565. my($prog) = $dir->lookup_accessible($com);
  1566. if ($prog) { # XXX Not checking execute permission.
  1567. if ((build $prog) eq 'errors') {
  1568. $tgt->{status} = 'errors';
  1569. return undef;
  1570. }
  1571. next com if $prog->ignore;
  1572. $self->{_comsig} .= 'sig'->signature($prog);
  1573. next com;
  1574. }
  1575. }
  1576. # Not found: let shell give an error.
  1577. }
  1578. $self->{_comsig}
  1579. }
  1580. sub includes {
  1581. my($self, $tgt) = @_;
  1582. my($sig) = '';
  1583. # Check for any quick scanners attached to source files.
  1584. my $dep;
  1585. for $dep (@{$tgt->{dep}}, @{$tgt->{sources}}) {
  1586. my($scanner) = $dep->{'srcscan',$self->{env}};
  1587. if ($scanner) {
  1588. $sig .= $scanner->includes($tgt, $dep);
  1589. }
  1590. }
  1591. # Add the command signature.
  1592. return &comsig . $sig;
  1593. }
  1594. # Builder for a library module (archive).
  1595. # We assume that a user command might be built and implement the
  1596. # appropriate dependencies on the command itself.
  1597. package build::command::library;
  1598. use vars qw( @ISA );
  1599. BEGIN { @ISA = qw(build::command) }
  1600. sub find {
  1601. my($class, $env) = @_;
  1602. bless find build::command($env, $env->{ARCOM})
  1603. }
  1604. # Always compatible with other library builders, so the user
  1605. # can define a single library from multiple places.
  1606. sub compatible {
  1607. my($self, $other) = @_;
  1608. ref($other) eq "build::command::library";
  1609. }
  1610. # A multi-target builder.
  1611. # This allows multiple targets to be associated with a single build
  1612. # script, without forcing all the code to be aware of multiple targets.
  1613. package build::multiple;
  1614. sub new {
  1615. my($class, $builder, $tgts) = @_;
  1616. bless { 'builder' => $builder, 'tgts' => $tgts };
  1617. }
  1618. sub script {
  1619. my($self, $tgt) = @_;
  1620. $self->{builder}->script($tgt);
  1621. }
  1622. sub includes {
  1623. my($self, $tgt) = @_;
  1624. $self->{builder}->includes($tgt);
  1625. }
  1626. sub compatible {
  1627. my($self, $tgt) = @_;
  1628. $self->{builder}->compatible($tgt);
  1629. }
  1630. sub cachin {
  1631. my($self, $tgt, $sig) = @_;
  1632. $self->{builder}->cachin($tgt, $sig);
  1633. }
  1634. sub cachout {
  1635. my($self, $tgt, $sig) = @_;
  1636. $self->{builder}->cachout($tgt, $sig);
  1637. }
  1638. sub action {
  1639. my($self, $invoked_tgt) = @_;
  1640. return $self->{built} if exists $self->{built};
  1641. # Make sure all targets in the group are unlinked before building any.
  1642. my($tgts) = $self->{tgts};
  1643. my $tgt;
  1644. for $tgt (@$tgts) {
  1645. futil::mkdir($tgt->{dir});
  1646. unlink($tgt->path) if ! $tgt->precious;
  1647. }
  1648. # Now do the action to build all the targets. For consistency
  1649. # we always call the action on the first target, just so that
  1650. # $> is deterministic.
  1651. $self->{built} = $self->{builder}->action($tgts->[0]);
  1652. # Now "build" all the other targets (except for the one
  1653. # we were called with). This guarantees that the signature
  1654. # of each target is updated appropriately. We force the
  1655. # targets to be built even if they have been previously
  1656. # considered and found to be OK; the only effect this
  1657. # has is to make sure that signature files are updated
  1658. # correctly.
  1659. for $tgt (@$tgts) {
  1660. if ($tgt ne $invoked_tgt) {
  1661. delete $tgt->{status};
  1662. 'sig'->invalidate($tgt);
  1663. build $tgt;
  1664. }
  1665. }
  1666. # Status of action.
  1667. $self->{built};
  1668. }
  1669. # Generic scanning module.
  1670. package scan;
  1671. # Returns the signature of files included by the specified files on
  1672. # behalf of the associated target. Any errors in handling the included
  1673. # files are propagated to the target on whose behalf this processing
  1674. # is being done. Signatures are cached for each unique file/scanner
  1675. # pair.
  1676. sub includes {
  1677. my($self, $tgt, @files) = @_;
  1678. my(%files, $file);
  1679. my($inc) = $self->{includes} || ($self->{includes} = {});
  1680. while ($file = pop @files) {
  1681. next if exists $files{$file};
  1682. if ($inc->{$file}) {
  1683. push(@files, @{$inc->{$file}});
  1684. $files{$file} = 'sig'->signature($file->rfile);
  1685. } else {
  1686. if ((build $file) eq 'errors') {
  1687. $tgt->{status} = 'errors'; # tgt inherits build status
  1688. return ();
  1689. }
  1690. $files{$file} = 'sig'->signature($file->rfile);
  1691. my(@includes) = $self->scan($file);
  1692. $inc->{$file} = \@includes;
  1693. push(@files, @includes);
  1694. }
  1695. }
  1696. 'sig'->collect(sort values %files)
  1697. }
  1698. # A simple scanner. This is used by the QuickScanfunction, to setup
  1699. # one-time target and environment-independent scanning for a source
  1700. # file. Only used for commands run by the Command method.
  1701. package scan::quickscan;
  1702. use vars qw( @ISA %scanner );
  1703. BEGIN { @ISA = qw(scan) }
  1704. sub find {
  1705. my($class, $code, $env, $pdirs) = @_;
  1706. if (! defined $pdirs) {
  1707. $pdirs = [ ] ;
  1708. } elsif (ref($pdirs) ne 'ARRAY') {
  1709. $pdirs = [ split(/$main::PATH_SEPARATOR/o, $pdirs) ];
  1710. }
  1711. my(@path) = map { $dir::cwd->lookupdir($_) } @$pdirs;
  1712. my($spath) = "@path";
  1713. $scanner{$code,$env,$spath} || do {
  1714. my($self) = { code => $code, env => $env, path => \@path };
  1715. $scanner{$code,$env,$spath} = bless $self;
  1716. }
  1717. }
  1718. # Scan the specified file for included file names.
  1719. sub scan {
  1720. my($self, $file) = @_;
  1721. my($code) = $self->{code};
  1722. my(@includes);
  1723. # File should have been built by now. If not, we'll ignore it.
  1724. return () unless open(SCAN, $file->rpath);
  1725. while(<SCAN>) {
  1726. push(@includes, grep($_ ne '', &$code));
  1727. }
  1728. close(SCAN);
  1729. my($wd) = $file->{dir};
  1730. my(@files);
  1731. my $name;
  1732. for $name (@includes) {
  1733. my $dir;
  1734. for $dir ($file->{dir}, @{$self->{path}}) {
  1735. my($include) = $dir->lookup_accessible($name);
  1736. if ($include) {
  1737. push(@files, $include) unless $include->ignore;
  1738. last;
  1739. }
  1740. }
  1741. }
  1742. @files
  1743. }
  1744. # CPP (C preprocessor) scanning module
  1745. package scan::cpp;
  1746. use vars qw( @ISA %scanner );
  1747. BEGIN { @ISA = qw(scan) }
  1748. # For this constructor, provide the include path argument (colon
  1749. # separated). Each path is taken relative to the provided directory.
  1750. # Note: a particular scanning object is assumed to always return the
  1751. # same result for the same input. This is why the search path is a
  1752. # parameter to the constructor for a CPP scanning object. We go to
  1753. # some pains to make sure that we return the same scanner object
  1754. # for the same path: otherwise we will unecessarily scan files.
  1755. sub find {
  1756. my($class, $dir, $pdirs) = @_;
  1757. if (! defined $pdirs) {
  1758. $pdirs = [ ];
  1759. } elsif (ref($pdirs) ne 'ARRAY') {
  1760. $pdirs = [ split(/$main::PATH_SEPARATOR/o, $pdirs) ];
  1761. }
  1762. my @path = map($dir->lookupdir($_), @$pdirs);
  1763. my($spath) = "@path";
  1764. $scanner{$spath} || do {
  1765. my($self) = {'path' => \@path};
  1766. $scanner{$spath} = bless $self;
  1767. }
  1768. }
  1769. # Scan the specified file for include lines.
  1770. sub scan {
  1771. my($self, $file) = @_;
  1772. my($angles, $quotes);
  1773. if (exists $file->{angles}) {
  1774. $angles = $file->{angles};
  1775. $quotes = $file->{quotes};
  1776. } else {
  1777. my(@anglenames, @quotenames);
  1778. return () unless open(SCAN, $file->rpath);
  1779. while (<SCAN>) {
  1780. next unless /^\s*#/;
  1781. if (/^\s*#\s*include\s*([<"])(.*?)[>"]/) {
  1782. if ($1 eq "<") {
  1783. push(@anglenames, $2);
  1784. } else {
  1785. push(@quotenames, $2);
  1786. }
  1787. }
  1788. }
  1789. close(SCAN);
  1790. $angles = $file->{angles} = \@anglenames;
  1791. $quotes = $file->{quotes} = \@quotenames;
  1792. }
  1793. my(@shortpath) = @{$self->{path}}; # path for <> style includes
  1794. my(@longpath) = ($file->{dir}, @shortpath); # path for "" style includes
  1795. my(@includes);
  1796. my $name;
  1797. for $name (@$angles) {
  1798. my $dir;
  1799. for $dir (@shortpath) {
  1800. my($include) = $dir->lookup_accessible($name);
  1801. if ($include) {
  1802. push(@includes, $include) unless $include->ignore;
  1803. last;
  1804. }
  1805. }
  1806. }
  1807. for $name (@$quotes) {
  1808. my $dir;
  1809. for $dir(@longpath) {
  1810. my($include) = $dir->lookup_accessible($name);
  1811. if ($include) {
  1812. push(@includes, $include) unless $include->ignore;
  1813. last;
  1814. }
  1815. }
  1816. }
  1817. return @includes
  1818. }
  1819. # Return the include flags that would be used for a C Compile.
  1820. sub iflags {
  1821. my($self, $env) = @_;
  1822. my($iflags) = '';
  1823. my($dpath);
  1824. for $dpath (map($_->path, @{$self->{path}})) {
  1825. $iflags .= " ".$env->{INCDIRPREFIX}.$dpath;
  1826. next if File::Spec->file_name_is_absolute($dpath);
  1827. if (@param::rpath) {
  1828. my $d;
  1829. if ($dpath eq $dir::CURDIR) {
  1830. foreach $d (map($_->path, @param::rpath)) {
  1831. $iflags .= " ".$env->{INCDIRPREFIX}.$d;
  1832. }
  1833. } else {
  1834. foreach $d (map($_->path, @param::rpath)) {
  1835. $iflags .= " ".$env->{INCDIRPREFIX}.File::Spec->catfile($d, $dpath);
  1836. }
  1837. }
  1838. }
  1839. }
  1840. $iflags
  1841. }
  1842. package File::Spec;
  1843. use vars qw( $_SEP $_MATCH_SEP $_MATCH_VOL );
  1844. # Cons is migrating to using File::Spec for portable path name
  1845. # manipulation. This is the right long-term direction, but there are
  1846. # some problems with making the transition:
  1847. #
  1848. # For multi-volume support, we need to use newer interfaces
  1849. # (splitpath, catpath, splitdir) that are only available in
  1850. # File::Spec 0.8.
  1851. #
  1852. # File::Spec 0.8 doesn't work with Perl 5.00[34] due to
  1853. # regular expression incompatibilities (use of \z).
  1854. #
  1855. # Forcing people to use a new version of a module is painful
  1856. # because (in the workplace) their administrators aren't
  1857. # always going to agree to install it everywhere.
  1858. #
  1859. # As a middle ground, we provide our own versions of all the File::Spec
  1860. # methods we use, supporting both UNIX and Win32. Some of these methods
  1861. # are home brew, some are cut-and-pasted from the real File::Spec methods.
  1862. # This way, we're not reinventing the whole wheel, at least.
  1863. #
  1864. # We can (and should) get rid of this class whenever 5.00[34] and
  1865. # versions of File::Spec prior to 0.9 (?) have faded sufficiently.
  1866. # We also may need to revisit whenever someone first wants to use
  1867. # Cons on some platform other than UNIX or Win32.
  1868. BEGIN {
  1869. if ($main::_WIN32) {
  1870. $_SEP = '\\';
  1871. $_MATCH_SEP = "[\Q/$_SEP\E]";
  1872. $_MATCH_VOL = "([a-z]:)?$_MATCH_SEP";
  1873. } else {
  1874. $_SEP = '/';
  1875. $_MATCH_SEP = "\Q$_SEP\E";
  1876. $_MATCH_VOL = $_MATCH_SEP;
  1877. }
  1878. }
  1879. sub canonpath {
  1880. my ($self, $path) = @_;
  1881. if ($main::_WIN32) {
  1882. $path =~ s/^([a-z]:)/\u$1/s;
  1883. $path =~ s|/|\\|g;
  1884. $path =~ s|([^\\])\\+|$1\\|g; # xx////xx -> xx/xx
  1885. $path =~ s|(\\\.)+\\|\\|g; # xx/././xx -> xx/xx
  1886. $path =~ s|^(\.\\)+||s unless $path eq ".\\"; # ./xx -> xx
  1887. $path =~ s|\\$||
  1888. unless $path =~ m#^([A-Z]:)?\\$#s; # xx/ -> xx
  1889. } else {
  1890. $path =~ s|/+|/|g unless($^O eq 'cygwin'); # xx////xx -> xx/xx
  1891. $path =~ s|(/\.)+/|/|g; # xx/././xx -> xx/xx
  1892. $path =~ s|^(\./)+||s unless $path eq "./"; # ./xx -> xx
  1893. $path =~ s|^/(\.\./)+|/|s; # /../../xx -> xx
  1894. $path =~ s|/$|| unless $path eq "/"; # xx/ -> xx
  1895. }
  1896. return $path;
  1897. }
  1898. sub catdir {
  1899. my $self = shift;
  1900. my @args = @_;
  1901. foreach (@args) {
  1902. # append a slash to each argument unless it has one there
  1903. $_ .= $_SEP if $_ eq '' || substr($_,-1) ne $_SEP;
  1904. }
  1905. return $self->canonpath(join('', @args));
  1906. }
  1907. sub catfile {
  1908. my $self = shift;
  1909. my $file = pop @_;
  1910. return $file unless @_;
  1911. my $dir = $self->catdir(@_);
  1912. $dir .= $_SEP unless substr($dir,-1) eq $_SEP;
  1913. $file = '' if ! defined($file);
  1914. return $dir.$file;
  1915. }
  1916. sub catpath {
  1917. my $path = $_[1] . $_[0]->catfile(@_[2..$#_]);
  1918. $path =~ s/(.)$_MATCH_SEP*$/$1/;
  1919. $path;
  1920. }
  1921. sub curdir {
  1922. '.'
  1923. }
  1924. sub file_name_is_absolute {
  1925. my ($self, $file) = @_;
  1926. return scalar($file =~ m{^$_MATCH_VOL}is);
  1927. }
  1928. sub splitdir {
  1929. my @dirs = split(/$_MATCH_SEP/, $_[1], -1);
  1930. push(@dirs, '') if $dirs[$#dirs];
  1931. @dirs;
  1932. }
  1933. sub splitpath {
  1934. my ($self, $path) = @_;
  1935. my $vol = '';
  1936. my $sep = $_SEP;
  1937. if ($main::_WIN32) {
  1938. if ($path =~ s#^([A-Za-z]:|(?:\\\\|//)[^\\/]+[\\/][^\\/]+)([\\/])#$2#) {
  1939. $vol = $1;
  1940. $sep = $2;
  1941. }
  1942. }
  1943. my(@path) = split(/$_MATCH_SEP/, $path, -1);
  1944. my $file = pop @path;
  1945. my $dirs = join($sep, @path, '');
  1946. return ($vol, $dirs, $file);
  1947. }
  1948. sub updir {
  1949. '..'
  1950. }
  1951. sub case_tolerant {
  1952. return $main::_WIN32;
  1953. }
  1954. # Directory and file handling. Files/dirs are represented by objects.
  1955. # Other packages are welcome to add component-specific attributes.
  1956. package dir;
  1957. use vars qw( $SEPARATOR $MATCH_SEPARATOR $CURDIR $UPDIR
  1958. $cwd_vol %root $top $cwd );
  1959. BEGIN {
  1960. # A portable way of determing our directory separator.
  1961. $SEPARATOR = File::Spec->catdir('', '');
  1962. # A fast-path regular expression to match a directory separator
  1963. # anywhere in a path name.
  1964. if ($SEPARATOR eq '/') {
  1965. $MATCH_SEPARATOR = "\Q$SEPARATOR\E";
  1966. } else {
  1967. $MATCH_SEPARATOR = "[\Q/$SEPARATOR\E]";
  1968. }
  1969. # Cache these values so we don't have to make a method call
  1970. # every time we need them.
  1971. $CURDIR = File::Spec->curdir; # '.' on UNIX
  1972. $UPDIR = File::Spec->updir; # '..' on UNIX
  1973. #
  1974. $cwd_vol = '';
  1975. }
  1976. # Annotate a node (file or directory) with info about the
  1977. # method that created it.
  1978. sub creator {
  1979. my($self, @frame) = @_;
  1980. $self->{'creator'} = \@frame if @frame;
  1981. $self->{'creator'};
  1982. }
  1983. # Handle a file|dir type exception. We only die if we find we were
  1984. # invoked by something in a Conscript/Construct file, because
  1985. # dependencies created directly by Cons' analysis shouldn't cause
  1986. # an error.
  1987. sub _type_exception {
  1988. my($e) = @_;
  1989. my($line, $sub);
  1990. (undef, undef, $line, $sub) = script::caller_info;
  1991. if (defined $line) {
  1992. my $err = "\"${\$e->path}\" already in use as a " . ref($e) . " before $sub on line $line";
  1993. if ($e->{'creator'}) {
  1994. my $script;
  1995. (undef, $script, $line, $sub) = @{$e->{'creator'}};
  1996. $err = "\t" . $err . ",\n\t\tdefined by $sub in $script, line $line";
  1997. }
  1998. $err .= "\n";
  1999. die $err;
  2000. }
  2001. }
  2002. # This wraps up all the common File::Spec logic that we use for parsing
  2003. # directory separators in a path and turning it into individual
  2004. # subdirectories that we must create, as well as creation of root
  2005. # nodes for any new file system volumes we find. File::Spec doesn't have
  2006. # intuitively obvious interfaces, so this is heavily commented.
  2007. #
  2008. # Note: This is NOT an object or class method;
  2009. # it's just a utility subroutine.
  2010. sub _parse_path {
  2011. my($dir, $path) = @_;
  2012. # Convert all slashes to the native directory separator.
  2013. # This allows Construct files to always be written with good
  2014. # old POSIX path names, regardless of what we're running on.
  2015. $path = File::Spec->canonpath($path);
  2016. # File::Spec doesn't understand the Cons convention of
  2017. # an initial '#' for top-relative files. Strip it.
  2018. my($toprel) = $path =~ s/^#//;
  2019. # Let File::Spec do the heavy lifting of parsing the path name.
  2020. my($vol, $directories, $entry) = File::Spec->splitpath($path);
  2021. my @dirs = File::Spec->splitdir($directories);
  2022. # If there was a file entry on the end of the path, then the
  2023. # last @dirs element is '' and we don't need it. If there
  2024. # wasn't a file entry on the end (File::Spec->splitpath() knew
  2025. # the last component was a directory), then the last @dirs
  2026. # element becomes the entry we want to look up.
  2027. my($e) = pop @dirs;
  2028. $entry = $e if $entry eq '';
  2029. if (File::Spec->file_name_is_absolute($path)) {
  2030. # An absolute path name. If no volume was supplied,
  2031. # use the volume of our current directory.
  2032. $vol = $cwd_vol if $vol eq '';
  2033. $vol = uc($vol) if File::Spec->case_tolerant;
  2034. if (! defined $root{$vol}) {
  2035. # This is our first time looking up a path name
  2036. # on this volume, so create a root node for it.
  2037. # (On UNIX systems, $vol is always '', so '/'
  2038. # always maps to the $root{''} node.)
  2039. $root{$vol} = {path => $vol.$SEPARATOR,
  2040. prefix => $vol.$SEPARATOR,
  2041. srcpath => $vol.$SEPARATOR,
  2042. 'exists' => 1 };
  2043. $root{$vol}->{'srcdir'} = $root{$vol};
  2044. bless $root{$vol};
  2045. }
  2046. # We're at the top, so strip the blank entry from the front of
  2047. # the @dirs array since the initial '/' it represents will now
  2048. # be supplied by the root node we return.
  2049. shift @dirs;
  2050. $dir = $root{$vol};
  2051. } elsif ($toprel) {
  2052. $dir = $dir::top;
  2053. }
  2054. ($dir, \@dirs, $entry);
  2055. }
  2056. # Common subroutine for creating directory nodes.
  2057. sub _create_dirs {
  2058. my ($dir, @dirs) = @_;
  2059. my $e;
  2060. foreach $e (@dirs) {
  2061. my $d = $dir->{member}->{$e};
  2062. if (! defined $d) {
  2063. bless $d = { 'entry' => $e, 'dir' => $dir, }, 'dir';
  2064. $d->creator(script::caller_info);
  2065. $d->{member}->{$dir::CURDIR} = $d;
  2066. $d->{member}->{$dir::UPDIR} = $dir;
  2067. $dir->{member}->{$e} = $d;
  2068. } elsif (ref $d eq 'entry') {
  2069. bless $d, 'dir';
  2070. $d->{member}->{$dir::CURDIR} = $d;
  2071. $d->{member}->{$dir::UPDIR} = $dir;
  2072. } elsif (ref $d eq 'file') {
  2073. # This clause is to supply backwards compatibility,
  2074. # with a warning, for anyone that's used FilePath
  2075. # to refer to a directory. After people have using
  2076. # 1.8 have had time to adjust (sometime in version
  2077. # 1.9 or later), we should remove this entire clause.
  2078. my($script, $line, $sub);
  2079. (undef, $script, $line, $sub) = @{$d->{'creator'}};
  2080. if ($sub eq 'script::FilePath') {
  2081. print STDERR "$0: Warning: $sub used to refer to a directory\n"
  2082. . "\tat line $line of $script. Use DirPath instead.\n";
  2083. bless $d, 'dir';
  2084. } else {
  2085. _type_exception($d);
  2086. }
  2087. } elsif (ref $d ne 'dir') {
  2088. _type_exception($d);
  2089. }
  2090. $dir = $d;
  2091. }
  2092. $dir;
  2093. }
  2094. # Look up an entry in a directory. This method is for when we don't
  2095. # care whether a file or directory is returned, so if the entry already
  2096. # exists, it will simply be returned. If not, we create it as a
  2097. # generic "entry" which can be later turned into a file or directory
  2098. # by a more-specific lookup.
  2099. #
  2100. # The file entry may be specified as relative, absolute (starts with /),
  2101. # or top-relative (starts with #).
  2102. sub lookup {
  2103. my($dir, $entry) = @_;
  2104. if ($entry !~ m#$MATCH_SEPARATOR#o) {
  2105. # Fast path: simple entry name in a known directory.
  2106. if ($entry =~ s/^#//) {
  2107. # Top-relative names begin with #.
  2108. $dir = $dir::top;
  2109. }
  2110. } else {
  2111. my $dirsref;
  2112. ($dir, $dirsref, $entry) = _parse_path($dir, $entry);
  2113. $dir = _create_dirs($dir, @$dirsref) if @$dirsref;
  2114. return if ! defined $dir;
  2115. return $dir if $entry eq '';
  2116. }
  2117. my $e = $dir->{member}->{$entry};
  2118. if (! defined $e) {
  2119. bless $e = { 'entry' => $entry, 'dir' => $dir, }, 'entry';
  2120. $e->creator(script::caller_info);
  2121. $dir->{member}->{$entry} = $e;
  2122. }
  2123. $e;
  2124. }
  2125. # Look up a file entry in a directory.
  2126. #
  2127. # The file entry may be specified as relative, absolute (starts with /),
  2128. # or top-relative (starts with #).
  2129. sub lookupfile {
  2130. my($dir, $entry) = @_;
  2131. if ($entry !~ m#$MATCH_SEPARATOR#o) {
  2132. # Fast path: simple entry name in a known directory.
  2133. if ($entry =~ s/^#//) {
  2134. # Top-relative names begin with #.
  2135. $dir = $dir::top;
  2136. }
  2137. } else {
  2138. my $dirsref;
  2139. ($dir, $dirsref, $entry) = _parse_path($dir, $entry);
  2140. $dir = _create_dirs($dir, @$dirsref) if @$dirsref;
  2141. return undef if $entry eq '';
  2142. }
  2143. my $f = $dir->{member}->{$entry};
  2144. if (! defined $f) {
  2145. bless $f = { 'entry' => $entry, 'dir' => $dir, }, 'file';
  2146. $f->creator(script::caller_info);
  2147. $dir->{member}->{$entry} = $f;
  2148. } elsif (ref $f eq 'entry') {
  2149. bless $f, 'file';
  2150. } elsif (ref $f ne 'file') {
  2151. _type_exception($f);
  2152. }
  2153. $f;
  2154. }
  2155. # Look up a (sub-)directory entry in a directory.
  2156. #
  2157. # The (sub-)directory entry may be specified as relative, absolute
  2158. # (starts with /), or top-relative (starts with #).
  2159. sub lookupdir {
  2160. my($dir, $entry) = @_;
  2161. my $dirsref;
  2162. if ($entry !~ m#$MATCH_SEPARATOR#o) {
  2163. # Fast path: simple entry name in a known directory.
  2164. if ($entry =~ s/^#//) {
  2165. # Top-relative names begin with #.
  2166. $dir = $dir::top;
  2167. }
  2168. } else {
  2169. ($dir, $dirsref, $entry) = _parse_path($dir, $entry);
  2170. }
  2171. _create_dirs($dir, @$dirsref, $entry);
  2172. }
  2173. # Look up a file entry and return it if it's accessible.
  2174. sub lookup_accessible {
  2175. my $file = $_[0]->lookupfile($_[1]);
  2176. return ($file && $file->accessible) ? $file : undef;
  2177. }
  2178. # Return the parent directory without doing a lookupdir,
  2179. # which would create a parent if it doesn't already exist.
  2180. # A return value of undef (! $dir->up) indicates a root directory.
  2181. sub up {
  2182. $_[0]->{member}->{$dir::UPDIR};
  2183. }
  2184. # Return whether this is an entry somewhere underneath the
  2185. # specified directory.
  2186. sub is_under {
  2187. my $dir = $_[0];
  2188. while ($dir) {
  2189. return 1 if $_[1] == $dir;
  2190. $dir = $dir->up;
  2191. }
  2192. return undef;
  2193. }
  2194. # Return the relative path from the calling directory ($_[1])
  2195. # to the object. If the object is not under the directory, then
  2196. # we return it as a top-relative or absolute path name.
  2197. sub relpath {
  2198. my ($dir, $obj) = @_;
  2199. my @dirs;
  2200. my $o = $obj;
  2201. while ($o) {
  2202. if ($dir == $o) {
  2203. if (@dirs < 2) {
  2204. return $dirs[0] || '';
  2205. } else {
  2206. return File::Spec->catdir(@dirs);
  2207. }
  2208. }
  2209. unshift(@dirs, $o->{entry});
  2210. $o = $o->up;
  2211. }
  2212. # The object was not underneath the specified directory.
  2213. # Use the node's cached path, which is either top-relative
  2214. # (in which case we append '#' to the beginning) or
  2215. # absolute.
  2216. my $p = $obj->path;
  2217. $p = '#' . $p if ! File::Spec->file_name_is_absolute($p);
  2218. return $p;
  2219. }
  2220. # Return the path of the directory (file paths implemented
  2221. # separately, below).
  2222. sub path {
  2223. $_[0]->{path} ||
  2224. ($_[0]->{path} = $_[0]->{dir}->prefix . $_[0]->{entry});
  2225. }
  2226. # Return the pathname as a prefix to be concatenated with an entry.
  2227. sub prefix {
  2228. return $_[0]->{prefix} if exists $_[0]->{prefix};
  2229. $_[0]->{prefix} = $_[0]->path . $SEPARATOR;
  2230. }
  2231. # Return the related source path prefix.
  2232. sub srcprefix {
  2233. return $_[0]->{srcprefix} if exists $_[0]->{srcprefix};
  2234. my($srcdir) = $_[0]->srcdir;
  2235. $srcdir->{srcprefix} = $srcdir eq $_[0] ? $srcdir->prefix
  2236. : $srcdir->srcprefix;
  2237. }
  2238. # Return the related source directory.
  2239. sub srcdir {
  2240. $_[0]->{'srcdir'} ||
  2241. ($_[0]->{'srcdir'} = $_[0]->{dir}->srcdir->lookupdir($_[0]->{entry}))
  2242. }
  2243. # Return if the directory is linked to a separate source directory.
  2244. sub is_linked {
  2245. return $_[0]->{is_linked} if defined $_[0]->{is_linked};
  2246. $_[0]->{is_linked} = $_[0]->path ne $_[0]->srcdir->path;
  2247. }
  2248. sub link {
  2249. my(@paths) = @_;
  2250. my($srcdir) = $dir::cwd->lookupdir(pop @paths)->srcdir;
  2251. map($dir::cwd->lookupdir($_)->{'srcdir'} = $srcdir, @paths);
  2252. # make a reverse lookup for the link.
  2253. $srcdir->{links} = [] if ! $srcdir->{links};
  2254. push @{$srcdir->{links}}, @paths;
  2255. }
  2256. use vars qw( @tail ); # TODO: Why global ????
  2257. sub linked_targets {
  2258. my $tgt = shift;
  2259. my @targets = ();
  2260. my $dir;
  2261. if (ref $tgt eq 'dir') {
  2262. $dir = $tgt;
  2263. } else {
  2264. push @tail, $tgt;
  2265. $dir = $tgt->{dir};
  2266. }
  2267. while ($dir) {
  2268. if (defined $dir->{links} && @{$dir->{links}}) {
  2269. push(@targets, map(File::Spec->catdir($_, @tail), @{$dir->{links}}));
  2270. #print STDERR "Found Link: ${\$dir->path} -> @{\$dir->{links}}\n";
  2271. }
  2272. unshift @tail, $dir->{entry};
  2273. $dir = $dir->up;
  2274. }
  2275. return map($dir::top->lookupdir($_), @targets);
  2276. }
  2277. sub accessible {
  2278. my $path = $_[0]->path;
  2279. my $err = "$0: you have attempted to use path \"$path\" both as a file " .
  2280. "and as a directory!\n";
  2281. die $err;
  2282. }
  2283. sub init {
  2284. my $path = Cwd::cwd();
  2285. # We know we can get away with passing undef to lookupdir
  2286. # as the directory because $dir is an absolute path.
  2287. $top = lookupdir(undef, $path);
  2288. $top->{'path'} = $top->{srcpath} = $dir::CURDIR;
  2289. $top->{'prefix'} = '';
  2290. $top->{'srcdir'} = $top;
  2291. $cwd = $top;
  2292. ($cwd_vol, undef, undef) = File::Spec->splitpath($path);
  2293. $cwd_vol = '' if ! defined $cwd_vol;
  2294. $cwd_vol = uc($cwd_vol) if File::Spec->case_tolerant;
  2295. }
  2296. package file;
  2297. use vars qw( @ISA $level );
  2298. BEGIN { @ISA = qw(dir); $level = 0 }
  2299. # Return the pathname of the file.
  2300. # Define this separately from dir::path because we don't want to
  2301. # cache all file pathnames (just directory pathnames).
  2302. sub path {
  2303. $_[0]->{dir}->prefix . $_[0]->{entry}
  2304. }
  2305. # Return the related source file path.
  2306. sub srcpath {
  2307. $_[0]->{dir}->srcprefix . $_[0]->{entry}
  2308. }
  2309. # Return if the file is (should be) linked to a separate source file.
  2310. sub is_linked {
  2311. $_[0]->{dir}->is_linked
  2312. }
  2313. # Repository file search. If the local file exists, that wins.
  2314. # Otherwise, return the first existing same-named file under a
  2315. # Repository directory. If there isn't anything with the same name
  2316. # under a Repository directory, return the local file name anyway
  2317. # so that some higher layer can try to construct it.
  2318. sub rfile {
  2319. return $_[0]->{rfile} if exists $_[0]->{rfile};
  2320. my($self) = @_;
  2321. my($rfile) = $self;
  2322. if (@param::rpath) {
  2323. my($path) = $self->path;
  2324. if (! File::Spec->file_name_is_absolute($path) && ! -f $path) {
  2325. my($dir);
  2326. foreach $dir (@param::rpath) {
  2327. my($t) = $dir->prefix . $path;
  2328. if (-f $t) {
  2329. $rfile = $_[0]->lookupfile($t);
  2330. $rfile->{is_on_rpath} = 1;
  2331. last;
  2332. }
  2333. }
  2334. }
  2335. }
  2336. $self->{rfile} = $rfile;
  2337. }
  2338. # returns the "precious" status of this file.
  2339. sub precious {
  2340. return $_[0]->{precious};
  2341. }
  2342. # "Erase" reference to a Repository file,
  2343. # making this a completely local file object
  2344. # by pointing it back to itself.
  2345. sub no_rfile {
  2346. $_[0]->{'rfile'} = $_[0];
  2347. }
  2348. # Return a path to the first existing file under a Repository directory,
  2349. # implicitly returning the current file's path if there isn't a
  2350. # same-named file under a Repository directory.
  2351. sub rpath {
  2352. $_[0]->{rpath} ||
  2353. ($_[0]->{rpath} = $_[0]->rfile->path)
  2354. }
  2355. # Return a path to the first linked srcpath file under a Repositoy
  2356. # directory, implicitly returning the current file's srcpath if there
  2357. # isn't a same-named file under a Repository directory.
  2358. sub rsrcpath {
  2359. return $_[0]->{rsrcpath} if exists $_[0]->{rsrcpath};
  2360. my($self) = @_;
  2361. my($path) = $self->{rsrcpath} = $self->srcpath;
  2362. if (@param::rpath && ! File::Spec->file_name_is_absolute($path) && ! -f $path) {
  2363. my($dir);
  2364. foreach $dir (@param::rpath) {
  2365. my($t) = $dir->prefix . $path;
  2366. if (-f $t) {
  2367. $self->{rsrcpath} = $t;
  2368. last;
  2369. }
  2370. }
  2371. }
  2372. $self->{rsrcpath};
  2373. }
  2374. # Return if a same-named file source file exists.
  2375. # This handles the interaction of Link and Repository logic.
  2376. # As a side effect, it will link a source file from its Linked
  2377. # directory (preferably local, but maybe in a repository)
  2378. # into a build directory from its proper Linked directory.
  2379. sub source_exists {
  2380. return $_[0]->{source_exists} if defined $_[0]->{source_exists};
  2381. my($self) = @_;
  2382. my($path) = $self->path;
  2383. my($time) = (stat($path))[9];
  2384. if ($self->is_linked) {
  2385. # Linked directory, local logic.
  2386. my($srcpath) = $self->srcpath;
  2387. my($srctime) = (stat($srcpath))[9];
  2388. if ($srctime) {
  2389. if (! $time || $srctime != $time) {
  2390. futil::install($srcpath, $self);
  2391. }
  2392. return $self->{source_exists} = 1;
  2393. }
  2394. # Linked directory, repository logic.
  2395. if (@param::rpath) {
  2396. if ($self != $self->rfile) {
  2397. return $self->{source_exists} = 1;
  2398. }
  2399. my($rsrcpath) = $self->rsrcpath;
  2400. if ($path ne $rsrcpath) {
  2401. my($rsrctime) = (stat($rsrcpath))[9];
  2402. if ($rsrctime) {
  2403. if (! $time || $rsrctime != $time) {
  2404. futil::install($rsrcpath, $self);
  2405. }
  2406. return $self->{source_exists} = 1;
  2407. }
  2408. }
  2409. }
  2410. # There was no source file in any Linked directory
  2411. # under any Repository. If there's one in the local
  2412. # build directory, it no longer belongs there.
  2413. if ($time) {
  2414. unlink($path) || die("$0: couldn't unlink $path ($!)\n");
  2415. }
  2416. return $self->{source_exists} = '';
  2417. } else {
  2418. if ($time) {
  2419. return $self->{source_exists} = 1;
  2420. }
  2421. if (@param::rpath && $self != $self->rfile) {
  2422. return $self->{source_exists} = 1;
  2423. }
  2424. return $self->{source_exists} = '';
  2425. }
  2426. }
  2427. # Return if a same-named derived file exists under a Repository directory.
  2428. sub derived_exists {
  2429. $_[0]->{derived_exists} ||
  2430. ($_[0]->{derived_exists} = ($_[0] != $_[0]->rfile));
  2431. }
  2432. # Return if this file is somewhere under a Repository directory.
  2433. sub is_on_rpath {
  2434. $_[0]->{is_on_rpath};
  2435. }
  2436. sub local {
  2437. my($self, $arg) = @_;
  2438. if (defined $arg) {
  2439. $self->{'local'} = $arg;
  2440. }
  2441. $self->{'local'};
  2442. }
  2443. # Return the entry name of the specified file with the specified
  2444. # suffix appended. Leave it untouched if the suffix is already there.
  2445. # Differs from the addsuffix function, below, in that this strips
  2446. # the existing suffix (if any) before appending the desired one.
  2447. sub base_suf {
  2448. my($entry) = $_[0]->{entry};
  2449. if ($entry !~ m/$_[1]$/) {
  2450. $entry =~ s/\.[^\.]*$//;
  2451. $entry .= $_[1];
  2452. }
  2453. $entry;
  2454. }
  2455. # Return the suffix of the file, for up to a 3 character
  2456. # suffix. Anything less returns nothing.
  2457. sub suffix {
  2458. if (! $main::_WIN32) {
  2459. $_[0]->{entry} =~ /\.[^\.\/]{0,3}$/;
  2460. $&
  2461. } else {
  2462. my @pieces = split(/\./, $_[0]->{entry});
  2463. my $suffix = pop(@pieces);
  2464. return ".$suffix";
  2465. }
  2466. }
  2467. # Called as a simple function file::addsuffix(name, suffix)
  2468. sub addsuffix {
  2469. my($name, $suffix) = @_;
  2470. if ($suffix && substr($name, -length($suffix)) ne $suffix) {
  2471. return $name .= $suffix;
  2472. }
  2473. $name;
  2474. }
  2475. # Return true if the file is (or will be) accessible.
  2476. # That is, if we can build it, or if it is already present.
  2477. sub accessible {
  2478. (exists $_[0]->{builder}) || ($_[0]->source_exists);
  2479. }
  2480. # Return true if the file should be ignored for the purpose
  2481. # of computing dependency information (should not be considered
  2482. # as a dependency and, further, should not be scanned for
  2483. # dependencies).
  2484. sub ignore {
  2485. return 0 if !$param::ignore;
  2486. return $_[0]->{ignore} if exists $_[0]->{ignore};
  2487. $_[0]->{ignore} = $_[0]->path =~ /$param::ignore/o;
  2488. }
  2489. # Build the file, if necessary.
  2490. sub build {
  2491. $_[0]->{status} || &file::_build;
  2492. }
  2493. sub _build {
  2494. my($self) = @_;
  2495. print main::DEPFILE $self->path, "\n" if $param::depfile;
  2496. print((' ' x $level), "Checking ", $self->path, "\n") if $param::depends;
  2497. if (!exists $self->{builder}) {
  2498. # We don't know how to build the file. This is OK, if
  2499. # the file is present as a source file, under either the
  2500. # local tree or a Repository.
  2501. if ($self->source_exists) {
  2502. return $self->{status} = 'handled';
  2503. } else {
  2504. my($name) = $self->path;
  2505. print("$0: don't know how to construct \"$name\"\n");
  2506. exit(1) unless $param::kflag;
  2507. return $self->{status} = 'errors'; # xxx used to be 'unknown'
  2508. }
  2509. }
  2510. # An associated build object exists, so we know how to build
  2511. # the file. We first compute the signature of the file, based
  2512. # on its dependendencies, then only rebuild the file if the
  2513. # signature has changed.
  2514. my($builder) = $self->{builder};
  2515. $level += 2;
  2516. my(@deps) = (@{$self->{dep}}, @{$self->{sources}});
  2517. my($rdeps) = \@deps;
  2518. if ($param::random) {
  2519. # If requested, build in a random order, instead of the
  2520. # order that the dependencies were listed.
  2521. my(%rdeps);
  2522. map { $rdeps{$_,'*' x int(rand 10)} = $_ } @deps;
  2523. $rdeps = [values(%rdeps)];
  2524. }
  2525. $self->{status} = '';
  2526. my $dep;
  2527. for $dep (@$rdeps) {
  2528. if ((build $dep) eq 'errors') {
  2529. # Propagate dependent errors to target.
  2530. # but try to build all dependents regardless of errors.
  2531. $self->{status} = 'errors';
  2532. }
  2533. }
  2534. # If any dependents had errors, then we abort.
  2535. if ($self->{status} eq 'errors') {
  2536. $level -= 2;
  2537. return 'errors';
  2538. }
  2539. # Compute the final signature of the file, based on
  2540. # the static dependencies (in order), dynamic dependencies,
  2541. # output path name, and (non-substituted) build script.
  2542. my($sig) = 'sig'->collect(map('sig'->signature($_->rfile), @deps),
  2543. $builder->includes($self),
  2544. $builder->script);
  2545. # May have gotten errors during computation of dynamic
  2546. # dependency signature, above.
  2547. $level -= 2;
  2548. return 'errors' if $self->{status} eq 'errors';
  2549. if (@param::rpath && $self->derived_exists) {
  2550. # There is no local file of this name, but there is one
  2551. # under a Repository directory.
  2552. if ('sig'->current($self->rfile, $sig)) {
  2553. # The Repository copy is current (its signature matches
  2554. # our calculated signature).
  2555. if ($self->local) {
  2556. # ...but they want a local copy, so provide it.
  2557. main::showcom("Local copy of ${\$self->path} from " .
  2558. "${\$self->rpath}");
  2559. futil::install($self->rpath, $self);
  2560. 'sig'->set($self, $sig);
  2561. }
  2562. return $self->{status} = 'handled';
  2563. }
  2564. # The signatures don't match, implicitly because something
  2565. # on which we depend exists locally. Get rid of the reference
  2566. # to the Repository file; we'll build this (and anything that
  2567. # depends on it) locally.
  2568. $self->no_rfile;
  2569. }
  2570. # Then check for currency.
  2571. if (! 'sig'->current($self, $sig)) {
  2572. # We have to build/derive the file.
  2573. print((' ' x $level), "Rebuilding ", $self->path, ": out of date.\n")
  2574. if $param::depends;
  2575. # First check to see if the built file is cached.
  2576. if ($builder->cachin($self, $sig)) {
  2577. 'sig'->set($self, $sig);
  2578. return $self->{status} = 'built';
  2579. } elsif ($builder->action($self)) {
  2580. $builder->cachout($self, $sig);
  2581. 'sig'->set($self, $sig);
  2582. return $self->{status} = 'built';
  2583. } else {
  2584. die("$0: errors constructing ${\$self->path}\n")
  2585. unless $param::kflag;
  2586. return $self->{status} = 'errors';
  2587. }
  2588. } else {
  2589. # Push this out to the cache if we've been asked to (-C option).
  2590. # Don't normally do this because it slows us down.
  2591. # In a fully built system, no accesses to the cache directory
  2592. # are required to check any files. This is a win if cache is
  2593. # heavily shared. Enabling this option puts the directory in the
  2594. # loop. Useful only when you wish to recreate a cache from a build.
  2595. if ($param::cachesync) {
  2596. $builder->cachout($self, $sig);
  2597. 'sig'->set($self, $sig);
  2598. }
  2599. return $self->{status} = 'handled';
  2600. }
  2601. }
  2602. # Bind an action to a file, with the specified sources. No return value.
  2603. sub bind {
  2604. my($self, $builder, @sources) = @_;
  2605. if ($self->{builder} && !$self->{builder}->compatible($builder)) {
  2606. # Even if not "compatible", we can still check to see if the
  2607. # derivation is identical. It should be identical if the builder is
  2608. # the same and the sources are the same.
  2609. if ("$self->{builder} @{$self->{sources}}" ne "$builder @sources") {
  2610. $main::errors++;
  2611. my($_foo1, $script1, $line1, $sub1) = @{$self->creator};
  2612. my($_foo2, $script2, $line2, $sub2) = script::caller_info;
  2613. my $err = "\t${\$self->path}\n" .
  2614. "\tbuilt (at least) two different ways:\n" .
  2615. "\t\t$script1, line $line1: $sub1\n" .
  2616. "\t\t$script2, line $line2: $sub2\n";
  2617. die $err;
  2618. }
  2619. return;
  2620. }
  2621. if ($param::wflag) {
  2622. my($script, $line, $sub);
  2623. (undef, $script, $line, $sub) = script::caller_info;
  2624. $self->{script} = '' if ! defined $self->{script};
  2625. $self->{script} .= "; " if $self->{script};
  2626. $self->{script} .= qq($sub in "$script", line $line);
  2627. }
  2628. $self->{builder} = $builder;
  2629. push(@{$self->{sources}}, @sources);
  2630. @{$self->{dep}} = () if ! defined $self->{dep};
  2631. $self->{conscript} = $priv::self->{script};
  2632. }
  2633. sub is_under {
  2634. $_[0]->{dir}->is_under($_[1]);
  2635. }
  2636. sub relpath {
  2637. my $dirpath = $_[0]->relpath($_[1]->{dir});
  2638. if (! $dirpath) {
  2639. return $_[1]->{entry};
  2640. } else {
  2641. File::Spec->catfile($dirpath, $_[1]->{entry});
  2642. }
  2643. }
  2644. # Generic entry (file or directory) handling.
  2645. # This is an empty subclass for nodes that haven't
  2646. # quite decided whether they're files or dirs.
  2647. # Use file methods until someone blesses them one way or the other.
  2648. package entry;
  2649. use vars qw( @ISA );
  2650. BEGIN { @ISA = qw(file) }
  2651. # File utilities
  2652. package futil;
  2653. # Install one file as another.
  2654. # Links them if possible (hard link), otherwise copies.
  2655. # Don't ask why, but the source is a path, the tgt is a file obj.
  2656. sub install {
  2657. my($sp, $tgt) = @_;
  2658. my($tp) = $tgt->path;
  2659. return 1 if $tp eq $sp;
  2660. return 1 if eval { link($sp, $tp) };
  2661. unlink($tp);
  2662. if (! futil::mkdir($tgt->{dir})) {
  2663. return undef;
  2664. }
  2665. return 1 if eval { link($sp, $tp) };
  2666. futil::copy($sp, $tp);
  2667. }
  2668. # Copy one file to another. Arguments are actual file names.
  2669. # Returns undef on failure. Preserves mtime and mode.
  2670. sub copy {
  2671. my ($sp, $tp) = @_;
  2672. my ($mode, $length, $atime, $mtime) = (stat($sp))[2,7,8,9];
  2673. # Use Perl standard library module for file copying, which handles
  2674. # binary copies. <schwarze@isa.de> 1998-06-18
  2675. if (! File::Copy::copy($sp, $tp)) {
  2676. warn qq($0: can\'t install "$sp" to "$tp" ($!)\n); #'
  2677. return undef;
  2678. }
  2679. # The file has been created, so try both the chmod and utime,
  2680. # first making sure the copy is writable (because permissions
  2681. # affect the ability to modify file times on some operating
  2682. # systems), and then changing permissions back if necessary.
  2683. my $ret = 1;
  2684. my $wmode = $mode | 0700;
  2685. if (! chmod $wmode, $tp) {
  2686. warn qq($0: can\'t set mode $wmode on file "$tp" ($!)\n); #'
  2687. $ret = undef;
  2688. }
  2689. if (! utime $atime, $mtime, $tp) {
  2690. warn qq($0: can\'t set modification time for file "$tp" ($!)\n); #'
  2691. $ret = undef;
  2692. }
  2693. if ($mode != $wmode && ! chmod $mode, $tp) {
  2694. warn qq($0: can\'t set mode $mode on file "$tp" ($!)\n); #'
  2695. $ret = undef;
  2696. }
  2697. return $ret;
  2698. }
  2699. # Ensure that the specified directory exists.
  2700. # Aborts on failure.
  2701. sub mkdir {
  2702. return 1 if $_[0]->{'exists'};
  2703. if (! futil::mkdir($_[0]->{dir})) { # Recursively make parent.
  2704. return undef;
  2705. }
  2706. my($path) = $_[0]->path;
  2707. if (!-d $path && !mkdir($path, 0777)) {
  2708. warn qq($0: can't create directory $path ($!).\n); #'
  2709. return undef;
  2710. }
  2711. $_[0]->{'exists'} = 1;
  2712. }
  2713. # Signature package.
  2714. package sig::hash;
  2715. use vars qw( $called );
  2716. sub init {
  2717. my($dir) = @_;
  2718. my($consign) = $dir->prefix . ".consign";
  2719. my($dhash) = $dir->{consign} = {};
  2720. if (-f $consign) {
  2721. open(CONSIGN, $consign) || die("$0: can't open $consign ($!)\n");
  2722. while(<CONSIGN>) {
  2723. chop;
  2724. my ($file, $sig) = split(/:/,$_);
  2725. $dhash->{$file} = $sig;
  2726. }
  2727. close(CONSIGN);
  2728. }
  2729. $dhash
  2730. }
  2731. # Read the hash entry for a particular file.
  2732. sub in {
  2733. my($dir) = $_[0]->{dir};
  2734. ($dir->{consign} || init($dir))->{$_[0]->{entry}}
  2735. }
  2736. # Write the hash entry for a particular file.
  2737. sub out {
  2738. my($file, $sig) = @_;
  2739. my($dir) = $file->{dir};
  2740. ($dir->{consign} || init($dir))->{$file->{entry}} = $sig;
  2741. $sig::hash::dirty{$dir} = $dir;
  2742. }
  2743. # Flush hash entries. Called at end or via ^C interrupt.
  2744. sub END {
  2745. return if $called++; # May be called twice.
  2746. close(CONSIGN); # in case this came in via ^C.
  2747. my $dir;
  2748. for $dir (values %sig::hash::dirty) {
  2749. my($consign) = $dir->prefix . ".consign";
  2750. my($constemp) = $consign . ".$$";
  2751. if (! open(CONSIGN, ">$constemp")) {
  2752. die("$0: can't create $constemp ($!)\n");
  2753. }
  2754. my($entry, $sig);
  2755. while (($entry, $sig) = each %{$dir->{consign}}) {
  2756. if (! print CONSIGN "$entry:$sig\n") {
  2757. die("$0: error writing to $constemp ($!)\n");
  2758. }
  2759. }
  2760. close(CONSIGN);
  2761. if (! rename($constemp, $consign)) {
  2762. if (futil::copy($constemp, $consign)) {
  2763. unlink($constemp);
  2764. } else {
  2765. die("$0: couldn't rename or copy $constemp to $consign " .
  2766. "($!)\n");
  2767. }
  2768. }
  2769. }
  2770. }
  2771. # Derived file caching.
  2772. package cache;
  2773. # Find a file in the cache. Return non-null if the file is in the cache.
  2774. sub in {
  2775. return undef unless $param::cache;
  2776. my($file, $sig) = @_;
  2777. # Add the path to the signature, to make it unique.
  2778. $sig = 'sig'->collect($sig, $file->path) unless $param::mixtargets;
  2779. my($dir) = substr($sig, 0, 1);
  2780. my($cp) = File::Spec->catfile($param::cache, $dir, $sig);
  2781. return -f $cp && futil::install($cp, $file);
  2782. }
  2783. # Try to flush a file to the cache, if not already there.
  2784. # If it doesn't make it out, due to an error, then that doesn't
  2785. # really matter.
  2786. sub out {
  2787. return unless $param::cache;
  2788. my($file, $sig) = @_;
  2789. # Add the path to the signature, to make it unique.
  2790. $sig = 'sig'->collect($sig, $file->path) unless $param::mixtargets;
  2791. my($dir) = substr($sig, 0, 1);
  2792. my($sp) = $file->path;
  2793. my($cp) = File::Spec->catfile($param::cache, $dir, $sig);
  2794. my($cdir) = File::Spec->catfile($param::cache, $dir);
  2795. if (! -d $cdir) {
  2796. mkdir($cdir, 0777) ||
  2797. die("$0: can't create cache directory $cdir ($!).\n");
  2798. } elsif (-f $cp) {
  2799. # Already cached: try to use that instead, to save space.
  2800. # This can happen if the -cs option is used on a previously
  2801. # uncached build, or if two builds occur simultaneously.
  2802. my($lp) = ".$sig";
  2803. unlink($lp);
  2804. return if ! eval { link($cp, $lp) };
  2805. rename($lp, $sp);
  2806. # Unix98 says, "If the old argument and the new argument both
  2807. # [refer] to the same existing file, the rename() function
  2808. # returns successfully and performs no other action." So, if
  2809. # $lp and $sp are links (i.e., $cp and $sp are links), $lp is
  2810. # left, and we must unlink it ourselves. If the rename failed
  2811. # for any reason, it is also good form to unlink the temporary
  2812. # $lp. Otherwise $lp no longer exists and, barring some race,
  2813. # the unlink fails silently.
  2814. unlink($lp);
  2815. return;
  2816. }
  2817. return if eval { link($sp, $cp) };
  2818. return if ! -f $sp; # if nothing to cache.
  2819. if (futil::copy($sp, "$cp.new")) {
  2820. rename("$cp.new", $cp);
  2821. }
  2822. }
  2823. # Generic signature handling
  2824. package sig;
  2825. use vars qw( @ISA );
  2826. sub select {
  2827. my($package, $subclass) = @_;
  2828. @ISA = ($package . "::" . $subclass);
  2829. };
  2830. # MD5-based signature package.
  2831. package sig::md5;
  2832. use vars qw( $md5 );
  2833. BEGIN {
  2834. my $module;
  2835. my @md5_modules = qw(Digest::MD5 MD5);
  2836. for (@md5_modules) {
  2837. eval "use $_";
  2838. if (! $@) {
  2839. $module = $_;
  2840. last;
  2841. }
  2842. }
  2843. die "Cannot find any MD5 module from: @md5_modules" if $@;
  2844. $md5 = new $module;
  2845. }
  2846. # Invalidate a cache entry.
  2847. sub invalidate {
  2848. delete $_[1]->{sig}
  2849. }
  2850. # Determine the current signature of an already-existing or
  2851. # non-existant file.
  2852. sub signature {
  2853. if (defined $_[1]->{sig}) {
  2854. return $_[1]->{sig};
  2855. }
  2856. my ($self, $file) = @_;
  2857. my($path) = $file->path;
  2858. my($time) = (stat($path))[9];
  2859. if ($time) {
  2860. my($sigtime) = sig::hash::in($file);
  2861. if ($file->is_on_rpath) {
  2862. if ($sigtime) {
  2863. my ($htime, $hsig) = split(' ',$sigtime);
  2864. if (! $hsig) {
  2865. # There was no separate $htime recorded in
  2866. # the .consign file, which implies that this
  2867. # is a source file in the repository.
  2868. # (Source file .consign entries don't record
  2869. # $htime.) Just return the signature that
  2870. # someone else conveniently calculated for us.
  2871. return $htime; # actually the signature
  2872. } else {
  2873. if (! $param::rep_sig_times_ok || $htime == $time) {
  2874. return $file->{sig} = $hsig;
  2875. }
  2876. }
  2877. }
  2878. return $file->{sig} = $file->path . $time;
  2879. }
  2880. if ($sigtime) {
  2881. my ($htime, $hsig) = split(' ',$sigtime);
  2882. if ($htime eq $time) {
  2883. return $file->{sig} = $hsig;
  2884. }
  2885. }
  2886. if (! File::Spec->file_name_is_absolute($path)) {
  2887. # A file in the local build directory. Assume we can write
  2888. # a signature file for it, and compute the actual source
  2889. # signature. We compute the file based on the build path,
  2890. # not source path, only because there might be parallel
  2891. # builds going on... In principle, we could use the source
  2892. # path and only compute this once.
  2893. my($sig) = srcsig($path);
  2894. sig::hash::out($file, $sig);
  2895. return $file->{sig} = $sig;
  2896. } else {
  2897. return $file->{sig} = $file->{entry} . $time;
  2898. }
  2899. }
  2900. $file->{sig} = '';
  2901. }
  2902. # Is the provided signature equal to the signature of the current
  2903. # instantiation of the target (and does the target exist)?
  2904. sub current {
  2905. my($self, $file, $sig) = @_;
  2906. # Uncomment this to debug checks for signature currency.
  2907. # <knight@baldmt.com> 1998-10-29
  2908. # my $fsig = $self->signature($file);
  2909. # print STDOUT "\$self->signature(${\$file->path})
  2910. # '$fsig' eq \$sig '$sig'\n";
  2911. # return $fsig eq $sig;
  2912. $self->signature($file) eq $sig;
  2913. }
  2914. # Store the signature for a file.
  2915. sub set {
  2916. my($self, $file, $sig) = @_;
  2917. my($time) = (stat($file->path))[9];
  2918. sig::hash::out($file, "$time $sig");
  2919. $file->{sig} = $sig
  2920. }
  2921. # Return an aggregate signature
  2922. sub collect {
  2923. my($self, @sigs) = @_;
  2924. # The following sequence is faster than calling the hex interface.
  2925. $md5->reset();
  2926. $md5->add(join('', $param::salt, @sigs));
  2927. # Uncomment this to debug dependency signatures.
  2928. # <schwarze@isa.de> 1998-05-08
  2929. # my $buf = join(', ', $param::salt, @sigs);
  2930. # print STDOUT "sigbuf=|$buf|\n";
  2931. # Uncomment this to print the result of dependency signature calculation.
  2932. # <knight@baldmt.com> 1998-10-13
  2933. # $buf = unpack("H*", $md5->digest());
  2934. # print STDOUT "\t=>|$buf|\n";
  2935. # return $buf;
  2936. unpack("H*", $md5->digest());
  2937. }
  2938. # Directly compute a file signature as the MD5 checksum of the
  2939. # bytes in the file.
  2940. sub srcsig {
  2941. my($path) = @_;
  2942. $md5->reset();
  2943. open(FILE, $path) || return '';
  2944. binmode(FILE);
  2945. $md5->addfile(\*FILE);
  2946. close(FILE);
  2947. # Uncomment this to print the result of file signature calculation.
  2948. # <knight@baldmt.com> 1998-10-13
  2949. # my $buf = unpack("H*", $md5->digest());
  2950. # print STDOUT "$path=|$buf|\n";
  2951. # return $buf;
  2952. unpack("H*", $md5->digest());
  2953. }
  2954. __END__;
  2955. =head1 NAME
  2956. Cons - A Software Construction System
  2957. =head1 DESCRIPTION
  2958. A guide and reference for version 2.2.0
  2959. Copyright (c) 1996-2000 Free Software Foundation, Inc.
  2960. This program is free software; you can redistribute it and/or modify
  2961. it under the terms of the GNU General Public License as published by
  2962. the Free Software Foundation; either version 2 of the License, or
  2963. (at your option) any later version.
  2964. This program is distributed in the hope that it will be useful,
  2965. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2966. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  2967. GNU General Public License for more details.
  2968. You should have received a copy of the GNU General Public License
  2969. along with this program; see the file COPYING. If not, write to
  2970. the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  2971. Boston, MA 02111-1307, USA.
  2972. =head1 Introduction
  2973. B<Cons> is a system for constructing, primarily, software, but is quite
  2974. different from previous software construction systems. Cons was designed
  2975. from the ground up to deal easily with the construction of software spread
  2976. over multiple source directories. Cons makes it easy to create build scripts
  2977. that are simple, understandable and maintainable. Cons ensures that complex
  2978. software is easily and accurately reproducible.
  2979. Cons uses a number of techniques to accomplish all of this. Construction
  2980. scripts are just Perl scripts, making them both easy to comprehend and very
  2981. flexible. Global scoping of variables is replaced with an import/export
  2982. mechanism for sharing information between scripts, significantly improving
  2983. the readability and maintainability of each script. B<Construction
  2984. environments> are introduced: these are Perl objects that capture the
  2985. information required for controlling the build process. Multiple
  2986. environments are used when different semantics are required for generating
  2987. products in the build tree. Cons implements automatic dependency analysis
  2988. and uses this to globally sequence the entire build. Variant builds are
  2989. easily produced from a single source tree. Intelligent build subsetting is
  2990. possible, when working on localized changes. Overrides can be setup to
  2991. easily override build instructions without modifying any scripts. MD5
  2992. cryptographic B<signatures> are associated with derived files, and are used
  2993. to accurately determine whether a given file needs to be rebuilt.
  2994. While offering all of the above, and more, Cons remains simple and easy to
  2995. use. This will, hopefully, become clear as you read the remainder of this
  2996. document.
  2997. =head1 Why Cons? Why not Make?
  2998. Cons is a B<make> replacement. In the following paragraphs, we look at a few
  2999. of the undesirable characteristics of make--and typical build environments
  3000. based on make--that motivated the development of Cons.
  3001. =head2 Build complexity
  3002. Traditional make-based systems of any size tend to become quite complex. The
  3003. original make utility and its derivatives have contributed to this tendency
  3004. in a number of ways. Make is not good at dealing with systems that are
  3005. spread over multiple directories. Various work-arounds are used to overcome
  3006. this difficulty; the usual choice is for make to invoke itself recursively
  3007. for each sub-directory of a build. This leads to complicated code, in which
  3008. it is often unclear how a variable is set, or what effect the setting of a
  3009. variable will have on the build as a whole. The make scripting language has
  3010. gradually been extended to provide more possibilities, but these have
  3011. largely served to clutter an already overextended language. Often, builds
  3012. are done in multiple passes in order to provide appropriate products from
  3013. one directory to another directory. This represents a further increase in
  3014. build complexity.
  3015. =head2 Build reproducibility
  3016. The bane of all makes has always been the correct handling of
  3017. dependencies. Most often, an attempt is made to do a reasonable job of
  3018. dependencies within a single directory, but no serious attempt is made to do
  3019. the job between directories. Even when dependencies are working correctly,
  3020. make's reliance on a simple time stamp comparison to determine whether a
  3021. file is out of date with respect to its dependents is not, in general,
  3022. adequate for determining when a file should be rederived. If an external
  3023. library, for example, is rebuilt and then ``snapped'' into place, the
  3024. timestamps on its newly created files may well be earlier than the last
  3025. local build, since it was built before it became visible.
  3026. =head2 Variant builds
  3027. Make provides only limited facilities for handling variant builds. With the
  3028. proliferation of hardware platforms and the need for debuggable
  3029. vs. optimized code, the ability to easily create these variants is
  3030. essential. More importantly, if variants are created, it is important to
  3031. either be able to separate the variants or to be able to reproduce the
  3032. original or variant at will. With make it is very difficult to separate the
  3033. builds into multiple build directories, separate from the source. And if
  3034. this technique isn't used, it's also virtually impossible to guarantee at
  3035. any given time which variant is present in the tree, without resorting to a
  3036. complete rebuild.
  3037. =head2 Repositories
  3038. Make provides only limited support for building software from code that
  3039. exists in a central repository directory structure. The VPATH feature of
  3040. GNU make (and some other make implementations) is intended to provide this,
  3041. but doesn't work as expected: it changes the path of target file to the
  3042. VPATH name too early in its analysis, and therefore searches for all
  3043. dependencies in the VPATH directory. To ensure correct development builds,
  3044. it is important to be able to create a file in a local build directory and
  3045. have any files in a code repository (a VPATH directory, in make terms) that
  3046. depend on the local file get rebuilt properly. This isn't possible with
  3047. VPATH, without coding a lot of complex repository knowledge directly into
  3048. the makefiles.
  3049. =head1 Keeping it simple
  3050. A few of the difficulties with make have been cited above. In this and
  3051. subsequent sections, we shall introduce Cons and show how these issues are
  3052. addressed.
  3053. =head2 Perl scripts
  3054. Cons is Perl-based. That is, Cons scripts--F<Conscript> and F<Construct>
  3055. files, the equivalent to F<Makefile> or F<makefile>--are all written in
  3056. Perl. This provides an immediate benefit: the language for writing scripts
  3057. is a familiar one. Even if you don't happen to be a Perl programmer, it
  3058. helps to know that Perl is basically just a simple declarative language,
  3059. with a well-defined flow of control, and familiar semantics. It has
  3060. variables that behave basically the way you would expect them to,
  3061. subroutines, flow of control, and so on. There is no special syntax
  3062. introduced for Cons. The use of Perl as a scripting language simplifies
  3063. the task of expressing the appropriate solution to the often complex
  3064. requirements of a build.
  3065. =head2 Hello, World!
  3066. To ground the following discussion, here's how you could build the B<Hello,
  3067. World!> C application with Cons:
  3068. $env = new cons();
  3069. Program $env 'hello', 'hello.c';
  3070. If you install this script in a directory, naming the script F<Construct>,
  3071. and create the F<hello.c> source file in the same directory, then you can
  3072. type C<cons hello> to build the application:
  3073. % cons hello
  3074. cc -c hello.c -o hello.o
  3075. cc -o hello hello.o
  3076. =head2 Construction environments
  3077. A key simplification of Cons is the idea of a B<construction environment>. A
  3078. construction environment is an B<object> characterized by a set of key/value
  3079. pairs and a set of B<methods. >In order to tell Cons how to build something,
  3080. you invoke the appropriate method via an appropriate construction
  3081. environment. Consider the following example:
  3082. $env = new cons(
  3083. CC => 'gcc',
  3084. LIBS => 'libworld.a'
  3085. );
  3086. Program $env 'hello', 'hello.c';
  3087. In this case, rather than using the default construction environment, as is,
  3088. we have overridden the value of C<CC> so that the GNU C Compiler equivalent
  3089. is used, instead. Since this version of B<Hello, World!> requires a library,
  3090. F<libworld.a>, we have specified that any program linked in this environment
  3091. should be linked with that library. If the library exists already, well and
  3092. good, but if not, then we'll also have to include the statement:
  3093. Library $env 'libworld', 'world.c';
  3094. Now if you type C<cons hello>, the library will be built before the program
  3095. is linked, and, of course, C<gcc> will be used to compile both modules:
  3096. % cons hello
  3097. gcc -c hello.c -o hello.o
  3098. gcc -c world.c -o world.o
  3099. ar r libworld.a world.o
  3100. ar: creating libworld.a
  3101. ranlib libworld.a
  3102. gcc -o hello hello.o libworld.a
  3103. =head2 Automatic and complete dependency analysis
  3104. With Cons, dependencies are handled automatically. Continuing the previous
  3105. example, note that when we modify F<world.c>, F<world.o> is recompiled,
  3106. F<libworld.a> recreated, and F<hello> relinked:
  3107. % vi world.c
  3108. [EDIT]
  3109. % cons hello
  3110. gcc -c world.c -o world.o
  3111. ar r libworld.a world.o
  3112. ar: creating libworld.a
  3113. ranlib libworld.a
  3114. gcc -o hello hello.o libworld.a
  3115. This is a relatively simple example: Cons ``knows'' F<world.o> depends upon
  3116. F<world.c>, because the dependency is explicitly set up by the C<Library>
  3117. method. It also knows that F<libworld.a> depends upon F<world.o> and that
  3118. F<hello> depends upon F<libworld.a>, all for similar reasons.
  3119. Now it turns out that F<hello.c> also includes the interface definition
  3120. file, F<world.h>:
  3121. % emacs world.h
  3122. [EDIT]
  3123. % cons hello
  3124. gcc -c hello.c -o hello.o
  3125. gcc -o hello hello.o libworld.a
  3126. How does Cons know that F<hello.c> includes F<world.h>, and that F<hello.o>
  3127. must therefore be recompiled? For now, suffice it to say that when
  3128. considering whether or not F<hello.o> is up-to-date, Cons invokes a scanner
  3129. for its dependency, F<hello.c>. This scanner enumerates the files included
  3130. by F<hello.c> to come up with a list of further dependencies, beyond those
  3131. made explicit by the Cons script. This process is recursive: any files
  3132. included by included files will also be scanned.
  3133. Isn't this expensive? The answer is--it depends. If you do a full build of a
  3134. large system, the scanning time is insignificant. If you do a rebuild of a
  3135. large system, then Cons will spend a fair amount of time thinking about it
  3136. before it decides that nothing has to be done (although not necessarily more
  3137. time than make!). The good news is that Cons makes it very easy to
  3138. intelligently subset your build, when you are working on localized changes.
  3139. =head2 Automatic global build sequencing
  3140. Because Cons does full and accurate dependency analysis, and does this
  3141. globally, for the entire build, Cons is able to use this information to take
  3142. full control of the B<sequencing> of the build. This sequencing is evident
  3143. in the above examples, and is equivalent to what you would expect for make,
  3144. given a full set of dependencies. With Cons, this extends trivially to
  3145. larger, multi-directory builds. As a result, all of the complexity involved
  3146. in making sure that a build is organized correctly--including multi-pass
  3147. hierarchical builds--is eliminated. We'll discuss this further in the next
  3148. sections.
  3149. =head1 Building large trees--still just as simple
  3150. =head2 A hierarchy of build scripts
  3151. A larger build, in Cons, is organized by creating a hierarchy of B<build
  3152. scripts>. At the top of the tree is a script called F<Construct>. The rest
  3153. of the scripts, by convention, are each called F<Conscript>. These scripts
  3154. are connected together, very simply, by the C<Build>, C<Export>, and
  3155. C<Import> commands.
  3156. =head2 The Build command
  3157. The C<Build> command takes a list of F<Conscript> file names, and arranges
  3158. for them to be included in the build. For example:
  3159. Build qw(
  3160. drivers/display/Conscript
  3161. drivers/mouse/Conscript
  3162. parser/Conscript
  3163. utilities/Conscript
  3164. );
  3165. This is a simple two-level hierarchy of build scripts: all the subsidiary
  3166. F<Conscript> files are mentioned in the top-level F<Construct> file. Notice
  3167. that not all directories in the tree necessarily have build scripts
  3168. associated with them.
  3169. This could also be written as a multi-level script. For example, the
  3170. F<Construct> file might contain this command:
  3171. Build qw(
  3172. parser/Conscript
  3173. drivers/Conscript
  3174. utilities/Conscript
  3175. );
  3176. and the F<Conscript> file in the F<drivers> directory might contain this:
  3177. Build qw(
  3178. display/Conscript
  3179. mouse/Conscript
  3180. );
  3181. Experience has shown that the former model is a little easier to understand,
  3182. since the whole construction tree is laid out in front of you, at the
  3183. top-level. Hybrid schemes are also possible. A separately maintained
  3184. component that needs to be incorporated into a build tree, for example,
  3185. might hook into the build tree in one place, but define its own construction
  3186. hierarchy.
  3187. By default, Cons does not change its working directory to the directory
  3188. containing a subsidiary F<Conscript> file it is including. This behavior
  3189. can be enabled for a build by specifying, in the top-level F<Construct>
  3190. file:
  3191. Conscript_chdir 1;
  3192. When enabled, Cons will change to the subsidiary F<Conscript> file's
  3193. containing directory while reading in that file, and then change back
  3194. to the top-level directory once the file has been processed.
  3195. It is expected that this behavior will become the default in some future
  3196. version of Cons. To prepare for this transition, builds that expect
  3197. Cons to remain at the top of the build while it reads in a subsidiary
  3198. F<Conscript> file should explicitly disable this feature as follows:
  3199. Conscript_chdir 0;
  3200. =head2 Relative, top-relative, and absolute file names
  3201. You may have noticed that the file names specified to the Build command are
  3202. relative to the location of the script it is invoked from. This is generally
  3203. true for other filename arguments to other commands, too, although we might
  3204. as well mention here that if you begin a file name with a hash mark, ``#'',
  3205. then that file is interpreted relative to the top-level directory (where the
  3206. F<Construct> file resides). And, not surprisingly, if you begin it with ``/'',
  3207. then it is considered to be an absolute pathname. This is true even on
  3208. systems which use a back slash rather than a forward slash to name absolute
  3209. paths.
  3210. =head2 Using modules in build scripts
  3211. You may pull modules into each F<Conscript> file using the normal Perl
  3212. C<use> or C<require> statements:
  3213. use English;
  3214. require My::Module;
  3215. Each C<use> or C<require> only affects the one F<Conscript> file in which
  3216. it appears. To use a module in multiple F<Conscript> files, you must
  3217. put a C<use> or C<require> statement in each one that needs the module.
  3218. =head2 Scope of variables
  3219. The top-level F<Construct> file and all F<Conscript> files begin life in
  3220. a common, separate Perl package. B<Cons> controls the symbol table for
  3221. the package so that, the symbol table for each script is empty, except
  3222. for the F<Construct> file, which gets some of the command line arguments.
  3223. All of the variables that are set or used, therefore, are set by the
  3224. script itself--not by some external script.
  3225. Variables can be explicitly B<imported> by a script from its parent
  3226. script. To import a variable, it must have been B<exported> by the parent
  3227. and initialized (otherwise an error will occur).
  3228. =head2 The Export command
  3229. The C<Export> command is used as in the following example:
  3230. $env = new cons();
  3231. $INCLUDE = "#export/include";
  3232. $LIB = "#export/lib";
  3233. Export qw( env INCLUDE LIB );
  3234. Build qw( util/Conscript );
  3235. The values of the simple variables mentioned in the C<Export> list will be
  3236. squirreled away by any subsequent C<Build> commands. The C<Export> command
  3237. will only export Perl B<scalar> variables, that is, variables whose name
  3238. begins with C<$>. Other variables, objects, etc. can be exported by
  3239. reference--but all scripts will refer to the same object, and this object
  3240. should be considered to be read-only by the subsidiary scripts and by the
  3241. original exporting script. It's acceptable, however, to assign a new value
  3242. to the exported scalar variable--that won't change the underlying variable
  3243. referenced. This sequence, for example, is OK:
  3244. $env = new cons();
  3245. Export qw( env INCLUDE LIB );
  3246. Build qw( util/Conscript );
  3247. $env = new cons(CFLAGS => '-O');
  3248. Build qw( other/Conscript );
  3249. It doesn't matter whether the variable is set before or after the C<Export>
  3250. command. The important thing is the value of the variable at the time the
  3251. C<Build> command is executed. This is what gets squirreled away. Any
  3252. subsequent C<Export> commands, by the way, invalidate the first: you must
  3253. mention all the variables you wish to export on each C<Export> command.
  3254. =head2 The Import command
  3255. Variables exported by the C<Export> command can be imported into subsidiary
  3256. scripts by the C<Import> command. The subsidiary script always imports
  3257. variables directly from the superior script. Consider this example:
  3258. Import qw( env INCLUDE );
  3259. This is only legal if the parent script exported both C<$env> and
  3260. C<$INCLUDE>. It also must have given each of these variables values. It is
  3261. OK for the subsidiary script to only import a subset of the exported
  3262. variables (in this example, C<$LIB>, which was exported by the previous
  3263. example, is not imported).
  3264. All the imported variables are automatically re-exported, so the sequence:
  3265. Import qw ( env INCLUDE );
  3266. Build qw ( beneath-me/Conscript );
  3267. will supply both C<$env> and C<$INCLUDE> to the subsidiary file. If only
  3268. C<$env> is to be exported, then the following will suffice:
  3269. Import qw ( env INCLUDE );
  3270. Export qw ( env );
  3271. Build qw ( beneath-me/Conscript );
  3272. Needless to say, the variables may be modified locally before invoking
  3273. C<Build> on the subsidiary script.
  3274. =head2 Build script evaluation order
  3275. The only constraint on the ordering of build scripts is that superior
  3276. scripts are evaluated before their inferior scripts. The top-level
  3277. F<Construct> file, for instance, is evaluated first, followed by any
  3278. inferior scripts. This is all you really need to know about the evaluation
  3279. order, since order is generally irrelevant. Consider the following C<Build>
  3280. command:
  3281. Build qw(
  3282. drivers/display/Conscript
  3283. drivers/mouse/Conscript
  3284. parser/Conscript
  3285. utilities/Conscript
  3286. );
  3287. We've chosen to put the script names in alphabetical order, simply because
  3288. that's the most convenient for maintenance purposes. Changing the order will
  3289. make no difference to the build.
  3290. =head1 A Model for sharing files
  3291. =head2 Some simple conventions
  3292. In any complex software system, a method for sharing build products needs to
  3293. be established. We propose a simple set of conventions which are trivial to
  3294. implement with Cons, but very effective.
  3295. The basic rule is to require that all build products which need to be shared
  3296. between directories are shared via an intermediate directory. We have
  3297. typically called this F<export>, and, in a C environment, provided
  3298. conventional sub-directories of this directory, such as F<include>, F<lib>,
  3299. F<bin>, etc.
  3300. These directories are defined by the top-level F<Construct> file. A simple
  3301. F<Construct> file for a B<Hello, World!> application, organized using
  3302. multiple directories, might look like this:
  3303. # Construct file for Hello, World!
  3304. # Where to put all our shared products.
  3305. $EXPORT = '#export';
  3306. Export qw( CONS INCLUDE LIB BIN );
  3307. # Standard directories for sharing products.
  3308. $INCLUDE = "$EXPORT/include";
  3309. $LIB = "$EXPORT/lib";
  3310. $BIN = "$EXPORT/bin";
  3311. # A standard construction environment.
  3312. $CONS = new cons (
  3313. CPPPATH => $INCLUDE, # Include path for C Compilations
  3314. LIBPATH => $LIB, # Library path for linking programs
  3315. LIBS => '-lworld', # List of standard libraries
  3316. );
  3317. Build qw(
  3318. hello/Conscript
  3319. world/Conscript
  3320. );
  3321. The F<world> directory's F<Conscript> file looks like this:
  3322. # Conscript file for directory world
  3323. Import qw( CONS INCLUDE LIB );
  3324. # Install the products of this directory
  3325. Install $CONS $LIB, 'libworld.a';
  3326. Install $CONS $INCLUDE, 'world.h';
  3327. # Internal products
  3328. Library $CONS 'libworld.a', 'world.c';
  3329. and the F<hello> directory's F<Conscript> file looks like this:
  3330. # Conscript file for directory hello
  3331. Import qw( CONS BIN );
  3332. # Exported products
  3333. Install $CONS $BIN, 'hello';
  3334. # Internal products
  3335. Program $CONS 'hello', 'hello.c';
  3336. To construct a B<Hello, World!> program with this directory structure, go to
  3337. the top-level directory, and invoke C<cons> with the appropriate
  3338. arguments. In the following example, we tell Cons to build the directory
  3339. F<export>. To build a directory, Cons recursively builds all known products
  3340. within that directory (only if they need rebuilding, of course). If any of
  3341. those products depend upon other products in other directories, then those
  3342. will be built, too.
  3343. % cons export
  3344. Install world/world.h as export/include/world.h
  3345. cc -Iexport/include -c hello/hello.c -o hello/hello.o
  3346. cc -Iexport/include -c world/world.c -o world/world.o
  3347. ar r world/libworld.a world/world.o
  3348. ar: creating world/libworld.a
  3349. ranlib world/libworld.a
  3350. Install world/libworld.a as export/lib/libworld.a
  3351. cc -o hello/hello hello/hello.o -Lexport/lib -lworld
  3352. Install hello/hello as export/bin/hello
  3353. =head2 Clean, understandable, location-independent scripts
  3354. You'll note that the two F<Conscript> files are very clean and
  3355. to-the-point. They simply specify products of the directory and how to build
  3356. those products. The build instructions are minimal: they specify which
  3357. construction environment to use, the name of the product, and the name of
  3358. the inputs. Note also that the scripts are location-independent: if you wish
  3359. to reorganize your source tree, you are free to do so: you only have to
  3360. change the F<Construct> file (in this example), to specify the new locations
  3361. of the F<Conscript> files. The use of an export tree makes this goal easy.
  3362. Note, too, how Cons takes care of little details for you. All the F<export>
  3363. directories, for example, were made automatically. And the installed files
  3364. were really hard-linked into the respective export directories, to save
  3365. space and time. This attention to detail saves considerable work, and makes
  3366. it even easier to produce simple, maintainable scripts.
  3367. =head1 Separating source and build trees
  3368. It's often desirable to keep any derived files from the build completely
  3369. separate from the source files. This makes it much easier to keep track of
  3370. just what is a source file, and also makes it simpler to handle B<variant>
  3371. builds, especially if you want the variant builds to co-exist.
  3372. =head2 Separating build and source directories using the Link command
  3373. Cons provides a simple mechanism that handles all of these requirements. The
  3374. C<Link> command is invoked as in this example:
  3375. Link 'build' => 'src';
  3376. The specified directories are ``linked'' to the specified source
  3377. directory. Let's suppose that you setup a source directory, F<src>, with the
  3378. sub-directories F<world> and F<hello> below it, as in the previous
  3379. example. You could then substitute for the original build lines the
  3380. following:
  3381. Build qw(
  3382. build/world/Conscript
  3383. build/hello/Conscript
  3384. );
  3385. Notice that you treat the F<Conscript> file as if it existed in the build
  3386. directory. Now if you type the same command as before, you will get the
  3387. following results:
  3388. % cons export
  3389. Install build/world/world.h as export/include/world.h
  3390. cc -Iexport/include -c build/hello/hello.c -o build/hello/hello.o
  3391. cc -Iexport/include -c build/world/world.c -o build/world/world.o
  3392. ar r build/world/libworld.a build/world/world.o
  3393. ar: creating build/world/libworld.a
  3394. ranlib build/world/libworld.a
  3395. Install build/world/libworld.a as export/lib/libworld.a
  3396. cc -o build/hello/hello build/hello/hello.o -Lexport/lib -lworld
  3397. Install build/hello/hello as export/bin/hello
  3398. Again, Cons has taken care of the details for you. In particular, you will
  3399. notice that all the builds are done using source files and object files from
  3400. the build directory. For example, F<build/world/world.o> is compiled from
  3401. F<build/world/world.c>, and F<export/include/world.h> is installed from
  3402. F<build/world/world.h>. This is accomplished on most systems by the simple
  3403. expedient of ``hard'' linking the required files from each source directory
  3404. into the appropriate build directory.
  3405. The links are maintained correctly by Cons, no matter what you do to the
  3406. source directory. If you modify a source file, your editor may do this ``in
  3407. place'' or it may rename it first and create a new file. In the latter case,
  3408. any hard link will be lost. Cons will detect this condition the next time
  3409. the source file is needed, and will relink it appropriately.
  3410. You'll also notice, by the way, that B<no> changes were required to the
  3411. underlying F<Conscript> files. And we can go further, as we shall see in the
  3412. next section.
  3413. =head1 Variant builds
  3414. =head2 Hello, World! for baNaNa and peAcH OS's
  3415. Variant builds require just another simple extension. Let's take as an
  3416. example a requirement to allow builds for both the baNaNa and peAcH
  3417. operating systems. In this case, we are using a distributed file system,
  3418. such as NFS to access the particular system, and only one or the other of
  3419. the systems has to be compiled for any given invocation of C<cons>. Here's
  3420. one way we could set up the F<Construct> file for our B<Hello, World!>
  3421. application:
  3422. # Construct file for Hello, World!
  3423. die qq(OS must be specified) unless $OS = $ARG{OS};
  3424. die qq(OS must be "peach" or "banana")
  3425. if $OS ne "peach" && $OS ne "banana";
  3426. # Where to put all our shared products.
  3427. $EXPORT = "#export/$OS";
  3428. Export qw( CONS INCLUDE LIB BIN );
  3429. # Standard directories for sharing products.
  3430. $INCLUDE = "$EXPORT/include";
  3431. $LIB = "$EXPORT/lib";
  3432. $BIN = "$EXPORT/bin";
  3433. # A standard construction environment.
  3434. $CONS = new cons (
  3435. CPPPATH => $INCLUDE, # Include path for C Compilations
  3436. LIBPATH => $LIB, # Library path for linking programs
  3437. LIBS => '-lworld', # List of standard libraries
  3438. );
  3439. # $BUILD is where we will derive everything.
  3440. $BUILD = "#build/$OS";
  3441. # Tell cons where the source files for $BUILD are.
  3442. Link $BUILD => 'src';
  3443. Build (
  3444. "$BUILD/hello/Conscript",
  3445. "$BUILD/world/Conscript",
  3446. );
  3447. Now if we login to a peAcH system, we can build our B<Hello, World!>
  3448. application for that platform:
  3449. % cons export OS=peach
  3450. Install build/peach/world/world.h as export/peach/include/world.h
  3451. cc -Iexport/peach/include -c build/peach/hello/hello.c -o build/peach/hello/hello.o
  3452. cc -Iexport/peach/include -c build/peach/world/world.c -o build/peach/world/world.o
  3453. ar r build/peach/world/libworld.a build/peach/world/world.o
  3454. ar: creating build/peach/world/libworld.a
  3455. ranlib build/peach/world/libworld.a
  3456. Install build/peach/world/libworld.a as export/peach/lib/libworld.a
  3457. cc -o build/peach/hello/hello build/peach/hello/hello.o -Lexport/peach/lib -lworld
  3458. Install build/peach/hello/hello as export/peach/bin/hello
  3459. =head2 Variations on a theme
  3460. Other variations of this model are possible. For example, you might decide
  3461. that you want to separate out your include files into platform dependent and
  3462. platform independent files. In this case, you'd have to define an
  3463. alternative to C<$INCLUDE> for platform-dependent files. Most F<Conscript>
  3464. files, generating purely platform-independent include files, would not have
  3465. to change.
  3466. You might also want to be able to compile your whole system with debugging
  3467. or profiling, for example, enabled. You could do this with appropriate
  3468. command line options, such as C<DEBUG=on>. This would then be translated
  3469. into the appropriate platform-specific requirements to enable debugging
  3470. (this might include turning off optimization, for example). You could
  3471. optionally vary the name space for these different types of systems, but, as
  3472. we'll see in the next section, it's not B<essential> to do this, since Cons
  3473. is pretty smart about rebuilding things when you change options.
  3474. =head1 Signatures
  3475. =head2 MD5 cryptographic signatures
  3476. Whenever Cons creates a derived file, it stores a B<signature> for that
  3477. file. The signature is stored in a separate file, one per directory. After
  3478. the previous example was compiled, the F<.consign> file in the
  3479. F<build/peach/world> directory looked like this:
  3480. world.o:834179303 23844c0b102ecdc0b4548d1cd1cbd8c6
  3481. libworld.a:834179304 9bf6587fa06ec49d864811a105222c00
  3482. The first number is a timestamp--for a UNIX systems, this is typically the
  3483. number of seconds since January 1st, 1970. The second value is an MD5
  3484. checksum. The B<Message Digest Algorithm> is an algorithm that, given an
  3485. input string, computes a strong cryptographic signature for that string. The
  3486. MD5 checksum stored in the F<.consign> file is, in effect, a digest of all
  3487. the dependency information for the specified file. So, for example, for the
  3488. F<world.o> file, this includes at least the F<world.c> file, and also any
  3489. header files that Cons knows about that are included, directly or indirectly
  3490. by F<world.c>. Not only that, but the actual command line that was used to
  3491. generate F<world.o> is also fed into the computation of the
  3492. signature. Similarly, F<libworld.a> gets a signature which ``includes'' all
  3493. the signatures of its constituents (and hence, transitively, the signatures
  3494. of B<their> constituents), as well as the command line that created the
  3495. file.
  3496. The signature of a non-derived file is computed, by default, by taking the
  3497. current modification time of the file and the file's entry name (unless
  3498. there happens to be a current F<.consign> entry for that file, in which case
  3499. that signature is used).
  3500. Notice that there is no need for a derived file to depend upon any
  3501. particular F<Construct> or F<Conscript> file--if changes to these files
  3502. affect the file in question, then this will be automatically reflected in
  3503. its signature, since relevant parts of the command line are included in the
  3504. signature. Unrelated changes will have no effect.
  3505. When Cons considers whether to derive a particular file, then, it first
  3506. computes the expected signature of the file. It then compares the file's
  3507. last modification time with the time recorded in the F<.consign> entry, if
  3508. one exists. If these times match, then the signature stored in the
  3509. F<.consign> file is considered to be accurate. If the file's previous
  3510. signature does not match the new, expected signature, then the file must be
  3511. rederived.
  3512. Notice that a file will be rederived whenever anything about a dependent
  3513. file changes. In particular, notice that B<any> change to the modification
  3514. time of a dependent (forward or backwards in time) will force recompilation
  3515. of the derived file.
  3516. The use of these signatures is an extremely simple, efficient, and effective
  3517. method of improving--dramatically--the reproducibility of a system.
  3518. We'll demonstrate this with a simple example:
  3519. # Simple "Hello, World!" Construct file
  3520. $CFLAGS = '-g' if $ARG{DEBUG} eq 'on';
  3521. $CONS = new cons(CFLAGS => $CFLAGS);
  3522. Program $CONS 'hello', 'hello.c';
  3523. Notice how Cons recompiles at the appropriate times:
  3524. % cons hello
  3525. cc -c hello.c -o hello.o
  3526. cc -o hello hello.o
  3527. % cons hello
  3528. cons: "hello" is up-to-date.
  3529. % cons DEBUG=on hello
  3530. cc -g -c hello.c -o hello.o
  3531. cc -o hello hello.o
  3532. % cons DEBUG=on hello
  3533. cons: "hello" is up-to-date.
  3534. % cons hello
  3535. cc -c hello.c -o hello.o
  3536. cc -o hello hello.o
  3537. =head1 Code Repositories
  3538. Many software development organizations will have one or more central
  3539. repository directory trees containing the current source code for one or
  3540. more projects, as well as the derived object files, libraries, and
  3541. executables. In order to reduce unnecessary recompilation, it is useful to
  3542. use files from the repository to build development software--assuming, of
  3543. course, that no newer dependency file exists in the local build tree.
  3544. =head2 Repository
  3545. Cons provides a mechanism to specify a list of code repositories that will
  3546. be searched, in-order, for source files and derived files not found in the
  3547. local build directory tree.
  3548. The following lines in a F<Construct> file will instruct Cons to look first
  3549. under the F</usr/experiment/repository> directory and then under the
  3550. F</usr/product/repository> directory:
  3551. Repository qw (
  3552. /usr/experiment/repository
  3553. /usr/product/repository
  3554. );
  3555. The repository directories specified may contain source files, derived files
  3556. (objects, libraries and executables), or both. If there is no local file
  3557. (source or derived) under the directory in which Cons is executed, then the
  3558. first copy of a same-named file found under a repository directory will be
  3559. used to build any local derived files.
  3560. Cons maintains one global list of repositories directories. Cons will
  3561. eliminate the current directory, and any non-existent directories, from the
  3562. list.
  3563. =head2 Finding the Construct file in a Repository
  3564. Cons will also search for F<Construct> and F<Conscript> files in the
  3565. repository tree or trees. This leads to a chicken-and-egg situation,
  3566. though: how do you look in a repository tree for a F<Construct> file if the
  3567. F<Construct> file tells you where the repository is? To get around this,
  3568. repositories may be specified via C<-R> options on the command line:
  3569. % cons -R /usr/experiment/repository -R /usr/product/repository .
  3570. Any repository directories specified in the F<Construct> or F<Conscript>
  3571. files will be appended to the repository directories specified by
  3572. command-line C<-R> options.
  3573. =head2 Repository source files
  3574. If the source code (include the F<Conscript> file) for the library version
  3575. of the I<Hello, World!> C application is in a repository (with no derived
  3576. files), Cons will use the repository source files to create the local object
  3577. files and executable file:
  3578. % cons -R /usr/src_only/repository hello
  3579. gcc -c /usr/src_only/repository/hello.c -o hello.o
  3580. gcc -c /usr/src_only/repository/world.c -o world.o
  3581. ar r libworld.a world.o
  3582. ar: creating libworld.a
  3583. ranlib libworld.a
  3584. gcc -o hello hello.o libworld.a
  3585. Creating a local source file will cause Cons to rebuild the appropriate
  3586. derived file or files:
  3587. % pico world.c
  3588. [EDIT]
  3589. % cons -R /usr/src_only/repository hello
  3590. gcc -c world.c -o world.o
  3591. ar r libworld.a world.o
  3592. ar: creating libworld.a
  3593. ranlib libworld.a
  3594. gcc -o hello hello.o libworld.a
  3595. And removing the local source file will cause Cons to revert back to
  3596. building the derived files from the repository source:
  3597. % rm world.c
  3598. % cons -R /usr/src_only/repository hello
  3599. gcc -c /usr/src_only/repository/world.c -o world.o
  3600. ar r libworld.a world.o
  3601. ar: creating libworld.a
  3602. ranlib libworld.a
  3603. gcc -o hello hello.o libworld.a
  3604. =head2 Repository derived files
  3605. If a repository tree contains derived files (usually object files,
  3606. libraries, or executables), Cons will perform its normal signature
  3607. calculation to decide whether the repository file is up-to-date or a derived
  3608. file must be built locally. This means that, in order to ensure correct
  3609. signature calculation, a repository tree must also contain the F<.consign>
  3610. files that were created by Cons when generating the derived files.
  3611. This would usually be accomplished by building the software in the
  3612. repository (or, alternatively, in a build directory, and then copying the
  3613. result to the repository):
  3614. % cd /usr/all/repository
  3615. % cons hello
  3616. gcc -c hello.c -o hello.o
  3617. gcc -c world.c -o world.o
  3618. ar r libworld.a world.o
  3619. ar: creating libworld.a
  3620. ranlib libworld.a
  3621. gcc -o hello hello.o libworld.a
  3622. (This is safe even if the F<Construct> file lists the F</usr/all/repository>
  3623. directory in a C<Repository> command because Cons will remove the current
  3624. directory from the repository list.)
  3625. Now if we want to build a copy of the application with our own F<hello.c>
  3626. file, we only need to create the one necessary source file, and use the
  3627. C<-R> option to have Cons use other files from the repository:
  3628. % mkdir $HOME/build1
  3629. % cd $HOME/build1
  3630. % ed hello.c
  3631. [EDIT]
  3632. % cons -R /usr/all/repository hello
  3633. gcc -c hello.c -o hello.o
  3634. gcc -o hello hello.o /usr/all/repository/libworld.a
  3635. Notice that Cons has not bothered to recreate a local F<libworld.a> library
  3636. (or recompile the F<world.o> module), but instead uses the already-compiled
  3637. version from the repository.
  3638. Because the MD5 signatures that Cons puts in the F<.consign> file contain
  3639. timestamps for the derived files, the signature timestamps must match the
  3640. file timestamps for a signature to be considered valid.
  3641. Some software systems may alter the timestamps on repository files (by
  3642. copying them, e.g.), in which case Cons will, by default, assume the
  3643. repository signatures are invalid and rebuild files unnecessarily. This
  3644. behavior may be altered by specifying:
  3645. Repository_Sig_Times_OK 0;
  3646. This tells Cons to ignore timestamps when deciding whether a signature is
  3647. valid. (Note that avoiding this sanity check means there must be proper
  3648. control over the repository tree to ensure that the derived files cannot be
  3649. modified without updating the F<.consign> signature.)
  3650. =head2 Local copies of files
  3651. If the repository tree contains the complete results of a build, and we try
  3652. to build from the repository without any files in our local tree, something
  3653. moderately surprising happens:
  3654. % mkdir $HOME/build2
  3655. % cd $HOME/build2
  3656. % cons -R /usr/all/repository hello
  3657. cons: "hello" is up-to-date.
  3658. Why does Cons say that the F<hello> program is up-to-date when there is no
  3659. F<hello> program in the local build directory? Because the repository (not
  3660. the local directory) contains the up-to-date F<hello> program, and Cons
  3661. correctly determines that nothing needs to be done to rebuild this
  3662. up-to-date copy of the file.
  3663. There are, however, many times in which it is appropriate to ensure that a
  3664. local copy of a file always exists. A packaging or testing script, for
  3665. example, may assume that certain generated files exist locally. Instead of
  3666. making these subsidiary scripts aware of the repository directory, the
  3667. C<Local> command may be added to a F<Construct> or F<Conscript> file to
  3668. specify that a certain file or files must appear in the local build
  3669. directory:
  3670. Local qw(
  3671. hello
  3672. );
  3673. Then, if we re-run the same command, Cons will make a local copy of the
  3674. program from the repository copy (telling you that it is doing so):
  3675. % cons -R /usr/all/repository hello
  3676. Local copy of hello from /usr/all/repository/hello
  3677. cons: "hello" is up-to-date.
  3678. Notice that, because the act of making the local copy is not considered a
  3679. "build" of the F<hello> file, Cons still reports that it is up-to-date.
  3680. Creating local copies is most useful for files that are being installed into
  3681. an intermediate directory (for sharing with other directories) via the
  3682. C<Install> command. Accompanying the C<Install> command for a file with a
  3683. companion C<Local> command is so common that Cons provides a
  3684. C<Install_Local> command as a convenient way to do both:
  3685. Install_Local $env, '#export', 'hello';
  3686. is exactly equivalent to:
  3687. Install $env '#export', 'hello';
  3688. Local '#export/hello';
  3689. Both the C<Local> and C<Install_Local> commands update the local F<.consign>
  3690. file with the appropriate file signatures, so that future builds are
  3691. performed correctly.
  3692. =head2 Repository dependency analysis
  3693. Due to its built-in scanning, Cons will search the specified repository
  3694. trees for included F<.h> files. Unless the compiler also knows about the
  3695. repository trees, though, it will be unable to find F<.h> files that only
  3696. exist in a repository. If, for example, the F<hello.c> file includes the
  3697. F<hello.h> file in its current directory:
  3698. % cons -R /usr/all/repository hello
  3699. gcc -c /usr/all/repository/hello.c -o hello.o
  3700. /usr/all/repository/hello.c:1: hello.h: No such file or directory
  3701. Solving this problem forces some requirements onto the way construction
  3702. environments are defined and onto the way the C C<#include> preprocessor
  3703. directive is used to include files.
  3704. In order to inform the compiler about the repository trees, Cons will add
  3705. appropriate C<-I> flags to the compilation commands. This means that the
  3706. C<CPPPATH> variable in the construct environment must explicitly specify all
  3707. subdirectories which are to be searched for included files, including the
  3708. current directory. Consequently, we can fix the above example by changing
  3709. the environment creation in the F<Construct> file as follows:
  3710. $env = new cons(
  3711. CC => 'gcc',
  3712. CPPPATH => '.',
  3713. LIBS => 'libworld.a',
  3714. );
  3715. Due to the definition of the C<CPPPATH> variable, this yields, when we
  3716. re-execute the command:
  3717. % cons -R /usr/all/repository hello
  3718. gcc -c -I. -I/usr/all/repository /usr/all/repository/hello.c -o hello.o
  3719. gcc -o hello hello.o /usr/all/repository/libworld.a
  3720. The order of the C<-I> flags replicates, for the C preprocessor, the same
  3721. repository-directory search path that Cons uses for its own dependency
  3722. analysis. If there are multiple repositories and multiple C<CPPPATH>
  3723. directories, Cons will append the repository directories to the beginning of
  3724. each C<CPPPATH> directory, rapidly multiplying the number of C<-I> flags.
  3725. As an extreme example, a F<Construct> file containing:
  3726. Repository qw(
  3727. /u1
  3728. /u2
  3729. );
  3730. $env = new cons(
  3731. CPPPATH => 'a:b:c',
  3732. );
  3733. Would yield a compilation command of:
  3734. cc -Ia -I/u1/a -I/u2/a -Ib -I/u1/b -I/u2/b -Ic -I/u1/c -I/u2/c -c hello.c -o hello.o
  3735. Because Cons relies on the compiler's C<-I> flags to communicate the order
  3736. in which repository directories must be searched, Cons' handling of
  3737. repository directories is fundamentally incompatible with using
  3738. double-quotes on the C<#include> directives in your C source code:
  3739. #include "file.h" /* DON'T USE DOUBLE-QUOTES LIKE THIS */
  3740. This is because most C preprocessors, when faced with such a directive, will
  3741. always first search the directory containing the source file. This
  3742. undermines the elaborate C<-I> options that Cons constructs to make the
  3743. preprocessor conform to its preferred search path.
  3744. Consequently, when using repository trees in Cons,
  3745. B<always> use angle-brackets for included files:
  3746. #include <file.h> /* USE ANGLE-BRACKETS INSTEAD */
  3747. =head2 Repository_List
  3748. Cons provides a C<Repository_List> command to return a list of all
  3749. repository directories in their current search order. This can be used for
  3750. debugging, or to do more complex Perl stuff:
  3751. @list = Repository_List;
  3752. print join(' ', @list), "\n";
  3753. =head2 Repository interaction with other Cons features
  3754. Cons' handling of repository trees interacts correctly with other Cons
  3755. features--which is to say, it generally does what you would expect.
  3756. Most notably, repository trees interact correctly, and rather powerfully,
  3757. with the 'Link' command. A repository tree may contain one or more
  3758. subdirectories for version builds established via C<Link> to a source
  3759. subdirectory. Cons will search for derived files in the appropriate build
  3760. subdirectories under the repository tree.
  3761. =head1 Default targets
  3762. Until now, we've demonstrated invoking Cons with an explicit target
  3763. to build:
  3764. % cons hello
  3765. Normally, Cons does not build anything unless a target is specified,
  3766. but specifying '.' (the current directory) will build everything:
  3767. % cons # does not build anything
  3768. % cons . # builds everything under the top-level directory
  3769. Adding the C<Default> method to any F<Construct> or F<Conscript> file will add
  3770. the specified targets to a list of default targets. Cons will build
  3771. these defaults if there are no targets specified on the command line.
  3772. So adding the following line to the top-level F<Construct> file will mimic
  3773. Make's typical behavior of building everything by default:
  3774. Default '.';
  3775. The following would add the F<hello> and F<goodbye> commands (in the
  3776. same directory as the F<Construct> or F<Conscript> file) to the default list:
  3777. Default qw(
  3778. hello
  3779. goodbye
  3780. );
  3781. The C<Default> method may be used more than once to add targets to the
  3782. default list.
  3783. =head1 Selective builds
  3784. Cons provides two methods for reducing the size of given build. The first is
  3785. by specifying targets on the command line, and the second is a method for
  3786. pruning the build tree. We'll consider target specification first.
  3787. =head2 Selective targeting
  3788. Like make, Cons allows the specification of ``targets'' on the command
  3789. line. Cons targets may be either files or directories. When a directory is
  3790. specified, this is simply a short-hand notation for every derivable
  3791. product--that Cons knows about--in the specified directory and below. For
  3792. example:
  3793. % cons build/hello/hello.o
  3794. means build F<hello.o> and everything that F<hello.o> might need. This is
  3795. from a previous version of the B<Hello, World!> program in which F<hello.o>
  3796. depended upon F<export/include/world.h>. If that file is not up-to-date
  3797. (because someone modified F<src/world/world.h)>, then it will be rebuilt,
  3798. even though it is in a directory remote from F<build/hello>.
  3799. In this example:
  3800. % cons build
  3801. Everything in the F<build> directory is built, if necessary. Again, this may
  3802. cause more files to be built. In particular, both F<export/include/world.h>
  3803. and F<export/lib/libworld.a> are required by the F<build/hello> directory,
  3804. and so they will be built if they are out-of-date.
  3805. If we do, instead:
  3806. % cons export
  3807. then only the files that should be installed in the export directory will be
  3808. rebuilt, if necessary, and then installed there. Note that C<cons build>
  3809. might build files that C<cons export> doesn't build, and vice-versa.
  3810. =head2 No ``special'' targets
  3811. With Cons, make-style ``special'' targets are not required. The simplest
  3812. analog with Cons is to use special F<export> directories, instead. Let's
  3813. suppose, for example, that you have a whole series of unit tests that are
  3814. associated with your code. The tests live in the source directory near the
  3815. code. Normally, however, you don't want to build these tests. One solution
  3816. is to provide all the build instructions for creating the tests, and then to
  3817. install the tests into a separate part of the tree. If we install the tests
  3818. in a top-level directory called F<tests>, then:
  3819. % cons tests
  3820. will build all the tests.
  3821. % cons export
  3822. will build the production version of the system (but not the tests), and:
  3823. % cons build
  3824. should probably be avoided (since it will compile tests unecessarily).
  3825. If you want to build just a single test, then you could explicitly name the
  3826. test (in either the F<tests> directory or the F<build> directory). You could
  3827. also aggregate the tests into a convenient hierarchy within the tests
  3828. directory. This hierarchy need not necessarily match the source hierarchy,
  3829. in much the same manner that the include hierarchy probably doesn't match
  3830. the source hierarchy (the include hierarchy is unlikely to be more than two
  3831. levels deep, for C programs).
  3832. If you want to build absolutely everything in the tree (subject to whatever
  3833. options you select), you can use:
  3834. % cons .
  3835. This is not particularly efficient, since it will redundantly walk all the
  3836. trees, including the source tree. The source tree, of course, may have
  3837. buildable objects in it--nothing stops you from doing this, even if you
  3838. normally build in a separate build tree.
  3839. =head1 Build Pruning
  3840. In conjunction with target selection, B<build pruning> can be used to reduce
  3841. the scope of the build. In the previous peAcH and baNaNa example, we have
  3842. already seen how script-driven build pruning can be used to make only half
  3843. of the potential build available for any given invocation of C<cons>. Cons
  3844. also provides, as a convenience, a command line convention that allows you
  3845. to specify which F<Conscript> files actually get ``built''--that is,
  3846. incorporated into the build tree. For example:
  3847. % cons build +world
  3848. The C<+> argument introduces a Perl regular expression. This must, of
  3849. course, be quoted at the shell level if there are any shell meta-characters
  3850. within the expression. The expression is matched against each F<Conscript>
  3851. file which has been mentioned in a C<Build> statement, and only those
  3852. scripts with matching names are actually incorporated into the build
  3853. tree. Multiple such arguments are allowed, in which case a match against any
  3854. of them is sufficient to cause a script to be included.
  3855. In the example, above, the F<hello> program will not be built, since Cons
  3856. will have no knowledge of the script F<hello/Conscript>. The F<libworld.a>
  3857. archive will be built, however, if need be.
  3858. There are a couple of uses for build pruning via the command line. Perhaps
  3859. the most useful is the ability to make local changes, and then, with
  3860. sufficient knowledge of the consequences of those changes, restrict the size
  3861. of the build tree in order to speed up the rebuild time. A second use for
  3862. build pruning is to actively prevent the recompilation of certain files that
  3863. you know will recompile due to, for example, a modified header file. You may
  3864. know that either the changes to the header file are immaterial, or that the
  3865. changes may be safely ignored for most of the tree, for testing
  3866. purposes.With Cons, the view is that it is pragmatic to admit this type of
  3867. behavior, with the understanding that on the next full build everything that
  3868. needs to be rebuilt will be. There is no equivalent to a ``make touch''
  3869. command, to mark files as permanently up-to-date. So any risk that is
  3870. incurred by build pruning is mitigated. For release quality work, obviously,
  3871. we recommend that you do not use build pruning (it's perfectly OK to use
  3872. during integration, however, for checking compilation, etc. Just be sure to
  3873. do an unconstrained build before committing the integration).
  3874. =head1 Temporary overrides
  3875. Cons provides a very simple mechanism for overriding aspects of a build. The
  3876. essence is that you write an override file containing one or more
  3877. C<Override> commands, and you specify this on the command line, when you run
  3878. C<cons>:
  3879. % cons -o over export
  3880. will build the F<export> directory, with all derived files subject to the
  3881. overrides present in the F<over> file. If you leave out the C<-o> option,
  3882. then everything necessary to remove all overrides will be rebuilt.
  3883. =head2 Overriding environment variables
  3884. The override file can contain two types of overrides. The first is incoming
  3885. environment variables. These are normally accessible by the F<Construct>
  3886. file from the C<%ENV> hash variable. These can trivially be overridden in
  3887. the override file by setting the appropriate elements of C<%ENV> (these
  3888. could also be overridden in the user's environment, of course).
  3889. =head2 The Override command
  3890. The second type of override is accomplished with the C<Override> command,
  3891. which looks like this:
  3892. Override <regexp>, <var1> => <value1>, <var2> => <value2>, ...;
  3893. The regular expression I<regexp> is matched against every derived file that
  3894. is a candidate for the build. If the derived file matches, then the
  3895. variable/value pairs are used to override the values in the construction
  3896. environment associated with the derived file.
  3897. Let's suppose that we have a construction environment like this:
  3898. $CONS = new cons(
  3899. COPT => '',
  3900. CDBG => '-g',
  3901. CFLAGS => '%COPT %CDBG',
  3902. );
  3903. Then if we have an override file F<over> containing this command:
  3904. Override '\.o$', COPT => '-O', CDBG => '';
  3905. then any C<cons> invocation with C<-o over> that creates F<.o> files via
  3906. this environment will cause them to be compiled with C<-O >and no C<-g>. The
  3907. override could, of course, be restricted to a single directory by the
  3908. appropriate selection of a regular expression.
  3909. Here's the original version of the Hello, World! program, built with this
  3910. environment. Note that Cons rebuilds the appropriate pieces when the
  3911. override is applied or removed:
  3912. % cons hello
  3913. cc -g -c hello.c -o hello.o
  3914. cc -o hello hello.o
  3915. % cons -o over hello
  3916. cc -O -c hello.c -o hello.o
  3917. cc -o hello hello.o
  3918. % cons -o over hello
  3919. cons: "hello" is up-to-date.
  3920. % cons hello
  3921. cc -g -c hello.c -o hello.o
  3922. cc -o hello hello.o
  3923. It's important that the C<Override> command only be used for temporary,
  3924. on-the-fly overrides necessary for development because the overrides are not
  3925. platform independent and because they rely too much on intimate knowledge of
  3926. the workings of the scripts. For temporary use, however, they are exactly
  3927. what you want.
  3928. Note that it is still useful to provide, say, the ability to create a fully
  3929. optimized version of a system for production use--from the F<Construct> and
  3930. F<Conscript> files. This way you can tailor the optimized system to the
  3931. platform. Where optimizer trade-offs need to be made (particular files may
  3932. not be compiled with full optimization, for example), then these can be
  3933. recorded for posterity (and reproducibility) directly in the scripts.
  3934. =head1 More on construction environments
  3935. =head2 Default construction variables
  3936. We have mentioned, and used, the concept of a B<construction environment>,
  3937. many times in the preceding pages. Now it's time to make this a little more
  3938. concrete. With the following statement:
  3939. $env = new cons();
  3940. a reference to a new, default construction environment is created. This
  3941. contains a number of construction variables and some methods. At the present
  3942. writing, the default list of construction variables is defined as follows:
  3943. CC => 'cc',
  3944. CFLAGS => '',
  3945. CCCOM => '%CC %CFLAGS %_IFLAGS -c %< -o %>',
  3946. INCDIRPREFIX => '-I',
  3947. CXX => '%CC',
  3948. CXXFLAGS => '%CFLAGS',
  3949. CXXCOM => '%CXX %CXXFLAGS %_IFLAGS -c %< -o %>',
  3950. LINK => '%CXX',
  3951. LINKCOM => '%LINK %LDFLAGS -o %> %< %_LDIRS %LIBS',
  3952. LINKMODULECOM => '%LD -r -o %> %<',
  3953. LIBDIRPREFIX => '-L',
  3954. AR => 'ar',
  3955. ARFLAGS => 'r',
  3956. ARCOM => "%AR %ARFLAGS %> %<\n%RANLIB %>",
  3957. RANLIB => 'ranlib',
  3958. AS => 'as',
  3959. ASFLAGS => '',
  3960. ASCOM => '%AS %ASFLAGS %< -o %>',
  3961. LD => 'ld',
  3962. LDFLAGS => '',
  3963. PREFLIB => 'lib',
  3964. SUFLIB => '.a',
  3965. SUFLIBS => '.so:.a',
  3966. SUFOBJ => '.o',
  3967. ENV => { 'PATH' => '/bin:/usr/bin' },
  3968. On Win32 systems (Windows NT), the following construction variables
  3969. are overridden in the default:
  3970. CC => 'cl',
  3971. CFLAGS => '/nologo',
  3972. CCCOM => '%CC %CFLAGS %_IFLAGS /c %< /Fo%>',
  3973. CXXCOM => '%CXX %CXXFLAGS %_IFLAGS /c %< /Fo%>',
  3974. INCDIRPREFIX => '/I',
  3975. LINK => 'link',
  3976. LINKCOM => '%LINK %LDFLAGS /out:%> %< %_LDIRS %LIBS',
  3977. LINKMODULECOM => '%LD /r /o %> %<',
  3978. LIBDIRPREFIX => '/LIBPATH:',
  3979. AR => 'lib',
  3980. ARFLAGS => '/nologo ',
  3981. ARCOM => "%AR %ARFLAGS /out:%> %<",
  3982. RANLIB => '',
  3983. LD => 'link',
  3984. LDFLAGS => '/nologo ',
  3985. PREFLIB => '',
  3986. SUFEXE => '.exe',
  3987. SUFLIB => '.lib',
  3988. SUFLIBS => '.dll:.lib',
  3989. SUFOBJ => '.obj',
  3990. These variables are used by the various methods associated with the
  3991. environment, in particular any method that ultimately invokes an external
  3992. command will substitute these variables into the final command, as
  3993. appropriate. For example, the C<Objects> method takes a number of source
  3994. files and arranges to derive, if necessary, the corresponding object
  3995. files. For example:
  3996. Objects $env 'foo.c', 'bar.c';
  3997. This will arrange to produce, if necessary, F<foo.o> and F<bar.o>. The
  3998. command invoked is simply C<%CCCOM>, which expands through substitution, to
  3999. the appropriate external command required to build each object. We will
  4000. explore the substitution rules further under the C<Command> method, below.
  4001. The construction variables are also used for other purposes. For example,
  4002. C<CPPPATH> is used to specify a colon-separated path of include
  4003. directories. These are intended to be passed to the C preprocessor and are
  4004. also used by the C-file scanning machinery to determine the dependencies
  4005. involved in a C Compilation. Variables beginning with underscore, are
  4006. created by various methods, and should normally be considered ``internal''
  4007. variables. For example, when a method is called which calls for the creation
  4008. of an object from a C source, the variable C<_IFLAGS> is created: this
  4009. corresponds to the C<-I> switches required by the C compiler to represent
  4010. the directories specified by C<CPPPATH>.
  4011. Note that, for any particular environment, the value of a variable is set
  4012. once, and then never reset (to change a variable, you must create a new
  4013. environment. Methods are provided for copying existing environments for this
  4014. purpose). Some internal variables, such as C<_IFLAGS> are created on demand,
  4015. but once set, they remain fixed for the life of the environment.
  4016. The C<CFLAGS>, C<LDFLAGS>, and C<ARFLAGS> variables all supply a place
  4017. for passing options to the compiler, loader, and archiver, respectively.
  4018. Less obviously, the C<INCDIRPREFIX> variable specifies the option string
  4019. to be appended to the beginning of each include directory so that the
  4020. compiler knows where to find F<.h> files. Similarly, the C<LIBDIRPREFIX>
  4021. variable specifies the option string to be appended to the beginning of
  4022. each directory that the linker should search for libraries.
  4023. Another variable, C<ENV>, is used to determine the system environment during
  4024. the execution of an external command. By default, the only environment
  4025. variable that is set is C<PATH>, which is the execution path for a UNIX
  4026. command. For the utmost reproducibility, you should really arrange to set
  4027. your own execution path, in your top-level F<Construct> file (or perhaps by
  4028. importing an appropriate construction package with the Perl C<use>
  4029. command). The default variables are intended to get you off the ground.
  4030. =head2 Interpolating construction variables
  4031. Construction environment variables may be interpolated in the source and
  4032. target file names by prefixing the construction variable name with C<%>.
  4033. $env = new cons(
  4034. DESTDIR => 'programs',
  4035. SRCDIR => 'src',
  4036. );
  4037. Program $env '%DESTDIR/hello', '%SRCDIR/hello.c';
  4038. Expansion of construction variables is recursive--that is, the file
  4039. name(s) will be re-expanded until no more substitutions can be made. If
  4040. a construction variable is not defined in the environment, then the null
  4041. string will be substituted.
  4042. =head1 Default construction methods
  4043. The list of default construction methods includes the following:
  4044. =head2 The C<new> constructor
  4045. The C<new> method is a Perl object constructor. That is, it is not invoked
  4046. via a reference to an existing construction environment B<reference>, but,
  4047. rather statically, using the name of the Perl B<package> where the
  4048. constructor is defined. The method is invoked like this:
  4049. $env = new cons(<overrides>);
  4050. The environment you get back is blessed into the package C<cons>, which
  4051. means that it will have associated with it the default methods described
  4052. below. Individual construction variables can be overridden by providing
  4053. name/value pairs in an override list. Note that to override any command
  4054. environment variable (i.e. anything under C<ENV>), you will have to override
  4055. all of them. You can get around this difficulty by using the C<copy> method
  4056. on an existing construction environment.
  4057. =head2 The C<clone> method
  4058. The C<clone> method creates a clone of an existing construction environment,
  4059. and can be called as in the following example:
  4060. $env2 = $env1->clone(<overrides>);
  4061. You can provide overrides in the usual manner to create a different
  4062. environment from the original. If you just want a new name for the same
  4063. environment (which may be helpful when exporting environments to existing
  4064. components), you can just use simple assignment.
  4065. =head2 The C<copy> method
  4066. The C<copy> method extracts the externally defined construction variables
  4067. from an environment and returns them as a list of name/value
  4068. pairs. Overrides can also be provided, in which case, the overridden values
  4069. will be returned, as appropriate. The returned list can be assigned to a
  4070. hash, as shown in the prototype, below, but it can also be manipulated in
  4071. other ways:
  4072. %env = $env1->copy(<overrides>);
  4073. The value of C<ENV>, which is itself a hash, is also copied to a new hash,
  4074. so this may be changed without fear of affecting the original
  4075. environment. So, for example, if you really want to override just the
  4076. C<PATH> variable in the default environment, you could do the following:
  4077. %cons = new cons()->copy();
  4078. $cons{ENV}{PATH} = "<your path here>";
  4079. $cons = new cons(%cons);
  4080. This will leave anything else that might be in the default execution
  4081. environment undisturbed.
  4082. =head2 The C<Install> method
  4083. The C<Install> method arranges for the specified files to be installed in
  4084. the specified directory. The installation is optimized: the file is not
  4085. copied if it can be linked. If this is not the desired behavior, you will
  4086. need to use a different method to install the file. It is called as follows:
  4087. Install $env <directory>, <names>;
  4088. Note that, while the files to be installed may be arbitrarily named,
  4089. only the last component of each name is used for the installed target
  4090. name. So, for example, if you arrange to install F<foo/bar> in F<baz>,
  4091. this will create a F<bar> file in the F<baz> directory (not F<foo/bar>).
  4092. =head2 The C<InstallAs> method
  4093. The C<InstallAs> method arranges for the specified source file(s) to be
  4094. installed as the specified target file(s). Multiple files should be
  4095. specified as a file list. The installation is optimized: the file is not
  4096. copied if it can be linked. If this is not the desired behavior, you will
  4097. need to use a different method to install the file. It is called as follows:
  4098. C<InstallAs> works in two ways:
  4099. Single file install:
  4100. InstallAs $env TgtFile, SrcFile;
  4101. Multiple file install:
  4102. InstallAs $env ['tgt1', 'tgt2'], ['src1', 'src2'];
  4103. Or, even as:
  4104. @srcs = qw(src1 src2 src3);
  4105. @tgts = qw(tgt1 tgt2 tgt3);
  4106. InstallAs $env [@tgts], [@srcs];
  4107. Both the target and the sources lists should be of the same length.
  4108. =head2 The C<Precious> method
  4109. The C<Precious> method asks cons not to delete the specified file or
  4110. list of files before building them again. It is invoked as:
  4111. Precious <files>;
  4112. This is especially useful for allowing incremental updates to libraries
  4113. or debug information files which are updated rather than rebuilt anew each
  4114. time. Cons will still delete the files when the C<-r> flag is specified.
  4115. =head2 The C<Command> method
  4116. The C<Command> method is a catchall method which can be used to arrange for
  4117. any external command to be called to update the target. For this command, a
  4118. target file and list of inputs is provided. In addition a construction
  4119. command line, or lines, is provided as a string (this string may have
  4120. multiple commands embedded within it, separated by new lines). C<Command> is
  4121. called as follows:
  4122. Command $env <target>, <inputs>, <construction command>;
  4123. The target is made dependent upon the list of input files specified, and the
  4124. inputs must be built successfully or Cons will not attempt to build the
  4125. target.
  4126. Within the construction command, any variable from the construction
  4127. environment may be introduced by prefixing the name of the construction
  4128. variable with C<%>. This is recursive: the command is expanded until no more
  4129. substitutions can be made. If a construction variable is not defined in the
  4130. environment, then the null string will be substituted. A doubled C<%%>
  4131. will be replaced by a single C<%> in the construction command.
  4132. There are several pseudo variables which will also be expanded:
  4133. =over 10
  4134. =item %>
  4135. The target file name (in a multi-target command, this is always the first
  4136. target mentioned).
  4137. =item %0
  4138. Same as C<%E<gt>>.
  4139. =item %1, %2, ..., %9
  4140. These refer to the first through ninth input file, respectively.
  4141. =item %E<lt>
  4142. The full set of inputs. If any of these have been used anywhere else in the
  4143. current command line (via C<%1>, C<%2>, etc.), then those will be deleted
  4144. from the list provided by C<%E<lt>>. Consider the following command found in a
  4145. F<Conscript> file in the F<test> directory:
  4146. Command $env 'tgt', qw(foo bar baz), qq(
  4147. echo %< -i %1 > %>
  4148. echo %< -i %2 >> %>
  4149. echo %< -i %3 >> %>
  4150. );
  4151. If F<tgt> needed to be updated, then this would result in the execution of
  4152. the following commands, assuming that no remapping has been established for
  4153. the F<test> directory:
  4154. echo test/bar test/baz -i test/foo > test/tgt
  4155. echo test/foo test/baz -i test/bar >> test/tgt
  4156. echo test/foo test/bar -i test/baz >> test/tgt
  4157. =back
  4158. Any of the above pseudo variables may be followed immediately by one of
  4159. the following suffixes to select a portion of the expanded path name:
  4160. :a the absolute path to the file name
  4161. :b the directory plus the file name stripped of any suffix
  4162. :d the directory
  4163. :f the file name
  4164. :s the file name suffix
  4165. :F the file name stripped of any suffix
  4166. Continuing with the above example, C<%<:f> would expand to C<foo bar baz>,
  4167. and C<%>:d> would expand to C<test>.
  4168. It is possible to programmatically rewrite part of the command by
  4169. enclosing part of it between C<%[> and C<%]>. This will call the
  4170. construction variable named as the first word enclosed in the brackets
  4171. as a Perl code reference; the results of this call will be used to
  4172. replace the contents of the brackets in the command line. For example,
  4173. given an existing input file named F<tgt.in>:
  4174. @keywords = qw(foo bar baz);
  4175. $env = new cons(X_COMMA => sub { join(",", @_) });
  4176. Command $env 'tgt', 'tgt.in', qq(
  4177. echo '# Keywords: %[X_COMMA @keywords %]' > %>
  4178. cat %< >> %>
  4179. );
  4180. This will execute:
  4181. echo '# Keywords: foo,bar,baz' > tgt
  4182. cat tgt.in >> tgt
  4183. After substitution occurs, strings of white space are converted into single
  4184. blanks, and leading and trailing white space is eliminated. It is therefore
  4185. not possible to introduce variable length white space in strings passed into
  4186. a command, without resorting to some sort of shell quoting.
  4187. If a multi-line command string is provided, the commands are executed
  4188. sequentially. If any of the commands fails, then none of the rest are
  4189. executed, and the target is not marked as updated, i.e. a new signature is
  4190. not stored for the target.
  4191. Normally, if all the commands succeed, and return a zero status (or whatever
  4192. platform-specific indication of success is required), then a new signature
  4193. is stored for the target. If a command erroneously reports success even
  4194. after a failure, then Cons will assume that the target file created by that
  4195. command is accurate and up-to-date.
  4196. The first word of each command string, after expansion, is assumed to be an
  4197. executable command looked up on the C<PATH> environment variable (which is,
  4198. in turn, specified by the C<ENV> construction variable). If this command is
  4199. found on the path, then the target will depend upon it: the command will
  4200. therefore be automatically built, as necessary. It's possible to write
  4201. multi-part commands to some shells, separated by semi-colons. Only the first
  4202. command word will be depended upon, however, so if you write your command
  4203. strings this way, you must either explicitly set up a dependency (with the
  4204. C<Depends> method), or be sure that the command you are using is a system
  4205. command which is expected to be available. If it isn't available, you will,
  4206. of course, get an error.
  4207. If any command (even one within a multi-line command) begins with
  4208. C<[perl]>, the remainder of that command line will be evaluated by the
  4209. running Perl instead of being forked by the shell. If an error occurs
  4210. in parsing the Perl or if the Perl expression returns 0 or undef, the
  4211. command will be considered to have failed. For example, here is a simple
  4212. command which creates a file C<foo> directly from Perl:
  4213. $env = new cons();
  4214. Command $env 'foo',
  4215. qq([perl] open(FOO,'>foo');print FOO "hi\\n"; close(FOO); 1);
  4216. Note that when the command is executed, you are in the same package as
  4217. when the F<Construct> or F<Conscript> file was read, so you can call
  4218. Perl functions you've defined in the same F<Construct> or F<Conscript>
  4219. file in which the C<Command> appears:
  4220. $env = new cons();
  4221. sub create_file {
  4222. my $file = shift;
  4223. open(FILE, ">$file");
  4224. print FILE "hi\n";
  4225. close(FILE);
  4226. return 1;
  4227. }
  4228. Command $env 'foo', "[perl] &create_file('%>')";
  4229. The Perl string will be used to generate the signature for the derived
  4230. file, so if you change the string, the file will be rebuilt. The contents
  4231. of any subroutines you call, however, are not part of the signature,
  4232. so if you modify a called subroutine such as C<create_file> above,
  4233. the target will I<not> be rebuilt. Caveat user.
  4234. Cons normally prints a command before executing it. This behavior is
  4235. suppressed if the first character of the command is C<@>. Note that
  4236. you may need to separate the C<@> from the command name or escape it to
  4237. prevent C<@cmd> from looking like an array to Perl quote operators that
  4238. perform interpolation:
  4239. # The first command line is incorrect,
  4240. # because "@cp" looks like an array
  4241. # to the Perl qq// function.
  4242. # Use the second form instead.
  4243. Command $env 'foo', 'foo.in', qq(
  4244. @cp %< tempfile
  4245. @ cp tempfile %>
  4246. );
  4247. If there are shell meta characters anywhere in the expanded command line,
  4248. such as C<E<lt>>, C<E<gt>>, quotes, or semi-colon, then the command
  4249. will actually be executed by invoking a shell. This means that a command
  4250. such as:
  4251. cd foo
  4252. alone will typically fail, since there is no command C<cd> on the path. But
  4253. the command string:
  4254. cd $<:d; tar cf $>:f $<:f
  4255. when expanded will still contain the shell meta character semi-colon, and a
  4256. shell will be invoked to interpret the command. Since C<cd> is interpreted
  4257. by this sub-shell, the command will execute as expected.
  4258. To specify a command with multiple targets, you can specify a reference to a
  4259. list of targets. In Perl, a list reference can be created by enclosing a
  4260. list in square brackets. Hence the following command:
  4261. Command $env ['foo.h', 'foo.c'], 'foo.template', q(
  4262. gen %1
  4263. );
  4264. could be used in a case where the command C<gen> creates two files, both
  4265. F<foo.h> and F<foo.c>.
  4266. =head2 The C<Objects> method
  4267. The C<Objects> method arranges to create the object files that correspond to
  4268. the specified source files. It is invoked as shown below:
  4269. @files = Objects $env <source or object files>;
  4270. Under Unix, source files ending in F<.s> and F<.c> are currently
  4271. supported, and will be compiled into a name of the same file ending
  4272. in F<.o>. By default, all files are created by invoking the external
  4273. command which results from expanding the C<CCCOM> construction
  4274. variable, with C<%E<lt>> and C<%E<gt>> set to the source and object
  4275. files, respectively (see the C<Command> method for expansion details).
  4276. The variable C<CPPPATH> is also used when scanning source files for
  4277. dependencies. This is a colon separated list of pathnames, and is also
  4278. used to create the construction variable C<_IFLAGS,> which will contain
  4279. the appropriate list of -C<I> options for the compilation. Any relative
  4280. pathnames in C<CPPPATH> is interpreted relative to the directory in
  4281. which the associated construction environment was created (absolute
  4282. and top-relative names may also be used). This variable is used by
  4283. C<CCCOM>. The behavior of this command can be modified by changing any
  4284. of the variables which are interpolated into C<CCCOM>, such as C<CC>,
  4285. C<CFLAGS>, and, indirectly, C<CPPPATH>. It's also possible to replace
  4286. the value of C<CCCOM>, itself. As a convenience, this file returns the
  4287. list of object filenames.
  4288. =head2 The C<Program> method
  4289. The C<Program> method arranges to link the specified program with the
  4290. specified object files. It is invoked in the following manner:
  4291. Program $env <program name>, <source or object files>;
  4292. The program name will have the value of the C<SUFEXE> construction
  4293. variable appended (by default, C<.exe> on Win32 systems, nothing on Unix
  4294. systems) if the suffix is not already present.
  4295. Source files may be specified in place of objects files--the C<Objects>
  4296. method will be invoked to arrange the conversion of all the files into
  4297. object files, and hence all the observations about the C<Objects> method,
  4298. above, apply to this method also.
  4299. The actual linking of the program will be handled by an external command
  4300. which results from expanding the C<LINKCOM> construction variable, with
  4301. C<%E<lt>> set to the object files to be linked (in the order presented),
  4302. and C<%E<gt>> set to the target (see the C<Command> method for expansion
  4303. details). The user may set additional variables in the construction
  4304. environment, including C<LINK>, to define which program to use for
  4305. linking, C<LIBPATH>, a colon-separated list of library search paths,
  4306. for use with library specifications of the form I<-llib>, and C<LIBS>,
  4307. specifying the list of libraries to link against (in either I<-llib>
  4308. form or just as pathnames. Relative pathnames in both C<LIBPATH> and
  4309. C<LIBS> are interpreted relative to the directory in which the associated
  4310. construction environment is created (absolute and top-relative names may
  4311. also be used). Cons automatically sets up dependencies on any libraries
  4312. mentioned in C<LIBS>: those libraries will be built before the command
  4313. is linked.
  4314. =head2 The C<Library> method
  4315. The C<Library> method arranges to create the specified library from the
  4316. specified object files. It is invoked as follows:
  4317. Library $env <library name>, <source or object files>;
  4318. The library name will have the value of the C<SUFLIB> construction
  4319. variable appended (by default, C<.lib> on Win32 systems, C<.a> on Unix
  4320. systems) if the suffix is not already present.
  4321. Source files may be specified in place of objects files--the C<Objects>
  4322. method will be invoked to arrange the conversion of all the files into
  4323. object files, and hence all the observations about the C<Objects> method,
  4324. above, apply to this method also.
  4325. The actual creation of the library will be handled by an external
  4326. command which results from expanding the C<ARCOM> construction variable,
  4327. with C<%E<lt>> set to the library members (in the order presented),
  4328. and C<%E<gt>> to the library to be created (see the C<Command> method
  4329. for expansion details). The user may set variables in the construction
  4330. environment which will affect the operation of the command. These
  4331. include C<AR>, the archive program to use, C<ARFLAGS>, which can be
  4332. used to modify the flags given to the program specified by C<AR>, and
  4333. C<RANLIB>, the name of a archive index generation program, if needed
  4334. (if the particular need does not require the latter functionality,
  4335. then C<ARCOM> must be redefined to not reference C<RANLIB>).
  4336. The C<Library> method allows the same library to be specified in multiple
  4337. method invocations. All of the contributing objects from all the invocations
  4338. (which may be from different directories) are combined and generated by a
  4339. single archive command. Note, however, that if you prune a build so that
  4340. only part of a library is specified, then only that part of the library will
  4341. be generated (the rest will disappear!).
  4342. =head2 The C<Module> method
  4343. The C<Module> method is a combination of the C<Program> and C<Command>
  4344. methods. Rather than generating an executable program directly, this command
  4345. allows you to specify your own command to actually generate a module. The
  4346. method is invoked as follows:
  4347. Module $env <module name>, <source or object files>, <construction command>;
  4348. This command is useful in instances where you wish to create, for example,
  4349. dynamically loaded modules, or statically linked code libraries.
  4350. =head2 The C<Depends> method
  4351. The C<Depends> method allows you to specify additional dependencies for a
  4352. target. It is invoked as follows:
  4353. Depends $env <target>, <dependencies>;
  4354. This may be occasionally useful, especially in cases where no scanner exists
  4355. (or is writable) for particular types of files. Normally, dependencies are
  4356. calculated automatically from a combination of the explicit dependencies set
  4357. up by the method invocation or by scanning source files.
  4358. A set of identical dependencies for multiple targets may be specified
  4359. using a reference to a list of targets. In Perl, a list reference can
  4360. be created by enclosing a list in square brackets. Hence the following
  4361. command:
  4362. Depends $env ['foo', 'bar'], 'input_file_1', 'input_file_2';
  4363. specifies that both the F<foo> and F<bar> files depend on the listed
  4364. input files.
  4365. =head2 The C<Ignore> method
  4366. The C<Ignore> method allows you to ignore explicitly dependencies that
  4367. Cons infers on its own. It is invoked as follows:
  4368. Ignore <patterns>;
  4369. This can be used to avoid recompilations due to changes in system header
  4370. files or utilities that are known to not affect the generated targets.
  4371. If, for example, a program is built in an NFS-mounted directory on
  4372. multiple systems that have different copies of F<stdio.h>, the differences
  4373. will affect the signatures of all derived targets built from source files
  4374. that C<#include E<lt>stdio.hE<gt>>. This will cause all those targets to
  4375. be rebuilt when changing systems. If this is not desirable behavior, then
  4376. the following line will remove the dependencies on the F<stdio.h> file:
  4377. Ignore '^/usr/include/stdio\.h$';
  4378. Note that the arguments to the C<Ignore> method are regular expressions,
  4379. so special characters must be escaped and you may wish to anchor the
  4380. beginning or end of the expression with C<^> or C<$> characters.
  4381. =head2 The C<Salt> method
  4382. The C<Salt> method adds a constant value to the signature calculation
  4383. for every derived file. It is invoked as follows:
  4384. Salt $string;
  4385. Changing the Salt value will force a complete rebuild of every derived
  4386. file. This can be used to force rebuilds in certain desired
  4387. circumstances. For example,
  4388. Salt `uname -s`;
  4389. Would force a complete rebuild of every derived file whenever the
  4390. operating system on which the build is performed (as reported by C<uname
  4391. -s>) changes.
  4392. =head2 The C<UseCache> method
  4393. The C<UseCache> method instructs Cons to maintain a cache of derived
  4394. files, to be shared among separate build trees of the same project.
  4395. UseCache("cache/<buildname>") || warn("cache directory not found");
  4396. =head2 The C<SourcePath> method
  4397. The C<SourcePath> mathod returns the real source path name of a file,
  4398. as opposted to the path name within a build directory. It is invoked
  4399. as follows:
  4400. $path = SourcePath <buildpath>;
  4401. =head2 The C<ConsPath> method
  4402. The C<ConsPath> method returns true if the supplied path is a derivable
  4403. file, and returns undef (false) otherwise.
  4404. It is invoked as follows:
  4405. $result = ConsPath <path>;
  4406. =head2 The C<SplitPath> method
  4407. The C<SplitPath> method looks up multiple path names in a string separated
  4408. by the default path separator for the operating system (':' on UNIX
  4409. systems, ';' on Windows NT), and returns the fully-qualified names.
  4410. It is invoked as follows:
  4411. @paths = SplitPath <pathlist>;
  4412. The C<SplitPath> method will convert names prefixed '#' to the
  4413. appropriate top-level build name (without the '#') and will convert
  4414. relative names to top-level names.
  4415. =head2 The C<DirPath> method
  4416. The C<DirPath> method returns the build path name(s) of a directory or
  4417. list of directories. It is invoked as follows:
  4418. $cwd = DirPath <paths>;
  4419. The most common use for the C<DirPath> method is:
  4420. $cwd = DirPath '.';
  4421. to fetch the path to the current directory of a subsidiary F<Conscript>
  4422. file.
  4423. =head2 The C<FilePath> method
  4424. The C<FilePath> method returns the build path name(s) of a file or
  4425. list of files. It is invoked as follows:
  4426. $file = FilePath <path>;
  4427. =head2 The C<Help> method
  4428. The C<Help> method specifies help text that will be displayed when the
  4429. user invokes C<cons -h>. This can be used to provide documentation
  4430. of specific targets, values, build options, etc. for the build tree.
  4431. It is invoked as follows:
  4432. Help <helptext>;
  4433. The C<Help> method may only be called once, and should typically be
  4434. specified in the top-level F<Construct> file.
  4435. =head1 Extending Cons
  4436. =head2 Overriding construction variables
  4437. There are several ways of extending Cons, which vary in degree of
  4438. difficulty. The simplest method is to define your own construction
  4439. environment, based on the default environment, but modified to reflect your
  4440. particular needs. This will often suffice for C-based applications. You can
  4441. use the C<new> constructor, and the C<clone> and C<copy> methods to create
  4442. hybrid environments. These changes can be entirely transparent to the
  4443. underlying F<Conscript> files.
  4444. =head2 Adding new methods
  4445. For slightly more demanding changes, you may wish to add new methods to the
  4446. C<cons> package. Here's an example of a very simple extension,
  4447. C<InstallScript>, which installs a tcl script in a requested location, but
  4448. edits the script first to reflect a platform-dependent path that needs to be
  4449. installed in the script:
  4450. # cons::InstallScript - Create a platform dependent version of a shell
  4451. # script by replacing string ``#!your-path-here'' with platform specific
  4452. # path $BIN_DIR.
  4453. sub cons::InstallScript {
  4454. my ($env, $dst, $src) = @_;
  4455. Command $env $dst, $src, qq(
  4456. sed s+your-path-here+$BIN_DIR+ %< > %>
  4457. chmod oug+x %>
  4458. );
  4459. }
  4460. Notice that this method is defined directly in the C<cons> package (by
  4461. prefixing the name with C<cons::>). A change made in this manner will be
  4462. globally visible to all environments, and could be called as in the
  4463. following example:
  4464. InstallScript $env "$BIN/foo", "foo.tcl";
  4465. For a small improvement in generality, the C<BINDIR> variable could be
  4466. passed in as an argument or taken from the construction environment--as
  4467. C<%BINDIR>.
  4468. =head2 Overriding methods
  4469. Instead of adding the method to the C<cons> name space, you could define a
  4470. new package which inherits existing methods from the C<cons> package and
  4471. overrides or adds others. This can be done using Perl's inheritance
  4472. mechanisms.
  4473. The following example defines a new package C<cons::switch> which overrides the
  4474. standard C<Library> method. The overridden method builds linked library
  4475. modules, rather than library archives. A new constructor is
  4476. provided. Environments created with this constructor will have the new
  4477. library method; others won't.
  4478. package cons::switch;
  4479. BEGIN {@ISA = 'cons'}
  4480. sub new {
  4481. shift;
  4482. bless new cons(@_);
  4483. }
  4484. sub Library {
  4485. my($env) = shift;
  4486. my($lib) = shift;
  4487. my(@objs) = Objects $env @_;
  4488. Command $env $lib, @objs, q(
  4489. %LD -r %LDFLAGS %< -o %>
  4490. );
  4491. }
  4492. This functionality could be invoked as in the following example:
  4493. $env = new cons::switch(@overrides);
  4494. ...
  4495. Library $env 'lib.o', 'foo.c', 'bar.c';
  4496. =head1 Invoking Cons
  4497. The C<cons> command is usually invoked from the root of the build tree. A
  4498. F<Construct> file must exist in that directory. If the C<-f> argument is
  4499. used, then an alternate F<Construct> file may be used (and, possibly, an
  4500. alternate root, since C<cons> will cd to F<Construct> file's containing
  4501. directory).
  4502. If C<cons> is invoked from a child of the root of the build tree with
  4503. the C<-t> argument, it will walk up the directory hierarchy looking for a
  4504. F<Construct> file. (An alternate name may still be specified with C<-f>.)
  4505. The targets supplied on the command line will be modified to be relative
  4506. to the discovered F<Construct> file. For example, from a directory
  4507. containing a top-level F<Construct> file, the following invocation:
  4508. % cd libfoo/subdir
  4509. % cons -t target
  4510. is exactly equivalent to:
  4511. % cons libfoo/subdir/target
  4512. If there are any C<Default> targets specified in the directory hierarchy's
  4513. F<Construct> or F<Conscript> files, only the default targets at or below
  4514. the directory from which C<cons -t> was invoked will be built.
  4515. The command is invoked as follows:
  4516. cons <arguments> -- <construct-args>
  4517. where I<arguments> can be any of the following, in any order:
  4518. =over 10
  4519. =item I<target>
  4520. Build the specified target. If I<target> is a directory, then recursively
  4521. build everything within that directory.
  4522. =item I<+pattern>
  4523. Limit the F<Conscript> files considered to just those that match I<pattern>,
  4524. which is a Perl regular expression. Multiple C<+> arguments are accepted.
  4525. =item I<name>=<val>
  4526. Sets I<name> to value I<val> in the C<ARG> hash passed to the top-level
  4527. F<Construct> file.
  4528. =item C<-cc>
  4529. Show command that would have been executed, when retrieving from cache. No
  4530. indication that the file has been retrieved is given; this is useful for
  4531. generating build logs that can be compared with real build logs.
  4532. =item C<-cd>
  4533. Disable all caching. Do not retrieve from cache nor flush to cache.
  4534. =item C<-cr>
  4535. Build dependencies in random order. This is useful when building multiple
  4536. similar trees with caching enabled.
  4537. =item C<-cs>
  4538. Synchronize existing build targets that are found to be up-to-date with
  4539. cache. This is useful if caching has been disabled with -cc or just recently
  4540. enabled with UseCache.
  4541. =item C<-d>
  4542. Enable dependency debugging.
  4543. =item C<-f> <file>
  4544. Use the specified file instead of F<Construct> (but first change to
  4545. containing directory of I<file>).
  4546. =item C<-h>
  4547. Show a help message local to the current build if one such is defined, and
  4548. exit.
  4549. =item C<-k>
  4550. Keep going as far as possible after errors.
  4551. =item C<-o> <file>
  4552. Read override file I<file>.
  4553. =item C<-p>
  4554. Show construction products in specified trees. No build is attempted.
  4555. =item C<-pa>
  4556. Show construction products and associated actions. No build is attempted.
  4557. =item C<-pw>
  4558. Show products and where they are defined. No build is attempted.
  4559. =item C<-q>
  4560. Don't be verbose about Installing and Removing targets.
  4561. =item C<-r>
  4562. Remove construction products associated with <targets>. No build is
  4563. attempted.
  4564. =item C<-R> <repos>
  4565. Search for files in I<repos>. Multiple B<-R> I<repos> directories are
  4566. searched in the order specified.
  4567. =item C<-t>
  4568. Traverse up the directory hierarchy looking for a F<Construct> file, if
  4569. none exists in the current directory. Targets will be modified to be
  4570. relative to the F<Construct> file.
  4571. =item C<-v>
  4572. Show C<cons> version and continue processing.
  4573. =item C<-V>
  4574. Show C<cons> version and exit.
  4575. =item C<-wf> <file>
  4576. Write all filenames considered into I<file>.
  4577. =item C<-x>
  4578. Show a help message similar to this one, and exit.
  4579. =back
  4580. And I<construct-args> can be any arguments that you wish to process in the
  4581. F<Construct> file. Note that there should be a B<--> separating the arguments
  4582. to cons and the arguments that you wish to process in the F<Construct> file.
  4583. Processing of I<construct-args> can be done by any standard package like
  4584. B<Getopt> or its variants, or any user defined package. B<cons> will pass in
  4585. the I<construct-args> as B<@ARGV> and will not attempt to interpret anything
  4586. after the B<-->.
  4587. % cons -R /usr/local/repository -d os=solaris +driver -- -c test -f DEBUG
  4588. would pass the following to cons
  4589. -R /usr/local/repository -d os=solaris +driver
  4590. and the following, to the top level F<Construct> file as B<@ARGV>
  4591. -c test -f DEBUG
  4592. Note that C<cons -r .> is equivalent to a full recursive C<make clean>,
  4593. but requires no support in the F<Construct> file or any F<Conscript>
  4594. files. This is most useful if you are compiling files into source
  4595. directories (if you separate the F<build> and F<export> directories,
  4596. then you can just remove the directories).
  4597. The options C<-p>, C<-pa>, and C<-pw> are extremely useful for use as an aid
  4598. in reading scripts or debugging them. If you want to know what script
  4599. installs F<export/include/foo.h>, for example, just type:
  4600. % cons -pw export/include/foo.h
  4601. =head1 Using and writing dependency scanners
  4602. QuickScan allows simple target-independent scanners to be set up for source
  4603. files. Only one QuickScan scanner may be associated with any given source
  4604. file and environment.
  4605. QuickScan is invoked as follows:
  4606. QuickScan CONSENV CODEREF, FILENAME [, PATH]
  4607. The subroutine referenced by CODEREF is expected to return a list of
  4608. filenames included directly by FILE. These filenames will, in turn, be
  4609. scanned. The optional PATH argument supplies a lookup path for finding
  4610. FILENAME and/or files returned by the user-supplied subroutine. The PATH
  4611. may be a reference to an array of lookup-directory names, or a string of
  4612. names separated by the system's separator character (':' on UNIX systems,
  4613. ';' on Windows NT).
  4614. The subroutine is called once for each line in the file, with $_ set to the
  4615. current line. If the subroutine needs to look at additional lines, or, for
  4616. that matter, the entire file, then it may read them itself, from the
  4617. filehandle SCAN. It may also terminate the loop, if it knows that no further
  4618. include information is available, by closing the filehandle.
  4619. Whether or not a lookup path is provided, QuickScan first tries to lookup
  4620. the file relative to the current directory (for the top-level file supplied
  4621. directly to QuickScan), or from the directory containing the file which
  4622. referenced the file. This is not very general, but seems good
  4623. enough--especially if you have the luxury of writing your own utilities and
  4624. can control the use of the search path in a standard way. Finally, the
  4625. search path is, currently, colon separated. This may not make the NT camp
  4626. happy.
  4627. Here's a real example, taken from a F<Construct> file here:
  4628. sub cons::SMFgen {
  4629. my($env, @tables) = @_;
  4630. foreach $t (@tables) {
  4631. $env->QuickScan(sub { /\b\S*?\.smf\b/g }, "$t.smf",
  4632. $env->{SMF_INCLUDE_PATH});
  4633. $env->Command(
  4634. ["$t.smdb.cc","$t.smdb.h","$t.snmp.cc","$t.ami.cc", "$t.http.cc"],
  4635. "$t.smf",
  4636. q(
  4637. smfgen %( %SMF_INCLUDE_OPT %) %<
  4638. )
  4639. );
  4640. }
  4641. }
  4642. [NOTE that the form C<$env-E<gt>QuickScan ...> and C<$env-E<gt>Command
  4643. ...> should not be necessary, but, for some reason, is required
  4644. for this particular invocation. This appears to be a bug in Perl or
  4645. a misunderstanding on my part; this invocation style does not always
  4646. appear to be necessary.]
  4647. This finds all names of the form <name>.smf in the file. It will return the
  4648. names even if they're found within comments, but that's OK (the mechanism is
  4649. forgiving of extra files; they're just ignored on the assumption that the
  4650. missing file will be noticed when the program, in this example, smfgen, is
  4651. actually invoked).
  4652. A scanner is only invoked for a given source file if it is needed by some
  4653. target in the tree. It is only ever invoked once for a given source file.
  4654. Here is another way to build the same scanner. This one uses an
  4655. explicit code reference, and also (unecessarily, in this case) reads
  4656. the whole file itself:
  4657. sub myscan {
  4658. my(@includes);
  4659. do {
  4660. push(@includes, /\b\S*?\.smf\b/g);
  4661. } while <SCAN>;
  4662. @includes
  4663. }
  4664. Note that the order of the loop is reversed, with the loop test at the
  4665. end. This is because the first line is already read for you. This scanner
  4666. can be attached to a source file by:
  4667. QuickScan $env \myscan, "$_.smf";
  4668. =head1 SUPPORT AND SUGGESTIONS
  4669. Cons is maintained by the user community. To subscribe, send mail to
  4670. B<cons-discuss-request@gnu.org> with body B<subscribe>.
  4671. Please report any suggestions through the B<cons-discuss@gnu.org> mailing
  4672. list.
  4673. =head1 BUGS
  4674. Sure to be some. Please report any bugs through the B<bug-cons@gnu.org>
  4675. mailing list.
  4676. =head1 INFORMATION ABOUT CONS
  4677. Information about CONS can be obtained from the official cons web site
  4678. B<http://www.dsmit.com/cons/> or its mirrors listed there.
  4679. The cons maintainers can be contacted by email at
  4680. B<cons-maintainers@gnu.org>
  4681. =head1 AUTHORS
  4682. Originally by Bob Sidebotham. Then significantly enriched by the members
  4683. of the Cons community B<cons-discuss@gnu.org>.
  4684. The Cons community would like to thank Ulrich Pfeifer for the original pod
  4685. documentation derived from the F<cons.html> file. Cons documentation is now
  4686. a part of the program itself.
  4687. =cut