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