doc: Document the portability of various tar formats better
[automake.git] / bin / aclocal.in
blobb3715d9c63c2e2de547b23c1bdd3854db0ca1099
1 #!@PERL@ -w
2 # -*- perl -*-
3 # @configure_input@
5 eval 'case $# in 0) exec @PERL@ -S "$0";; *) exec @PERL@ -S "$0" "$@";; esac'
6     if 0;
8 # aclocal - create aclocal.m4 by scanning configure.ac
10 # Copyright (C) 1996-2018 Free Software Foundation, Inc.
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 2, or (at your option)
15 # any later version.
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 # GNU General Public License for more details.
22 # You should have received a copy of the GNU General Public License
23 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
25 # Written by Tom Tromey <tromey@redhat.com>, and
26 # Alexandre Duret-Lutz <adl@gnu.org>.
28 BEGIN
30   unshift (@INC, '@datadir@/@PACKAGE@-@APIVERSION@')
31     unless $ENV{AUTOMAKE_UNINSTALLED};
34 use strict;
36 use Automake::Config;
37 use Automake::General;
38 use Automake::Configure_ac;
39 use Automake::Channels;
40 use Automake::ChannelDefs;
41 use Automake::XFile;
42 use Automake::FileUtils;
43 use File::Basename;
44 use File::Path ();
46 # Some globals.
48 # Support AC_CONFIG_MACRO_DIRS also with older autoconf.
49 # FIXME: To be removed in Automake 2.0, once we can assume autoconf
50 #        2.70 or later.
51 # FIXME: keep in sync with 'internal/ac-config-macro-dirs.m4'.
52 my $ac_config_macro_dirs_fallback =
53   'm4_ifndef([AC_CONFIG_MACRO_DIRS], [' .
54     'm4_defun([_AM_CONFIG_MACRO_DIRS], [])' .
55     'm4_defun([AC_CONFIG_MACRO_DIRS], [_AM_CONFIG_MACRO_DIRS($@)])' .
56   '])';
58 # We do not operate in threaded mode.
59 $perl_threads = 0;
61 # Include paths for searching macros.  We search macros in this order:
62 # user-supplied directories first, then the directory containing the
63 # automake macros, and finally the system-wide directories for
64 # third-party macros.
65 # @user_includes can be augmented with -I or AC_CONFIG_MACRO_DIRS.
66 # @automake_includes can be reset with the '--automake-acdir' option.
67 # @system_includes can be augmented with the 'dirlist' file or the
68 # ACLOCAL_PATH environment variable, and reset with the '--system-acdir'
69 # option.
70 my @user_includes = ();
71 my @automake_includes = ('@datadir@/aclocal-' . $APIVERSION);
72 my @system_includes = ('@datadir@/aclocal');
74 # Whether we should copy M4 file in $user_includes[0].
75 my $install = 0;
77 # --diff
78 my @diff_command;
80 # --dry-run
81 my $dry_run = 0;
83 # configure.ac or configure.in.
84 my $configure_ac;
86 # Output file name.
87 my $output_file = 'aclocal.m4';
89 # Option --force.
90 my $force_output = 0;
92 # Modification time of the youngest dependency.
93 my $greatest_mtime = 0;
95 # Which macros have been seen.
96 my %macro_seen = ();
98 # Remember the order into which we scanned the files.
99 # It's important to output the contents of aclocal.m4 in the opposite order.
100 # (Definitions in first files we have scanned should override those from
101 # later files.  So they must appear last in the output.)
102 my @file_order = ();
104 # Map macro names to file names.
105 my %map = ();
107 # Ditto, but records the last definition of each macro as returned by --trace.
108 my %map_traced_defs = ();
110 # Map basenames to macro names.
111 my %invmap = ();
113 # Map file names to file contents.
114 my %file_contents = ();
116 # Map file names to file types.
117 my %file_type = ();
118 use constant FT_USER => 1;
119 use constant FT_AUTOMAKE => 2;
120 use constant FT_SYSTEM => 3;
122 # Map file names to included files (transitively closed).
123 my %file_includes = ();
125 # Files which have already been added.
126 my %file_added = ();
128 # Files that have already been scanned.
129 my %scanned_configure_dep = ();
131 # Serial numbers, for files that have one.
132 # The key is the basename of the file,
133 # the value is the serial number represented as a list.
134 my %serial = ();
136 # Matches a macro definition.
137 #   AC_DEFUN([macroname], ...)
138 # or
139 #   AC_DEFUN(macroname, ...)
140 # When macroname is '['-quoted , we accept any character in the name,
141 # except ']'.  Otherwise macroname stops on the first ']', ',', ')',
142 # or '\n' encountered.
143 my $ac_defun_rx =
144   "(?:AU_ALIAS|A[CU]_DEFUN|AC_DEFUN_ONCE)\\((?:\\[([^]]+)\\]|([^],)\n]+))";
146 # Matches an AC_REQUIRE line.
147 my $ac_require_rx = "AC_REQUIRE\\((?:\\[([^]]+)\\]|([^],)\n]+))\\)";
149 # Matches an m4_include line.
150 my $m4_include_rx = "(m4_|m4_s|s)include\\((?:\\[([^]]+)\\]|([^],)\n]+))\\)";
152 # Match a serial number.
153 my $serial_line_rx = '^#\s*serial\s+(\S*)';
154 my $serial_number_rx = '^\d+(?:\.\d+)*$';
156 # Autoconf version.  This variable is set by 'trace_used_macros'.
157 my $ac_version;
159 # User directory containing extra m4 files for macros definition,
160 # as extracted from calls to the macro AC_CONFIG_MACRO_DIRS.
161 # This variable is updated by 'trace_used_macros'.
162 my @ac_config_macro_dirs;
164 # If set, names a temporary file that must be erased on abnormal exit.
165 my $erase_me;
167 # Constants for the $ERR_LEVEL parameter of the 'scan_m4_dirs' function.
168 use constant SCAN_M4_DIRS_SILENT => 0;
169 use constant SCAN_M4_DIRS_WARN => 1;
170 use constant SCAN_M4_DIRS_ERROR => 2;
172 ################################################################
174 # Prototypes for all subroutines.
176 sub add_file ($);
177 sub add_macro ($);
178 sub check_acinclude ();
179 sub install_file ($$);
180 sub list_compare (\@\@);
181 sub parse_ACLOCAL_PATH ();
182 sub parse_arguments ();
183 sub reset_maps ();
184 sub scan_configure ();
185 sub scan_configure_dep ($);
186 sub scan_file ($$$);
187 sub scan_m4_dirs ($$@);
188 sub scan_m4_files ();
189 sub strip_redundant_includes (%);
190 sub trace_used_macros ();
191 sub unlink_tmp (;$);
192 sub usage ($);
193 sub version ();
194 sub write_aclocal ($@);
195 sub xmkdir_p ($);
197 ################################################################
199 # Erase temporary file ERASE_ME.  Handle signals.
200 sub unlink_tmp (;$)
202   my ($sig) = @_;
204   if ($sig)
205     {
206       verb "caught SIG$sig, bailing out";
207     }
208   if (defined $erase_me && -e $erase_me && !unlink ($erase_me))
209     {
210       fatal "could not remove '$erase_me': $!";
211     }
212   undef $erase_me;
214   # reraise default handler.
215   if ($sig)
216     {
217       $SIG{$sig} = 'DEFAULT';
218       kill $sig => $$;
219     }
222 $SIG{'INT'} = $SIG{'TERM'} = $SIG{'QUIT'} = $SIG{'HUP'} = 'unlink_tmp';
223 END { unlink_tmp }
225 sub xmkdir_p ($)
227   my $dir = shift;
228   local $@ = undef;
229   return
230     if -d $dir or eval { File::Path::mkpath $dir };
231   chomp $@;
232   $@ =~ s/\s+at\s.*\bline\s\d+.*$//;
233   fatal "could not create directory '$dir': $@";
236 # Check macros in acinclude.m4.  If one is not used, warn.
237 sub check_acinclude ()
239   foreach my $key (keys %map)
240     {
241       # FIXME: should print line number of acinclude.m4.
242       msg ('syntax', "macro '$key' defined in acinclude.m4 but never used")
243         if $map{$key} eq 'acinclude.m4' && ! exists $macro_seen{$key};
244     }
247 sub reset_maps ()
249   $greatest_mtime = 0;
250   %macro_seen = ();
251   @file_order = ();
252   %map = ();
253   %map_traced_defs = ();
254   %file_contents = ();
255   %file_type = ();
256   %file_includes = ();
257   %file_added = ();
258   %scanned_configure_dep = ();
259   %invmap = ();
260   %serial = ();
261   undef &search;
264 # install_file ($SRC, $DESTDIR)
265 sub install_file ($$)
267   my ($src, $destdir) = @_;
268   my $dest = $destdir . "/" . basename ($src);
269   my $diff_dest;
271   verb "installing $src to $dest";
273   if ($force_output
274       || !exists $file_contents{$dest}
275       || $file_contents{$src} ne $file_contents{$dest})
276     {
277       if (-e $dest)
278         {
279           msg 'note', "overwriting '$dest' with '$src'";
280           $diff_dest = $dest;
281         }
282       else
283         {
284           msg 'note', "installing '$dest' from '$src'";
285         }
287       if (@diff_command)
288         {
289           if (! defined $diff_dest)
290             {
291               # $dest does not exist.  We create an empty one just to
292               # run diff, and we erase it afterward.  Using the real
293               # the destination file (rather than a temporary file) is
294               # good when diff is run with options that display the
295               # file name.
296               #
297               # If creating $dest fails, fall back to /dev/null.  At
298               # least one diff implementation (Tru64's) cannot deal
299               # with /dev/null.  However working around this is not
300               # worth the trouble since nobody run aclocal on a
301               # read-only tree anyway.
302               $erase_me = $dest;
303               my $f = new IO::File "> $dest";
304               if (! defined $f)
305                 {
306                   undef $erase_me;
307                   $diff_dest = '/dev/null';
308                 }
309               else
310                 {
311                   $diff_dest = $dest;
312                   $f->close;
313                 }
314             }
315           my @cmd = (@diff_command, $diff_dest, $src);
316           $! = 0;
317           verb "running: @cmd";
318           my $res = system (@cmd);
319           Automake::FileUtils::handle_exec_errors "@cmd", 1
320             if $res;
321           unlink_tmp;
322         }
323       elsif (!$dry_run)
324         {
325           xmkdir_p ($destdir);
326           xsystem ('cp', $src, $dest);
327         }
328     }
331 # Compare two lists of numbers.
332 sub list_compare (\@\@)
334   my @l = @{$_[0]};
335   my @r = @{$_[1]};
336   while (1)
337     {
338       if (0 == @l)
339         {
340           return (0 == @r) ? 0 : -1;
341         }
342       elsif (0 == @r)
343         {
344           return 1;
345         }
346       elsif ($l[0] < $r[0])
347         {
348           return -1;
349         }
350       elsif ($l[0] > $r[0])
351         {
352           return 1;
353         }
354       shift @l;
355       shift @r;
356     }
359 ################################################################
361 # scan_m4_dirs($TYPE, $ERR_LEVEL, @DIRS)
362 # -----------------------------------------------
363 # Scan all M4 files installed in @DIRS for new macro definitions.
364 # Register each file as of type $TYPE (one of the FT_* constants).
365 # If a directory in @DIRS cannot be read:
366 #  - fail hard                if $ERR_LEVEL == SCAN_M4_DIRS_ERROR
367 #  - just print a warning     if $ERR_LEVEL == SCAN_M4_DIRS_WA
368 #  - continue silently        if $ERR_LEVEL == SCAN_M4_DIRS_SILENT
369 sub scan_m4_dirs ($$@)
371   my ($type, $err_level, @dirlist) = @_;
373   foreach my $m4dir (@dirlist)
374     {
375       if (! opendir (DIR, $m4dir))
376         {
377           # TODO: maybe avoid complaining only if errno == ENONENT?
378           my $message = "couldn't open directory '$m4dir': $!";
380           if ($err_level == SCAN_M4_DIRS_ERROR)
381             {
382               fatal $message;
383             }
384           elsif ($err_level == SCAN_M4_DIRS_WARN)
385             {
386               msg ('unsupported', $message);
387               next;
388             }
389           elsif ($err_level == SCAN_M4_DIRS_SILENT)
390             {
391               next; # Silently ignore.
392             }
393           else
394             {
395                prog_error "invalid \$err_level value '$err_level'";
396             }
397         }
399       # We reverse the directory contents so that foo2.m4 gets
400       # used in preference to foo1.m4.
401       foreach my $file (reverse sort grep (! /^\./, readdir (DIR)))
402         {
403           # Only examine .m4 files.
404           next unless $file =~ /\.m4$/;
406           # Skip some files when running out of srcdir.
407           next if $file eq 'aclocal.m4';
409           my $fullfile = File::Spec->canonpath ("$m4dir/$file");
410           scan_file ($type, $fullfile, 'aclocal');
411         }
412       closedir (DIR);
413     }
416 # Scan all the installed m4 files and construct a map.
417 sub scan_m4_files ()
419   # First, scan configure.ac.  It may contain macro definitions,
420   # or may include other files that define macros.
421   scan_file (FT_USER, $configure_ac, 'aclocal');
423   # Then, scan acinclude.m4 if it exists.
424   if (-f 'acinclude.m4')
425     {
426       scan_file (FT_USER, 'acinclude.m4', 'aclocal');
427     }
429   # Finally, scan all files in our search paths.
431   if (@user_includes)
432     {
433       # Don't explore the same directory multiple times.  This is here not
434       # only for speedup purposes.  We need this when the user has e.g.
435       # specified 'ACLOCAL_AMFLAGS = -I m4' and has also set
436       # AC_CONFIG_MACRO_DIR[S]([m4]) in configure.ac.  This makes the 'm4'
437       # directory to occur twice here and fail on the second call to
438       # scan_m4_dirs([m4]) when the 'm4' directory doesn't exist.
439       # TODO: Shouldn't there be rather a check in scan_m4_dirs for
440       #       @user_includes[0]?
441       @user_includes = uniq @user_includes;
443       # Don't complain if the first user directory doesn't exist, in case
444       # we need to create it later (can happen if '--install' was given).
445       scan_m4_dirs (FT_USER,
446                     $install ? SCAN_M4_DIRS_SILENT : SCAN_M4_DIRS_WARN,
447                     $user_includes[0]);
448       scan_m4_dirs (FT_USER,
449                     SCAN_M4_DIRS_ERROR,
450                     @user_includes[1..$#user_includes]);
451     }
452   scan_m4_dirs (FT_AUTOMAKE, SCAN_M4_DIRS_ERROR, @automake_includes);
453   scan_m4_dirs (FT_SYSTEM, SCAN_M4_DIRS_ERROR, @system_includes);
455   # Construct a new function that does the searching.  We use a
456   # function (instead of just evaluating $search in the loop) so that
457   # "die" is correctly and easily propagated if run.
458   my $search = "sub search {\nmy \$found = 0;\n";
459   foreach my $key (reverse sort keys %map)
460     {
461       $search .= ('if (/\b\Q' . $key . '\E(?!\w)/) { add_macro ("' . $key
462                   . '"); $found = 1; }' . "\n");
463     }
464   $search .= "return \$found;\n};\n";
465   eval $search;
466   prog_error "$@\n search is $search" if $@;
469 ################################################################
471 # Add a macro to the output.
472 sub add_macro ($)
474   my ($macro) = @_;
476   # Ignore unknown required macros.  Either they are not really
477   # needed (e.g., a conditional AC_REQUIRE), in which case aclocal
478   # should be quiet, or they are needed and Autoconf itself will
479   # complain when we trace for macro usage later.
480   return unless defined $map{$macro};
482   verb "saw macro $macro";
483   $macro_seen{$macro} = 1;
484   add_file ($map{$macro});
487 # scan_configure_dep ($file)
488 # --------------------------
489 # Scan a configure dependency (configure.ac, or separate m4 files)
490 # for uses of known macros and AC_REQUIREs of possibly unknown macros.
491 # Recursively scan m4_included files.
492 sub scan_configure_dep ($)
494   my ($file) = @_;
495   # Do not scan a file twice.
496   return ()
497     if exists $scanned_configure_dep{$file};
498   $scanned_configure_dep{$file} = 1;
500   my $mtime = mtime $file;
501   $greatest_mtime = $mtime if $greatest_mtime < $mtime;
503   my $contents = exists $file_contents{$file} ?
504     $file_contents{$file} : contents $file;
506   my $line = 0;
507   my @rlist = ();
508   my @ilist = ();
509   foreach (split ("\n", $contents))
510     {
511       ++$line;
512       # Remove comments from current line.
513       s/\bdnl\b.*$//;
514       s/\#.*$//;
515       # Avoid running all the following regexes on white lines.
516       next if /^\s*$/;
518       while (/$m4_include_rx/go)
519         {
520           my $ifile = $2 || $3;
521           # Skip missing 'sinclude'd files.
522           next if $1 ne 'm4_' && ! -f $ifile;
523           push @ilist, $ifile;
524         }
526       while (/$ac_require_rx/go)
527         {
528           push (@rlist, $1 || $2);
529         }
531       # The search function is constructed dynamically by
532       # scan_m4_files.  The last parenthetical match makes sure we
533       # don't match things that look like macro assignments or
534       # AC_SUBSTs.
535       if (! &search && /(^|\s+)(AM_[A-Z0-9_]+)($|[^\]\)=A-Z0-9_])/)
536         {
537           # Macro not found, but AM_ prefix found.
538           # Make this just a warning, because we do not know whether
539           # the macro is actually used (it could be called conditionally).
540           msg ('unsupported', "$file:$line",
541                "macro '$2' not found in library");
542         }
543     }
545   add_macro ($_) foreach (@rlist);
546   scan_configure_dep ($_) foreach @ilist;
549 # add_file ($FILE)
550 # ----------------
551 # Add $FILE to output.
552 sub add_file ($)
554   my ($file) = @_;
556   # Only add a file once.
557   return if ($file_added{$file});
558   $file_added{$file} = 1;
560   scan_configure_dep $file;
563 # Point to the documentation for underquoted AC_DEFUN only once.
564 my $underquoted_manual_once = 0;
566 # scan_file ($TYPE, $FILE, $WHERE)
567 # --------------------------------
568 # Scan a single M4 file ($FILE), and all files it includes.
569 # Return the list of included files.
570 # $TYPE is one of FT_USER, FT_AUTOMAKE, or FT_SYSTEM, depending
571 # on where the file comes from.
572 # $WHERE is the location to use in the diagnostic if the file
573 # does not exist.
574 sub scan_file ($$$)
576   my ($type, $file, $where) = @_;
577   my $basename = basename $file;
579   # Do not scan the same file twice.
580   return @{$file_includes{$file}} if exists $file_includes{$file};
581   # Prevent potential infinite recursion (if two files include each other).
582   return () if exists $file_contents{$file};
584   unshift @file_order, $file;
586   $file_type{$file} = $type;
588   fatal "$where: file '$file' does not exist" if ! -e $file;
590   my $fh = new Automake::XFile $file;
591   my $contents = '';
592   my @inc_files = ();
593   my %inc_lines = ();
595   my $defun_seen = 0;
596   my $serial_seen = 0;
597   my $serial_older = 0;
599   while ($_ = $fh->getline)
600     {
601       # Ignore '##' lines.
602       next if /^##/;
604       $contents .= $_;
605       my $line = $_;
607       if ($line =~ /$serial_line_rx/go)
608         {
609           my $number = $1;
610           if ($number !~ /$serial_number_rx/go)
611             {
612               msg ('syntax', "$file:$.",
613                    "ill-formed serial number '$number', "
614                    . "expecting a version string with only digits and dots");
615             }
616           elsif ($defun_seen)
617             {
618               # aclocal removes all definitions from M4 file with the
619               # same basename if a greater serial number is found.
620               # Encountering a serial after some macros will undefine
621               # these macros...
622               msg ('syntax', "$file:$.",
623                    'the serial number must appear before any macro definition');
624             }
625           # We really care about serials only for non-automake macros
626           # and when --install is used.  But the above diagnostics are
627           # made regardless of this, because not using --install is
628           # not a reason not the fix macro files.
629           elsif ($install && $type != FT_AUTOMAKE)
630             {
631               $serial_seen = 1;
632               my @new = split (/\./, $number);
634               verb "$file:$.: serial $number";
636               if (!exists $serial{$basename}
637                   || list_compare (@new, @{$serial{$basename}}) > 0)
638                 {
639                   # Delete any definition we knew from the old macro.
640                   foreach my $def (@{$invmap{$basename}})
641                     {
642                       verb "$file:$.: ignoring previous definition of $def";
643                       delete $map{$def};
644                     }
645                   $invmap{$basename} = [];
646                   $serial{$basename} = \@new;
647                 }
648               else
649                 {
650                   $serial_older = 1;
651                 }
652             }
653         }
655       # Remove comments from current line.
656       # Do not do it earlier, because the serial line is a comment.
657       $line =~ s/\bdnl\b.*$//;
658       $line =~ s/\#.*$//;
660       while ($line =~ /$ac_defun_rx/go)
661         {
662           $defun_seen = 1;
663           if (! defined $1)
664             {
665               msg ('syntax', "$file:$.", "underquoted definition of $2"
666                    . "\n  run info Automake 'Extending aclocal'\n"
667                    . "  or see https://www.gnu.org/software/automake/manual/"
668                    . "automake.html#Extending-aclocal")
669                 unless $underquoted_manual_once;
670               $underquoted_manual_once = 1;
671             }
673           # If this macro does not have a serial and we have already
674           # seen a macro with the same basename earlier, we should
675           # ignore the macro (don't exit immediately so we can still
676           # diagnose later #serial numbers and underquoted macros).
677           $serial_older ||= ($type != FT_AUTOMAKE
678                              && !$serial_seen && exists $serial{$basename});
680           my $macro = $1 || $2;
681           if (!$serial_older && !defined $map{$macro})
682             {
683               verb "found macro $macro in $file: $.";
684               $map{$macro} = $file;
685               push @{$invmap{$basename}}, $macro;
686             }
687           else
688             {
689               # Note: we used to give an error here if we saw a
690               # duplicated macro.  However, this turns out to be
691               # extremely unpopular.  It causes actual problems which
692               # are hard to work around, especially when you must
693               # mix-and-match tool versions.
694               verb "ignoring macro $macro in $file: $.";
695             }
696         }
698       while ($line =~ /$m4_include_rx/go)
699         {
700           my $ifile = $2 || $3;
701           # Skip missing 'sinclude'd files.
702           next if $1 ne 'm4_' && ! -f $ifile;
703           push (@inc_files, $ifile);
704           $inc_lines{$ifile} = $.;
705         }
706     }
708   # Ignore any file that has an old serial (or no serial if we know
709   # another one with a serial).
710   return ()
711     if ($serial_older ||
712         ($type != FT_AUTOMAKE && !$serial_seen && exists $serial{$basename}));
714   $file_contents{$file} = $contents;
716   # For some reason I don't understand, it does not work
717   # to do "map { scan_file ($_, ...) } @inc_files" below.
718   # With Perl 5.8.2 it undefines @inc_files.
719   my @copy = @inc_files;
720   my @all_inc_files = (@inc_files,
721                        map { scan_file ($type, $_,
722                                         "$file:$inc_lines{$_}") } @copy);
723   $file_includes{$file} = \@all_inc_files;
724   return @all_inc_files;
727 # strip_redundant_includes (%FILES)
728 # ---------------------------------
729 # Each key in %FILES is a file that must be present in the output.
730 # However some of these files might already include other files in %FILES,
731 # so there is no point in including them another time.
732 # This removes items of %FILES which are already included by another file.
733 sub strip_redundant_includes (%)
735   my %files = @_;
737   # Always include acinclude.m4, even if it does not appear to be used.
738   $files{'acinclude.m4'} = 1 if -f 'acinclude.m4';
739   # File included by $configure_ac are redundant.
740   $files{$configure_ac} = 1;
742   # Files at the end of @file_order should override those at the beginning,
743   # so it is important to preserve these trailing files.  We can remove
744   # a file A if it is going to be output before a file B that includes
745   # file A, not the converse.
746   foreach my $file (reverse @file_order)
747     {
748       next unless exists $files{$file};
749       foreach my $ifile (@{$file_includes{$file}})
750         {
751           next unless exists $files{$ifile};
752           delete $files{$ifile};
753           verb "$ifile is already included by $file";
754         }
755     }
757   # configure.ac is implicitly included.
758   delete $files{$configure_ac};
760   return %files;
763 sub trace_used_macros ()
765   my %files = map { $map{$_} => 1 } keys %macro_seen;
766   %files = strip_redundant_includes %files;
768   # When AC_CONFIG_MACRO_DIRS is used, avoid possible spurious warnings
769   # from autom4te about macros being "m4_require'd but not m4_defun'd";
770   # for more background, see:
771   # https://lists.gnu.org/archive/html/autoconf-patches/2012-11/msg00004.html
772   # as well as autoconf commit 'v2.69-44-g1ed0548', "warn: allow aclocal
773   # to silence m4_require warnings".
774   my $early_m4_code .= "m4_define([m4_require_silent_probe], [-])";
776   my $traces = ($ENV{AUTOM4TE} || '@am_AUTOM4TE@');
777   $traces .= " --language Autoconf-without-aclocal-m4 ";
778   $traces = "echo '$early_m4_code' | $traces - ";
780   # Support AC_CONFIG_MACRO_DIRS also with older autoconf.
781   # Note that we can't use '$ac_config_macro_dirs_fallback' here, because
782   # a bug in option parsing code of autom4te 2.68 and earlier will cause
783   # it to read standard input last, even if the "-" argument is specified
784   # early.
785   # FIXME: To be removed in Automake 2.0, once we can assume autoconf
786   #        2.70 or later.
787   $traces .= "$automake_includes[0]/internal/ac-config-macro-dirs.m4 ";
789   # All candidate files.
790   $traces .= join (' ',
791                    (map { "'$_'" }
792                     (grep { exists $files{$_} } @file_order))) . " ";
794   # All candidate macros.
795   $traces .= join (' ',
796                    (map { "--trace='$_:\$f::\$n::\${::}%'" }
797                     ('AC_DEFUN',
798                      'AC_DEFUN_ONCE',
799                      'AU_DEFUN',
800                      '_AM_AUTOCONF_VERSION',
801                      'AC_CONFIG_MACRO_DIR_TRACE',
802                      # FIXME: Tracing the next two macros is a hack for
803                      # compatibility with older autoconf.  Remove this in
804                      # Automake 2.0, when we can assume Autoconf 2.70 or
805                      # later.
806                      'AC_CONFIG_MACRO_DIR',
807                      '_AM_CONFIG_MACRO_DIRS')),
808                    # Do not trace $1 for all other macros as we do
809                    # not need it and it might contains harmful
810                    # characters (like newlines).
811                    (map { "--trace='$_:\$f::\$n'" } (keys %macro_seen)));
813   verb "running $traces $configure_ac";
815   my $tracefh = new Automake::XFile ("$traces $configure_ac |");
817   @ac_config_macro_dirs = ();
819   my %traced = ();
821   while ($_ = $tracefh->getline)
822     {
823       chomp;
824       my ($file, $macro, $arg1) = split (/::/);
826       $traced{$macro} = 1 if exists $macro_seen{$macro};
828       if ($macro eq 'AC_DEFUN' || $macro eq 'AC_DEFUN_ONCE'
829             || $macro eq 'AU_DEFUN')
830         {
831           $map_traced_defs{$arg1} = $file;
832         }
833       elsif ($macro eq '_AM_AUTOCONF_VERSION')
834         {
835           $ac_version = $arg1;
836         }
837       elsif ($macro eq 'AC_CONFIG_MACRO_DIR_TRACE')
838         {
839           push @ac_config_macro_dirs, $arg1;
840         }
841       # FIXME: We still need to trace AC_CONFIG_MACRO_DIR
842       # for compatibility with older autoconf.  Remove this
843       # once we can assume Autoconf 2.70 or later.
844       elsif ($macro eq 'AC_CONFIG_MACRO_DIR')
845         {
846           @ac_config_macro_dirs = ($arg1);
847         }
848       # FIXME:This is an hack for compatibility with older autoconf.
849       # Remove this once we can assume Autoconf 2.70 or later.
850       elsif ($macro eq '_AM_CONFIG_MACRO_DIRS')
851         {
852            # Empty leading/trailing fields might be produced by split,
853            # hence the grep is really needed.
854            push @ac_config_macro_dirs, grep (/./, (split /\s+/, $arg1));
855         }
856     }
858   # FIXME: in Autoconf >= 2.70, AC_CONFIG_MACRO_DIR calls
859   # AC_CONFIG_MACRO_DIR_TRACE behind the scenes, which could
860   # leave unwanted duplicates in @ac_config_macro_dirs.
861   # Remove this in Automake 2.0, when we'll stop tracing
862   # AC_CONFIG_MACRO_DIR explicitly.
863   @ac_config_macro_dirs = uniq @ac_config_macro_dirs;
865   $tracefh->close;
867   return %traced;
870 sub scan_configure ()
872   # Make sure we include acinclude.m4 if it exists.
873   if (-f 'acinclude.m4')
874     {
875       add_file ('acinclude.m4');
876     }
877   scan_configure_dep ($configure_ac);
880 ################################################################
882 # Write output.
883 # Return 0 iff some files were installed locally.
884 sub write_aclocal ($@)
886   my ($output_file, @macros) = @_;
887   my $output = '';
889   my %files = ();
890   # Get the list of files containing definitions for the macros used.
891   # (Filter out unused macro definitions with $map_traced_defs.  This
892   # can happen when an Autoconf macro is conditionally defined:
893   # aclocal sees the potential definition, but this definition is
894   # actually never processed and the Autoconf implementation is used
895   # instead.)
896   for my $m (@macros)
897     {
898       $files{$map{$m}} = 1
899         if (exists $map_traced_defs{$m}
900             && $map{$m} eq $map_traced_defs{$m});
901     }
902   # Do not explicitly include a file that is already indirectly included.
903   %files = strip_redundant_includes %files;
905   my $installed = 0;
907   for my $file (grep { exists $files{$_} } @file_order)
908     {
909       # Check the time stamp of this file, and of all files it includes.
910       for my $ifile ($file, @{$file_includes{$file}})
911         {
912           my $mtime = mtime $ifile;
913           $greatest_mtime = $mtime if $greatest_mtime < $mtime;
914         }
916       # If the file to add looks like outside the project, copy it
917       # to the output.  The regex catches filenames starting with
918       # things like '/', '\', or 'c:\'.
919       if ($file_type{$file} != FT_USER
920           || $file =~ m,^(?:\w:)?[\\/],)
921         {
922           if (!$install || $file_type{$file} != FT_SYSTEM)
923             {
924               # Copy the file into aclocal.m4.
925               $output .= $file_contents{$file} . "\n";
926             }
927           else
928             {
929               # Install the file (and any file it includes).
930               my $dest;
931               for my $ifile (@{$file_includes{$file}}, $file)
932                 {
933                   install_file ($ifile, $user_includes[0]);
934                 }
935               $installed = 1;
936             }
937         }
938       else
939         {
940           # Otherwise, simply include the file.
941           $output .= "m4_include([$file])\n";
942         }
943     }
945   if ($installed)
946     {
947       verb "running aclocal anew, because some files were installed locally";
948       return 0;
949     }
951   # Nothing to output?!
952   # FIXME: Shouldn't we diagnose this?
953   return 1 if ! length ($output);
955   if ($ac_version)
956     {
957       # Do not use "$output_file" here for the same reason we do not
958       # use it in the header below.  autom4te will output the name of
959       # the file in the diagnostic anyway.
960       $output = "m4_ifndef([AC_AUTOCONF_VERSION],
961   [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl
962 m4_if(m4_defn([AC_AUTOCONF_VERSION]), [$ac_version],,
963 [m4_warning([this file was generated for autoconf $ac_version.
964 You have another version of autoconf.  It may work, but is not guaranteed to.
965 If you have problems, you may need to regenerate the build system entirely.
966 To do so, use the procedure documented by the package, typically 'autoreconf'.])])
968 $output";
969     }
971   # We used to print "# $output_file generated automatically etc."  But
972   # this creates spurious differences when using autoreconf.  Autoreconf
973   # creates aclocal.m4t and then rename it to aclocal.m4, but the
974   # rebuild rules generated by Automake create aclocal.m4 directly --
975   # this would gives two ways to get the same file, with a different
976   # name in the header.
977   $output = "# generated automatically by aclocal $VERSION -*- Autoconf -*-
979 # Copyright (C) 1996-$RELEASE_YEAR Free Software Foundation, Inc.
981 # This file is free software; the Free Software Foundation
982 # gives unlimited permission to copy and/or distribute it,
983 # with or without modifications, as long as this notice is preserved.
985 # This program is distributed in the hope that it will be useful,
986 # but WITHOUT ANY WARRANTY, to the extent permitted by law; without
987 # even the implied warranty of MERCHANTABILITY or FITNESS FOR A
988 # PARTICULAR PURPOSE.
990 $ac_config_macro_dirs_fallback
991 $output";
993   # We try not to update $output_file unless necessary, because
994   # doing so invalidate Autom4te's cache and therefore slows down
995   # tools called after aclocal.
996   #
997   # We need to overwrite $output_file in the following situations.
998   #   * The --force option is in use.
999   #   * One of the dependencies is younger.
1000   #     (Not updating $output_file in this situation would cause
1001   #     make to call aclocal in loop.)
1002   #   * The contents of the current file are different from what
1003   #     we have computed.
1004   if (!$force_output
1005       && $greatest_mtime < mtime ($output_file)
1006       && $output eq contents ($output_file))
1007     {
1008       verb "$output_file unchanged";
1009       return 1;
1010     }
1012   verb "writing $output_file";
1014   if (!$dry_run)
1015     {
1016       if (-e $output_file && !unlink $output_file)
1017         {
1018           fatal "could not remove '$output_file': $!";
1019         }
1020       my $out = new Automake::XFile "> $output_file";
1021       print $out $output;
1022     }
1023   return 1;
1026 ################################################################
1028 # Print usage and exit.
1029 sub usage ($)
1031   my ($status) = @_;
1033   print <<'EOF';
1034 Usage: aclocal [OPTION]...
1036 Generate 'aclocal.m4' by scanning 'configure.ac' or 'configure.in'
1038 Options:
1039       --automake-acdir=DIR  directory holding automake-provided m4 files
1040       --system-acdir=DIR    directory holding third-party system-wide files
1041       --diff[=COMMAND]      run COMMAND [diff -u] on M4 files that would be
1042                             changed (implies --install and --dry-run)
1043       --dry-run             pretend to, but do not actually update any file
1044       --force               always update output file
1045       --help                print this help, then exit
1046   -I DIR                    add directory to search list for .m4 files
1047       --install             copy third-party files to the first -I directory
1048       --output=FILE         put output in FILE (default aclocal.m4)
1049       --print-ac-dir        print name of directory holding system-wide
1050                               third-party m4 files, then exit
1051       --verbose             don't be silent
1052       --version             print version number, then exit
1053   -W, --warnings=CATEGORY   report the warnings falling in CATEGORY
1055 Warning categories include:
1056   syntax        dubious syntactic constructs (default)
1057   unsupported   unknown macros (default)
1058   all           all the warnings (default)
1059   no-CATEGORY   turn off warnings in CATEGORY
1060   none          turn off all the warnings
1061   error         treat warnings as errors
1063 Report bugs to <@PACKAGE_BUGREPORT@>.
1064 GNU Automake home page: <@PACKAGE_URL@>.
1065 General help using GNU software: <https://www.gnu.org/gethelp/>.
1067   exit $status;
1070 # Print version and exit.
1071 sub version ()
1073   print <<EOF;
1074 aclocal (GNU $PACKAGE) $VERSION
1075 Copyright (C) $RELEASE_YEAR Free Software Foundation, Inc.
1076 License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl-2.0.html>
1077 This is free software: you are free to change and redistribute it.
1078 There is NO WARRANTY, to the extent permitted by law.
1080 Written by Tom Tromey <tromey\@redhat.com>
1081        and Alexandre Duret-Lutz <adl\@gnu.org>.
1083   exit 0;
1086 # Parse command line.
1087 sub parse_arguments ()
1089   my $print_and_exit = 0;
1090   my $diff_command;
1092   my %cli_options =
1093     (
1094      'help'             => sub { usage(0); },
1095      'version'          => \&version,
1096      'system-acdir=s'   => sub { shift; @system_includes = @_; },
1097      'automake-acdir=s' => sub { shift; @automake_includes = @_; },
1098      'diff:s'           => \$diff_command,
1099      'dry-run'          => \$dry_run,
1100      'force'            => \$force_output,
1101      'I=s'              => \@user_includes,
1102      'install'          => \$install,
1103      'output=s'         => \$output_file,
1104      'print-ac-dir'     => \$print_and_exit,
1105      'verbose'          => sub { setup_channel 'verb', silent => 0; },
1106      'W|warnings=s'     => \&parse_warnings,
1107      );
1109   use Automake::Getopt ();
1110   Automake::Getopt::parse_options %cli_options;
1112   if (@ARGV > 0)
1113     {
1114       fatal ("non-option arguments are not accepted: '$ARGV[0]'.\n"
1115              . "Try '$0 --help' for more information.");
1116     }
1118   if ($print_and_exit)
1119     {
1120       print "@system_includes\n";
1121       exit 0;
1122     }
1124   if (defined $diff_command)
1125     {
1126       $diff_command = 'diff -u' if $diff_command eq '';
1127       @diff_command = split (' ', $diff_command);
1128       $install = 1;
1129       $dry_run = 1;
1130     }
1132   # Finally, adds any directory listed in the 'dirlist' file.
1133   if (@system_includes && open (DIRLIST, "$system_includes[0]/dirlist"))
1134     {
1135       while (<DIRLIST>)
1136         {
1137           # Ignore '#' lines.
1138           next if /^#/;
1139           # strip off newlines and end-of-line comments
1140           s/\s*\#.*$//;
1141           chomp;
1142           foreach my $dir (glob)
1143             {
1144               push (@system_includes, $dir) if -d $dir;
1145             }
1146         }
1147       close (DIRLIST);
1148     }
1151 # Add any directory listed in the 'ACLOCAL_PATH' environment variable
1152 # to the list of system include directories.
1153 sub parse_ACLOCAL_PATH ()
1155   return if not defined $ENV{"ACLOCAL_PATH"};
1156   # Directories in ACLOCAL_PATH should take precedence over system
1157   # directories, so we use unshift.  However, directories that
1158   # come first in ACLOCAL_PATH take precedence over directories
1159   # coming later, which is why the result of split is reversed.
1160   foreach my $dir (reverse split /:/, $ENV{"ACLOCAL_PATH"})
1161     {
1162       unshift (@system_includes, $dir) if $dir ne '' && -d $dir;
1163     }
1166 ################################################################
1168 # Don't refer to installation directories from the build environment
1169 if (exists $ENV{"AUTOMAKE_UNINSTALLED"})
1170   {
1171     @automake_includes = ();
1172     @system_includes = ();
1173   }
1175 @automake_includes = ($ENV{"ACLOCAL_AUTOMAKE_DIR"})
1176   if (exists $ENV{"ACLOCAL_AUTOMAKE_DIR"});
1178 parse_WARNINGS;             # Parse the WARNINGS environment variable.
1179 parse_arguments;
1180 parse_ACLOCAL_PATH;
1181 $configure_ac = require_configure_ac;
1183 # We may have to rerun aclocal if some file have been installed, but
1184 # it should not happen more than once.  The reason we must run again
1185 # is that once the file has been moved from /usr/share/aclocal/ to the
1186 # local m4/ directory it appears at a new place in the search path,
1187 # hence it should be output at a different position in aclocal.m4.  If
1188 # we did not rerun aclocal, the next run of aclocal would produce a
1189 # different aclocal.m4.
1190 my $loop = 0;
1191 my $rerun_due_to_macrodir = 0;
1192 while (1)
1193   {
1194     ++$loop;
1195     prog_error "too many loops" if $loop > 2 + $rerun_due_to_macrodir;
1197     reset_maps;
1198     scan_m4_files;
1199     scan_configure;
1200     last if $exit_code;
1201     my %macro_traced = trace_used_macros;
1203     if (!$rerun_due_to_macrodir && @ac_config_macro_dirs)
1204       {
1205         # The directory specified in calls to the AC_CONFIG_MACRO_DIRS
1206         # m4 macro (if any) must go after the user includes specified
1207         # explicitly with the '-I' option.
1208         push @user_includes, @ac_config_macro_dirs;
1209         # We might have to scan some new directory of .m4 files.
1210         $rerun_due_to_macrodir++;
1211         next;
1212       }
1214     if ($install && !@user_includes)
1215       {
1216         fatal "installation of third-party macros impossible without " .
1217               "-I options nor AC_CONFIG_MACRO_DIR{,S} m4 macro(s)";
1218       }
1220     last if write_aclocal ($output_file, keys %macro_traced);
1221     last if $dry_run;
1222   }
1223 check_acinclude;
1225 exit $exit_code;