]> git.donarmstrong.com Git - debhelper.git/blob - Debian/Debhelper/Dh_Lib.pm
refactor cross command generation
[debhelper.git] / Debian / Debhelper / Dh_Lib.pm
1 #!/usr/bin/perl -w
2 #
3 # Library functions for debhelper programs, perl version.
4 #
5 # Joey Hess, GPL copyright 1997-2008.
6
7 package Debian::Debhelper::Dh_Lib;
8 use strict;
9
10 use Exporter;
11 use vars qw(@ISA @EXPORT %dh);
12 @ISA=qw(Exporter);
13 @EXPORT=qw(&init &doit &complex_doit &verbose_print &error &warning &tmpdir
14             &pkgfile &pkgext &pkgfilename &isnative &autoscript &filearray
15             &filedoublearray &getpackages &basename &dirname &xargs %dh
16             &compat &addsubstvar &delsubstvar &excludefile &package_arch
17             &is_udeb &udeb_filename &debhelper_script_subst &escape_shell
18             &inhibit_log &load_log &write_log &dpkg_architecture_value
19             &sourcepackage
20             &is_make_jobserver_unavailable &clean_jobserver_makeflags
21             &cross_command);
22
23 my $max_compat=8;
24
25 sub init {
26         my %params=@_;
27
28         # Check to see if an option line starts with a dash,
29         # or DH_OPTIONS is set.
30         # If so, we need to pass this off to the resource intensive 
31         # Getopt::Long, which I'd prefer to avoid loading at all if possible.
32         if ((defined $ENV{DH_OPTIONS} && length $ENV{DH_OPTIONS}) ||
33             (defined $ENV{DH_INTERNAL_OPTIONS} && length $ENV{DH_INTERNAL_OPTIONS}) ||
34             grep /^-/, @ARGV) {
35                 eval "use Debian::Debhelper::Dh_Getopt";
36                 error($@) if $@;
37                 Debian::Debhelper::Dh_Getopt::parseopts(%params);
38         }
39
40         # Another way to set excludes.
41         if (exists $ENV{DH_ALWAYS_EXCLUDE} && length $ENV{DH_ALWAYS_EXCLUDE}) {
42                 push @{$dh{EXCLUDE}}, split(":", $ENV{DH_ALWAYS_EXCLUDE});
43         }
44         
45         # Generate EXCLUDE_FIND.
46         if ($dh{EXCLUDE}) {
47                 $dh{EXCLUDE_FIND}='';
48                 foreach (@{$dh{EXCLUDE}}) {
49                         my $x=$_;
50                         $x=escape_shell($x);
51                         $x=~s/\./\\\\./g;
52                         $dh{EXCLUDE_FIND}.="-regex .\\*$x.\\* -or ";
53                 }
54                 $dh{EXCLUDE_FIND}=~s/ -or $//;
55         }
56         
57         # Check to see if DH_VERBOSE environment variable was set, if so,
58         # make sure verbose is on.
59         if (defined $ENV{DH_VERBOSE} && $ENV{DH_VERBOSE} ne "") {
60                 $dh{VERBOSE}=1;
61         }
62
63         # Check to see if DH_NO_ACT environment variable was set, if so, 
64         # make sure no act mode is on.
65         if (defined $ENV{DH_NO_ACT} && $ENV{DH_NO_ACT} ne "") {
66                 $dh{NO_ACT}=1;
67         }
68
69         # Get the name of the main binary package (first one listed in
70         # debian/control). Only if the main package was not set on the
71         # command line.
72         if (! exists $dh{MAINPACKAGE} || ! defined $dh{MAINPACKAGE}) {
73                 my @allpackages=getpackages();
74                 $dh{MAINPACKAGE}=$allpackages[0];
75         }
76
77         # Check if packages to build have been specified, if not, fall back to
78         # the default, building all relevant packages.
79         if (! defined $dh{DOPACKAGES} || ! @{$dh{DOPACKAGES}}) {
80                 push @{$dh{DOPACKAGES}}, getpackages('both');
81         }
82
83         # Check to see if -P was specified. If so, we can only act on a single
84         # package.
85         if ($dh{TMPDIR} && $#{$dh{DOPACKAGES}} > 0) {
86                 error("-P was specified, but multiple packages would be acted on (".join(",",@{$dh{DOPACKAGES}}).").");
87         }
88
89         # Figure out which package is the first one we were instructed to build.
90         # This package gets special treatement: files and directories specified on
91         # the command line may affect it.
92         $dh{FIRSTPACKAGE}=${$dh{DOPACKAGES}}[0];
93
94         # If no error handling function was specified, just propigate
95         # errors out.
96         if (! exists $dh{ERROR_HANDLER} || ! defined $dh{ERROR_HANDLER}) {
97                 $dh{ERROR_HANDLER}='exit \$?';
98         }
99 }
100
101 # Run at exit. Add the command to the log files for the packages it acted
102 # on, if it's exiting successfully.
103 my $write_log=1;
104 sub END {
105         if ($? == 0 && $write_log) {
106                 write_log(basename($0), @{$dh{DOPACKAGES}});
107         }
108 }
109
110 sub load_log {
111         my ($package, $db)=@_;
112         my $ext=pkgext($package);
113
114         my @log;
115         open(LOG, "<", "debian/${ext}debhelper.log") || return;
116         while (<LOG>) {
117                 chomp;
118                 push @log, $_;
119                 $db->{$package}{$_}=1 if defined $db;
120         }
121         close LOG;
122         return @log;
123 }
124
125 sub write_log {
126         my $cmd=shift;
127         my @packages=@_;
128
129         return if defined $ENV{DH_INHIBIT_LOG} && $cmd eq $ENV{DH_INHIBIT_LOG};
130
131         foreach my $package (@packages) {
132                 my $ext=pkgext($package);
133                 my $log="debian/${ext}debhelper.log";
134                 open(LOG, ">>", $log) || error("failed to write to ${log}: $!");
135                 print LOG $cmd."\n";
136                 close LOG;
137         }
138 }
139
140 sub inhibit_log {
141         $write_log=0;
142 }
143
144 # Pass it an array containing the arguments of a shell command like would
145 # be run by exec(). It turns that into a line like you might enter at the
146 # shell, escaping metacharacters and quoting arguments that contain spaces.
147 sub escape_shell {
148         my @args=@_;
149         my $line="";
150         my @ret;
151         foreach my $word (@args) {
152                 if ($word=~/\s/) {
153                         # Escape only a few things since it will be quoted.
154                         # Note we use double quotes because you cannot
155                         # escape ' in single quotes, while " can be escaped
156                         # in double.
157                         # This does make -V"foo bar" turn into "-Vfoo bar",
158                         # but that will be parsed identically by the shell
159                         # anyway..
160                         $word=~s/([\n`\$"\\])/\\$1/g;
161                         push @ret, "\"$word\"";
162                 }
163                 else {
164                         # This list is from _Unix in a Nutshell_. (except '#')
165                         $word=~s/([\s!"\$()*+#;<>?@\[\]\\`|~])/\\$1/g;
166                         push @ret,$word;
167                 }
168         }
169         return join(' ', @ret);
170 }
171
172 # Run a command, and display the command to stdout if verbose mode is on.
173 # All commands that modifiy files in $TMP should be ran via this 
174 # function.
175 #
176 # Note that this cannot handle complex commands, especially anything
177 # involving redirection. Use complex_doit instead.
178 sub doit {
179         verbose_print(escape_shell(@_));
180
181         if (! $dh{NO_ACT}) {
182                 system(@_) == 0 || _error_exitcode(join(" ", @_));
183         }
184 }
185
186 # Run a command and display the command to stdout if verbose mode is on.
187 # Use doit() if you can, instead of this function, because this function
188 # forks a shell. However, this function can handle more complicated stuff
189 # like redirection.
190 sub complex_doit {
191         verbose_print(join(" ",@_));
192         
193         if (! $dh{NO_ACT}) {
194                 # The join makes system get a scalar so it forks off a shell.
195                 system(join(" ", @_)) == 0 || _error_exitcode(join(" ", @_))
196         }                       
197 }
198
199 sub _error_exitcode {
200         my $command=shift;
201         if ($? == -1) {
202                 error("$command failed to to execute: $!");
203         }
204         elsif ($? & 127) {
205                 error("$command died with signal ".($? & 127));
206         }
207         else {
208                 error("$command returned exit code ".($? >> 8));
209         }
210 }
211
212 # Run a command that may have a huge number of arguments, like xargs does.
213 # Pass in a reference to an array containing the arguments, and then other
214 # parameters that are the command and any parameters that should be passed to
215 # it each time.
216 sub xargs {
217         my $args=shift;
218
219         # The kernel can accept command lines up to 20k worth of characters.
220         my $command_max=20000; # LINUX SPECIFIC!!
221                         # (And obsolete; it's bigger now.)
222                         # I could use POSIX::ARG_MAX, but that would be slow.
223
224         # Figure out length of static portion of command.
225         my $static_length=0;
226         foreach (@_) {
227                 $static_length+=length($_)+1;
228         }
229         
230         my @collect=();
231         my $length=$static_length;
232         foreach (@$args) {
233                 if (length($_) + 1 + $static_length > $command_max) {
234                         error("This command is greater than the maximum command size allowed by the kernel, and cannot be split up further. What on earth are you doing? \"@_ $_\"");
235                 }
236                 $length+=length($_) + 1;
237                 if ($length < $command_max) {
238                         push @collect, $_;
239                 }
240                 else {
241                         doit(@_,@collect) if $#collect > -1;
242                         @collect=($_);
243                         $length=$static_length + length($_) + 1;
244                 }
245         }
246         doit(@_,@collect) if $#collect > -1;
247 }
248
249 # Print something if the verbose flag is on.
250 sub verbose_print {
251         my $message=shift;
252         
253         if ($dh{VERBOSE}) {
254                 print "\t$message\n";
255         }
256 }
257
258 # Output an error message and die (can be caught).
259 sub error {
260         my $message=shift;
261
262         die basename($0).": $message\n";
263 }
264
265 # Output a warning.
266 sub warning {
267         my $message=shift;
268         
269         print STDERR basename($0).": $message\n";
270 }
271
272 # Returns the basename of the argument passed to it.
273 sub basename {
274         my $fn=shift;
275
276         $fn=~s/\/$//g; # ignore trailing slashes
277         $fn=~s:^.*/(.*?)$:$1:;
278         return $fn;
279 }
280
281 # Returns the directory name of the argument passed to it.
282 sub dirname {
283         my $fn=shift;
284         
285         $fn=~s/\/$//g; # ignore trailing slashes
286         $fn=~s:^(.*)/.*?$:$1:;
287         return $fn;
288 }
289
290 # Pass in a number, will return true iff the current compatibility level
291 # is less than or equal to that number.
292 {
293         my $warned_compat=0;
294         my $c;
295
296         sub compat {
297                 my $num=shift;
298         
299                 if (! defined $c) {
300                         $c=1;
301                         if (defined $ENV{DH_COMPAT}) {
302                                 $c=$ENV{DH_COMPAT};
303                         }
304                         elsif (-e 'debian/compat') {
305                                 # Try the file..
306                                 open (COMPAT_IN, "debian/compat") || error "debian/compat: $!";
307                                 my $l=<COMPAT_IN>;
308                                 close COMPAT_IN;
309                                 if (! defined $l || ! length $l) {
310                                         warning("debian/compat is empty, assuming level $c");
311                                 }
312                                 else {
313                                         chomp $l;
314                                         $c=$l;
315                                 }
316                         }
317                 }
318
319                 if ($c <= 4 && ! $warned_compat) {
320                         warning("Compatibility levels before 5 are deprecated.");
321                         $warned_compat=1;
322                 }
323         
324                 if ($c > $max_compat) {
325                         error("Sorry, but $max_compat is the highest compatibility level supported by this debhelper.");
326                 }
327
328                 return ($c <= $num);
329         }
330 }
331
332 # Pass it a name of a binary package, it returns the name of the tmp dir to
333 # use, for that package.
334 sub tmpdir {
335         my $package=shift;
336
337         if ($dh{TMPDIR}) {
338                 return $dh{TMPDIR};
339         }
340         elsif (compat(1) && $package eq $dh{MAINPACKAGE}) {
341                 # This is for back-compatibility with the debian/tmp tradition.
342                 return "debian/tmp";
343         }
344         else {
345                 return "debian/$package";
346         }
347 }
348
349 # Pass this the name of a binary package, and the name of the file wanted
350 # for the package, and it will return the actual existing filename to use.
351 #
352 # It tries several filenames:
353 #   * debian/package.filename.buildarch
354 #   * debian/package.filename.buildos
355 #   * debian/package.filename
356 #   * debian/filename (if the package is the main package)
357 # If --name was specified then the files
358 # must have the name after the package name:
359 #   * debian/package.name.filename.buildarch
360 #   * debian/package.name.filename.buildos
361 #   * debian/package.name.filename
362 #   * debian/name.filename (if the package is the main package)
363 sub pkgfile {
364         my $package=shift;
365         my $filename=shift;
366
367         if (defined $dh{NAME}) {
368                 $filename="$dh{NAME}.$filename";
369         }
370         
371         # First, check for files ending in buildarch and buildos.
372         my $match;
373         foreach my $file (glob("debian/$package.$filename.*")) {
374                 next if ! -f $file;
375                 next if $dh{IGNORE} && exists $dh{IGNORE}->{$file};
376                 if ($file eq "debian/$package.$filename.".buildarch()) {
377                         $match=$file;
378                         # buildarch files are used in preference to buildos files.
379                         last;
380                 }
381                 elsif ($file eq "debian/$package.$filename.".buildos()) {
382                         $match=$file;
383                 }
384         }
385         return $match if defined $match;
386
387         my @try=("debian/$package.$filename");
388         if ($package eq $dh{MAINPACKAGE}) {
389                 push @try, "debian/$filename";
390         }
391         
392         foreach my $file (@try) {
393                 if (-f $file &&
394                     (! $dh{IGNORE} || ! exists $dh{IGNORE}->{$file})) {
395                         return $file;
396                 }
397
398         }
399
400         return "";
401
402 }
403
404 # Pass it a name of a binary package, it returns the name to prefix to files
405 # in debian/ for this package.
406 sub pkgext {
407         my $package=shift;
408
409         if (compat(1) and $package eq $dh{MAINPACKAGE}) {
410                 return "";
411         }
412         return "$package.";
413 }
414
415 # Pass it the name of a binary package, it returns the name to install
416 # files by in eg, etc. Normally this is the same, but --name can override
417 # it.
418 sub pkgfilename {
419         my $package=shift;
420
421         if (defined $dh{NAME}) {
422                 return $dh{NAME};
423         }
424         return $package;
425 }
426
427 # Returns 1 if the package is a native debian package, null otherwise.
428 # As a side effect, sets $dh{VERSION} to the version of this package.
429 {
430         # Caches return code so it only needs to run dpkg-parsechangelog once.
431         my %isnative_cache;
432         
433         sub isnative {
434                 my $package=shift;
435
436                 return $isnative_cache{$package} if defined $isnative_cache{$package};
437                 
438                 # Make sure we look at the correct changelog.
439                 my $isnative_changelog=pkgfile($package,"changelog");
440                 if (! $isnative_changelog) {
441                         $isnative_changelog="debian/changelog";
442                 }
443                 # Get the package version.
444                 my $version=`dpkg-parsechangelog -l$isnative_changelog`;
445                 ($dh{VERSION})=$version=~m/Version:\s*(.*)/m;
446                 # Did the changelog parse fail?
447                 if (! defined $dh{VERSION}) {
448                         error("changelog parse failure");
449                 }
450
451                 # Is this a native Debian package?
452                 if ($dh{VERSION}=~m/.*-/) {
453                         return $isnative_cache{$package}=0;
454                 }
455                 else {
456                         return $isnative_cache{$package}=1;
457                 }
458         }
459 }
460
461 # Automatically add a shell script snippet to a debian script.
462 # Only works if the script has #DEBHELPER# in it.
463 #
464 # Parameters:
465 # 1: package
466 # 2: script to add to
467 # 3: filename of snippet
468 # 4: sed to run on the snippet. Ie, s/#PACKAGE#/$PACKAGE/
469 sub autoscript {
470         my $package=shift;
471         my $script=shift;
472         my $filename=shift;
473         my $sed=shift || "";
474
475         # This is the file we will modify.
476         my $outfile="debian/".pkgext($package)."$script.debhelper";
477
478         # Figure out what shell script snippet to use.
479         my $infile;
480         if (defined($ENV{DH_AUTOSCRIPTDIR}) && 
481             -e "$ENV{DH_AUTOSCRIPTDIR}/$filename") {
482                 $infile="$ENV{DH_AUTOSCRIPTDIR}/$filename";
483         }
484         else {
485                 if (-e "/usr/share/debhelper/autoscripts/$filename") {
486                         $infile="/usr/share/debhelper/autoscripts/$filename";
487                 }
488                 else {
489                         error("/usr/share/debhelper/autoscripts/$filename does not exist");
490                 }
491         }
492
493         if (-e $outfile && ($script eq 'postrm' || $script eq 'prerm')
494            && !compat(5)) {
495                 # Add fragments to top so they run in reverse order when removing.
496                 complex_doit("echo \"# Automatically added by ".basename($0)."\"> $outfile.new");
497                 complex_doit("sed \"$sed\" $infile >> $outfile.new");
498                 complex_doit("echo '# End automatically added section' >> $outfile.new");
499                 complex_doit("cat $outfile >> $outfile.new");
500                 complex_doit("mv $outfile.new $outfile");
501         }
502         else {
503                 complex_doit("echo \"# Automatically added by ".basename($0)."\">> $outfile");
504                 complex_doit("sed \"$sed\" $infile >> $outfile");
505                 complex_doit("echo '# End automatically added section' >> $outfile");
506         }
507 }
508
509 # Removes a whole substvar line.
510 sub delsubstvar {
511         my $package=shift;
512         my $substvar=shift;
513
514         my $ext=pkgext($package);
515         my $substvarfile="debian/${ext}substvars";
516
517         if (-e $substvarfile) {
518                 complex_doit("grep -s -v '^${substvar}=' $substvarfile > $substvarfile.new || true");
519                 doit("mv", "$substvarfile.new","$substvarfile");
520         }
521 }
522                                 
523 # Adds a dependency on some package to the specified
524 # substvar in a package's substvar's file.
525 sub addsubstvar {
526         my $package=shift;
527         my $substvar=shift;
528         my $deppackage=shift;
529         my $verinfo=shift;
530         my $remove=shift;
531
532         my $ext=pkgext($package);
533         my $substvarfile="debian/${ext}substvars";
534         my $str=$deppackage;
535         $str.=" ($verinfo)" if defined $verinfo && length $verinfo;
536
537         # Figure out what the line will look like, based on what's there
538         # now, and what we're to add or remove.
539         my $line="";
540         if (-e $substvarfile) {
541                 my %items;
542                 open(SUBSTVARS_IN, "$substvarfile") || error "read $substvarfile: $!";
543                 while (<SUBSTVARS_IN>) {
544                         chomp;
545                         if (/^\Q$substvar\E=(.*)/) {
546                                 %items = map { $_ => 1} split(", ", $1);
547                                 
548                                 last;
549                         }
550                 }
551                 close SUBSTVARS_IN;
552                 if (! $remove) {
553                         $items{$str}=1;
554                 }
555                 else {
556                         delete $items{$str};
557                 }
558                 $line=join(", ", sort keys %items);
559         }
560         elsif (! $remove) {
561                 $line=$str;
562         }
563
564         if (length $line) {
565                  complex_doit("(grep -s -v ${substvar} $substvarfile; echo ".escape_shell("${substvar}=$line").") > $substvarfile.new");
566                  doit("mv", "$substvarfile.new", $substvarfile);
567         }
568         else {
569                 delsubstvar($package,$substvar);
570         }
571 }
572
573 # Reads in the specified file, one line at a time. splits on words, 
574 # and returns an array of arrays of the contents.
575 # If a value is passed in as the second parameter, then glob
576 # expansion is done in the directory specified by the parameter ("." is
577 # frequently a good choice).
578 sub filedoublearray {
579         my $file=shift;
580         my $globdir=shift;
581
582         my @ret;
583         open (DH_FARRAY_IN, $file) || error("cannot read $file: $1");
584         while (<DH_FARRAY_IN>) {
585                 chomp;
586                 # Only ignore comments and empty lines in v5 mode.
587                 if (! compat(4)) {
588                         next if /^#/ || /^$/;
589                 }
590                 my @line;
591                 # Only do glob expansion in v3 mode.
592                 #
593                 # The tricky bit is that the glob expansion is done
594                 # as if we were in the specified directory, so the
595                 # filenames that come out are relative to it.
596                 if (defined $globdir && ! compat(2)) {
597                         foreach (map { glob "$globdir/$_" } split) {
598                                 s#^$globdir/##;
599                                 push @line, $_;
600                         }
601                 }
602                 else {
603                         @line = split;
604                 }
605                 push @ret, [@line];
606         }
607         close DH_FARRAY_IN;
608         
609         return @ret;
610 }
611
612 # Reads in the specified file, one word at a time, and returns an array of
613 # the result. Can do globbing as does filedoublearray.
614 sub filearray {
615         return map { @$_ } filedoublearray(@_);
616 }
617
618 # Passed a filename, returns true if -X says that file should be excluded.
619 sub excludefile {
620         my $filename = shift;
621         foreach my $f (@{$dh{EXCLUDE}}) {
622                 return 1 if $filename =~ /\Q$f\E/;
623         }
624         return 0;
625 }
626
627 {
628         my %dpkg_arch_output;
629         sub dpkg_architecture_value {
630                 my $var = shift;
631                 if (! exists($dpkg_arch_output{$var})) {
632                         local $_;
633                         open(PIPE, '-|', 'dpkg-architecture')
634                                 or error("dpkg-architecture failed");
635                         while (<PIPE>) {
636                                 chomp;
637                                 my ($k, $v) = split(/=/, $_, 2);
638                                 $dpkg_arch_output{$k} = $v;
639                         }
640                         close(PIPE);
641                 }
642                 return $dpkg_arch_output{$var};
643         }
644 }
645
646 # Returns the build architecture.
647 sub buildarch {
648         dpkg_architecture_value('DEB_HOST_ARCH');
649 }
650
651 # Returns the build OS.
652 sub buildos {
653         dpkg_architecture_value("DEB_HOST_ARCH_OS");
654 }
655
656 # Passed an arch and a list of arches to match against, returns true if matched
657 {
658         my %knownsame;
659
660         sub samearch {
661                 my $arch=shift;
662                 my @archlist=split(/\s+/,shift);
663         
664                 foreach my $a (@archlist) {
665                         # Avoid expensive dpkg-architecture call to compare
666                         # with a simple architecture name. "linux-any" and
667                         # other architecture wildcards are (currently)
668                         # always hypenated.
669                         if ($a !~ /-/) {
670                                 return 1 if $arch eq $a;
671                         }
672                         elsif (exists $knownsame{$arch}{$a}) {
673                                 return 1 if $knownsame{$arch}{$a};
674                         }
675                         elsif (system("dpkg-architecture", "-a$arch", "-i$a") == 0) {
676                                 return $knownsame{$arch}{$a}=1;
677                         }
678                         else {
679                                 $knownsame{$arch}{$a}=0;
680                         }
681                 }
682         
683                 return 0;
684         }
685 }
686
687 # Returns source package name
688 sub sourcepackage {
689         open (CONTROL, 'debian/control') ||
690             error("cannot read debian/control: $!\n");
691         while (<CONTROL>) {
692                 chomp;
693                 s/\s+$//;
694                 if (/^Source:\s*(.*)/) {
695                         close CONTROL;
696                         return $1;
697                 }
698         }
699
700         close CONTROL;
701         error("could not find Source: line in control file.");
702 }
703
704 # Returns a list of packages in the control file.
705 # Pass "arch" or "indep" to specify arch-dependant (that will be built
706 # for the system's arch) or independant. If nothing is specified,
707 # returns all packages. Also, "both" returns the union of "arch" and "indep"
708 # packages.
709 # As a side effect, populates %package_arches and %package_types with the
710 # types of all packages (not only those returned).
711 my (%package_types, %package_arches);
712 sub getpackages {
713         my $type=shift;
714
715         %package_types=();
716         %package_arches=();
717         
718         $type="" if ! defined $type;
719
720         my $package="";
721         my $arch="";
722         my $package_type;
723         my @list=();
724         my %seen;
725         open (CONTROL, 'debian/control') ||
726                 error("cannot read debian/control: $!\n");
727         while (<CONTROL>) {
728                 chomp;
729                 s/\s+$//;
730                 if (/^Package:\s*(.*)/) {
731                         $package=$1;
732                         # Detect duplicate package names in the same control file.
733                         if (! $seen{$package}) {
734                                 $seen{$package}=1;
735                         }
736                         else {
737                                 error("debian/control has a duplicate entry for $package");
738                         }
739                         $package_type="deb";
740                 }
741                 if (/^Architecture:\s*(.*)/) {
742                         $arch=$1;
743                 }
744                 if (/^(?:X[BC]*-)?Package-Type:\s*(.*)/) {
745                         $package_type=$1;
746                 }
747                 
748                 if (!$_ or eof) { # end of stanza.
749                         if ($package) {
750                                 $package_types{$package}=$package_type;
751                                 $package_arches{$package}=$arch;
752                         }
753
754                         if ($package &&
755                             ((($type eq 'indep' || $type eq 'both') && $arch eq 'all') ||
756                              (($type eq 'arch'  || $type eq 'both') && ($arch eq 'any' ||
757                                              ($arch ne 'all' &&
758                                               samearch(buildarch(), $arch)))) ||
759                              ! $type)) {
760                                 push @list, $package;
761                                 $package="";
762                                 $arch="";
763                         }
764                 }
765         }
766         close CONTROL;
767
768         return @list;
769 }
770
771 # Returns the arch a package will build for.
772 sub package_arch {
773         my $package=shift;
774         
775         if (! exists $package_arches{$package}) {
776                 warning "package $package is not in control info";
777                 return buildarch();
778         }
779         return $package_arches{$package} eq 'all' ? "all" : buildarch();
780 }
781
782 # Return true if a given package is really a udeb.
783 sub is_udeb {
784         my $package=shift;
785         
786         if (! exists $package_types{$package}) {
787                 warning "package $package is not in control info";
788                 return 0;
789         }
790         return $package_types{$package} eq 'udeb';
791 }
792
793 # Generates the filename that is used for a udeb package.
794 sub udeb_filename {
795         my $package=shift;
796         
797         my $filearch=package_arch($package);
798         isnative($package); # side effect
799         my $version=$dh{VERSION};
800         $version=~s/^[0-9]+://; # strip any epoch
801         return "${package}_${version}_$filearch.udeb";
802 }
803
804 # Handles #DEBHELPER# substitution in a script; also can generate a new
805 # script from scratch if none exists but there is a .debhelper file for it.
806 sub debhelper_script_subst {
807         my $package=shift;
808         my $script=shift;
809         
810         my $tmp=tmpdir($package);
811         my $ext=pkgext($package);
812         my $file=pkgfile($package,$script);
813
814         if ($file ne '') {
815                 if (-f "debian/$ext$script.debhelper") {
816                         # Add this into the script, where it has #DEBHELPER#
817                         complex_doit("perl -pe 's~#DEBHELPER#~qx{cat debian/$ext$script.debhelper}~eg' < $file > $tmp/DEBIAN/$script");
818                 }
819                 else {
820                         # Just get rid of any #DEBHELPER# in the script.
821                         complex_doit("sed s/#DEBHELPER#// < $file > $tmp/DEBIAN/$script");
822                 }
823                 doit("chown","0:0","$tmp/DEBIAN/$script");
824                 doit("chmod",755,"$tmp/DEBIAN/$script");
825         }
826         elsif ( -f "debian/$ext$script.debhelper" ) {
827                 complex_doit("printf '#!/bin/sh\nset -e\n' > $tmp/DEBIAN/$script");
828                 complex_doit("cat debian/$ext$script.debhelper >> $tmp/DEBIAN/$script");
829                 doit("chown","0:0","$tmp/DEBIAN/$script");
830                 doit("chmod",755,"$tmp/DEBIAN/$script");
831         }
832 }
833
834 # Checks if make's jobserver is enabled via MAKEFLAGS, but
835 # the FD used to communicate with it is actually not available.
836 sub is_make_jobserver_unavailable {
837         if (exists $ENV{MAKEFLAGS} && 
838             $ENV{MAKEFLAGS} =~ /(?:^|\s)--jobserver-fds=(\d+)/) {
839                 if (!open(my $in, "<&$1")) {
840                         return 1; # unavailable
841                 }
842                 else {
843                         close $in;
844                         return 0; # available
845                 }
846         }
847
848         return; # no jobserver specified
849 }
850
851 # Cleans out jobserver options from MAKEFLAGS.
852 sub clean_jobserver_makeflags {
853         if (exists $ENV{MAKEFLAGS}) {
854                 if ($ENV{MAKEFLAGS} =~ /(?:^|\s)--jobserver-fds=(\d+)/) {
855                         $ENV{MAKEFLAGS} =~ s/(?:^|\s)--jobserver-fds=\S+//g;
856                         $ENV{MAKEFLAGS} =~ s/(?:^|\s)-j\b//g;
857                 }
858                 delete $ENV{MAKEFLAGS} if $ENV{MAKEFLAGS} =~ /^\s*$/;
859         }
860 }
861
862 # If cross-compiling, returns appropriate cross version of command.
863 sub cross_command {
864         my $command=shift;
865         if (dpkg_architecture_value("DEB_BUILD_GNU_TYPE")
866             ne dpkg_architecture_value("DEB_HOST_GNU_TYPE")) {
867                 return dpkg_architecture_value("DEB_HOST_GNU_TYPE")."-$command";
868         }
869         else {
870                 return $command;
871         }
872 }
873
874 1